Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Closed stderr pipes no longer crash the app, CLI or MCP server (#10111) (#10126)

semmelrindea6e7126bf111
diff --git a/apps/solidcraft-cli/src/alias.rs b/apps/solidcraft-cli/src/alias.rs
index 7030880d37..34d8256cb6 100644
--- a/apps/solidcraft-cli/src/alias.rs
+++ b/apps/solidcraft-cli/src/alias.rs
@@ -11,7 +11,7 @@ use std::process::{Command, ExitCode};
const TARGET: &str = "solidcraft-cli";
fn main() -> ExitCode {
- eprintln!("solvecraft-cli is deprecated and will be removed in a later release: use solidcraft-cli");
+ solidcraft_engine::note!("solvecraft-cli is deprecated and will be removed in a later release: use solidcraft-cli");
let sibling = std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(|dir| dir.join(format!("{TARGET}{}", std::env::consts::EXE_SUFFIX))))
@@ -23,7 +23,7 @@ fn main() -> ExitCode {
None => ExitCode::FAILURE,
},
Err(e) => {
- eprintln!("solvecraft-cli: could not run {}: {e}", program.to_string_lossy());
+ solidcraft_engine::note!("solvecraft-cli: could not run {}: {e}", program.to_string_lossy());
ExitCode::FAILURE
}
}
diff --git a/apps/solidcraft-cli/src/fuzz.rs b/apps/solidcraft-cli/src/fuzz.rs
index 7b1fa61a37..52ff343ff2 100644
--- a/apps/solidcraft-cli/src/fuzz.rs
+++ b/apps/solidcraft-cli/src/fuzz.rs
@@ -33,8 +33,8 @@ pub fn one(args: &[String]) -> Result<(), String> {
std::panic::set_hook(Box::new(|_| {
PANICS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}));
- eprintln!("design {seed}");
- let run = fuzz::run_with(seed, steps, &mut |st| eprintln!("step {}", serde_json::to_string(st).unwrap_or_default()));
+ solidcraft_engine::note!("design {seed}");
+ let run = fuzz::run_with(seed, steps, &mut |st| solidcraft_engine::note!("step {}", serde_json::to_string(st).unwrap_or_default()));
let mut design = json!({
"outcome": run.outcome,
"steps": run.steps.iter().map(|s| s.kind).collect::<Vec<_>>(),
@@ -45,13 +45,13 @@ pub fn one(args: &[String]) -> Result<(), String> {
if run.outcome.is_bug() {
design["script"] = run.script();
if minimise {
- eprintln!("minimise");
+ solidcraft_engine::note!("minimise");
let m = fuzz::minimise(&run);
design["minimal"] = json!({"outcome": m.outcome, "steps": m.steps.iter().map(|s| s.kind).collect::<Vec<_>>(), "script": m.script()});
}
}
let (a, b) = solidcraft_engine::fuzz::boolean_shapes(seed);
- eprintln!("boolean {seed} {} {}", serde_json::to_string(&a).unwrap_or_default(), serde_json::to_string(&b).unwrap_or_default());
+ solidcraft_engine::note!("boolean {seed} {} {}", serde_json::to_string(&a).unwrap_or_default(), serde_json::to_string(&b).unwrap_or_default());
let b = boolean_case(seed);
let bp = PANICS.swap(0, std::sync::atomic::Ordering::SeqCst);
println!("{}", json!({"seed": seed, "design": design, "boolean": b, "boolean_panics": bp}));
@@ -162,11 +162,14 @@ fn record(v: &Value, out_dir: Option<&str>) {
let d = &v["design"];
let bug = matches!(d["outcome"]["kind"].as_str(), Some("failed" | "panic" | "invalid" | "volume"));
if bug || v.get("timeout").is_some() || v.get("crash").is_some() {
- eprintln!("seed {seed}: {}", if bug { format!("{} {}", d["outcome"]["kind"], d["outcome"]["detail"]) } else { format!("{v}") });
+ solidcraft_engine::note!(
+ "seed {seed}: {}",
+ if bug { format!("{} {}", d["outcome"]["kind"], d["outcome"]["detail"]) } else { format!("{v}") }
+ );
}
let bk = v["boolean"]["outcome"].as_str().unwrap_or("ok");
if bk != "ok" {
- eprintln!("seed {seed}: boolean {bk} {}", v["boolean"]["detail"]);
+ solidcraft_engine::note!("seed {seed}: boolean {bk} {}", v["boolean"]["detail"]);
}
if let Some(dir) = out_dir {
use std::io::Write;
diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs
index de03f741d7..fa62ab6928 100644
--- a/apps/solidcraft-cli/src/main.rs
+++ b/apps/solidcraft-cli/src/main.rs
@@ -154,7 +154,7 @@ fn main() -> ExitCode {
}
};
if let Err(e) = max_file_size(&mut args) {
- eprintln!("error: {e}");
+ solidcraft_engine::note!("error: {e}");
return ExitCode::FAILURE;
}
let r = match args.first().map(String::as_str) {
@@ -235,7 +235,7 @@ fn main() -> ExitCode {
match r {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
- eprintln!("error: {e}");
+ solidcraft_engine::note!("error: {e}");
ExitCode::FAILURE
}
}
@@ -351,7 +351,7 @@ fn run_script_warning(s: &mut Session, path: &str, script: &Value) -> Result<Vec
/// Step `step`'s `param_warnings` on stderr, one per line, named after the script at `path`.
fn print_param_warnings(path: &str, step: usize, r: &Value) {
for w in r.get("param_warnings").and_then(Value::as_array).into_iter().flatten() {
- eprintln!("{path}: step {}: {}", step + 1, w.as_str().unwrap_or_default());
+ solidcraft_engine::note!("{path}: step {}: {}", step + 1, w.as_str().unwrap_or_default());
}
}
@@ -598,10 +598,10 @@ fn cmd_script(args: &[String]) -> Result<(), String> {
let out = flag(args, "--out");
let r = s.execute("timeline.export_script", &json!({"path": out})).map_err(|e| e.to_string())?;
for what in r["omitted"].as_array().into_iter().flatten().filter_map(Value::as_str) {
- eprintln!("note: the script leaves out {what}");
+ solidcraft_engine::note!("note: the script leaves out {what}");
}
match out {
- Some(out) => eprintln!("{out}: {} steps", r["steps"]),
+ Some(out) => solidcraft_engine::note!("{out}: {} steps", r["steps"]),
None => println!("{}", pretty(&r["script"])),
}
Ok(())
@@ -632,7 +632,7 @@ fn cmd_gpu(args: &[String]) -> Result<(), String> {
);
match s.lands_on {
Some(solidcraft_gpu::select::Landing::Cpu) => {
- eprintln!("warning: {}", solidcraft_engine::capture::CPU_WARNING);
+ solidcraft_engine::note!("warning: {}", solidcraft_engine::capture::CPU_WARNING);
Ok(())
}
Some(_) => Ok(()),
@@ -709,7 +709,7 @@ fn cmd_snapshot(args: &[String]) -> Result<(), String> {
std::fs::write(out, &png.bytes).map_err(|e| format!("{out}: {e}"))?;
let mut reply = json!({"path": out, "width": w, "height": h, "bytes": png.bytes.len(), "renderer": png.renderer});
if let Some(w) = solidcraft_engine::capture::warning(png.renderer) {
- eprintln!("warning: {w}");
+ solidcraft_engine::note!("warning: {w}");
reply["warning"] = json!(w);
}
println!("{}", pretty(&reply));
@@ -796,7 +796,7 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> {
.then(|| solidcraft_mcp::agent_scope(flags(args, "--allow-path").into_iter().map(std::path::PathBuf::from)));
if let Some(s) = &scope {
let roots: Vec<String> = s.roots().iter().map(|r| r.display().to_string()).collect();
- eprintln!(
+ solidcraft_engine::note!(
"solidcraft mcp: files limited to {} and the folders of designs opened or saved here (--allow-path DIR adds one, --allow-any-path lifts the limit)",
roots.join(", ")
);
@@ -804,7 +804,7 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> {
.and_then(|p| std::path::Path::new(p).parent())
.map(|d| if d.as_os_str().is_empty() { std::path::Path::new(".") } else { d });
if let Some(why) = design_dir.and_then(solidcraft_engine::io::vfs::design_folder_refusal) {
- eprintln!("solidcraft mcp: the design's folder is left out because {why}; add it with --allow-path if you mean it");
+ solidcraft_engine::note!("solidcraft mcp: the design's folder is left out because {why}; add it with --allow-path if you mean it");
}
}
// How calls that break a command's parameter contract are treated, headless or bridged.
@@ -818,7 +818,7 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> {
// Serve without the app too: the tools connect once it runs, and say it isn't until then.
let mut remote = solidcraft_mcp::Remote::new(addr, flag(args, "--token")).with_param_check(param_check);
if let Err(e) = remote.try_connect() {
- eprintln!(
+ solidcraft_engine::note!(
"solidcraft mcp: no SolidCraft app at {addr} yet ({e}); start it with `solidcraft --control {port}` \
(or SOLIDCRAFT_CONTROL_PORT={port}), tool calls connect once it runs"
);
@@ -835,7 +835,7 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> {
(None, None) => {
let auto = !args.iter().any(|a| a == "--headless");
if auto && let Some(port) = discover_app() {
- eprintln!("solidcraft mcp: bridged to the running app at 127.0.0.1:{port} (--headless starts a session of its own)");
+ solidcraft_engine::note!("solidcraft mcp: bridged to the running app at 127.0.0.1:{port} (--headless starts a session of its own)");
let remote = solidcraft_mcp::Remote::new(&format!("127.0.0.1:{port}"), flag(args, "--token")).with_param_check(param_check);
return serve_mcp(Box::new(remote), scope);
}
diff --git a/apps/solidcraft-cli/tests/help_output.rs b/apps/solidcraft-cli/tests/help_output.rs
index cef9983fe4..4dd5cd7358 100644
--- a/apps/solidcraft-cli/tests/help_output.rs
+++ b/apps/solidcraft-cli/tests/help_output.rs
@@ -188,3 +188,26 @@ fn max_file_size_raises_the_limit_and_refuses_bad_sizes() {
assert!(!output.status.success() && !stderr.contains("too large"), "{stderr}");
let _ = std::fs::remove_dir_all(&dir);
}
+
+/// #10111: a line for a stderr whose reader has gone (the pipe closed before it, as an agent may
+/// leave the MCP server's, and the app that one starts) is dropped, and the command ends as it
+/// would with stderr open: here a script that isn't there fails with 1, where `eprintln!`
+/// panicked with "failed printing to stderr" (101).
+#[test]
+fn a_closed_stderr_does_not_stop_the_cli() {
+ for _ in 0..5 {
+ let mut child = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli"))
+ .args(["run", "no-such-script.json"])
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped())
+ .spawn()
+ .unwrap();
+ drop(child.stderr.take());
+ assert_eq!(child.wait().unwrap().code(), Some(1));
+ }
+ // The old name's alias writes its deprecation notice first: an agent still configured with
+ // `solvecraft-cli mcp` must get the server, not that panic.
+ let mut child = Command::new(env!("CARGO_BIN_EXE_solvecraft-cli")).arg("--help").stdout(Stdio::null()).stderr(Stdio::piped()).spawn().unwrap();
+ drop(child.stderr.take());
+ assert_eq!(child.wait().unwrap().code(), Some(0));
+}
diff --git a/apps/solidcraft/src/control_server.rs b/apps/solidcraft/src/control_server.rs
index 996d7c54a9..01b1c2127a 100644
--- a/apps/solidcraft/src/control_server.rs
+++ b/apps/solidcraft/src/control_server.rs
@@ -68,7 +68,9 @@ pub fn start(listen_on: control_auth::Listen, ctx: egui::Context) -> Receiver<Co
Ok(l) => {
if let Some(port) = listen_on_listener(l, token.clone(), tx, ctx, false) {
if matches!(listen_on, control_auth::Listen::Default) {
- eprintln!("solidcraft: control channel on the default port 127.0.0.1:{port} (Preferences > Assistant turns it off)");
+ solidcraft_engine::note!(
+ "solidcraft: control channel on the default port 127.0.0.1:{port} (Preferences > Assistant turns it off)"
+ );
}
// The discovery file: where `solidcraft-cli mcp` finds this app with no arguments.
match control_auth::write_current_port(port) {
@@ -77,14 +79,14 @@ pub fn start(listen_on: control_auth::Listen, ctx: egui::Context) -> Receiver<Co
*p = Some((port, token));
}
}
- Err(e) => eprintln!("solidcraft: could not write the control discovery file ({e})"),
+ Err(e) => solidcraft_engine::note!("solidcraft: could not write the control discovery file ({e})"),
}
}
}
- Err(e) => eprintln!("solidcraft: control server failed to bind 127.0.0.1: {e}"),
+ Err(e) => solidcraft_engine::note!("solidcraft: control server failed to bind 127.0.0.1: {e}"),
}
}
- None => eprintln!("solidcraft: control server not started: no random token available"),
+ None => solidcraft_engine::note!("solidcraft: control server not started: no random token available"),
}
rx
}
@@ -95,13 +97,13 @@ pub fn start(listen_on: control_auth::Listen, ctx: egui::Context) -> Receiver<Co
/// requests go to `tx`, where the chat's gate reads them; one may wait long for the user's Allow.
pub fn listen_agent(tx: Sender<ControlRequest>, ctx: egui::Context) -> Option<u16> {
let Some(token) = new_token() else {
- eprintln!("solidcraft: agent chat endpoint not started: no random token available");
+ solidcraft_engine::note!("solidcraft: agent chat endpoint not started: no random token available");
return None;
};
let listener = match TcpListener::bind(("127.0.0.1", 0)) {
Ok(l) => l,
Err(e) => {
- eprintln!("solidcraft: control server failed to bind 127.0.0.1: {e}");
+ solidcraft_engine::note!("solidcraft: control server failed to bind 127.0.0.1: {e}");
return None;
}
};
@@ -115,19 +117,21 @@ fn listen_on_listener(listener: TcpListener, token: String, tx: Sender<ControlRe
match control_auth::token_path(port) {
Some(path) => match control_auth::write_token_file(&path, &token) {
Ok(()) => {
- eprintln!("solidcraft: control server listening on 127.0.0.1:{port} (token in {})", path.display());
+ solidcraft_engine::note!("solidcraft: control server listening on 127.0.0.1:{port} (token in {})", path.display());
if let Ok(mut files) = TOKEN_FILES.lock() {
files.push((path, token.clone()));
}
}
- Err(e) => eprintln!(
+ Err(e) => solidcraft_engine::note!(
"solidcraft: control server listening on 127.0.0.1:{port}, but its token file {} could not be written ({e}); \
clients need SOLIDCRAFT_CONTROL_TOKEN",
path.display()
),
},
None => {
- eprintln!("solidcraft: control server listening on 127.0.0.1:{port}; no data folder for its token, clients need SOLIDCRAFT_CONTROL_TOKEN")
+ solidcraft_engine::note!(
+ "solidcraft: control server listening on 127.0.0.1:{port}; no data folder for its token, clients need SOLIDCRAFT_CONTROL_TOKEN"
+ )
}
}
let token = std::sync::Arc::new(token);
diff --git a/apps/solidcraft/src/device_lost.rs b/apps/solidcraft/src/device_lost.rs
index 2f598c69c1..01c4f6c638 100644
--- a/apps/solidcraft/src/device_lost.rs
+++ b/apps/solidcraft/src/device_lost.rs
@@ -112,7 +112,7 @@ pub fn restart(software: bool, lost_at: u64, reason: &str) {
pub fn end() -> ! {
let watchdog = std::thread::Builder::new().name("solidcraft-exit".into()).spawn(|| {
std::thread::sleep(END_GRACE);
- eprintln!("SolidCraft graphics: still closing after the device was lost; aborting");
+ solidcraft_engine::note!("SolidCraft graphics: still closing after the device was lost; aborting");
std::process::abort();
});
if let Err(e) = watchdog {
diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs
index 6a01cb998a..5ad5b85a06 100644
--- a/apps/solidcraft/src/main.rs
+++ b/apps/solidcraft/src/main.rs
@@ -79,7 +79,7 @@ fn mark(step: &str) {
static START: std::sync::OnceLock<(std::time::Instant, bool)> = std::sync::OnceLock::new();
let (start, on) = START.get_or_init(|| (std::time::Instant::now(), solidcraft_engine::geom::env::var_os("PROFILE_STARTUP").is_some()));
if *on {
- eprintln!("startup {:>6.0} ms {step}", start.elapsed().as_secs_f64() * 1000.0);
+ solidcraft_engine::note!("startup {:>6.0} ms {step}", start.elapsed().as_secs_f64() * 1000.0);
}
}
@@ -368,7 +368,7 @@ impl App {
let Some(gpu) = self.gpu.as_mut().filter(|g| g.lost_at.is_none() && g.lost.is_lost()) else { return };
let reason = gpu.lost.reason().unwrap_or_default();
log::error!("graphics: the device was lost ({reason}); closing to start again");
- eprintln!("SolidCraft graphics: the device was lost ({reason}); starting again");
+ solidcraft_engine::note!("SolidCraft graphics: the device was lost ({reason}); starting again");
solidcraft_engine::crash::phase(&format!("graphics device lost: {reason}"));
gpu.lost_at = Some(device_lost::now_secs());
gpu.reason = reason;
@@ -993,7 +993,7 @@ fn main() -> eframe::Result {
if let Some(value) = max_file_size {
let applied = startup::max_file_size(value.as_deref()).and_then(|bytes| solidcraft_engine::io::limits::set_override(Some(bytes)));
if let Err(error) = applied {
- eprintln!("SolidCraft: {error}");
+ solidcraft_engine::note!("SolidCraft: {error}");
return Err(eframe::Error::AppCreation(std::io::Error::other(error).into()));
}
}
@@ -1025,7 +1025,7 @@ fn main() -> eframe::Result {
let fallback_note = std::env::var(startup::FALLBACK_NOTE_ENV).ok().map(|s| s.chars().take(4096).collect::<String>());
if let Some(note) = &fallback_note {
log::warn!("{note}");
- eprintln!("SolidCraft: {note}");
+ solidcraft_engine::note!("SolidCraft: {note}");
notes.push(note.clone());
}
let saved_samples = if safe_mode { None } else { msaa() };
@@ -1138,13 +1138,13 @@ fn main() -> eframe::Result {
// Windows: the taskbar button shows the mark even when slow first frames keep the
// taskbar waiting for the window's icon.
if !native_frame::set_class_icon(cc) {
- eprintln!("SolidCraft window: no class icon; the taskbar may show a generic one");
+ solidcraft_engine::note!("SolidCraft window: no class icon; the taskbar may show a generic one");
}
// The OS hit test offers the resize border, at the window's DPI, from the first
// message (#1381).
app.native_resize_border = custom_titlebar && native_frame::install(cc);
if custom_titlebar && !app.native_resize_border {
- eprintln!("SolidCraft window: no native resize border; egui edge zones instead");
+ solidcraft_engine::note!("SolidCraft window: no native resize border; egui edge zones instead");
}
}
app.integrated_titlebar = cfg!(target_os = "macos");
@@ -1175,9 +1175,10 @@ fn main() -> eframe::Result {
.collect();
let info = rs.adapter.get_info();
if !app.preferences.graphics_adapter.is_empty() && !info.name.eq_ignore_ascii_case(app.preferences.graphics_adapter.as_str()) {
- eprintln!(
+ solidcraft_engine::note!(
"SolidCraft graphics: preferred adapter {:?} was not used; using {:?} instead",
- app.preferences.graphics_adapter, info.name
+ app.preferences.graphics_adapter,
+ info.name
);
}
let samples = scene_msaa_request(saved_samples);
@@ -1185,7 +1186,7 @@ fn main() -> eframe::Result {
eframe::egui_wgpu::supported_msaa_samples(&rs.adapter, &rs.device, rs.target_format, depth)
});
let scene_samples = scene_samples(info.backend, u32::from(samples), &supported);
- eprintln!("SolidCraft graphics: {:?}, MSAA {scene_samples}x (requested {}x)", rs.adapter.get_info().backend, samples);
+ solidcraft_engine::note!("SolidCraft graphics: {:?}, MSAA {scene_samples}x (requested {}x)", rs.adapter.get_info().backend, samples);
solidcraft_engine::crash::phase("viewport pipelines (shader compile)");
let scene_samples = app.set_wgpu_split(rs, depth_bits, STENCIL_BITS, scene_samples);
app.msaa_supported = supported;
@@ -1346,7 +1347,7 @@ fn wgpu_options(cpu: bool, preference: Option<&str>) -> eframe::egui_wgpu::WgpuC
let retry = std::env::var(startup::RETRY_BACKEND_ENV).ok();
let preference = if cpu { preference } else { retry.as_deref().or(preference) };
if let Some(backends) = startup::choose_backends(cfg!(target_os = "windows"), env_set, cpu, preference, startup::has_hardware_adapter) {
- eprintln!("SolidCraft graphics: starting {backends:?}");
+ solidcraft_engine::note!("SolidCraft graphics: starting {backends:?}");
setup.instance_descriptor.backends = backends;
}
let intel_mac = cfg!(all(target_os = "macos", target_arch = "x86_64"));
@@ -1372,7 +1373,7 @@ fn wgpu_options(cpu: bool, preference: Option<&str>) -> eframe::egui_wgpu::WgpuC
/// event loop or a failed device; each retry advances through the APIs, then software once.
fn no_window(error: eframe::Error, tried_cpu: bool, failed: eframe::wgpu::Backends, settings: Option<&std::path::Path>) -> eframe::Result {
log::error!("the window could not open: {error}");
- eprintln!("SolidCraft: the window could not open: {error}");
+ solidcraft_engine::note!("SolidCraft: the window could not open: {error}");
// This failure was handled, so neither the marker nor the journal should call it a crash.
if let Some(dir) = settings {
startup::started(dir);
@@ -1385,7 +1386,7 @@ fn no_window(error: eframe::Error, tried_cpu: bool, failed: eframe::wgpu::Backen
let previous = std::env::var(startup::FALLBACK_NOTE_ENV).unwrap_or_default();
let note = startup::fallback_note(&previous, failed, next, &error.to_string());
log::warn!("{note}");
- eprintln!("SolidCraft: {note}");
+ solidcraft_engine::note!("SolidCraft: {note}");
let mut command = std::process::Command::new(exe);
command.args(std::env::args_os().skip(1)).env(startup::FALLBACK_NOTE_ENV, note);
if next == "cpu" {
diff --git a/apps/solidcraft/src/startup.rs b/apps/solidcraft/src/startup.rs
index ecbfed06b2..1f9df7a05e 100644
--- a/apps/solidcraft/src/startup.rs
+++ b/apps/solidcraft/src/startup.rs
@@ -357,7 +357,7 @@ pub fn relaunch_with_version_compat() -> Result<bool, String> {
return Ok(false);
}
log::info!("startup: OCLP detected; re-launching with {}=1", SYSTEM_VERSION_COMPAT_ENV);
- eprintln!("SolidCraft: OCLP detected; re-launching with {}=1", SYSTEM_VERSION_COMPAT_ENV);
+ solidcraft_engine::note!("SolidCraft: OCLP detected; re-launching with {}=1", SYSTEM_VERSION_COMPAT_ENV);
let exe = std::env::current_exe().map_err(|e| format!("could not find own executable: {e}"))?;
let status = std::process::Command::new(&exe)
.args(std::env::args_os().skip(1))
diff --git a/crates/engine/src/crash.rs b/crates/engine/src/crash.rs
index 0a585167a7..21bcda6999 100644
--- a/crates/engine/src/crash.rs
+++ b/crates/engine/src/crash.rs
@@ -485,12 +485,12 @@ fn hook(info: &std::panic::PanicHookInfo<'_>) -> bool {
q.push(p);
}
});
- eprintln!("SolidCraft: internal error caught in a command; a crash report will be written");
+ solidcraft_geom::note!("SolidCraft: internal error caught in a command; a crash report will be written");
} else {
// Outside any command: what the journal knows has to do.
let kind = if recovered { "kernel_panic_recovered" } else { "panic" };
if let Some(id) = write_from_journal(state, kind, Some(&p)) {
- eprintln!("SolidCraft: internal error; crash report {}", state.dir.join(&id).display());
+ solidcraft_geom::note!("SolidCraft: internal error; crash report {}", state.dir.join(&id).display());
if !recovered && let Ok(mut j) = state.journal.try_lock() {
j.record(&json!({ "reported": id }));
}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 3940b3f15b..26dfa31a5f 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -55,6 +55,7 @@ pub use cmd::{
pub use solidcraft_doc as doc;
pub use solidcraft_doc::Visibility;
pub use solidcraft_geom as geom;
+pub use solidcraft_geom::note;
pub use solidcraft_io as io;
pub use solidcraft_kernel as kernel;
pub use solidcraft_profile as profile;
diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs
index 1b719d2a25..f6195126f3 100644
--- a/crates/geom/src/lib.rs
+++ b/crates/geom/src/lib.rs
@@ -41,6 +41,7 @@ pub mod section;
pub mod simplify;
pub mod spline_space;
pub mod srgb;
+pub mod stderr;
pub mod tess;
pub mod title_block;
pub mod tspline;
diff --git a/crates/geom/src/stderr.rs b/crates/geom/src/stderr.rs
new file mode 100644
index 0000000000..07b7d8020f
--- /dev/null
+++ b/crates/geom/src/stderr.rs
@@ -0,0 +1,20 @@
+//! A line on stderr that never stops the program: a process another program started (an agent
+//! running `solidcraft mcp`, the app that one started) writes into a pipe that program may have
+//! closed, and `eprintln!` then panics with "failed printing to stderr" (#10111). A closed stderr
+//! is no reason to stop.
+
+use std::io::Write;
+
+/// Write `args` and a line break to stderr, as `eprintln!` does, ignoring a failed write.
+pub fn note(args: std::fmt::Arguments<'_>) {
+ let mut err = std::io::stderr().lock();
+ let _ = err.write_fmt(args).and_then(|()| err.write_all(b"\n"));
+}
+
+/// [`note`] with `format!` arguments: `eprintln!` for code that keeps running when stderr is gone.
+#[macro_export]
+macro_rules! note {
+ ($($arg:tt)*) => {
+ $crate::stderr::note(format_args!($($arg)*))
+ };
+}
diff --git a/crates/gpu/src/concurrent.rs b/crates/gpu/src/concurrent.rs
index fc8a0917e5..29fe49bed9 100644
--- a/crates/gpu/src/concurrent.rs
+++ b/crates/gpu/src/concurrent.rs
@@ -193,7 +193,7 @@ mod tests {
#[test]
fn jobs_hand_back_what_they_built() {
let Ok((_, device, _)) = crate::open_headless() else {
- eprintln!("skipped: no GPU adapter");
+ solidcraft_geom::note!("skipped: no GPU adapter");
return;
};
let runs = AtomicUsize::new(0);
@@ -215,7 +215,7 @@ mod tests {
#[test]
fn an_error_on_a_job_reaches_the_callers_error_scope() {
let Ok((_, device, _)) = crate::open_headless() else {
- eprintln!("skipped: no GPU adapter");
+ solidcraft_geom::note!("skipped: no GPU adapter");
return;
};
let runs = AtomicUsize::new(0);
@@ -238,7 +238,7 @@ mod tests {
#[test]
fn a_job_dropped_unjoined_whose_thread_panicked_does_not_panic_the_scope() {
let Ok((_, device, _)) = crate::open_headless() else {
- eprintln!("skipped: no GPU adapter");
+ solidcraft_geom::note!("skipped: no GPU adapter");
return;
};
let finished = scope(&device, |jobs| {
@@ -255,7 +255,7 @@ mod tests {
#[test]
fn a_job_whose_thread_panicked_runs_again_on_the_calling_thread() {
let Ok((_, device, _)) = crate::open_headless() else {
- eprintln!("skipped: no GPU adapter");
+ solidcraft_geom::note!("skipped: no GPU adapter");
return;
};
let built = scope(&device, |jobs| {
diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs
index d84e361836..c889acb289 100644
--- a/crates/mcp/src/backend.rs
+++ b/crates/mcp/src/backend.rs
@@ -363,7 +363,7 @@ impl Remote {
}
if told.elapsed() >= PROGRESS_EVERY {
let secs = self.outstanding.as_ref().map_or(0, Outstanding::secs);
- eprintln!("solidcraft-mcp: {what} is still running in the app ({secs} s); waiting for it");
+ solidcraft_engine::note!("solidcraft-mcp: {what} is still running in the app ({secs} s); waiting for it");
told = Instant::now();
}
std::thread::sleep(self.waits.poll.min(limit.saturating_sub(waited)));
@@ -457,7 +457,7 @@ impl Remote {
// Timed out in the app, still running (#1618): wait for its result on this connection.
if v.get("running").and_then(Value::as_bool) == Some(true) {
self.outstanding = Some(Outstanding { what: what.clone(), effect: Some(effect), since: sent });
- eprintln!(
+ solidcraft_engine::note!(
"solidcraft-mcp: {what} is still running in the app after {} s; waiting up to {} s more for it",
sent.elapsed().as_secs(),
self.waits.pending.as_secs()
@@ -865,7 +865,7 @@ impl Auto {
return;
}
if let Some(port) = (self.discover)() {
- eprintln!("solidcraft mcp: the SolidCraft app is running now; bridged to 127.0.0.1:{port}");
+ solidcraft_engine::note!("solidcraft mcp: the SolidCraft app is running now; bridged to 127.0.0.1:{port}");
let level = self.param_check();
self.remote = Some(Remote::new(&format!("127.0.0.1:{port}"), self.token.as_deref()).with_param_check(level));
self.headless = None;
diff --git a/crates/ui-egui/src/frame_watch.rs b/crates/ui-egui/src/frame_watch.rs
index 7224975edc..4bfece2d0d 100644
--- a/crates/ui-egui/src/frame_watch.rs
+++ b/crates/ui-egui/src/frame_watch.rs
@@ -65,6 +65,6 @@ pub(crate) fn end(app: &mut SolveApp) {
}
if ms > SLOW_MS && solidcraft_engine::geom::env::var_os("PROFILE_FRAMES").is_some() {
let steps: Vec<String> = app.frame_watch.steps.iter().filter(|(_, t)| *t >= 1.0).map(|(n, t)| format!("{n} {t:.0}")).collect();
- eprintln!("SolidCraft slow frame: {ms:.0} ms ({phase}) [{}]", steps.join(", "));
+ solidcraft_engine::note!("SolidCraft slow frame: {ms:.0} ms ({phase}) [{}]", steps.join(", "));
}
}
diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs
index 160b21eaf9..d5a9a1e6d5 100644
--- a/crates/ui-egui/src/gpu.rs
+++ b/crates/ui-egui/src/gpu.rs
@@ -141,7 +141,7 @@ pub(crate) fn tick_tessellation(app: &mut crate::SolveApp) {
if let Some(gpu) = app.viewport.gpu.as_mut() {
gpu.tess = true;
#[cfg(not(target_arch = "wasm32"))]
- eprintln!("SolidCraft graphics: GPU tessellation ready; bodies are evaluated on the GPU from now on");
+ solidcraft_engine::note!("SolidCraft graphics: GPU tessellation ready; bodies are evaluated on the GPU from now on");
}
}
}
@@ -161,7 +161,7 @@ pub fn log_uncaptured_errors(device: &wgpu::Device) {
if reported.fetch_add(1, Ordering::Relaxed) < 8 {
log::error!("GPU: {e}");
#[cfg(not(target_arch = "wasm32"))]
- eprintln!("SolidCraft graphics: {e}");
+ solidcraft_engine::note!("SolidCraft graphics: {e}");
}
}));
}
diff --git a/crates/ui-egui/src/open_meshing.rs b/crates/ui-egui/src/open_meshing.rs
index 4dad02ba4a..b0e7730f1a 100644
--- a/crates/ui-egui/src/open_meshing.rs
+++ b/crates/ui-egui/src/open_meshing.rs
@@ -217,7 +217,7 @@ pub(crate) fn tick(app: &mut SolveApp, ctx: &egui::Context) {
}
if profiling() {
let ms = began.map_or(0.0, |t| (ctx.input(|i| i.time) - t) * 1000.0);
- eprintln!("SolidCraft open meshing: all {} bodies shown after {ms:.0} ms", world.bodies.len());
+ solidcraft_engine::note!("SolidCraft open meshing: all {} bodies shown after {ms:.0} ms", world.bodies.len());
}
// Framed from outlines and not moved since: frame the meshes.
if framed == Some(app.cam) {
@@ -279,7 +279,7 @@ pub(crate) fn refresh(app: &mut SolveApp, now: f64) {
if !m.first_shown && !st.bodies.is_empty() {
m.first_shown = true;
if profiling() {
- eprintln!("SolidCraft open meshing: first {} bodies shown after {:.0} ms", st.bodies.len(), (now - began) * 1000.0);
+ solidcraft_engine::note!("SolidCraft open meshing: first {} bodies shown after {:.0} ms", st.bodies.len(), (now - began) * 1000.0);
}
}
m.shown = Some((done, Arc::new(st)));