diff --git a/crates/engine/src/cmd/diagnostics.rs b/crates/engine/src/cmd/diagnostics.rs index 25a4756dc..57c7eb9d9 100644 --- a/crates/engine/src/cmd/diagnostics.rs +++ b/crates/engine/src/cmd/diagnostics.rs @@ -1,55 +1,94 @@ //! Crash reports, for agents and people (see `crate::crash` and docs/crash-reports.md): list //! them, read one, delete them. They live on this computer and are never sent anywhere. -use serde_json::{Value, json}; +use serde_json::Value; use super::CommandSpec; use crate::params::{bad, str_}; +use crate::schema::diagnostics::{ + CrashReport, CrashReportList, CrashReportParams, CrashReportsClearParams, CrashReportsCleared, CrashReportsParams, CrashTestParams, + CrashTestResult, +}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session, crash}; +const LIST_CONTRACT: TypedContract = TypedContract::new(); +const READ_CONTRACT: TypedContract = TypedContract::new(); +const CLEAR_CONTRACT: TypedContract = TypedContract::new(); +const CRASH_TEST_CONTRACT: TypedContract = TypedContract::new(); + pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("diagnostics.crash_reports", "Crash Reports", list).icon("bug_report").noundo().params( - "limit?: number (default 20). Lists this computer's crash reports, newest first: {dir, reports: [{id, kind, time, message, \ - command, count, version, path, replayable}]}. kind: command_panic | panic | kernel_panic_recovered | unclean_exit. \ - Read one with diagnostics.crash_report; reproduce it with `solidcraft-cli crashes replay `", - ), - CommandSpec::new("diagnostics.crash_report", "Crash Report", read).icon("bug_report").noundo().params( - "id: report id. The whole report: message, location, backtrace, app version and commit, system, the command that \ - crashed and the recent ones, notes, and design_path / replay_path when the crash can be replayed \ - (`solidcraft-cli run --in `)", - ), - CommandSpec::new("diagnostics.crash_reports.clear", "Delete Crash Reports", clear) + CommandSpec::new("diagnostics.crash_reports", "Crash Reports", crate::checked!("diagnostics.crash_reports", list)) + .icon("bug_report") + .noundo() + .contract(&LIST_CONTRACT) + .output(output_schema_for::) + .params( + "limit?: number (default 20). Lists this computer's crash reports, newest first: {dir, reports: [{id, kind, time, message, \ + command, count, version, path, replayable}]}. kind: command_panic | panic | kernel_panic_recovered | unclean_exit. \ + Read one with diagnostics.crash_report; reproduce it with `solidcraft-cli crashes replay `", + ), + CommandSpec::new("diagnostics.crash_report", "Crash Report", crate::checked!("diagnostics.crash_report", read)) + .icon("bug_report") + .noundo() + .contract(&READ_CONTRACT) + .output(output_schema_for::) + .params( + "id: report id. The whole report: message, location, backtrace, app version and commit, system, the command that \ + crashed and the recent ones, notes, and design_path / replay_path when the crash can be replayed \ + (`solidcraft-cli run --in `)", + ), + CommandSpec::new("diagnostics.crash_reports.clear", "Delete Crash Reports", crate::checked!("diagnostics.crash_reports.clear", clear)) .icon("delete") .noundo() + .contract(&CLEAR_CONTRACT) + .output(output_schema_for::) .params("id?: one report (default: all). Returns {deleted}"), - CommandSpec::new("diagnostics.crash_test", "Crash Test", crash_test).icon("bug_report").noundo().enabled(crash_test_enabled).params( - "mode: panic | kernel | abort. Checks that crash reports work: panic = an internal error in this command (caught; \ - the design is unchanged), kernel = one inside the geometry kernel (caught), abort = the app ends at once (reported \ - at the next start). Only when the SOLIDCRAFT_CRASH_TEST environment variable is set", - ), + CommandSpec::new("diagnostics.crash_test", "Crash Test", crate::checked!("diagnostics.crash_test", crash_test)) + .icon("bug_report") + .noundo() + .enabled(crash_test_enabled) + .contract(&CRASH_TEST_CONTRACT) + .output(output_schema_for::) + .params( + "mode: panic | kernel | abort. Checks that crash reports work: panic = an internal error in this command (caught; \ + the design is unchanged), kernel = one inside the geometry kernel (caught), abort = the app ends at once (reported \ + at the next start). Only when the SOLIDCRAFT_CRASH_TEST environment variable is set", + ), ]; fn dir(cmd: &str) -> Result { crash::default_dir().ok_or_else(|| bad(cmd, "no crash folder on this system")) } +fn reply(cmd: &str, reply: impl serde::Serialize) -> Result { + serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string())) +} + fn list(_: &mut Session, p: &Value) -> Result { - let d = dir("diagnostics.crash_reports")?; + let cmd = "diagnostics.crash_reports"; + let d = dir(cmd)?; let limit = p.get("limit").and_then(Value::as_u64).map_or(20, |n| n.min(1000)) as usize; let mut reports = crash::list(&d); reports.truncate(limit); - Ok(json!({ "dir": d.to_string_lossy(), "reports": reports })) + reply(cmd, CrashReportList { dir: d.to_string_lossy().into_owned(), reports, param_warnings: Vec::new() }) } fn read(_: &mut Session, p: &Value) -> Result { let cmd = "diagnostics.crash_report"; let id = str_(p, "id").ok_or_else(|| bad(cmd, "`id` is required (see diagnostics.crash_reports)"))?; - crash::read(&dir(cmd)?, id).map_err(|e| bad(cmd, e)) + // `crash::read` gives only a report that is a JSON object. + let report = match crash::read(&dir(cmd)?, id).map_err(|e| bad(cmd, e))? { + Value::Object(report) => report, + _ => return Err(bad(cmd, format!("no crash report `{id}`"))), + }; + reply(cmd, CrashReport { report, param_warnings: Vec::new() }) } fn clear(_: &mut Session, p: &Value) -> Result { - let d = dir("diagnostics.crash_reports.clear")?; - Ok(json!({ "deleted": crash::clear(&d, str_(p, "id")) })) + let cmd = "diagnostics.crash_reports.clear"; + let d = dir(cmd)?; + reply(cmd, CrashReportsCleared { deleted: crash::clear(&d, str_(p, "id")), param_warnings: Vec::new() }) } fn crash_test_enabled(_: &Session) -> std::result::Result<(), String> { diff --git a/crates/engine/src/crash.rs b/crates/engine/src/crash.rs index e307c645d..fb4123573 100644 --- a/crates/engine/src/crash.rs +++ b/crates/engine/src/crash.rs @@ -71,20 +71,23 @@ pub struct Build { pub built: &'static str, } -/// One report, as listed. -#[derive(Clone, Debug, PartialEq, serde::Serialize)] +/// One report, as listed (and as `diagnostics.crash_reports` describes it, #10909). +#[derive(Clone, Debug, PartialEq, serde::Serialize, schemars::JsonSchema)] pub struct Summary { + /// The report's id, which `diagnostics.crash_report` reads. pub id: String, /// `command_panic`, `panic`, `kernel_panic_recovered` or `unclean_exit`. pub kind: String, /// When the report was first recorded (UTC). Unclean exits are recorded at a later launch, /// which may be days after the session ended, rather than at the exact exit time. pub time: String, + /// The internal error's message. pub message: String, /// The command running when it happened, if one was. pub command: Option, /// Times it happened. pub count: u64, + /// The version of SolidCraft it happened in. pub version: String, /// The report's folder. pub path: String, diff --git a/crates/engine/src/schema/diagnostics.rs b/crates/engine/src/schema/diagnostics.rs new file mode 100644 index 000000000..5d80fe4da --- /dev/null +++ b/crates/engine/src/schema/diagnostics.rs @@ -0,0 +1,155 @@ +//! Contracts and result types for the commands in `cmd/diagnostics.rs`: the crash reports on +//! this computer (#10909). + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::{Map, Value, json}; + +/// List this computer's crash reports, newest first. They stay on this computer and are never +/// sent anywhere. Read one with `diagnostics.crash_report`; reproduce one with +/// `solidcraft-cli crashes replay `. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CrashReportsParams { + /// How many reports to list, newest first. Default: 20; at most 1000 are listed, whatever + /// the limit. + #[serde(default)] + pub limit: Option, +} + +/// What `diagnostics.crash_reports` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CrashReportList { + /// The crash report folder on this computer. + pub dir: String, + /// The reports, newest first. + pub reports: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// Read one crash report: the whole report as it was saved, with the paths of its files. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CrashReportParams { + /// The report's id, as `diagnostics.crash_reports` lists it. + pub id: String, +} + +/// What `diagnostics.crash_report` returns: the report as saved, with where its files are. A +/// report from an earlier release may lack some of these fields, and a report can carry more +/// (`startup_phase`, `native`). +#[derive(Debug, Serialize)] +pub struct CrashReport { + /// The report's fields. + #[serde(flatten)] + pub report: Map, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +impl JsonSchema for CrashReport { + fn schema_name() -> Cow<'static, str> { + "CrashReport".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let path = + |what: &str| json!({"description": format!("Where the report's {what} is on this computer; only when it has one."), "type": "string"}); + json_schema!({ + "description": "A crash report as saved, with where its files are. A report from an earlier release may lack some fields, and a report can carry more.", + "type": "object", + "properties": { + "id": {"description": "The report's id.", "type": "string"}, + "kind": {"description": "command_panic, panic, kernel_panic_recovered or unclean_exit.", "type": "string"}, + "signature": {"description": "What tells this crash apart from others, so a repeat counts against the same report."}, + "count": {"description": "How many times it happened.", "type": "integer", "minimum": 0}, + "first_seen": {"description": "When it was first recorded (UTC). An unclean exit is recorded at a later launch."}, + "last_seen": {"description": "When it was last recorded (UTC)."}, + "app": {"description": "The app's version, commit and build date."}, + "system": {"description": "The operating system, architecture and graphics environment."}, + "session": {"description": "How long the app had been running."}, + "message": {"description": "The internal error's message."}, + "location": {"description": "Where in the code it happened."}, + "thread": {"description": "The thread it happened on."}, + "backtrace": {"description": "The stack, one frame `symbol (file:line)` each."}, + "command": {"description": "The command running when it happened, with its parameters, if one was."}, + "base": {"description": "What the replay starts from."}, + "recent_commands": {"description": "The commands run before it."}, + "files": {"description": "The files saved with the report, by what they are."}, + "reproduce": {"description": "The command line that replays the crash, when it can be."}, + "notes": {"description": "What the report could not record, and why."}, + "path": {"description": "The report's folder on this computer.", "type": "string"}, + "design_path": path("design"), + "replay_path": path("replay (`solidcraft-cli run --in `)"), + "minidump_path": path("minidump"), + "param_warnings": {"description": "In the warn parameter-check mode: what the call's parameters got wrong.", "type": "array", "items": {"type": "string"}} + } + }) + } +} + +/// Delete one crash report, or all of them. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CrashReportsClearParams { + /// The report to delete, as `diagnostics.crash_reports` lists it. Default: every report. An + /// id that names no report deletes nothing. + #[serde(default)] + pub id: Option, +} + +/// What `diagnostics.crash_reports.clear` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CrashReportsCleared { + /// How many reports were deleted. + pub deleted: usize, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// Check that crash reports work, by crashing on purpose. Only when the SOLIDCRAFT_CRASH_TEST +/// environment variable is set. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct CrashTestParams { + /// What to break. + pub mode: CrashTestMode, +} + +/// What `diagnostics.crash_test` breaks. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum CrashTestMode { + /// An internal error in this command, caught: the design is unchanged. + Panic, + /// An internal error inside the geometry kernel, caught. + Kernel, + /// The app ends at once; the report is made at the next start. + Abort, +} + +impl<'de> Deserialize<'de> for CrashTestMode { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) if s == "panic" => Ok(CrashTestMode::Panic), + Value::String(s) if s == "kernel" => Ok(CrashTestMode::Kernel), + Value::String(s) if s == "abort" => Ok(CrashTestMode::Abort), + _ => Err(D::Error::custom("must be panic, kernel or abort")), + } + } +} + +/// What `diagnostics.crash_test` would return. It never succeeds: it ends in an internal error +/// that is caught and reported (`panic`, `kernel`), or it ends the app (`abort`). +#[derive(Debug, Serialize, JsonSchema)] +pub struct CrashTestResult {} + +#[cfg(test)] +#[path = "diagnostics_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/diagnostics_tests.rs b/crates/engine/src/schema/diagnostics_tests.rs new file mode 100644 index 000000000..43cb3d684 --- /dev/null +++ b/crates/engine/src/schema/diagnostics_tests.rs @@ -0,0 +1,100 @@ +use serde_json::{Value, json}; + +use super::{ + CrashReport, CrashReportList, CrashReportParams, CrashReportsClearParams, CrashReportsCleared, CrashReportsParams, CrashTestMode, CrashTestParams, +}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["limit"]); + assert_keys(input_schema_for::(), &["id"]); + assert_keys(input_schema_for::(), &["id"]); + assert_keys(input_schema_for::(), &["mode"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[("diagnostics.crash_report", json!({"id": "no-such-report"}))]); +} + +/// The crash test runs only with SOLIDCRAFT_CRASH_TEST set, so its mode is checked here: the +/// schema lists the three modes (one `const` each, with what it breaks), the type reads them, +/// and anything else gets the handler's message. +#[test] +fn the_crash_test_mode_is_one_of_three() { + let schema = input_schema_for::(); + let schema = schema.as_value(); + let listed: Vec<&str> = schema["$defs"]["CrashTestMode"]["oneOf"].as_array().into_iter().flatten().filter_map(|m| m["const"].as_str()).collect(); + assert_eq!(listed, ["panic", "kernel", "abort"], "{schema}"); + for (mode, want) in [("panic", CrashTestMode::Panic), ("kernel", CrashTestMode::Kernel), ("abort", CrashTestMode::Abort)] { + let p = json!({ "mode": mode }); + assert_eq!(serde_json::from_value::(p.clone()).ok().map(|p| p.mode), Some(want), "{mode}"); + assert!(conforms(schema, schema, &p), "{p}"); + } + for mode in [json!("Panic"), json!("explode"), json!(""), json!(1), json!(null)] { + let p = json!({ "mode": mode }); + let error = serde_json::from_value::(p.clone()).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("must be panic, kernel or abort"), "{p}: {error}"); + assert!(!mode.as_str().is_some_and(|m| listed.contains(&m)), "{p}"); + } +} + +/// A report in this test process's crash folder, as the app writes one, with a design and a +/// replay beside it. +fn write_report(id: &str) { + let dir = crate::crash::default_dir().unwrap_or_else(|| panic!("no crash folder")).join(id); + std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{e}")); + let report = json!({ + "format": 1, "id": id, "kind": "command_panic", "signature": "00000000deadbeef", "count": 2, + "first_seen": "2026-11-01T12:00:00Z", "last_seen": "2026-11-01T12:05:00Z", + "app": {"version": "0.29.0", "commit": "abc", "built": "2026-10-31"}, + "system": {"os": "windows", "arch": "x86_64", "environment": ""}, "session": {"uptime_s": 60}, + "message": "an internal error", "location": "here.rs:1", "thread": "main", "backtrace": ["f (here.rs:1)"], + "command": {"command": "solid.box", "params": {}}, "base": "new", "recent_commands": [], + "files": {"design": "design.sc", "replay": "replay.json"}, "reproduce": format!("solidcraft-cli crashes replay {id}"), "notes": [], + "startup_phase": "running" + }); + for (name, text) in [("report.json", report.to_string()), ("design.sc", "{}".into()), ("replay.json", "[]".into())] { + std::fs::write(dir.join(name), text).unwrap_or_else(|e| panic!("{e}")); + } +} + +/// #10909: listing, reading and deleting reports reply as their output schemas say, in Warn +/// without warnings for good calls and with them for a misspelt key; strict refuses an `id` +/// that isn't text, which the handler would read as no id and so delete every report. +#[test] +fn crash_report_commands_reply_with_their_schemas() { + let id = "20261101-120000-00000000deadbeef"; + write_report(id); + let (list_schema, report_schema, cleared_schema) = + (output_schema_for::(), output_schema_for::(), output_schema_for::()); + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let run = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + let matches = |schema: &schemars::Schema, r: &Value, warned: bool| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{r}"); + }; + for p in [json!({}), json!({"limit": 5}), json!({"limit": 0}), json!({"limit": 5000})] { + let r = run(&mut s, "diagnostics.crash_reports", p.clone()); + matches(&list_schema, &r, false); + let listed = r["reports"].as_array().is_some_and(|a| a.iter().any(|x| x["id"] == id)); + assert_eq!(listed, p["limit"] != json!(0), "{p}: {r}"); + } + matches(&list_schema, &run(&mut s, "diagnostics.crash_reports", json!({"limit": "5"})), true); + let r = run(&mut s, "diagnostics.crash_report", json!({"id": id})); + matches(&report_schema, &r, false); + assert_eq!((r["id"].as_str(), r["count"].as_u64(), r["startup_phase"].as_str()), (Some(id), Some(2), Some("running")), "{r}"); + assert!(r["design_path"].is_string() && r["replay_path"].is_string() && r["path"].is_string(), "{r}"); + matches(&report_schema, &run(&mut s, "diagnostics.crash_report", json!({"id": id, "ids": [id]})), true); + matches(&cleared_schema, &run(&mut s, "diagnostics.crash_reports.clear", json!({"id": "20261101-120000-0000000000000000"})), false); + let mut strict = Session { param_check: ParamCheck::Strict, ..Session::default() }; + let error = strict.execute("diagnostics.crash_reports.clear", &json!({"id": 5})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("`id`"), "{error}"); + let r = run(&mut s, "diagnostics.crash_reports.clear", json!({"id": id})); + matches(&cleared_schema, &r, false); + assert_eq!(r["deleted"], 1, "the report was still there to delete: {r}"); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 8ad9d071b..0e233d120 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -58,6 +58,7 @@ pub mod bom; pub mod component; pub mod config; pub mod construct; +pub mod diagnostics; pub mod edit; pub mod features; pub mod file; diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt index c85ab61a9..f98799380 100644 --- a/crates/engine/src/schema/unconverted.txt +++ b/crates/engine/src/schema/unconverted.txt @@ -53,10 +53,6 @@ contact.edit contact.enable_all contact.enable_sets contact.list -diagnostics.crash_report -diagnostics.crash_reports -diagnostics.crash_reports.clear -diagnostics.crash_test doc.open doc.recover doc.recovery_discard