Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions crates/mesh-llm-events/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,7 @@ pub enum OutputLevel {
Info,
Warn,
Error,
Fatal,
}

impl OutputLevel {
Expand All @@ -373,6 +374,7 @@ impl OutputLevel {
OutputLevel::Info => "info",
OutputLevel::Warn => "warn",
OutputLevel::Error => "error",
OutputLevel::Fatal => "fatal",
}
}
}
Expand Down Expand Up @@ -559,6 +561,10 @@ pub enum OutputEvent {
message: String,
context: Option<String>,
},
Fatal {
message: String,
context: Option<String>,
},
ShutdownRequested {
signal: &'static str,
},
Expand Down Expand Up @@ -611,6 +617,7 @@ impl OutputEvent {
OutputEvent::RequestRouted { .. } => "request_routed",
OutputEvent::Warning { .. } => "warning",
OutputEvent::Error { .. } => "error",
OutputEvent::Fatal { .. } => "fatal",
OutputEvent::ShutdownRequested { signal } => signal,
OutputEvent::Shutdown { .. } => "shutdown",
OutputEvent::LlamaNativeLog { category, .. } => category,
Expand All @@ -625,6 +632,7 @@ impl OutputEvent {
OutputEvent::LlamaNativeLog { .. } => OutputLevel::Debug,
OutputEvent::Warning { .. } => OutputLevel::Warn,
OutputEvent::Error { .. } => OutputLevel::Error,
OutputEvent::Fatal { .. } => OutputLevel::Fatal,
_ => OutputLevel::Info,
}
}
Expand Down Expand Up @@ -780,6 +788,7 @@ impl OutputEvent {
}
OutputEvent::Warning { message, .. } => message.clone(),
OutputEvent::Error { message, .. } => message.clone(),
OutputEvent::Fatal { message, .. } => message.clone(),
OutputEvent::ShutdownRequested { signal } => format!("shutdown requested ({signal})"),
OutputEvent::Shutdown { reason } => reason
.clone()
Expand Down
115 changes: 101 additions & 14 deletions crates/mesh-llm-host-runtime/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,26 +286,85 @@ impl MeshTracingStderrWriter {
}

routing.set(true);
let event = match self.level {
tracing::Level::ERROR => OutputEvent::Error {
message: message.clone(),
context: Some("stderr".to_string()),
},
tracing::Level::WARN => OutputEvent::Warning {
message: message.clone(),
context: Some("stderr".to_string()),
},
_ => OutputEvent::Info {
message: message.clone(),
context: Some("stderr".to_string()),
},
};
let dashboard_message = strip_ansi_escape_sequences(&message);
let event = self.dashboard_event_for_message(&dashboard_message);
let result =
mesh_llm_events::emit_event(event).or_else(|_| write_stderr_line(&message));
routing.set(false);
result
})
}

fn dashboard_event_for_message(&self, message: &str) -> OutputEvent {
let (message, context) = normalize_tracing_message(&self.target, message);
match self.level {
tracing::Level::ERROR => OutputEvent::Error { message, context },
tracing::Level::WARN => OutputEvent::Warning { message, context },
_ => OutputEvent::Info { message, context },
}
}
}

fn normalize_tracing_message(target: &str, message: &str) -> (String, Option<String>) {
let message = message.trim().to_string();
if target.starts_with("noq_proto") {
return (
normalize_noq_proto_message(target, &message),
Some("transport".to_string()),
);
}

(message, Some("stderr".to_string()))
}

fn normalize_noq_proto_message(target: &str, message: &str) -> String {
let without_prefix = message
.find(target)
.and_then(|target_index| {
message[target_index + target.len()..]
.find(':')
.map(|colon_index| message[target_index + target.len() + colon_index + 1..].trim())
})
.unwrap_or(message)
.trim();
format_noq_proto_fields(without_prefix)
}

fn format_noq_proto_fields(message: &str) -> String {
let Some(rest) = message.strip_prefix("err=") else {
return message.to_string();
};
let Some((err, detail)) = rest.split_once(' ') else {
return message.to_string();
};
if detail.trim().is_empty() {
message.to_string()
} else {
format!("{} (err={err})", detail.trim())
}
}

