Pārlūkot izejas kodu

Release 0.8.1.27: verified off->on power sequence, persistent run timer, cross-stage TX guard, debug logs & fast MT/RMT fixes

XJKJ STL 1 nedēļu atpakaļ
vecāks
revīzija
f99b8c4dcc

+ 1 - 1
Dockerfile

@@ -14,7 +14,7 @@ COPY config/ ./config/
 COPY build/native/stl_native_server /usr/local/bin/stl_native_server
 
 ARG STL_BUILD_COMMIT=vd012-native
-ARG STL_VERSION=0.8.1.26
+ARG STL_VERSION=0.8.1.27
 ENV STL_BUILD_COMMIT=${STL_BUILD_COMMIT} \
     STL_VERSION=${STL_VERSION}
 

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.8.1.26
+0.8.1.27

+ 2 - 2
docker-compose.yml

@@ -3,9 +3,9 @@ services:
     build:
       context: .
       args:
-        STL_VERSION: ${STL_VERSION:-0.8.1.26}
+        STL_VERSION: ${STL_VERSION:-0.8.1.27}
         STL_BUILD_COMMIT: ${STL_BUILD_COMMIT:-vd012-native}
-    image: xjkj-stl:0.8.1.26
+    image: xjkj-stl:0.8.1.27
     container_name: xjkj-stl-backend
     restart: unless-stopped
     stop_grace_period: 30s

+ 329 - 75
native/stl_accel/src/actors.rs

@@ -23,7 +23,7 @@ use std::path::PathBuf;
 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
 use std::sync::{mpsc, Arc, Condvar, Mutex, RwLock};
 use std::thread;
-use std::time::Duration;
+use std::time::{Duration, Instant};
 
 #[derive(Clone)]
 pub struct StationPublishedView {
@@ -155,6 +155,12 @@ pub enum StationMsg {
         sdr_output: Option<String>,
         bmc_state: Option<String>,
     },
+    PowerSequenceDone {
+        boot_id: String,
+        ok: bool,
+        resolved_host: Option<String>,
+        err_msg: Option<String>,
+    },
     /// Deterministic test/simulation helper (used by unit tests & local dry verification)
     TestInjectSerial {
         bytes: Vec<u8>,
@@ -182,6 +188,9 @@ pub enum IpmiJob {
         user: String,
         pass: String,
         hint_off: bool,
+        boot_id: String,
+        station_id: String,
+        debug_log_path: Option<PathBuf>,
     },
     PollTelemetry {
         host: String,
@@ -1046,14 +1055,28 @@ fn mark_station_dirty(
 }
 
 #[inline]
-fn dispatch_pending_bmc_power(st: &mut StationState, ipmi_tx: &mpsc::Sender<IpmiJob>) {
+fn dispatch_pending_bmc_power(
+    st: &mut StationState,
+    ipmi_tx: &mpsc::Sender<IpmiJob>,
+    enable_hw_bg_probes: bool,
+) {
     if let Some(act) = st.pending_bmc_power_action.take() {
         if act == "smart_restart" && st.bmc_enabled && !st.bmc_host.is_empty() {
+            if !enable_hw_bg_probes {
+                st.power_seq_in_progress = false;
+                st.power_seq_started_ms = 0;
+                return;
+            }
+            st.power_seq_in_progress = true;
+            st.power_seq_started_ms = now_ms();
             let _ = ipmi_tx.send(IpmiJob::SmartRestart {
                 host: st.bmc_host.clone(),
                 user: st.bmc_user.clone(),
                 pass: st.bmc_password.clone(),
                 hint_off: st.server_power == "off",
+                boot_id: st.boot_id.clone(),
+                station_id: st.station_id.clone(),
+                debug_log_path: st.debug_log_path.clone(),
             });
         }
     }
@@ -1071,6 +1094,11 @@ pub fn spawn_station_actor(
     push_hub: Arc<PushBroadcaster>,
     enable_hw_bg_probes: bool,
 ) -> StationHandle {
+    if st.debug_log_path.is_none() {
+        let dbg_dir = data_dir.join("debug");
+        let _ = std::fs::create_dir_all(&dbg_dir);
+        st.debug_log_path = Some(dbg_dir.join(format!("{}.log", st.station_id)));
+    }
     if enable_hw_bg_probes && st.has_stale_station_state() {
         st.reset_on_disconnect();
     }
@@ -1102,53 +1130,199 @@ pub fn spawn_station_actor(
                         host,
                         user,
                         pass,
-                        hint_off,
+                        hint_off: _,
+                        boot_id,
+                        station_id,
+                        debug_log_path,
                     } => {
                         if host.is_empty() {
+                            let _ = actor_tx_for_ipmi.send(StationMsg::PowerSequenceDone {
+                                boot_id,
+                                ok: false,
+                                resolved_host: None,
+                                err_msg: Some("BMC host 为空,无法执行先关机再开机".to_string()),
+                            });
+                            if ev_fd_for_ipmi >= 0 {
+                                unsafe {
+                                    lib::stl_eventfd_notify(ev_fd_for_ipmi);
+                                }
+                            }
                             continue;
                         }
-                        let is_off = run_ipmi_with_session(
+                        let log_pwr = |msg: &str| {
+                            if let Some(ref p) = debug_log_path {
+                                crate::storage::append_debug_log_path(p, &station_id, "POWER", msg);
+                            }
+                        };
+                        let notify_actor = || {
+                            if ev_fd_for_ipmi >= 0 {
+                                unsafe {
+                                    lib::stl_eventfd_notify(ev_fd_for_ipmi);
+                                }
+                            }
+                        };
+
+                        let mut resolved: Option<String> = None;
+                        log_pwr(&format!("SEQ_BEGIN host={} boot_id={}", host, boot_id));
+
+                        // Step 1: Ensure verified POWER OFF (up to 4 retries, 35s timeout)
+                        let mut off_verified = false;
+                        if let Ok((rh, s)) = run_ipmi_with_session(
                             Some(&mut session),
                             &host,
                             &user,
                             &pass,
                             &["chassis", "power", "status"],
-                        )
-                        .map(|(_, s)| s.to_ascii_lowercase().contains(" is off"))
-                        .unwrap_or(hint_off);
-                        let act = if is_off { "on" } else { "reset" };
-                        let res = run_ipmi_with_session(
-                            Some(&mut session),
-                            &host,
-                            &user,
-                            &pass,
-                            &["chassis", "power", act],
-                        );
-                        let resolved = match res {
-                            Ok((rh, _)) => Some(rh),
-                            Err(_) if act == "reset" => run_ipmi_with_session(
+                        ) {
+                            resolved = Some(rh);
+                            if s.to_ascii_lowercase().contains(" is off") {
+                                off_verified = true;
+                                log_pwr("STEP1_OFF_ALREADY_VERIFIED");
+                            }
+                        }
+
+                        if !off_verified {
+                            let off_deadline = Instant::now() + Duration::from_secs(35);
+                            let mut off_attempts: u32 = 0;
+                            let mut last_off_send = Instant::now() - Duration::from_secs(10);
+                            while Instant::now() < off_deadline {
+                                if off_attempts < 4
+                                    && last_off_send.elapsed() >= Duration::from_millis(2500)
+                                {
+                                    off_attempts += 1;
+                                    last_off_send = Instant::now();
+                                    let target_h = resolved.as_deref().unwrap_or(&host);
+                                    match run_ipmi_with_session(
+                                        Some(&mut session),
+                                        target_h,
+                                        &user,
+                                        &pass,
+                                        &["chassis", "power", "off"],
+                                    ) {
+                                        Ok((rh, _)) => {
+                                            resolved = Some(rh);
+                                            log_pwr(&format!("STEP1_OFF_CMD attempt={} ok=true", off_attempts));
+                                        }
+                                        Err(e) => {
+                                            log_pwr(&format!("STEP1_OFF_CMD attempt={} err={}", off_attempts, e));
+                                        }
+                                    }
+                                    thread::sleep(Duration::from_millis(900));
+                                } else {
+                                    thread::sleep(Duration::from_millis(1200));
+                                }
+                                let target_h = resolved.as_deref().unwrap_or(&host);
+                                if let Ok((rh, s)) = run_ipmi_with_session(
+                                    Some(&mut session),
+                                    target_h,
+                                    &user,
+                                    &pass,
+                                    &["chassis", "power", "status"],
+                                ) {
+                                    resolved = Some(rh);
+                                    let low = s.to_ascii_lowercase();
+                                    if low.contains(" is off") {
+                                        off_verified = true;
+                                        log_pwr(&format!("STEP1_OFF_VERIFIED attempts={}", off_attempts));
+                                        break;
+                                    }
+                                }
+                            }
+                        }
+
+                        if !off_verified {
+                            let err = format!(
+                                "BMC ({}) 关机确认超时或重试 4 次后仍未处于 Power Off",
+                                resolved.as_deref().unwrap_or(&host)
+                            );
+                            log_pwr(&format!("STEP1_OFF_FAILED {}", err));
+                            let _ = actor_tx_for_ipmi.send(StationMsg::PowerSequenceDone {
+                                boot_id,
+                                ok: false,
+                                resolved_host: resolved,
+                                err_msg: Some(err),
+                            });
+                            notify_actor();
+                            continue;
+                        }
+
+                        // Publish confirmed OFF telemetry cleanly without interrupting power sequence
+                        let _ = actor_tx_for_ipmi.send(StationMsg::IpmiTelemetry {
+                            resolved_host: resolved.clone(),
+                            power: Some("off".to_string()),
+                            sdr_output: None,
+                            bmc_state: Some("online".to_string()),
+                        });
+                        notify_actor();
+
+                        // Step 2: Hardware discharge / settle wait before powering back on
+                        thread::sleep(Duration::from_millis(2000));
+
+                        // Step 3: Ensure verified POWER ON (up to 4 retries, 35s timeout)
+                        let mut on_verified = false;
+                        let on_deadline = Instant::now() + Duration::from_secs(35);
+                        let mut on_attempts: u32 = 0;
+                        let mut last_on_send = Instant::now() - Duration::from_secs(10);
+                        while Instant::now() < on_deadline {
+                            if on_attempts < 4
+                                && last_on_send.elapsed() >= Duration::from_millis(2500)
+                            {
+                                on_attempts += 1;
+                                last_on_send = Instant::now();
+                                let target_h = resolved.as_deref().unwrap_or(&host);
+                                match run_ipmi_with_session(
+                                    Some(&mut session),
+                                    target_h,
+                                    &user,
+                                    &pass,
+                                    &["chassis", "power", "on"],
+                                ) {
+                                    Ok((rh, _)) => {
+                                        resolved = Some(rh);
+                                        log_pwr(&format!("STEP3_ON_CMD attempt={} ok=true", on_attempts));
+                                    }
+                                    Err(e) => {
+                                        log_pwr(&format!("STEP3_ON_CMD attempt={} err={}", on_attempts, e));
+                                    }
+                                }
+                                thread::sleep(Duration::from_millis(900));
+                            } else {
+                                thread::sleep(Duration::from_millis(1200));
+                            }
+                            let target_h = resolved.as_deref().unwrap_or(&host);
+                            if let Ok((rh, s)) = run_ipmi_with_session(
                                 Some(&mut session),
-                                &host,
+                                target_h,
                                 &user,
                                 &pass,
-                                &["chassis", "power", "on"],
-                            )
-                            .ok()
-                            .map(|(rh, _)| rh),
-                            Err(_) => None,
+                                &["chassis", "power", "status"],
+                            ) {
+                                resolved = Some(rh);
+                                if s.to_ascii_lowercase().contains(" is on") {
+                                    on_verified = true;
+                                    log_pwr(&format!("STEP3_ON_VERIFIED attempts={}", on_attempts));
+                                    break;
+                                }
+                            }
+                        }
+
+                        let err_msg = if on_verified {
+                            None
+                        } else {
+                            let e = format!(
+                                "BMC ({}) 开机确认超时或重试 4 次后仍未处于 Power On",
+                                resolved.as_deref().unwrap_or(&host)
+                            );
+                            log_pwr(&format!("STEP3_ON_FAILED {}", e));
+                            Some(e)
                         };
-                        let bmc_ok = resolved.is_some();
-                        let _ = actor_tx_for_ipmi.send(StationMsg::IpmiTelemetry {
+                        let _ = actor_tx_for_ipmi.send(StationMsg::PowerSequenceDone {
+                            boot_id,
+                            ok: on_verified,
                             resolved_host: resolved,
-                            power: if bmc_ok { Some("on".to_string()) } else { None },
-                            sdr_output: None,
-                            bmc_state: Some(if bmc_ok { "online" } else { "offline" }.to_string()),
+                            err_msg,
                         });
-                        if ev_fd_for_ipmi >= 0 {
-                            unsafe {
-                                lib::stl_eventfd_notify(ev_fd_for_ipmi);
-                            }
-                        }
+                        notify_actor();
                     }
                     IpmiJob::PollTelemetry { host, user, pass, refresh_sdr } => {
                         let host_reachable = !host.is_empty()
@@ -1567,7 +1741,7 @@ pub fn spawn_station_actor(
                             } else {
                                 None
                             };
-                            dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor);
+                            dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor, enable_hw_bg_probes);
                             if method == "ConfigureConnections" {
                                 next_ipmi_poll_ms = 0;
                             }
@@ -1598,6 +1772,7 @@ pub fn spawn_station_actor(
                                 &data_dir,
                                 &pxe_tftp_dir,
                                 &ipmi_tx_for_actor,
+                                enable_hw_bg_probes,
                             );
                             uart_clone.publish(&st, false);
                             if let Ok(mut guard) = view_clone.write() {
@@ -1702,7 +1877,7 @@ pub fn spawn_station_actor(
                                 let prev_power = st.server_power.clone();
                                 if pwr == "off" {
                                     st.clear_all_dimm_temps();
-                                    if !st.is_run_active() && !st.awaiting_dimm_replacement {
+                                    if !st.power_seq_in_progress && !st.is_run_active() && !st.awaiting_dimm_replacement {
                                         st.reset_dimms_for_new_boot();
                                     }
                                     state_dirty = true;
@@ -1714,6 +1889,7 @@ pub fn spawn_station_actor(
                                     state_dirty = true;
                                 }
                                 if pwr == "off"
+                                    && !st.power_seq_in_progress
                                     && !st.is_run_active()
                                     && st.observed_phase != "powered_off"
                                 {
@@ -1722,7 +1898,8 @@ pub fn spawn_station_actor(
                                     st.prompt_ready = false;
                                     st.hot.prompt_ready = false;
                                     state_dirty = true;
-                                } else if pwr == "on"
+                                } else if !st.power_seq_in_progress
+                                    && pwr == "on"
                                     && (prev_power == "off" || st.observed_phase == "powered_off")
                                 {
                                     let bp_state_now = st.boot_execution.get_str_or("state", "idle");
@@ -1757,6 +1934,89 @@ pub fn spawn_station_actor(
                                 }
                             }
                         }
+                        StationMsg::PowerSequenceDone {
+                            boot_id,
+                            ok,
+                            resolved_host,
+                            err_msg,
+                        } => {
+                            if !boot_id.is_empty() && boot_id != st.boot_id {
+                                st.log_debug(
+                                    "POWER",
+                                    &format!(
+                                        "STALE_SEQUENCE_IGNORED seq_boot_id={} current_boot_id={} ok={}",
+                                        boot_id, st.boot_id, ok
+                                    ),
+                                );
+                                continue;
+                            }
+                            st.power_seq_in_progress = false;
+                            st.power_seq_started_ms = 0;
+                            if ok {
+                                if let Some(rh) = resolved_host {
+                                    if !rh.is_empty() && rh != st.bmc_host {
+                                        if st.console_host == st.bmc_host {
+                                            st.console_host = rh.clone();
+                                        }
+                                        st.bmc_host = rh;
+                                    }
+                                }
+                                st.bmc_state = "online".to_string();
+                                st.server_power = "on".to_string();
+                                st.cleaner.clear_halfline();
+                                st.prompt_ready = false;
+                                st.hot.prompt_ready = false;
+                                st.hot.awaiting_reset_banner = false;
+                                st.next_reconnect_probe_ms = 0;
+                                st.log_debug(
+                                    "POWER",
+                                    &format!(
+                                        "SEQUENCE_DONE ok=true boot_id={} run_started={} boot_seq={}",
+                                        st.boot_id, st.run_started_unix_ms, st.boot_seq
+                                    ),
+                                );
+                                if matches!(
+                                    st.boot_execution.get_str_or("state", "idle").as_str(),
+                                    "running" | "waiting_boot"
+                                ) {
+                                    st.boot_execution.set(
+                                        "waiting_reason",
+                                        JsonVal::Str(format!(
+                                            "BMC ({}) 已确认先关机再开机,等待 BIOS 启动与 ICT 提示符",
+                                            st.bmc_host
+                                        )),
+                                    );
+                                    st.boot_execution
+                                        .set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
+                                }
+                                pending_sdr_refresh = true;
+                                next_ipmi_poll_ms = now_ms() + 1500;
+                            } else {
+                                st.hot.awaiting_reset_banner = false;
+                                let msg = err_msg
+                                    .unwrap_or_else(|| "BMC 先关机再开机电源序列失败".to_string());
+                                st.log_debug(
+                                    "POWER",
+                                    &format!("SEQUENCE_DONE ok=false boot_id={} err={}", st.boot_id, msg),
+                                );
+                                if st.is_run_active() {
+                                    st.task_status = "failed".to_string();
+                                    let batch_continuing =
+                                        st.task_batch.get_str_or("state", "idle") == "running"
+                                            && !st.task_batch.get_bool("stop_on_fail").unwrap_or(true);
+                                    if !batch_continuing {
+                                        st.freeze_run_timing(now_ms());
+                                    }
+                                    st.boot_execution
+                                        .set("state", JsonVal::Str("failed".to_string()));
+                                    st.boot_execution.set("error", JsonVal::Str(msg.clone()));
+                                    st.boot_execution.set("waiting_reason", JsonVal::Str(msg));
+                                    st.boot_execution
+                                        .set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
+                                }
+                            }
+                            state_dirty = true;
+                        }
                         StationMsg::TestInjectSerial {
                             bytes,
                             force_boot_state,
@@ -1815,7 +2075,7 @@ pub fn spawn_station_actor(
                                 &data_dir,
                                 &pxe_tftp_dir,
                             );
-                            dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor);
+                            dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor, enable_hw_bg_probes);
                             state_dirty = true;
                             if let Ok(mut guard) = view_clone.write() {
                                 *guard = build_published_view(&st);
@@ -1840,7 +2100,7 @@ pub fn spawn_station_actor(
                                 &data_dir,
                                 &pxe_tftp_dir,
                             );
-                            dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor);
+                            dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor, enable_hw_bg_probes);
                             state_dirty = true;
                             uart_clone.publish(&st, false);
                             if let Ok(mut guard) = view_clone.write() {
@@ -1863,7 +2123,7 @@ pub fn spawn_station_actor(
                                 &data_dir,
                                 &pxe_tftp_dir,
                             );
-                            dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor);
+                            dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor, enable_hw_bg_probes);
                             state_dirty = true;
                             uart_clone.publish(&st, false);
                             if let Ok(mut guard) = view_clone.write() {
@@ -1953,7 +2213,7 @@ pub fn spawn_station_actor(
                     &data_dir,
                     &pxe_tftp_dir,
                 );
-                dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor);
+                dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor, enable_hw_bg_probes);
                 if st.boot_execution.get_str_or("state", "idle") != prev_bp_state
                     || st.task_batch.get_str_or("state", "idle") != prev_tb_state
                     || st.task_status != prev_task_status
@@ -2028,25 +2288,29 @@ pub fn spawn_station_actor(
                 // (or station is unconfigured idle), clear stale channel PASS/FAIL, presence,
                 // temperatures, and run state so frontends never display phantom legacy states.
                 if enable_hw_bg_probes {
-                    let bmc_disconnected = !st.bmc_enabled
-                        || st.bmc_host.is_empty()
-                        || st.bmc_state == "offline"
-                        || st.bmc_state == "disabled";
-                    let serial_disconnected = !st.console_online && st.pty_master_fd < 0;
-                    if bmc_disconnected && serial_disconnected {
-                        if st.has_stale_station_state() {
-                            let since = *offline_since_ms.get_or_insert(now);
-                            let grace_ms = if st.is_run_active() { 12_000 } else { 1_500 };
-                            if now.saturating_sub(since) >= grace_ms {
-                                st.reset_on_disconnect();
+                    if st.power_seq_in_progress {
+                        offline_since_ms = None;
+                    } else {
+                        let bmc_disconnected = !st.bmc_enabled
+                            || st.bmc_host.is_empty()
+                            || st.bmc_state == "offline"
+                            || st.bmc_state == "disabled";
+                        let serial_disconnected = !st.console_online && st.pty_master_fd < 0;
+                        if bmc_disconnected && serial_disconnected {
+                            if st.has_stale_station_state() {
+                                let since = *offline_since_ms.get_or_insert(now);
+                                let grace_ms = if st.is_run_active() { 90_000 } else { 5_000 };
+                                if now.saturating_sub(since) >= grace_ms {
+                                    st.reset_on_disconnect();
+                                    offline_since_ms = None;
+                                    state_dirty = true;
+                                }
+                            } else {
                                 offline_since_ms = None;
-                                state_dirty = true;
                             }
                         } else {
                             offline_since_ms = None;
                         }
-                    } else {
-                        offline_since_ms = None;
                     }
                 }
 
@@ -2090,6 +2354,7 @@ fn handle_actor_start_test(
     data_dir: &PathBuf,
     pxe_tftp_dir: &PathBuf,
     ipmi_tx: &mpsc::Sender<IpmiJob>,
+    enable_hw_bg_probes: bool,
 ) -> Result<(StartTestActorReply, Option<JsonVal>), (String, String)> {
     if !st.bmc_enabled
         && st.bmc_host.is_empty()
@@ -2133,19 +2398,17 @@ fn handle_actor_start_test(
     }
     st.next_reconnect_probe_ms = 0;
 
+    st.log_debug(
+        "TASK",
+        &format!(
+            "StartTest continue_timer={} prev_boot={} prev_power={} prev_started={}",
+            continue_timer, prev_boot_id, prev_power, preserved_started
+        ),
+    );
     if params.get("profiles").is_some() || params.get("tasks").is_some() {
         match submit_task_batch(st, params, contract, pxe_state, data_dir, pxe_tftp_dir) {
             Ok(tb) => {
-                if let Some(act) = st.pending_bmc_power_action.take() {
-                    if act == "smart_restart" && st.bmc_enabled && !st.bmc_host.is_empty() {
-                        let _ = ipmi_tx.send(IpmiJob::SmartRestart {
-                            host: st.bmc_host.clone(),
-                            user: st.bmc_user.clone(),
-                            pass: st.bmc_password.clone(),
-                            hint_off: prev_power == "off",
-                        });
-                    }
-                }
+                dispatch_pending_bmc_power(st, ipmi_tx, enable_hw_bg_probes);
                 st.command = strip_private_keys_recursive(clean_cmd_projection);
                 let audit = AuditRecordDraft {
                     category: "task_batch".to_string(),
@@ -2214,16 +2477,7 @@ fn handle_actor_start_test(
         return Err(("FAILED_PRECONDITION".to_string(), e));
     }
 
-    if let Some(act) = st.pending_bmc_power_action.take() {
-        if act == "smart_restart" && st.bmc_enabled && !st.bmc_host.is_empty() {
-            let _ = ipmi_tx.send(IpmiJob::SmartRestart {
-                host: st.bmc_host.clone(),
-                user: st.bmc_user.clone(),
-                pass: st.bmc_password.clone(),
-                hint_off: prev_power == "off",
-            });
-        }
-    }
+    dispatch_pending_bmc_power(st, ipmi_tx, enable_hw_bg_probes);
 
     st.command = strip_private_keys_recursive(clean_cmd_projection);
     let audit = Some(AuditRecordDraft {

+ 5 - 0
native/stl_accel/src/commands.rs

@@ -1056,6 +1056,11 @@ pub fn handle_station_command_nonblocking(
                     ("interactive_start_mt", mt_steps, true, m, true)
                 };
             meta.set("command", JsonVal::Str(raw_path));
+            if st.run_started_unix_ms <= 0 {
+                st.start_run_timing(now_ms(), "StartMt");
+            } else {
+                st.run_ended_unix_ms = 0;
+            }
             if mark_mt_started {
                 st.plan_mt_started = true;
             }

+ 1 - 1
native/stl_accel/src/config.rs

@@ -1,4 +1,4 @@
-// config.rs — Server CLI arguments, version/commit metadata, and station config loader (v0.8.1.26)
+// config.rs — Server CLI arguments, version/commit metadata, and station config loader (v0.8.1.27)
 
 use crate::json::{parse_json, JsonVal};
 use std::env;

+ 13 - 0
native/stl_accel/src/devices.rs

@@ -363,6 +363,19 @@ pub fn write_station_paced(st: &mut StationState, data: &[u8]) -> Result<(), Str
     if data.is_empty() {
         return Ok(());
     }
+    let preview = String::from_utf8_lossy(data)
+        .replace('\r', "\\r")
+        .replace('\n', "\\n");
+    st.log_debug(
+        "TX",
+        &format!(
+            "bytes={} phase={} prompt_kind={} data={}",
+            data.len(),
+            st.observed_phase,
+            st.prompt_kind,
+            preview
+        ),
+    );
     st.clear_halfline_on_tx();
     st.tx_pacer.enqueue(data);
     flush_tx_pacer(st, now_ms())

+ 31 - 7
native/stl_accel/src/firmware.rs

@@ -288,10 +288,19 @@ impl FirmwareContract {
                 mapped.push(o);
             }
         } else {
-            // Hovsee 107_VD012 / 108_VD012 (.166): translate canonical `actm.trfcsb` -> `actm.trfcfgrcsb`
+            // Hovsee 107_VD012 / 108_VD012 (.166): translate canonical `actm.trfcsb` -> `actm.trfcfgrcsb`,
+            // and never emit `ap disable` (Hovsee rejects `ap disable` with Invalid or not support command).
             let has_trfcfgrcsb = ovs.iter().any(|o| o.get_str_or("id", "") == "actm.trfcfgrcsb");
             for mut o in ovs {
-                if o.get_str_or("id", "") == "actm.trfcsb" {
+                let id_s = o.get_str_or("id", "");
+                if id_s == "ap"
+                    && o.get_str_or("value", "")
+                        .trim()
+                        .eq_ignore_ascii_case("disable")
+                {
+                    continue;
+                }
+                if id_s == "actm.trfcsb" {
                     if has_trfcfgrcsb {
                         continue;
                     }
@@ -706,12 +715,27 @@ impl FirmwareContract {
                     }
                     continue;
                 }
-            } else if item_id == "actm.trfcsb" {
-                if !has_trfcfgrcsb {
-                    expanded_lines.push(format!("actm trfcfgrcsb {}", val));
-                    active_ids.insert(item_id);
+            } else {
+                if item_id == "ap" && val.eq_ignore_ascii_case("disable") {
+                    continue;
+                }
+                if item_id == "rmt" && val.eq_ignore_ascii_case("disable") {
+                    for idx in [48u32, 49u32] {
+                        let ln = format!("maskmain {}", idx);
+                        if !expanded_lines.contains(&ln) {
+                            expanded_lines.push(ln);
+                        }
+                    }
+                    active_ids.insert("maskmain".to_string());
+                    continue;
+                }
+                if item_id == "actm.trfcsb" {
+                    if !has_trfcfgrcsb {
+                        expanded_lines.push(format!("actm trfcfgrcsb {}", val));
+                        active_ids.insert(item_id);
+                    }
+                    continue;
                 }
-                continue;
             }
 
             let base_cmd = self.uip_commands.get(&item_id).unwrap();

+ 209 - 2
native/stl_accel/src/main.rs

@@ -3581,7 +3581,28 @@ Hovsee V0.1 Pro Build: 1000No UI (64-bit)\r\n",
         assert_eq!(sc.get_bool("ict_stage2_complete"), Some(true));
         assert_eq!(sc.get_bool("uefi_complete"), Some(true));
 
-        // 2. Subsequent Stage 2 / ICT banner after MT DOES count as external reboot and resets timer.
+        // 2a. Mid-MT unexpected ICT banner preserves task timer until task completes or new start command arrives.
+        hub.test_inject_serial(
+            "S1",
+            b"**********Copyright 2026-2035 Hovsee inc. IMC Config Tool************\r\n",
+            None,
+            false,
+        );
+        let mid_banner = hub.read_station_view("S1").unwrap();
+        assert_eq!(mid_banner.qt_clean_station.get_str_or("started_unix_ms", ""), t0_started);
+        assert_eq!(mid_banner.qt_clean_station.get_str_or("task_status", ""), "running");
+        assert_eq!(mid_banner.qt_clean_station.get_str_or("boot_id", ""), "B-S1-1");
+
+        // 2b. Once MT completes, a subsequent Stage 2 / ICT banner counts as external reboot and resets timer.
+        hub.test_inject_serial(
+            "S1",
+            b"Finished pass #1 (of 1) with 0 error(s)\r\nTest Complete\r\n",
+            Some("running"),
+            false,
+        );
+        let done_mt = hub.read_station_view("S1").unwrap();
+        assert_eq!(done_mt.qt_clean_station.get_str_or("started_unix_ms", ""), t0_started);
+        assert_eq!(done_mt.qt_clean_station.get_str_or("task_status", ""), "completed");
         hub.test_inject_serial(
             "S1",
             b"**********Copyright 2026-2035 Hovsee inc. IMC Config Tool************\r\n",
@@ -3685,7 +3706,7 @@ Please press ENTER to start UIP\r\n\
             web_dir: Path::new("web").to_path_buf(),
             contracts_path: Path::new("contracts/firmware-vd012.json").to_path_buf(),
             web_password: Some("xjkj123456!".to_string()),
-            version: "0.8.1.26".to_string(),
+            version: "0.8.1.27".to_string(),
             commit: "unit-test".to_string(),
         };
         let hub = AppHub::init_for_test(&args);
@@ -3846,4 +3867,190 @@ Please press ENTER to start UIP\r\n\
         let _ = srv_thread.join();
         let _ = std::fs::remove_dir_all(&tmp_dir);
     }
+
+    #[test]
+    fn test_power_sequence_timing_rmt_skipped_mt_progress_and_debug_log() {
+        use crate::actors::StationMsg;
+        use crate::firmware::FirmwareContract;
+        use crate::pxe::try_ingest_local_pxe_report;
+        use crate::results::{now_ms, StationState};
+        use crate::workflow::{control_boot_plan, step_boot_plan};
+
+        lib::init_hardware();
+        let tmp_dir = env::temp_dir().join(format!(
+            "stl_v27_power_timer_{}_{}",
+            std::process::id(),
+            now_ms()
+        ));
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+        std::fs::create_dir_all(tmp_dir.join("station-controls")).unwrap();
+        std::fs::create_dir_all(tmp_dir.join("debug")).unwrap();
+        let tftp_dir = tmp_dir.join("pxe_tftp");
+        std::fs::create_dir_all(&tftp_dir).unwrap();
+
+        let contract =
+            FirmwareContract::load(Path::new("/workspace/XJKJ-STL/contracts/firmware-vd012.json"));
+
+        // 1. Verified Off->On power sequence + persistent timing + debug log
+        let mut st = StationState::new("S2", "Station 2", "192.168.2.167", "");
+        st.debug_log_path = Some(tmp_dir.join("debug").join("S2.log"));
+        let _ = control_boot_plan(&mut st, "restart", &tmp_dir).unwrap();
+        let started_t0 = st.run_started_unix_ms;
+        assert!(started_t0 > 0);
+        assert_eq!(st.pending_bmc_power_action.as_deref(), Some("smart_restart"));
+        // Simulate real HW actor dispatching SmartRestart
+        st.power_seq_in_progress = true;
+        st.power_seq_started_ms = now_ms();
+
+        // Stale serial lines during power_seq_in_progress MUST NOT trigger prompt or clear timing
+        st.observe_serial_chunk(b"[0][Hovsee]Current stage is 1\r\n[0][Hovsee]Please input your command:");
+        assert!(!st.prompt_ready);
+        assert_eq!(st.run_started_unix_ms, started_t0);
+
+        // Simulated 95s power sequence timeout fails cleanly and freezes timing
+        st.power_seq_started_ms = now_ms() - 96_000;
+        step_boot_plan(&mut st, &contract);
+        assert!(!st.power_seq_in_progress);
+        assert_eq!(st.task_status, "failed");
+        assert_eq!(st.run_started_unix_ms, started_t0);
+        assert!(st.run_ended_unix_ms >= started_t0);
+        assert!(st.boot_execution.get_str_or("error", "").contains("95s"));
+
+        // 2. Test full AppHub power_seq + errhandle disable + rmt_complete=false when skipped + single-test MT=1/1 PASS + summary elapsed_ms
+        let args = ServerArgs {
+            config_path: Path::new("config/backend.example.json").to_path_buf(),
+            data_dir: tmp_dir.clone(),
+            web_listen: "127.0.0.1:0".to_string(),
+            tftp_listen: "disabled".to_string(),
+            web_dir: Path::new("web").to_path_buf(),
+            contracts_path: Path::new("contracts/firmware-vd012.json").to_path_buf(),
+            web_password: None,
+            version: "0.8.1.27".to_string(),
+            commit: "unit-test".to_string(),
+        };
+        let hub = AppHub::init_for_test(&args);
+        let s1 = hub.stations.get("S1").unwrap();
+
+        let req = parse_json(
+            r#"{
+                "command_id": "v27-run-1",
+                "station_id": "S1",
+                "run_rmt": false,
+                "run_amt": true,
+                "run_mt": true,
+                "uip_overrides": [
+                    {"id": "errhandle", "mode": "override", "value": "disable"}
+                ],
+                "amt": {
+                    "enabled": true,
+                    "only_tests": [0],
+                    "tp_end_step": 0
+                },
+                "mt": {
+                    "enabled": true,
+                    "tstlist": "0",
+                    "memory_range": "custom",
+                    "addr_lim_lo": "0x10000000",
+                    "addr_lim_hi": "0x14000000",
+                    "numpass": 1,
+                    "exit_mode": 2
+                }
+            }"#,
+        )
+        .unwrap();
+        hub.dispatch_rpc("StartTest", &req, true).unwrap();
+        let v0 = hub.read_station_view("S1").unwrap();
+        let run_t0 = v0.run_started_unix_ms;
+        assert!(run_t0 > 0);
+
+        // Stale PowerSequenceDone from wrong boot_id is ignored; matching PowerSequenceDone completes cleanly
+        s1.send(StationMsg::PowerSequenceDone {
+            boot_id: "WRONG-BOOT".to_string(),
+            ok: false,
+            resolved_host: None,
+            err_msg: Some("stale".to_string()),
+        });
+        hub.force_tick("S1");
+        assert_eq!(hub.read_station_view("S1").unwrap().run_started_unix_ms, run_t0);
+
+        let cur_boot_id = hub.read_station_view("S1").unwrap().boot_id;
+        s1.send(StationMsg::PowerSequenceDone {
+            boot_id: cur_boot_id,
+            ok: true,
+            resolved_host: Some("192.168.2.166".to_string()),
+            err_msg: None,
+        });
+        hub.force_tick("S1");
+
+        // Run through BIOS + Hovsee Stage1 + Training + RMT STOP (0 rows = skipped) + AMT 1/1 + Stage2 + UEFI + MT Test #0 PASS
+        hub.test_inject_serial(
+            "S1",
+            b"[HS_BIOS]Version:GNRSRF_AP(SDP)_RDIMM_108_VD012_20260612, Release Date:20260612, Vendor: AMI Inc.\r\n\
+[HS_DRAM]Socket:0,Channel:0,Dimm:0,Rank:2,Size:64GB,Width:x4,Vendor:Hynix,Type:DDR5 RDIMM,Speed:5600,HS_DIMM_SN:SN0A,DimmLocation:CPU0_CHA\r\n\
+[0][Hovsee]Current stage is 1\r\n\
+[0][Hovsee]Please input your command:\r\n\
+[0][Hovsee]Exit ICT ddr test and go on training\r\n\
+[HS_BIOS][Training][ScktId: 0][124]DDR Training -- SUCCEEDED,Time=12000 ms\r\n\
+STOP_RMT_N0\r\n\
+[0] AMT Version GNR-4.3.3\r\n\
+[0][AMT #] \r\n\
+AMT Test Algo Count: 1\r\n\
+AMT Test Result: PASS\r\n\
+[0][Hovsee]Current stage is 2\r\n\
+[0][Hovsee]Please input your command:\r\n\
+UEFI Interactive Shell v2.2\r\n\
+FS0:\\EFI\\> \r\n",
+            Some("running"),
+            false,
+        );
+
+        let mid_uefi = hub.read_station_view("S1").unwrap();
+        assert_eq!(mid_uefi.run_started_unix_ms, run_t0, "Timer must stay running when MT is enabled");
+        assert_eq!(mid_uefi.run_ended_unix_ms, 0, "Timer must NOT stop before MT completes");
+        assert_eq!(mid_uefi.stage_completions.get_bool("rmt_complete"), Some(false), "Skipped RMT with 0 rows must not claim rmt_complete=true");
+
+        hub.test_inject_serial(
+            "S1",
+            b"118.efi\r\n\
+Hovsee V0.1 Pro Build: 1000No UI (64-bit)\r\n\
+2026-11-18 10:00:01 - Running test #0 (Test 0: Address test, walking ones, no cache)\r\n\
+2026-11-18 10:00:05 - MtSupportRunAllTests - Test execution time: 4.123s (Test 0)\r\n\
+2026-11-18 10:00:06 - Finished pass #1 (of 1) (Cumulative error count: 0, buffer full count: 0)\r\n\
+2026-11-18 10:00:06 - #Tests Passed     : 1/1\r\n\
+FS0:\\EFI\\> \r\n",
+            Some("running"),
+            false,
+        );
+        hub.force_tick("S1");
+        let after_mt = hub.read_station_view("S1").unwrap();
+        assert_eq!(after_mt.task_status, "completed");
+        assert_eq!(after_mt.qt_clean_station.get_str_or("verdict", ""), "pass");
+        assert_eq!(after_mt.run_started_unix_ms, run_t0);
+        assert!(after_mt.run_ended_unix_ms >= run_t0);
+        let mt_res = after_mt.qt_clean_station.get("mt_result").unwrap();
+        assert_eq!(mt_res.get_str_or("status", ""), "pass");
+        assert_eq!(mt_res.get_i64("tests_completed"), Some(1));
+        assert_eq!(mt_res.get_i64("tests_total"), Some(1));
+        assert_eq!(mt_res.get_i64("progress_pct"), Some(100));
+
+        // Verify archived summary.json persisted elapsed_ms > 0 (or >=0 matching ended-started) and debug log exists
+        let sum_path = after_mt
+            .task_history
+            .last()
+            .and_then(|h| h.get_str("summary_path"))
+            .unwrap_or("");
+        assert!(!sum_path.is_empty(), "Archived summary_path must exist");
+        let sum_txt = std::fs::read_to_string(sum_path).unwrap();
+        let sum_json = parse_json(&sum_txt).unwrap();
+        assert_eq!(
+            sum_json.get_i64("elapsed_ms"),
+            Some((after_mt.run_ended_unix_ms - after_mt.run_started_unix_ms).max(0))
+        );
+        let dbg_s1 = std::fs::read_to_string(tmp_dir.join("debug").join("S1.log")).unwrap();
+        assert!(dbg_s1.contains("[TIMER]"));
+        assert!(dbg_s1.contains("MT_PASS_COMPLETE"));
+
+        let _ = try_ingest_local_pxe_report(&tftp_dir, 0, "");
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+    }
 }

+ 40 - 0
native/stl_accel/src/pxe.rs

@@ -234,6 +234,46 @@ fn parse_test_id_list(arr: &[JsonVal]) -> Vec<i64> {
     out
 }
 
+pub fn configured_mt_test_count(cfg: &JsonVal) -> usize {
+    if let Some(arr) = cfg.get_arr("only_tests") {
+        let v = parse_test_id_list(arr);
+        if !v.is_empty() {
+            return v.len();
+        }
+    }
+    if let Some(arr) = cfg.get_arr("selected") {
+        let v = parse_test_id_list(arr);
+        if !v.is_empty() {
+            return v.len();
+        }
+    }
+    if let Some(arr) = cfg.get_arr("algorithms") {
+        let v = parse_test_id_list(arr);
+        if !v.is_empty() {
+            return v.len();
+        }
+    }
+    if let Some(arr) = cfg.get_arr("skip_tests") {
+        let skip = parse_test_id_list(arr);
+        if !skip.is_empty() {
+            return (0..=25).filter(|n| !skip.contains(n)).count().max(1);
+        }
+    }
+    let raw = cfg.get_str_or("tstlist", DEFAULT_FORMAL_TSTLIST);
+    let mut ids = Vec::new();
+    for tok in raw.split(',').map(|s| s.trim()).filter(|s| !s.is_empty()) {
+        if let Some(idx) = mt_test_name_to_idx(tok).or_else(|| tok.parse::<i64>().ok()) {
+            if (0..=25).contains(&idx) && !ids.contains(&idx) {
+                ids.push(idx);
+            }
+        }
+    }
+    if !ids.is_empty() {
+        return ids.len();
+    }
+    26
+}
+
 pub fn render_mt86_cfg_text(cfg: &JsonVal, tftp_server_ip: &str) -> String {
     let fallback_tst = cfg.get_str_or("tstlist", DEFAULT_FORMAL_TSTLIST);
     let only_nums = cfg

+ 380 - 109
native/stl_accel/src/results.rs

@@ -4,6 +4,7 @@
 use crate::json::JsonVal;
 use crate::lib;
 use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::path::PathBuf;
 use std::time::{SystemTime, UNIX_EPOCH};
 
 pub const RAW_RING_CAPACITY: usize = 16 * 1024 * 1024;
@@ -449,6 +450,7 @@ pub struct StationState {
     pub active_amt_cpus: BTreeSet<i64>,
     pub mt_result: JsonVal,
     pub mt_per_test_errs: BTreeMap<i32, i64>,
+    pub mt_completed_test_ids: BTreeSet<i32>,
     pub uip_overrides: Vec<JsonVal>,
     pub uip_raw_commands: Vec<String>,
     pub mt_selection: JsonVal,
@@ -502,6 +504,9 @@ pub struct StationState {
     pub in_internal_warm_reset: bool,
     pub amt_prefers_short_cmd: bool,
     pub amt_fallback_attempted: bool,
+    pub power_seq_in_progress: bool,
+    pub power_seq_started_ms: i64,
+    pub debug_log_path: Option<PathBuf>,
     pub dimm_seen_in_boot: [bool; 24],
     pub had_bmc_sdr: [bool; 24],
     pub sdr_absent_streak: [u8; 24],
@@ -643,6 +648,7 @@ impl StationState {
             active_amt_cpus: BTreeSet::new(),
             mt_result: JsonVal::obj(),
             mt_per_test_errs: BTreeMap::new(),
+            mt_completed_test_ids: BTreeSet::new(),
             uip_overrides: Vec::new(),
             uip_raw_commands: Vec::new(),
             mt_selection: mt_sel,
@@ -696,6 +702,9 @@ impl StationState {
             in_internal_warm_reset: false,
             amt_prefers_short_cmd: false,
             amt_fallback_attempted: false,
+            power_seq_in_progress: false,
+            power_seq_started_ms: 0,
+            debug_log_path: None,
             dimm_seen_in_boot: [false; 24],
             had_bmc_sdr: [false; 24],
             sdr_absent_streak: [0; 24],
@@ -793,6 +802,13 @@ impl StationState {
         self.sdr_absent_streak = [0; 24];
     }
 
+    #[inline]
+    pub fn log_debug(&self, category: &str, msg: &str) {
+        if let Some(ref p) = self.debug_log_path {
+            crate::storage::append_debug_log_path(p, &self.station_id, category, msg);
+        }
+    }
+
     pub fn clear_for_external_restart(
         &mut self,
         now: i64,
@@ -800,6 +816,29 @@ impl StationState {
         force_new_boot_id: bool,
     ) {
         let bp_state_now = self.boot_execution.get_str_or("state", "idle");
+        let is_terminal_bp = matches!(
+            bp_state_now.as_str(),
+            "blocked" | "failed" | "completed" | "stopped" | "interrupted"
+        ) || matches!(
+            self.task_status.as_str(),
+            "failed" | "completed" | "interrupted"
+        );
+        let keep_active_run = self.power_seq_in_progress
+            || (self.is_run_active() && !self.has_any_failure_state() && !is_terminal_bp);
+        self.log_debug(
+            "RESET",
+            &format!(
+                "clear_for_external_restart reason={} force_new_boot_id={} keep_active_run={} run_active={} started={} ended={} bp_state={} task_status={}",
+                reason_detail,
+                force_new_boot_id,
+                keep_active_run,
+                self.is_run_active(),
+                self.run_started_unix_ms,
+                self.run_ended_unix_ms,
+                bp_state_now,
+                self.task_status
+            ),
+        );
         let had_active_or_finished_run = self.run_ended_unix_ms > 0
             || self.single_run_started_ms > 0
             || self.single_run_active
@@ -827,16 +866,19 @@ impl StationState {
         self.amt_fallback_attempted = false;
         self.mt_result = JsonVal::obj();
         self.mt_per_test_errs.clear();
+        self.mt_completed_test_ids.clear();
         self.plan_configured.clear();
         self.plan_done.clear();
         self.plan_amt_started.clear();
         self.plan_mt_started = false;
-        self.single_run_active = false;
-        self.single_run_id.clear();
-        self.single_run_started_ms = 0;
-        if had_active_or_finished_run {
-            self.run_started_unix_ms = 0;
-            self.run_ended_unix_ms = 0;
+        if !keep_active_run {
+            self.single_run_active = false;
+            self.single_run_id.clear();
+            self.single_run_started_ms = 0;
+            if had_active_or_finished_run {
+                self.run_started_unix_ms = 0;
+                self.run_ended_unix_ms = 0;
+            }
         }
         self.mt_started_unix_ms = 0;
         self.mt_report_sync_pending = false;
@@ -863,39 +905,41 @@ impl StationState {
         self.async_script.clear();
         self.tx_pacer.clear();
         self.pending_complete_signal = None;
-        self.task_status = "not_started".to_string();
-        self.stage_intents.clear();
-        self.last_uip_apply = None;
-        self.last_amt_apply = None;
-        self.last_amt_start = None;
-        self.last_phase_action = None;
-        self.command = JsonVal::Null;
-        if bp_state_now != "idle"
-            || !self.boot_execution.get_str_or("id", "").is_empty()
-            || !self.boot_execution.get_str_or("boot_id", "").is_empty()
-            || !self.boot_execution.get_str_or("error", "").is_empty()
-            || !self.boot_execution.get_str_or("current_stage", "").is_empty()
-            || !self.boot_execution.get_str_or("waiting_reason", "").is_empty()
-            || self
-                .boot_execution
-                .get_arr("handled_inputs")
-                .map(|a| !a.is_empty())
-                .unwrap_or(false)
-            || self
-                .boot_execution
-                .get_f64("started_unix_ms")
-                .unwrap_or(0.0)
-                > 0.0
-        {
-            self.boot_execution.set("id", JsonVal::Str(String::new()));
-            self.boot_execution.set("boot_id", JsonVal::Str(String::new()));
-            self.boot_execution.set("state", JsonVal::Str("idle".to_string()));
-            self.boot_execution.set("current_stage", JsonVal::Str(String::new()));
-            self.boot_execution.set("error", JsonVal::Str(String::new()));
-            self.boot_execution.set("waiting_reason", JsonVal::Str(String::new()));
-            self.boot_execution.set("handled_inputs", JsonVal::Arr(Vec::new()));
-            self.boot_execution.set("started_unix_ms", JsonVal::Num(0.0));
-            self.boot_execution.set("updated_unix_ms", JsonVal::Num(now as f64));
+        if !keep_active_run {
+            self.task_status = "not_started".to_string();
+            self.stage_intents.clear();
+            self.last_uip_apply = None;
+            self.last_amt_apply = None;
+            self.last_amt_start = None;
+            self.last_phase_action = None;
+            self.command = JsonVal::Null;
+            if bp_state_now != "idle"
+                || !self.boot_execution.get_str_or("id", "").is_empty()
+                || !self.boot_execution.get_str_or("boot_id", "").is_empty()
+                || !self.boot_execution.get_str_or("error", "").is_empty()
+                || !self.boot_execution.get_str_or("current_stage", "").is_empty()
+                || !self.boot_execution.get_str_or("waiting_reason", "").is_empty()
+                || self
+                    .boot_execution
+                    .get_arr("handled_inputs")
+                    .map(|a| !a.is_empty())
+                    .unwrap_or(false)
+                || self
+                    .boot_execution
+                    .get_f64("started_unix_ms")
+                    .unwrap_or(0.0)
+                    > 0.0
+            {
+                self.boot_execution.set("id", JsonVal::Str(String::new()));
+                self.boot_execution.set("boot_id", JsonVal::Str(String::new()));
+                self.boot_execution.set("state", JsonVal::Str("idle".to_string()));
+                self.boot_execution.set("current_stage", JsonVal::Str(String::new()));
+                self.boot_execution.set("error", JsonVal::Str(String::new()));
+                self.boot_execution.set("waiting_reason", JsonVal::Str(String::new()));
+                self.boot_execution.set("handled_inputs", JsonVal::Arr(Vec::new()));
+                self.boot_execution.set("started_unix_ms", JsonVal::Num(0.0));
+                self.boot_execution.set("updated_unix_ms", JsonVal::Num(now as f64));
+            }
         }
     }
 
@@ -950,6 +994,15 @@ impl StationState {
 
     pub fn reset_on_disconnect(&mut self) {
         let now = now_ms();
+        self.log_debug(
+            "RESET",
+            &format!(
+                "reset_on_disconnect prev_started={} prev_ended={} task_status={} boot_id={}",
+                self.run_started_unix_ms, self.run_ended_unix_ms, self.task_status, self.boot_id
+            ),
+        );
+        self.power_seq_in_progress = false;
+        self.power_seq_started_ms = 0;
         self.console_online = false;
         self.hot.console_online = false;
         self.hot.reset_for_new_boot(now);
@@ -1005,6 +1058,7 @@ impl StationState {
         self.active_amt_cpus.clear();
         self.mt_result = JsonVal::obj();
         self.mt_per_test_errs.clear();
+        self.mt_completed_test_ids.clear();
         self.unsupported_commands.clear();
         self.last_err_stage.clear();
         for v in self.stage_errors.values_mut() {
@@ -1089,10 +1143,34 @@ impl StationState {
             || self.observed_stages.contains("mt")
     }
 
+    #[inline]
+    pub fn start_run_timing(&mut self, now: i64, reason: &str) {
+        self.run_started_unix_ms = now;
+        self.run_ended_unix_ms = 0;
+        self.log_debug(
+            "TIMER",
+            &format!(
+                "START reason={} started_unix_ms={} boot_id={}",
+                reason, now, self.boot_id
+            ),
+        );
+    }
+
     #[inline]
     pub fn freeze_run_timing(&mut self, now: i64) {
         if self.run_started_unix_ms > 0 && self.run_ended_unix_ms == 0 {
             self.run_ended_unix_ms = now.max(self.run_started_unix_ms);
+            self.log_debug(
+                "TIMER",
+                &format!(
+                    "FREEZE started_unix_ms={} ended_unix_ms={} elapsed_ms={} task_status={} boot_id={}",
+                    self.run_started_unix_ms,
+                    self.run_ended_unix_ms,
+                    self.run_ended_unix_ms - self.run_started_unix_ms,
+                    self.task_status,
+                    self.boot_id
+                ),
+            );
         }
     }
 
@@ -1104,9 +1182,9 @@ impl StationState {
     /// Monotonic phase advance within the current boot (prevents stage regression during training/RMT/POST).
     fn advance_phase(&mut self, new_phase: &str, detail: &str, now: i64) {
         if self.run_started_unix_ms == 0 && self.is_run_active() {
-            self.run_started_unix_ms = now;
-            self.run_ended_unix_ms = 0;
+            self.start_run_timing(now, &format!("advance_phase:{}", new_phase));
         }
+        let prev_phase = self.observed_phase.clone();
         let stg = self.observed_uip_stage.unwrap_or(1);
         let new_rk = phase_rank(new_phase, stg);
         if new_rk >= self.hot.stage_rank || new_phase == "uefi" && self.hot.mt_pass_complete || new_phase == "uefi" && self.hot.mt_fail_complete {
@@ -1116,6 +1194,21 @@ impl StationState {
             self.observed_phase = new_phase.to_string();
             self.observed_detail = detail.to_string();
         }
+        if prev_phase != self.observed_phase || detail == "rmt_completed" || detail == "mt_complete" {
+            self.log_debug(
+                "STAGE",
+                &format!(
+                    "phase {}->{} detail={} rank={} run_started={} run_ended={} boot_id={}",
+                    prev_phase,
+                    self.observed_phase,
+                    detail,
+                    self.hot.stage_rank,
+                    self.run_started_unix_ms,
+                    self.run_ended_unix_ms,
+                    self.boot_id
+                ),
+            );
+        }
         self.observed_stages.insert(new_phase.to_string());
         self.observed_unix_ms = now;
         self.hot.observed_unix_ms = now;
@@ -1258,6 +1351,13 @@ impl StationState {
         err.set("message", JsonVal::Str(msg.to_string()));
         err.set("observed_unix_ms", JsonVal::Str(now.to_string()));
         list.push(err);
+        self.log_debug(
+            "ERROR",
+            &format!(
+                "stage={} kind={} cpu={:?} ch={:?} msg={}",
+                stage, kind, cpu, ch, msg
+            ),
+        );
     }
 
     pub fn record_stage_error(
@@ -1666,6 +1766,16 @@ impl StationState {
         if let Some(tp) = report.get_str("tests_passed") {
             self.mt_result
                 .set("tests_passed", JsonVal::Str(tp.to_string()));
+            if let Some((p_s, t_s)) = tp.split_once('/') {
+                if let (Ok(p_n), Ok(t_n)) = (p_s.trim().parse::<i64>(), t_s.trim().parse::<i64>()) {
+                    if t_n > 0 {
+                        self.mt_result.set("tests_total", JsonVal::Num(t_n as f64));
+                        self.mt_result.set("tests_completed", JsonVal::Num(p_n.max(0) as f64));
+                        let pct = ((p_n.max(0) * 100) / t_n).clamp(0, 100);
+                        self.mt_result.set("progress_pct", JsonVal::Num(pct as f64));
+                    }
+                }
+            }
         }
         if let Some(el) = report.get_str("elapsed") {
             self.mt_result.set("elapsed", JsonVal::Str(el.to_string()));
@@ -1700,6 +1810,20 @@ impl StationState {
             self.hot.mt_pass_complete = true;
             self.hot.mt_fail_complete = false;
             self.mt_result.set("status", JsonVal::Str("pass".to_string()));
+            let tot = self
+                .mt_result
+                .get_i64("tests_total")
+                .filter(|&t| t > 0)
+                .unwrap_or_else(|| crate::pxe::configured_mt_test_count(&self.mt_selection) as i64);
+            let done = self
+                .mt_result
+                .get_i64("tests_completed")
+                .filter(|&d| d > 0)
+                .unwrap_or(tot)
+                .max(tot);
+            self.mt_result.set("tests_total", JsonVal::Num(tot as f64));
+            self.mt_result.set("tests_completed", JsonVal::Num(done as f64));
+            self.mt_result.set("progress_pct", JsonVal::Num(100.0));
             for idx in 0..24 {
                 if self.dimms[idx].presence == "present"
                     && self.dimms[idx].enabled != "disabled"
@@ -1746,6 +1870,13 @@ impl StationState {
             self.boot_execution.set("waiting_reason", JsonVal::Str(reason.clone()));
             self.boot_execution.set("error", JsonVal::Str(reason));
             self.boot_execution.set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
+            self.log_debug(
+                "STAGE",
+                &format!(
+                    "latched failure stage={} boot_id={} started={} ended={}",
+                    stage, self.boot_id, self.run_started_unix_ms, self.run_ended_unix_ms
+                ),
+            );
         }
         has_err
     }
@@ -1763,8 +1894,11 @@ impl StationState {
         self.plan_paused = false;
         if had_block_or_fail {
             let now = now_ms();
+            self.log_debug("RESET", "confirm_dimm_replacement cleared blocked/failed run");
             self.hot.reset_for_new_boot(now);
             self.in_internal_warm_reset = false;
+            self.power_seq_in_progress = false;
+            self.power_seq_started_ms = 0;
             self.latest_mt_report_path.clear();
             self.run_started_unix_ms = 0;
             self.run_ended_unix_ms = 0;
@@ -1785,6 +1919,7 @@ impl StationState {
             self.active_amt_cpus.clear();
             self.mt_result = JsonVal::obj();
             self.mt_per_test_errs.clear();
+            self.mt_completed_test_ids.clear();
             self.async_script.clear();
             self.prompt_ready = false;
             self.prompt_kind.clear();
@@ -1870,6 +2005,11 @@ impl StationState {
             self.observe_clean_line(&line_bytes, tag_mask, now);
         }
 
+        if self.power_seq_in_progress {
+            self.cleaner.clear_halfline();
+            return;
+        }
+
         // Check partial half-line tail for RMT dots or live prompts without trailing newline
         let hl_opt = {
             let hl = self.cleaner.halfline_bytes();
@@ -1902,6 +2042,9 @@ impl StationState {
             return;
         }
         let trimmed_bytes = &line_bytes[s..e];
+        if self.power_seq_in_progress {
+            return;
+        }
         let ev = lib::re2c_parse_line(trimmed_bytes, tag_mask);
         if ev.fw_family == 1 || ev.fw_family == 2 {
             self.hot.fw_family = ev.fw_family;
@@ -1939,6 +2082,31 @@ impl StationState {
             self.amt_prefers_short_cmd = true;
         }
 
+        // Update MT completed test counter & accurate percentage from No-UI per-test execution summaries
+        if trimmed.contains("MtSupportRunAllTests - Test execution time:") {
+            if let Some(pos) = trimmed.find("(Test ") {
+                let tail = &trimmed[pos + "(Test ".len()..];
+                let digits: String = tail.chars().take_while(|c| c.is_ascii_digit()).collect();
+                if let Ok(tid) = digits.parse::<i32>() {
+                    if (0..=25).contains(&tid) {
+                        self.hot.mt_banner_seen = true;
+                        self.mt_completed_test_ids.insert(tid);
+                        let cfg_tot =
+                            crate::pxe::configured_mt_test_count(&self.mt_selection) as i64;
+                        let done = self.mt_completed_test_ids.len() as i64;
+                        let tot = cfg_tot.max(done).max(1);
+                        let pct = ((done * 100) / tot).clamp(0, 100);
+                        self.mt_result
+                            .set("tests_completed", JsonVal::Num(done as f64));
+                        self.mt_result.set("tests_total", JsonVal::Num(tot as f64));
+                        self.mt_result.set("progress_pct", JsonVal::Num(pct as f64));
+                        self.mt_result
+                            .set("observed_unix_ms", JsonVal::Str(now.to_string()));
+                    }
+                }
+            }
+        }
+
         // Capture expected MemTest86 report filename emitted before/during TFTP upload
         if let Some(pos) = trimmed.find("Saving test report to ") {
             let cand = trimmed[pos + "Saving test report to ".len()..]
@@ -2096,6 +2264,7 @@ impl StationState {
                 self.amt_fallback_attempted = false;
                 self.mt_result = JsonVal::obj();
                 self.mt_per_test_errs.clear();
+                self.mt_completed_test_ids.clear();
                 self.plan_configured.clear();
                 self.plan_done.clear();
                 self.plan_amt_started.clear();
@@ -2116,19 +2285,22 @@ impl StationState {
                     self.task_status.as_str(),
                     "failed" | "completed" | "interrupted"
                 );
+                let task_in_progress =
+                    self.is_run_active() && !self.has_any_failure_state() && !is_terminal;
                 // Stage 2 (`Current stage is 2`) emits `STL_LK_ICT_BANNER_HOVSEE / CXMT`
                 // inside the same boot right after Training/RMT/AMT (`started_unix_ms` must stay).
-                // Only clear for external restart after entering Stage 2+ or when already terminal/blocked.
-                if is_terminal
-                    || self.awaiting_dimm_replacement
-                    || self.hot.ict_stage2_complete
-                    || self.hot.uefi_complete
-                    || self.hot.mt_banner_seen
-                    || self.hot.mt_pass_complete
-                    || self.hot.mt_fail_complete
-                    || self.observed_stages.contains("uefi")
-                    || self.observed_stages.contains("mt")
-                    || self.observed_stages.contains("post")
+                // Only clear for external restart when NOT actively running a task or when already terminal/blocked.
+                if !task_in_progress
+                    && (is_terminal
+                        || self.awaiting_dimm_replacement
+                        || self.hot.ict_stage2_complete
+                        || self.hot.uefi_complete
+                        || self.hot.mt_banner_seen
+                        || self.hot.mt_pass_complete
+                        || self.hot.mt_fail_complete
+                        || self.observed_stages.contains("uefi")
+                        || self.observed_stages.contains("mt")
+                        || self.observed_stages.contains("post"))
                 {
                     self.clear_for_external_restart(now, "ict_banner_reboot", true);
                 }
@@ -2141,21 +2313,24 @@ impl StationState {
                 let cpu = if ev.cpu >= 0 { ev.cpu as i64 } else { 0 };
                 if stg == 1 {
                     let bp_state_now = self.boot_execution.get_str_or("state", "idle");
+                    let is_terminal = matches!(
+                        bp_state_now.as_str(),
+                        "blocked" | "failed" | "completed" | "stopped" | "interrupted"
+                    ) || matches!(
+                        self.task_status.as_str(),
+                        "failed" | "completed" | "interrupted"
+                    );
+                    let task_in_progress =
+                        self.is_run_active() && !self.has_any_failure_state() && !is_terminal;
                     if self.has_any_failure_state()
-                        || self.hot.training_complete
-                        || self.hot.rmt_complete
-                        || self.hot.amt_complete
-                        || self.hot.ict_stage2_complete
-                        || self.hot.uefi_complete
-                        || self.hot.mt_pass_complete
-                        || matches!(
-                            bp_state_now.as_str(),
-                            "blocked" | "failed" | "completed" | "stopped" | "interrupted"
-                        )
-                        || matches!(
-                            self.task_status.as_str(),
-                            "failed" | "completed" | "interrupted"
-                        )
+                        || is_terminal
+                        || (!task_in_progress
+                            && (self.hot.training_complete
+                                || self.hot.rmt_complete
+                                || self.hot.amt_complete
+                                || self.hot.ict_stage2_complete
+                                || self.hot.uefi_complete
+                                || self.hot.mt_pass_complete))
                     {
                         self.clear_for_external_restart(now, "uip_stage1_reboot", true);
                     }
@@ -2210,15 +2385,18 @@ impl StationState {
                         self.task_status.as_str(),
                         "failed" | "completed" | "interrupted"
                     );
+                    let task_in_progress =
+                        self.is_run_active() && !self.has_any_failure_state() && !is_terminal;
                     if self.has_any_failure_state()
                         || is_terminal
-                        || self.hot.amt_complete
-                        || self.hot.ict_stage2_complete
-                        || self.hot.uefi_complete
-                        || self.hot.mt_banner_seen
-                        || self.observed_stages.contains("amt")
-                        || self.observed_stages.contains("uefi")
-                        || self.observed_stages.contains("mt")
+                        || (!task_in_progress
+                            && (self.hot.amt_complete
+                                || self.hot.ict_stage2_complete
+                                || self.hot.uefi_complete
+                                || self.hot.mt_banner_seen
+                                || self.observed_stages.contains("amt")
+                                || self.observed_stages.contains("uefi")
+                                || self.observed_stages.contains("mt")))
                     {
                         self.clear_for_external_restart(now, "dram_inventory_reboot", true);
                     }
@@ -2530,16 +2708,21 @@ impl StationState {
                 if let Some(cpu) = target_cpu {
                     let entry = self.rmt_results.entry(cpu).or_insert(RmtCpuResult {
                         cpu,
-                        state: "completed".to_string(),
+                        state: "skipped".to_string(),
                         measurement_rows: 0,
                         min_dq_width: i32::MAX,
                         min_vref_width: i32::MAX,
                         execution_supported: true,
                         verdict_supported: false,
                     });
-                    entry.state = "completed".to_string();
                     entry.execution_supported = true;
-                    entry.verdict_supported = entry.measurement_rows > 0;
+                    if entry.measurement_rows > 0 {
+                        entry.state = "completed".to_string();
+                        entry.verdict_supported = true;
+                    } else {
+                        entry.state = "skipped".to_string();
+                        entry.verdict_supported = false;
+                    }
                 }
                 let present_cpus: Vec<i64> = (0..self.cpu_count as i64)
                     .filter(|c| {
@@ -2551,12 +2734,15 @@ impl StationState {
                     present_cpus.iter().all(|c| {
                         self.rmt_results
                             .get(c)
-                            .map(|r| r.state == "completed")
+                            .map(|r| matches!(r.state.as_str(), "completed" | "skipped"))
                             .unwrap_or(false)
                     })
                 } else {
                     !self.rmt_results.is_empty()
-                        && self.rmt_results.values().all(|r| r.state == "completed")
+                        && self
+                            .rmt_results
+                            .values()
+                            .all(|r| matches!(r.state.as_str(), "completed" | "skipped"))
                 };
                 self.prompt_ready = false;
                 self.hot.prompt_ready = false;
@@ -2564,9 +2750,16 @@ impl StationState {
                 if all_done && has_rmt_rows {
                     self.hot.rmt_complete = true;
                     self.advance_phase("rmt", "rmt_completed", now);
-                } else {
+                } else if has_rmt_rows || self.observed_stages.contains("rmt") {
                     self.advance_phase("rmt", "rmt_running", now);
                 }
+                self.log_debug(
+                    "STAGE",
+                    &format!(
+                        "RMT_STOP has_rmt_rows={} all_done={} rmt_complete={} line={}",
+                        has_rmt_rows, all_done, self.hot.rmt_complete, trimmed
+                    ),
+                );
                 *self.stage_step_counts.entry("rmt".to_string()).or_insert(0) += 1;
             }
             lib::STL_LK_AMT_BANNER => {
@@ -2798,15 +2991,47 @@ impl StationState {
                 self.prompt_ready = false;
                 self.hot.prompt_ready = false;
                 self.advance_phase("mt", "mt_running", now);
+                let cfg_tot = crate::pxe::configured_mt_test_count(&self.mt_selection) as i64;
+                if self.mt_result.get_i64("tests_total").is_none() {
+                    self.mt_result
+                        .set("tests_total", JsonVal::Num(cfg_tot as f64));
+                    self.mt_result.set("tests_completed", JsonVal::Num(0.0));
+                    self.mt_result.set("progress_pct", JsonVal::Num(0.0));
+                }
                 if ev.kind == lib::STL_LK_MT_PROGRESS {
-                    if ev.val0 >= 0 {
-                        self.mt_result.set("tests_completed", JsonVal::Num(ev.val0 as f64));
-                    }
-                    if ev.val1 > 0 {
-                        self.mt_result.set("tests_total", JsonVal::Num(ev.val1 as f64));
-                    }
-                    if ev.val2 >= 0 {
-                        self.mt_result.set("progress_pct", JsonVal::Num(ev.val2 as f64));
+                    // `Running test #N` emits val0=tid, val1=25 from re2c; translate to configured test count
+                    if trimmed.contains("Running test #") && ev.val1 == 25 {
+                        let done = (self.mt_completed_test_ids.len() as i64).min(cfg_tot);
+                        let tot = cfg_tot.max(done).max(1);
+                        let cur_tid = (ev.val0 as i64).max(0);
+                        let pct = if done > 0 {
+                            ((done * 100) / tot).clamp(0, 100)
+                        } else if tot > 1 {
+                            ((cur_tid * 100) / tot).clamp(0, 99)
+                        } else {
+                            0
+                        };
+                        self.mt_result
+                            .set("current_test_id", JsonVal::Num(cur_tid as f64));
+                        self.mt_result
+                            .set("tests_completed", JsonVal::Num(done as f64));
+                        self.mt_result
+                            .set("tests_total", JsonVal::Num(tot as f64));
+                        self.mt_result
+                            .set("progress_pct", JsonVal::Num(pct as f64));
+                    } else {
+                        if ev.val1 > 0 {
+                            if ev.val0 >= 0 {
+                                self.mt_result
+                                    .set("tests_completed", JsonVal::Num(ev.val0 as f64));
+                            }
+                            self.mt_result
+                                .set("tests_total", JsonVal::Num(ev.val1 as f64));
+                        }
+                        if ev.val2 >= 0 {
+                            self.mt_result
+                                .set("progress_pct", JsonVal::Num(ev.val2 as f64));
+                        }
                     }
                 }
                 if !self.hot.mt_pass_complete && !self.hot.mt_fail_complete {
@@ -2891,6 +3116,27 @@ impl StationState {
                     self.mark_present_channels_training_pass();
                     self.mt_result.set("status", JsonVal::Str("pass".to_string()));
                     self.mt_result.set("complete", JsonVal::Bool(true));
+                    let tot = self
+                        .mt_result
+                        .get_i64("tests_total")
+                        .filter(|&t| t > 0 && t != 25)
+                        .unwrap_or_else(|| {
+                            crate::pxe::configured_mt_test_count(&self.mt_selection) as i64
+                        });
+                    let done = (self.mt_completed_test_ids.len() as i64).max(tot);
+                    let final_tot = tot.max(done).max(1);
+                    self.mt_result
+                        .set("tests_total", JsonVal::Num(final_tot as f64));
+                    self.mt_result
+                        .set("tests_completed", JsonVal::Num(final_tot as f64));
+                    self.mt_result.set("progress_pct", JsonVal::Num(100.0));
+                    self.log_debug(
+                        "MT",
+                        &format!(
+                            "MT_PASS_COMPLETE tests={}/{} progress=100 run_started={} run_ended={} boot_id={}",
+                            final_tot, final_tot, self.run_started_unix_ms, self.run_ended_unix_ms, self.boot_id
+                        ),
+                    );
                     for idx in 0..24 {
                         if self.dimms[idx].presence == "present"
                             && self.dimms[idx].enabled != "disabled"
@@ -2957,28 +3203,32 @@ impl StationState {
             self.task_status.as_str(),
             "failed" | "completed" | "interrupted"
         );
-        if ev.kind == lib::STL_LK_ICT_ENTER_HINT
-            && (is_terminal
-                || self.awaiting_dimm_replacement
-                || self.hot.ict_stage2_complete
-                || self.hot.uefi_complete
-                || self.hot.mt_banner_seen
-                || self.hot.mt_pass_complete
-                || self.hot.mt_fail_complete
-                || self.observed_stages.contains("uefi")
-                || self.observed_stages.contains("mt")
-                || self.observed_stages.contains("post"))
-        {
-            self.clear_for_external_restart(now, "uip_enter_reboot", true);
-        } else if ev.kind == lib::STL_LK_ICT_PROMPT
-            && (self.hot.uefi_complete
-                || self.hot.mt_banner_seen
-                || self.hot.mt_pass_complete
-                || self.hot.mt_fail_complete
-                || self.observed_stages.contains("uefi")
-                || self.observed_stages.contains("mt"))
-        {
-            self.clear_for_external_restart(now, "uip_prompt_reboot", true);
+        let task_in_progress =
+            self.is_run_active() && !self.has_any_failure_state() && !is_terminal && !self.awaiting_dimm_replacement;
+        if !task_in_progress {
+            if ev.kind == lib::STL_LK_ICT_ENTER_HINT
+                && (is_terminal
+                    || self.awaiting_dimm_replacement
+                    || self.hot.ict_stage2_complete
+                    || self.hot.uefi_complete
+                    || self.hot.mt_banner_seen
+                    || self.hot.mt_pass_complete
+                    || self.hot.mt_fail_complete
+                    || self.observed_stages.contains("uefi")
+                    || self.observed_stages.contains("mt")
+                    || self.observed_stages.contains("post"))
+            {
+                self.clear_for_external_restart(now, "uip_enter_reboot", true);
+            } else if ev.kind == lib::STL_LK_ICT_PROMPT
+                && (self.hot.uefi_complete
+                    || self.hot.mt_banner_seen
+                    || self.hot.mt_pass_complete
+                    || self.hot.mt_fail_complete
+                    || self.observed_stages.contains("uefi")
+                    || self.observed_stages.contains("mt"))
+            {
+                self.clear_for_external_restart(now, "uip_prompt_reboot", true);
+            }
         }
         if self.hot.awaiting_reset_banner && self.bmc_enabled && !self.bmc_host.is_empty() {
             return;
@@ -3069,6 +3319,27 @@ impl StationState {
                         self.hot.mt_pass_complete = true;
                         self.mark_present_channels_training_pass();
                         self.mt_result.set("status", JsonVal::Str("pass".to_string()));
+                        let tot = self
+                            .mt_result
+                            .get_i64("tests_total")
+                            .filter(|&t| t > 0 && t != 25)
+                            .unwrap_or_else(|| {
+                                crate::pxe::configured_mt_test_count(&self.mt_selection) as i64
+                            });
+                        let done = (self.mt_completed_test_ids.len() as i64).max(tot);
+                        let final_tot = tot.max(done).max(1);
+                        self.mt_result
+                            .set("tests_total", JsonVal::Num(final_tot as f64));
+                        self.mt_result
+                            .set("tests_completed", JsonVal::Num(final_tot as f64));
+                        self.mt_result.set("progress_pct", JsonVal::Num(100.0));
+                        self.log_debug(
+                            "MT",
+                            &format!(
+                                "UEFI_RETURN_PASS tests={}/{} progress=100 run_started={} run_ended={} boot_id={}",
+                                final_tot, final_tot, self.run_started_unix_ms, self.run_ended_unix_ms, self.boot_id
+                            ),
+                        );
                         for idx in 0..24 {
                             if self.dimms[idx].presence == "present"
                                 && self.dimms[idx].enabled != "disabled"

+ 30 - 2
native/stl_accel/src/storage.rs

@@ -45,10 +45,39 @@ pub fn strip_private_keys_recursive(val: &JsonVal) -> JsonVal {
     }
 }
 
+pub fn append_debug_log_path(path: &Path, sid: &str, category: &str, msg: &str) {
+    if let Some(parent) = path.parent() {
+        let _ = fs::create_dir_all(parent);
+    }
+    if let Ok(meta) = fs::metadata(path) {
+        if meta.len() > 10 * 1024 * 1024 {
+            let bak = path.with_extension("log.1");
+            let _ = fs::rename(path, &bak);
+        }
+    }
+    let ts = now_ms();
+    let secs = (ts / 1000).max(0);
+    let ms = (ts % 1000).max(0);
+    let hh = (secs / 3600) % 24;
+    let mm = (secs / 60) % 60;
+    let ss = secs % 60;
+    let clean_msg = msg.replace('\r', "\\r").replace('\n', " | ");
+    let line = format!(
+        "[{} {:02}:{:02}:{:02}.{:03}][{}][{}] {}\n",
+        ts, hh, mm, ss, ms, sid, category, clean_msg
+    );
+    if let Ok(mut f) = fs::OpenOptions::new().create(true).append(true).open(path) {
+        let _ = f.write_all(line.as_bytes());
+    }
+}
+
 pub fn load_station_settings(data_dir: &Path, stations: &mut BTreeMap<String, StationState>) {
     let dir = data_dir.join("station-controls");
     let _ = fs::create_dir_all(&dir);
+    let dbg_dir = data_dir.join("debug");
+    let _ = fs::create_dir_all(&dbg_dir);
     for (sid, st) in stations.iter_mut() {
+        st.debug_log_path = Some(dbg_dir.join(format!("{}.log", sid)));
         let p = dir.join(format!("{}.json", sid));
         let Ok(txt) = fs::read_to_string(&p) else {
             continue;
@@ -338,8 +367,7 @@ pub fn archive_task_run(
     disk_summary.set("repeat_index", JsonVal::Num(repeat_index as f64));
     disk_summary.set("repeat_total", JsonVal::Num(repeat_total as f64));
     disk_summary.set("verdict", JsonVal::Str(verdict.to_string()));
-    disk_summary.set("started_unix_ms", JsonVal::Str(started_ms.to_string()));
-    disk_summary.set("ended_unix_ms", JsonVal::Str(ended_ms.to_string()));
+    crate::results::patch_timing_fields(&mut disk_summary, started_ms, ended_ms, ended_ms);
     disk_summary.set("bytes_logged", JsonVal::Num((raw_vec.len()) as f64));
     disk_summary.set("log_raw_path", JsonVal::Str(raw_path.to_string_lossy().to_string()));
     disk_summary.set("log_clean_path", JsonVal::Str(clean_path.to_string_lossy().to_string()));

+ 104 - 12
native/stl_accel/src/workflow.rs

@@ -317,6 +317,43 @@ pub fn tick_async_script(st: &mut StationState) {
 
     // Dispatch next step if any
     while st.tx_pacer.is_empty() && st.async_script.waiting_prompt_kind.is_empty() {
+        if let Some(peek_step) = st.async_script.steps.front() {
+            let tag = st.async_script.context_tag.as_str();
+            let wrong_context = if matches!(
+                tag,
+                "plan_uip1" | "plan_uip2" | "intent_uip" | "interactive_uip" | "interactive_continue_uip"
+            ) {
+                matches!(st.prompt_kind.as_str(), "amt" | "uefi" | "grub_menu" | "grub_cli")
+                    || (tag == "plan_uip1"
+                        && matches!(st.observed_phase.as_str(), "amt" | "uefi" | "mt"))
+            } else if matches!(
+                tag,
+                "plan_amt" | "intent_amt" | "interactive_amt" | "interactive_amt_cmd" | "interactive_start_amt"
+            ) {
+                matches!(st.prompt_kind.as_str(), "uefi" | "grub_menu" | "grub_cli")
+                    || (st.prompt_kind == "uip" && st.prompt_uip_stage.unwrap_or(1) > 1)
+                    || matches!(st.observed_phase.as_str(), "uefi" | "mt")
+            } else if matches!(
+                tag,
+                "plan_mt" | "intent_mt" | "probe_mt_efi" | "interactive_start_mt" | "interactive_uefi_ls"
+            ) {
+                matches!(st.prompt_kind.as_str(), "uip" | "amt")
+            } else {
+                false
+            };
+            if wrong_context {
+                let abort_msg = format!(
+                    "拒绝跨阶段注入串口命令 (tag={}, phase={}, prompt_kind={}, pending='{}')",
+                    tag, st.observed_phase, st.prompt_kind, peek_step.line
+                );
+                st.log_debug("TX_ABORT", &abort_msg);
+                if let Some(tx) = st.async_script.completion_tx.take() {
+                    let _ = tx.send(Err(abort_msg));
+                }
+                st.async_script.clear();
+                return;
+            }
+        }
         let Some(step) = st.async_script.steps.pop_front() else {
             finish_async_script(st, now);
             return;
@@ -593,13 +630,22 @@ pub fn control_boot_plan_impl(
             let mut waiting_msg = "等待实际控制台阶段提示符".to_string();
             if action == "restart" {
                 if st.bmc_enabled && !st.bmc_host.is_empty() {
-                    // Dispatch non-blocking BMC power action to dedicated IPMI worker!
+                    // Queue verified BMC Off -> On power sequence; dispatcher enables gate when real HW probes are active
                     st.pending_bmc_power_action = Some("smart_restart".to_string());
-                    st.server_power = "on".to_string();
+                    st.log_debug(
+                        "POWER",
+                        &format!(
+                            "QUEUE_SMART_RESTART host={} prev_power={} boot_seq={}",
+                            st.bmc_host, st.server_power, st.boot_seq + 1
+                        ),
+                    );
                     waiting_msg = format!(
-                        "已向 BMC ({}) 异步下发主板开机/复位重启指令,等待新 BIOS 启动与 ICT 提示符",
+                        "正在执行 BMC ({}) 先关机再开机电源序列,确认上电后等待 BIOS 启动与 ICT 提示符",
                         st.bmc_host
                     );
+                } else {
+                    st.power_seq_in_progress = false;
+                    st.power_seq_started_ms = 0;
                 }
                 st.boot_seq += 1;
                 st.hot.boot_seq = st.boot_seq;
@@ -608,11 +654,23 @@ pub fn control_boot_plan_impl(
                 st.hot.reset_for_new_boot(now);
                 st.hot.awaiting_reset_banner = true;
                 st.in_internal_warm_reset = false;
-                if !preserve_batch_timer || st.run_started_unix_ms <= 0 {
-                    st.run_started_unix_ms = now;
+                if !preserve_batch_timer {
+                    st.start_run_timing(now, "control_boot_plan:restart");
+                } else if st.run_started_unix_ms <= 0 {
+                    st.start_run_timing(now, "control_boot_plan:restart_batch_init");
+                } else {
+                    st.run_ended_unix_ms = 0;
+                    st.log_debug(
+                        "TIMER",
+                        &format!(
+                            "CONTINUE_BATCH action=restart started_unix_ms={} boot_id={}",
+                            st.run_started_unix_ms, st.boot_id
+                        ),
+                    );
                 }
-                st.run_ended_unix_ms = 0;
                 st.mt_started_unix_ms = 0;
+                st.mt_per_test_errs.clear();
+                st.mt_completed_test_ids.clear();
                 st.mt_report_sync_pending = false;
                 st.mt_report_fetched_for_boot = false;
                 st.mt_waiting_report_until_ms = 0;
@@ -642,12 +700,20 @@ pub fn control_boot_plan_impl(
                 st.last_err_stage.clear();
                 st.reset_dimms_for_new_boot();
             } else {
-                if st.run_started_unix_ms <= 0
-                    || (!preserve_batch_timer && st.run_ended_unix_ms > 0)
-                {
-                    st.run_started_unix_ms = now;
+                if !preserve_batch_timer {
+                    st.start_run_timing(now, "control_boot_plan:start");
+                } else if st.run_started_unix_ms <= 0 {
+                    st.start_run_timing(now, "control_boot_plan:start_batch_init");
+                } else {
+                    st.run_ended_unix_ms = 0;
+                    st.log_debug(
+                        "TIMER",
+                        &format!(
+                            "CONTINUE_BATCH action=start started_unix_ms={} boot_id={}",
+                            st.run_started_unix_ms, st.boot_id
+                        ),
+                    );
                 }
-                st.run_ended_unix_ms = 0;
                 st.diag_session_id = format!("D-{}-{}-{}", st.station_id, st.boot_seq.max(1), now);
             }
             st.awaiting_dimm_replacement = false;
@@ -714,6 +780,8 @@ pub fn control_boot_plan_impl(
             Ok(st.boot_execution.clone())
         }
         "stop" => {
+            st.power_seq_in_progress = false;
+            st.power_seq_started_ms = 0;
             st.plan_paused = false;
             st.single_run_active = false;
             st.freeze_run_timing(now);
@@ -1007,6 +1075,25 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
     if st.awaiting_dimm_replacement || st.plan_paused {
         return;
     }
+    if st.power_seq_in_progress {
+        let now = now_ms();
+        if now.saturating_sub(st.power_seq_started_ms) > 95_000 {
+            st.power_seq_in_progress = false;
+            st.hot.awaiting_reset_banner = false;
+            let err_msg = "BMC 先关机再开机电源序列超时 (>95s)".to_string();
+            st.log_debug("POWER", &format!("SEQUENCE_TIMEOUT boot_id={}", st.boot_id));
+            st.task_status = "failed".to_string();
+            st.freeze_run_timing(now);
+            st.boot_execution
+                .set("state", JsonVal::Str("failed".to_string()));
+            st.boot_execution.set("error", JsonVal::Str(err_msg.clone()));
+            st.boot_execution
+                .set("waiting_reason", JsonVal::Str(err_msg));
+            st.boot_execution
+                .set("updated_unix_ms", JsonVal::Num(now as f64));
+        }
+        return;
+    }
     if st.hot.awaiting_reset_banner && st.bmc_enabled && !st.bmc_host.is_empty() {
         return;
     }
@@ -2140,6 +2227,11 @@ pub fn step_task_batch(
             } else {
                 now
             };
+            let ended_ms = if st.run_ended_unix_ms > 0 {
+                st.run_ended_unix_ms
+            } else {
+                now
+            };
             let prof_clone = st.single_run_profile.clone();
             let (_, _, summary_obj) = archive_task_run(
                 data_dir,
@@ -2152,7 +2244,7 @@ pub fn step_task_batch(
                 1,
                 verdict,
                 started_ms,
-                now,
+                ended_ms,
                 &prof_clone,
             );
             st.task_history.push(summary_obj.clone());