fn strip_ansi_escape_sequences(input: &str) -> String {
let mut output = String::with_capacity(input.len());
let mut chars = input.chars().peekable();

while let Some(ch) = chars.next() {
if ch != '\u{1b}' {
output.push(ch);
continue;
}

if matches!(chars.peek(), Some('[')) {
chars.next();
for code in chars.by_ref() {
if ('@'..='~').contains(&code) {
break;
}
}
}
}

output
}

impl Write for MeshTracingStderrWriter {
Expand Down Expand Up @@ -9057,6 +9116,34 @@ mod tests {
}
}

#[test]
fn noq_proto_tracing_messages_use_transport_context() {
let message = "2026-06-11T03:49:18.033043Z WARN noq_proto::connection: err=LastOpenPath failed closing path";

let (message, context) = normalize_tracing_message("noq_proto::connection", message);

assert_eq!(message, "failed closing path (err=LastOpenPath)");
assert_eq!(context.as_deref(), Some("transport"));
}

#[test]
fn routed_tracing_messages_strip_ansi_sequences() {
let formatted = "\u{1b}[2m2026-06-11T03:49:18.033043Z\u{1b}[0m \u{1b}[33m WARN\u{1b}[0m";

assert_eq!(
strip_ansi_escape_sequences(formatted),
"2026-06-11T03:49:18.033043Z WARN"
);
}

#[test]
fn non_proto_tracing_messages_keep_stderr_context() {
let (message, context) = normalize_tracing_message("mesh_llm::runtime", "runtime warning");

assert_eq!(message, "runtime warning");
assert_eq!(context.as_deref(), Some("stderr"));
}

fn reconciliation_target_with_required_bytes(
required_bytes: Option<u64>,
) -> api::status::ModelTargetPayload {
Expand Down
84 changes: 84 additions & 0 deletions crates/mesh-llm-tui/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,90 @@
#![forbid(unsafe_code)]

use std::{panic::PanicHookInfo, sync::Once};

pub mod output;
pub mod terminal_progress;

pub use output::*;

static PANIC_HOOK: Once = Once::new();

pub fn install_terminal_panic_hook() {
PANIC_HOOK.call_once(|| {
let previous_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
force_restore_tui_after_panic();
let _ = emit_fatal_panic(panic_message(info), panic_context(info));
previous_hook(info);
}));
});
}

fn panic_message(info: &PanicHookInfo<'_>) -> String {
if let Some(message) = info.payload().downcast_ref::<&str>() {
(*message).to_string()
} else if let Some(message) = info.payload().downcast_ref::<String>() {
message.clone()
} else {
"panic occurred".to_string()
}
}

fn panic_context(info: &PanicHookInfo<'_>) -> Option<String> {
info.location()
.map(|location| format!("panic at {}:{}", location.file(), location.line()))
}

#[cfg(test)]
mod tests {
use super::install_terminal_panic_hook;
use std::{
panic::{self, AssertUnwindSafe},
sync::{
Arc, Mutex,
atomic::{AtomicUsize, Ordering},
},
};

#[test]
fn install_terminal_panic_hook_chains_previous_hook() {
let previous_hook_calls = Arc::new(AtomicUsize::new(0));
let previous_payload = Arc::new(Mutex::new(None));
let previous_location = Arc::new(Mutex::new(None));

let hook_calls = Arc::clone(&previous_hook_calls);
let hook_payload = Arc::clone(&previous_payload);
let hook_location = Arc::clone(&previous_location);
panic::set_hook(Box::new(move |info| {
hook_calls.fetch_add(1, Ordering::SeqCst);
let payload = info
.payload()
.downcast_ref::<&str>()
.map(|message| (*message).to_string())
.or_else(|| info.payload().downcast_ref::<String>().cloned());
*hook_payload.lock().expect("payload lock") = payload;
*hook_location.lock().expect("location lock") =
info.location().map(|location| location.file().to_string());
}));

install_terminal_panic_hook();

let result = panic::catch_unwind(AssertUnwindSafe(|| {
panic!("panic hook smoke test");
}));

assert!(result.is_err());
assert_eq!(previous_hook_calls.load(Ordering::SeqCst), 1);
assert_eq!(
previous_payload.lock().expect("payload lock").as_deref(),
Some("panic hook smoke test")
);
assert_eq!(
previous_location
.lock()
.expect("location lock")
.as_deref(),
Some(file!())
);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
Loading
Loading