diff --git a/changelog.d/20261007-diagnostics-valid-json.md b/changelog.d/20261007-diagnostics-valid-json.md new file mode 100644 index 0000000..a321311 --- /dev/null +++ b/changelog.d/20261007-diagnostics-valid-json.md @@ -0,0 +1,7 @@ +--- +area: manager +type: fixed +audience: admins +title: Diagnostic files with database checks stay readable after secrets are removed +--- +Removing a line that mentioned a secret could break the JSON files in a diagnostic package. Secret values are now replaced instead, so the files stay valid. diff --git a/changelog.d/20261007-one-click-diagnostics.md b/changelog.d/20261007-one-click-diagnostics.md new file mode 100644 index 0000000..9bf18f0 --- /dev/null +++ b/changelog.d/20261007-one-click-diagnostics.md @@ -0,0 +1,7 @@ +--- +area: manager +type: added +audience: admins +title: One button collects all diagnostics, including crashes and Windows crash records +--- +Report a problem collects logs, crash reports and small dumps, Windows crash records, update journals and the running server programs in one file, then shows its folder. Crashes without a server crash report are no longer missing. diff --git a/changelog.d/20261007-report-routing.md b/changelog.d/20261007-report-routing.md new file mode 100644 index 0000000..7820136 --- /dev/null +++ b/changelog.d/20261007-report-routing.md @@ -0,0 +1,7 @@ +--- +area: manager +type: added +audience: admins +title: Problem reports go to the right project +--- +Choose what the problem is about: Manager and other modules, CoA Companions, or SQUID Playerbots. The report opens in that project's GitHub page with the versions filled in. The bot system that is switched on is preselected. diff --git a/crates/coa-core/src/diag.rs b/crates/coa-core/src/diag.rs index 431f097..0466bff 100644 --- a/crates/coa-core/src/diag.rs +++ b/crates/coa-core/src/diag.rs @@ -172,19 +172,158 @@ pub fn squash_repeated_config_warnings(text: &str) -> String { s } +const SENSITIVE: [&str; 7] = ["password", "passwd", "secret", "token", "apikey", "api_key", "databaseinfo"]; + /// Remove things that must never leave the machine from log text. pub fn redact(text: &str) -> String { let mut out = Vec::new(); for line in text.lines() { let l = line.to_lowercase(); - let sensitive = ["password", "passwd", "secret", "token", "apikey", "api_key", "databaseinfo"].iter().any(|k| l.contains(k)); + let sensitive = SENSITIVE.iter().any(|k| l.contains(k)); out.push(if sensitive { "[line removed: may contain a secret]".to_string() } else { line.to_string() }); } out.join("\n") } +/// The same for JSON: values under a sensitive key and strings that look like `password=...` are replaced, and the +/// result stays valid JSON (removing a whole line would break the file for whoever reads it). Text that is not JSON +/// falls back to the line rule. +pub fn redact_json(text: &str) -> String { + fn scrub(v: &mut serde_json::Value) { + use serde_json::Value; + match v { + Value::Object(map) => { + for (key, value) in map.iter_mut() { + let k = key.to_lowercase(); + if SENSITIVE.iter().any(|s| k.contains(s)) && !value.is_object() && !value.is_array() { + *value = Value::String("[redacted]".into()); + } else { + scrub(value); + } + } + } + Value::Array(items) => items.iter_mut().for_each(scrub), + Value::String(s) => { + let l = s.to_lowercase(); + if ["password=", "passwd=", "secret=", "token=", "apikey=", "api_key=", "password:"].iter().any(|k| l.contains(k)) { + *s = "[redacted]".into(); + } + } + _ => {} + } + } + match serde_json::from_str::(text) { + Ok(mut v) => { + scrub(&mut v); + serde_json::to_string_pretty(&v).unwrap_or_else(|_| redact(text)) + } + Err(_) => redact(text), + } +} + +/// Keep the events of a `wevtutil ... /f:text` listing that mention one of `needles` (compared without case), in the +/// order listed, at most `max` of them. +pub fn filter_event_blocks(listing: &str, needles: &[&str], max: usize) -> String { + let mut blocks: Vec> = Vec::new(); + for line in listing.lines() { + if line.starts_with("Event[") || blocks.is_empty() { + blocks.push(Vec::new()); + } + if let Some(b) = blocks.last_mut() { b.push(line); } + } + blocks + .into_iter() + .map(|b| b.join("\n")) + .filter(|b| { let l = b.to_lowercase(); needles.iter().any(|n| l.contains(n)) }) + .take(max) + .collect::>() + .join("\n\n") +} + +/// Drop the lines of an event listing that name the person or the computer. +pub fn drop_identity_lines(listing: &str) -> String { + listing + .lines() + .filter(|l| { let t = l.trim_start(); !(t.starts_with("User:") || t.starts_with("User Name:") || t.starts_with("Computer:")) }) + .collect::>() + .join("\n") +} + +/// `wevtutil /uni:true` writes UTF-16 with a byte order mark; anything else is read as UTF-8 (lossy). +fn decode_console_output(bytes: &[u8]) -> String { + if bytes.starts_with(&[0xFF, 0xFE]) { + let units: Vec = bytes[2..].chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + String::from_utf16_lossy(&units) + } else { + String::from_utf8_lossy(bytes).into_owned() + } +} + +/// Crashes and hangs Windows recorded for the server programs in the last two weeks. This is the only trace of a crash +/// that ends the process without the server's own crash report (a stack buffer overrun, for example). The lines that +/// name the user and the computer are left out. +#[cfg(windows)] +fn windows_events() -> String { + use std::os::windows::process::CommandExt; + let query = "*[System[(Provider[@Name='Application Error' or @Name='Windows Error Reporting' or @Name='Application Hang']) and TimeCreated[timediff(@SystemTime) <= 1209600000]]]"; + let out = std::process::Command::new("wevtutil") + .args(["qe", "Application", &format!("/q:{query}"), "/c:300", "/rd:true", "/f:text", "/uni:true"]) + .creation_flags(0x0800_0000) + .output(); + match out { + Ok(o) if o.status.success() => { + let text = filter_event_blocks(&decode_console_output(&o.stdout), &["worldserver", "authserver", "mysqld", "coa server manager", "coa-server-manager"], 40); + if text.is_empty() { "No crash or hang of the server programs was recorded by Windows in the last 14 days.".into() } else { drop_identity_lines(&text) } + } + Ok(o) => format!("Windows event log could not be read: {}", decode_console_output(&o.stderr).trim()), + Err(e) => format!("Windows event log could not be read: {e}"), + } +} + +#[cfg(not(windows))] +fn windows_events() -> String { + String::new() +} + +/// Newest files of a folder with the given extension (compared without case): path, size, modified time. +fn newest_files(dir: &Path, ext: &str, limit: usize) -> Vec<(PathBuf, u64, std::time::SystemTime)> { + let Ok(rd) = fs::read_dir(dir) else { return Vec::new() }; + let mut v: Vec<_> = rd + .flatten() + .filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case(ext))) + .filter_map(|e| { let m = e.metadata().ok()?; m.is_file().then(|| (e.path(), m.len(), m.modified().unwrap_or(std::time::UNIX_EPOCH))) }) + .collect(); + v.sort_by(|a, b| b.2.cmp(&a.2)); + v.truncate(limit); + v +} + +/// Which server programs run right now and from where, next to what the Manager made of it. A program started from a +/// folder or a copy the Manager does not know shows up here even when the Manager reports "port in use". +fn processes_report(root: &Path, ports: &layout::Ports) -> String { + let here = root.to_string_lossy().to_lowercase().replace('/', "\\"); + let listen = process::listeners_detailed(); + let mut out = String::from("Server programs running now (any folder):\n"); + let found = process::find_by_file_names(&["worldserver.exe", "authserver.exe", "mysqld.exe"]); + if found.is_empty() { out.push_str(" none\n"); } + for p in found { + let ports_of: Vec = listen.iter().filter(|l| l.pid == p.pid).map(|l| l.port.to_string()).collect(); + let inside = p.exe.to_lowercase().replace('/', "\\").starts_with(&here); + out.push_str(&format!(" pid {} {} | listening on: {} | {}\n", p.pid, p.exe, if ports_of.is_empty() { "-".into() } else { ports_of.join(", ") }, if inside { "inside this server folder" } else { "OUTSIDE this server folder" })); + } + let o = process::observe(root, ports); + out.push_str("\nThe Manager's view:\n"); + for s in [Some(&o.mysql), Some(&o.auth), Some(&o.world), o.secondary_world.as_ref()].into_iter().flatten() { + out.push_str(&format!(" {:<16} {:?} port {} {}{}\n", s.name, s.state, s.port, s.pid.map(|p| format!("pid {p}")).unwrap_or_default(), s.conflict.as_ref().map(|c| format!(" | port held by pid {} {}", c.pid, c.exe.clone().unwrap_or_default())).unwrap_or_default())); + } + out +} + /// Zip with what a maintainer needs to debug a problem, with secrets removed. Returns the number of files inside. +/// One call collects everything: the Manager's and the server's logs, crash reports and small crash dumps, Windows' +/// own record of crashes, the update journals, the running server programs and the settings the client depends on. pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &InstallMeta, report: &Report, out_zip: &Path) -> Result { + const DUMP_FILE_MAX: u64 = 30 * 1024 * 1024; let file = fs::File::create(out_zip)?; let mut zip = zip::ZipWriter::new(file); let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); @@ -195,8 +334,10 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I n += 1; Ok(()) }; + let ports = layout::read_ports(root); let summary = serde_json::json!({ "manager": crate::MANAGER_VERSION, + "exported_utc": chrono::Utc::now().to_rfc3339(), "core": meta.core, "bots": meta.bots, "squid_bots": crate::squid::release(root), @@ -206,7 +347,25 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I "wow_client_set": meta.client_path.is_some(), }); add("summary.json", serde_json::to_string_pretty(&summary)?.as_bytes())?; - for (name, path) in [("manager.log", manager_log.to_path_buf()), ("manager-install.log", meta_dir.join("logs/manager.log")), ("Server.log.tail", root.join("Core/Logs/Server.log")), ("Errors.log.tail", root.join("Core/Logs/Errors.log")), ("Auth.log.tail", root.join("Core/Logs/Auth.log")), ("world-console.log.tail", root.join("Core/Logs/world-console.log")), ("mysql-error.log.tail", root.join("mysql/logs/mysql-error.log"))] { + + // Logs. The newest update logs of the repack's own updater are added under their own names. + let mut logs: Vec<(String, PathBuf)> = vec![ + ("manager.log".into(), manager_log.to_path_buf()), + ("manager-install.log".into(), meta_dir.join("logs/manager.log")), + ("Server.log.tail".into(), root.join("Core/Logs/Server.log")), + ("Errors.log.tail".into(), root.join("Core/Logs/Errors.log")), + ("Auth.log.tail".into(), root.join("Core/Logs/Auth.log")), + ("world-console.log.tail".into(), root.join("Core/Logs/world-console.log")), + ("CoaBots.log.tail".into(), root.join("Core/Logs/CoaBots.log")), + ("Playerbots.log.tail".into(), root.join("Core/Logs/Playerbots.log")), + ("supervisor.log.tail".into(), root.join("Core/Logs/supervisor.log")), + ("mysql-error.log.tail".into(), root.join("mysql/logs/mysql-error.log")), + ]; + let updater_logs = newest_files(&root.join("Core/Logs"), "log", usize::MAX).into_iter().filter(|(p, _, _)| p.file_name().is_some_and(|f| f.to_string_lossy().to_lowercase().starts_with("update-"))); + for (p, _, _) in updater_logs.take(2) { + logs.push((format!("{}.tail", p.file_name().unwrap_or_default().to_string_lossy()), p)); + } + for (name, path) in logs { // A module that reads a missing setting on every tick fills a log with one warning, thousands of times; read far // enough back to see past that, fold the repeats, then keep the last part. let bytes = tail(&path, 8 * 1024 * 1024); @@ -214,9 +373,44 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I let text = squash_repeated_config_warnings(&String::from_utf8_lossy(&bytes)); let keep = text.len().saturating_sub(512 * 1024); let start = (keep..text.len()).find(|i| text.is_char_boundary(*i)).unwrap_or(text.len()); - add(name, redact(&text[start..]).as_bytes())?; + add(&name, redact(&text[start..]).as_bytes())?; } } + + // Crash reports of the server (text, and the small dumps next to them), and what Windows recorded for the programs. + let crashes = root.join("Core/Crashes"); + let mut listing = String::new(); + for (p, len, _) in newest_files(&crashes, "txt", 10) { + let name = p.file_name().unwrap_or_default().to_string_lossy().into_owned(); + listing.push_str(&format!("{name} ({len} bytes)\n")); + let text = String::from_utf8_lossy(&tail(&p, 1024 * 1024)).into_owned(); + add(&format!("crashes/{name}"), redact(&text).as_bytes())?; + } + for (p, len, _) in newest_files(&crashes, "dmp", 3) { + let name = p.file_name().unwrap_or_default().to_string_lossy().into_owned(); + if len > DUMP_FILE_MAX { + listing.push_str(&format!("{name} ({len} bytes) not included: larger than {} MB\n", DUMP_FILE_MAX >> 20)); + } else if let Ok(bytes) = fs::read(&p) { + listing.push_str(&format!("{name} ({len} bytes) included\n")); + add(&format!("crashes/{name}"), &bytes)?; + } + } + add("crashes.txt", if listing.is_empty() { "No crash reports in Core/Crashes.".to_string() } else { listing }.as_bytes())?; + let events = windows_events(); + if !events.is_empty() { add("windows-events.txt", events.as_bytes())?; } + add("processes.txt", processes_report(root, &ports).as_bytes())?; + + // The newest update journals: the state of each update and the reason it failed. + let mut journals: Vec<_> = fs::read_dir(meta_dir.join("updates")).into_iter().flatten().flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && e.file_name().to_string_lossy().chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))) + .collect(); + journals.sort_by_key(|e| std::cmp::Reverse(e.file_name())); + for e in journals.into_iter().take(5) { + if let Ok(text) = fs::read_to_string(e.path().join("txn.json")) { + add(&format!("updates/{}-txn.json", e.file_name().to_string_lossy()), redact_json(&text).as_bytes())?; + } + } + // Which files the server's own configuration folders hold, and the two CoA switches that decide whether the game // client can talk to the world server at all. let mut present = String::new(); @@ -244,10 +438,10 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I } } if let Ok(b) = fs::read(root.join("RELEASE.json")) { - add("RELEASE.json", redact(&String::from_utf8_lossy(&b)).as_bytes())?; + add("RELEASE.json", redact_json(&String::from_utf8_lossy(&b)).as_bytes())?; } if let Ok(b) = fs::read(meta_dir.join("logs/database-checks.json")) { - add("database-checks.json", redact(&String::from_utf8_lossy(&b)).as_bytes())?; + add("database-checks.json", redact_json(&String::from_utf8_lossy(&b)).as_bytes())?; } zip.finish().map_err(|e| Error::Invalid(e.to_string()))?; Ok(n) @@ -289,6 +483,68 @@ real error assert!(!t.contains("PASS") && !t.contains("abc")); } + #[test] + fn json_redaction_keeps_the_file_valid_and_hides_the_secrets() { + let t = redact_json(r#"{"id":"rev_20261006_token_cache","password":"hunter2","nested":{"apiKey":"k","note":"login with password=abc"},"list":[{"secret":1},"ok"]}"#); + let v: serde_json::Value = serde_json::from_str(&t).expect("still JSON"); + assert_eq!(v["id"], "rev_20261006_token_cache", "an id that merely contains a word is kept"); + assert_eq!(v["password"], "[redacted]"); + assert_eq!(v["nested"]["apiKey"], "[redacted]"); + assert_eq!(v["nested"]["note"], "[redacted]"); + assert_eq!(v["list"][0]["secret"], "[redacted]"); + assert_eq!(v["list"][1], "ok"); + assert!(!t.contains("hunter2") && !t.contains("abc")); + assert!(redact_json("not json\nPassword=1").contains("[line removed"), "text falls back to the line rule"); + } + + #[test] + fn windows_events_are_filtered_to_the_server_programs() { + let listing = "Event[0]:\n Provider Name: Application Error\n Description: Faulting application name: worldserver.exe, version: 0.0.0.0\n\nEvent[1]:\n Provider Name: Application Error\n Description: Faulting application name: notepad.exe\n\nEvent[2]:\n Description: Faulting application name: MYSQLD.EXE\n"; + let out = filter_event_blocks(listing, &["worldserver", "mysqld"], 10); + assert!(out.contains("worldserver.exe") && out.contains("MYSQLD.EXE") && !out.contains("notepad")); + assert_eq!(filter_event_blocks(listing, &["worldserver", "mysqld"], 1).matches("Event[").count(), 1); + } + + #[test] + fn event_text_loses_the_user_and_computer_lines_and_reads_utf16() { + let out = drop_identity_lines("Event[0]\n Source: Application Error\n User: S-1-5-21-1\n User Name: PC\\Dion\n Computer: PC\n Description: worldserver.exe"); + assert!(out.contains("Source") && out.contains("worldserver.exe")); + assert!(!out.contains("S-1-5") && !out.contains("Dion") && !out.contains("Computer")); + let mut bytes = vec![0xFF, 0xFE]; + for u in "Сбой worldserver".encode_utf16() { bytes.extend_from_slice(&u.to_le_bytes()); } + assert_eq!(decode_console_output(&bytes), "Сбой worldserver"); + assert_eq!(decode_console_output(b"plain"), "plain"); + } + + #[test] + fn the_package_carries_crash_reports_update_journals_and_the_process_view() { + let d = tempfile::tempdir().unwrap(); + let root = d.path().join("srv"); + layout::testkit::fake_repack(&root); + fs::create_dir_all(root.join("Core/Crashes")).unwrap(); + fs::write(root.join("Core/Crashes/567e_worldserver.exe_[4-10_21-25-31].txt"), "Exception code: C0000005\nRCX:0\n").unwrap(); + fs::write(root.join("Core/Crashes/567e_worldserver.exe_[4-10_21-25-31].dmp"), b"MDMP-small").unwrap(); + fs::write(root.join("Core/Logs/CoaBots.log"), "bot line\n").unwrap(); + fs::write(root.join("Core/Logs/update-1.8-20261005.log"), "updater line\n").unwrap(); + let meta_dir = d.path().join("srv.manager"); + fs::create_dir_all(meta_dir.join("updates/20261006-082021-0_261006_1-abc")).unwrap(); + fs::write(meta_dir.join("updates/20261006-082021-0_261006_1-abc/txn.json"), r#"{"state":"rolled-back","message":"Database update 2026_02_24_00 failed: duplicate column"}"#).unwrap(); + fs::create_dir_all(meta_dir.join("updates/not a journal!")).unwrap(); + let meta = InstallMeta::new(InstallKind::Imported, &root); + let report = run(&root, &meta); + let zip_path = d.path().join("diag.zip"); + export_package(&root, &meta_dir, &d.path().join("none.log"), &meta, &report, &zip_path).unwrap(); + let mut z = zip::ZipArchive::new(fs::File::open(&zip_path).unwrap()).unwrap(); + let names: Vec = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).collect(); + for want in ["crashes.txt", "processes.txt", "CoaBots.log.tail", "update-1.8-20261005.log.tail", "updates/20261006-082021-0_261006_1-abc-txn.json", "crashes/567e_worldserver.exe_[4-10_21-25-31].txt", "crashes/567e_worldserver.exe_[4-10_21-25-31].dmp"] { + assert!(names.iter().any(|n| n == want), "{want} is in the package: {names:?}"); + } + assert!(!names.iter().any(|n| n.contains("not a journal"))); + let mut listing = String::new(); + z.by_name("crashes.txt").unwrap().read_to_string(&mut listing).unwrap(); + assert!(listing.contains("included")); + } + #[test] fn verify_reports_missing_and_changed_managed_files_only() { let d = tempfile::tempdir().unwrap(); diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index 38502dc..968a16d 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -37,6 +37,7 @@ pub mod realmlist; pub mod realms; pub mod registry; pub mod release; +pub mod report; pub mod release_schema; pub mod update; pub mod upnp; diff --git a/crates/coa-core/src/process.rs b/crates/coa-core/src/process.rs index 6f157b0..646eead 100644 --- a/crates/coa-core/src/process.rs +++ b/crates/coa-core/src/process.rs @@ -250,6 +250,19 @@ pub fn is_alive(record: &ProcessIdentity) -> bool { identity(record.pid).map(|cur| cur.same_as(record)).unwrap_or(false) } +/// Every running process whose image file is named one of `names` (compared without case), wherever it lives. Only for +/// diagnostics: a process found this way is not trusted to belong to any installation. +pub fn find_by_file_names(names: &[&str]) -> Vec { + sys::all_pids() + .into_iter() + .filter_map(identity) + .filter(|p| { + let file = p.exe.rsplit(['\\', '/']).next().unwrap_or(""); + names.iter().any(|n| file.eq_ignore_ascii_case(n)) + }) + .collect() +} + /// Every running process whose image is exactly `exe`. pub fn find_by_exe(exe: &Path) -> Vec { let want = exe.to_string_lossy().to_lowercase().replace('/', "\\"); diff --git a/crates/coa-core/src/report.rs b/crates/coa-core/src/report.rs new file mode 100644 index 0000000..0509052 --- /dev/null +++ b/crates/coa-core/src/report.rs @@ -0,0 +1,116 @@ +//! Where a problem report goes. A report about the bots goes to the repository of the bot system in question, anything +//! else to the Manager's own. The repositories come from the module catalog, so there is one list to keep right. + +use std::path::Path; + +use serde::Serialize; + +pub const MANAGER_REPO: &str = "Corfirean/coa-server-manager"; + +/// One place a report can be filed. `id` is what the page sends back; `repo` is `owner/name` on GitHub. +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +pub struct Target { + pub id: &'static str, + pub repo: String, + /// The report form asks for the Manager's labels only where we own the repository. + pub ours: bool, +} + +/// `https://github.com/owner/name/tree/main/x` -> `owner/name`. +fn repo_of(url: &str) -> Option { + let rest = url.strip_prefix("https://github.com/")?; + let mut parts = rest.split('/'); + let (owner, name) = (parts.next()?, parts.next()?); + let ok = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)); + (ok(owner) && ok(name)).then(|| format!("{owner}/{name}")) +} + +fn catalog_repo(id: &str) -> Option { + crate::modules::catalog().into_iter().find(|e| e.id == id).and_then(|e| repo_of(&e.repo)) +} + +/// The three places, in the order the page lists them. A bot system whose repository is unknown falls back to the Manager's. +pub fn targets() -> Vec { + let mut v = vec![Target { id: "manager", repo: MANAGER_REPO.into(), ours: true }]; + for (id, module) in [("companions", "companions"), ("squid", "playerbots")] { + if let Some(repo) = catalog_repo(module) { + v.push(Target { id, repo: repo.clone(), ours: repo.starts_with("Corfirean/") }); + } + } + v +} + +pub fn target(id: &str) -> Option { + targets().into_iter().find(|t| t.id == id) +} + +/// True for the "new issue" page of one of the targets: exactly that page, optionally with a query. +pub fn is_new_issue_url(url: &str) -> bool { + targets().iter().any(|t| { + let base = format!("https://github.com/{}/issues/new", t.repo); + url == base || url.starts_with(&format!("{base}?")) + }) +} + +/// What the report form fills in about the bot systems of this server. +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +pub struct Bots { + /// The target the form should start with: the bot system that is switched on, else the Manager. + pub suggested: &'static str, + /// The release of SQUID Playerbots, when it is the one switched on. + pub squid_version: Option, +} + +pub fn bots(root: &Path) -> Bots { + let list = crate::modules::list(root); + let on = |id: &str| list.iter().find(|m| m.id == id).filter(|m| m.installed && m.enabled); + let squid = on("playerbots"); + Bots { + suggested: if squid.is_some() { "squid" } else if on("companions").is_some() { "companions" } else { "manager" }, + squid_version: squid.and_then(|m| m.version.clone()).filter(|v| !v.is_empty()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_three_targets_come_from_the_catalog() { + let t = targets(); + let repo = |id: &str| t.iter().find(|x| x.id == id).map(|x| x.repo.clone()); + assert_eq!(repo("manager").as_deref(), Some("Corfirean/coa-server-manager")); + assert_eq!(repo("companions").as_deref(), Some("Corfirean/mod-coa-playerbots")); + assert_eq!(repo("squid").as_deref(), Some("Zyth45/mod-playerbots")); + assert!(t.iter().find(|x| x.id == "squid").is_some_and(|x| !x.ours)); + } + + #[test] + fn repository_names_are_read_from_module_links() { + assert_eq!(repo_of("https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/x").as_deref(), Some("Corfirean/azerothcore-wotlk-coa")); + assert_eq!(repo_of("https://github.com/Zyth45/mod-playerbots").as_deref(), Some("Zyth45/mod-playerbots")); + assert_eq!(repo_of("https://example.com/a/b"), None); + assert_eq!(repo_of("https://github.com/a"), None); + } + + #[test] + fn only_the_new_issue_pages_of_the_targets_are_allowed() { + assert!(is_new_issue_url("https://github.com/Zyth45/mod-playerbots/issues/new")); + assert!(is_new_issue_url("https://github.com/Corfirean/mod-coa-playerbots/issues/new?title=a&body=b")); + assert!(!is_new_issue_url("https://github.com/Zyth45/mod-playerbots/issues/newer")); + assert!(!is_new_issue_url("https://github.com/Zyth45/other/issues/new")); + assert!(!is_new_issue_url("https://evil.example/Corfirean/coa-server-manager/issues/new")); + } + + #[test] + fn the_suggested_target_follows_the_bot_system_that_is_on() { + let d = tempfile::tempdir().unwrap(); + let root = d.path().join("srv"); + crate::layout::testkit::fake_repack(&root); + let conf = root.join("Core/configs/modules"); + std::fs::write(conf.join("mod_coa_playerbots.conf"), "CoaBots.Enable = 1\n").unwrap(); + assert_eq!(bots(&root).suggested, "companions"); + std::fs::write(conf.join("mod_coa_playerbots.conf"), "CoaBots.Enable = 0\n").unwrap(); + assert_eq!(bots(&root).suggested, "manager"); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index e930549..0af0ae9 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1265,10 +1265,9 @@ struct FriendsStatus { #[tauri::command] fn open_link(url: String) -> std::result::Result<(), UiError> { const ALLOWED: &[&str] = &["https://tailscale.com/", "https://login.tailscale.com/", "https://portforward.com/", "https://github.com/Corfirean/"]; - // A prefilled "new issue" page of this project: the address must be exactly that page, and its query may carry - // `&` between the (percent-encoded) title and text. - const NEW_ISSUE: &str = "https://github.com/Corfirean/coa-server-manager/issues/new"; - let issue = url == NEW_ISSUE || url.starts_with(&format!("{NEW_ISSUE}?")); + // A prefilled "new issue" page of one of the places a report can go (the Manager, Companions, SQUID Playerbots): the + // address must be exactly that page, and its query may carry `&` between the (percent-encoded) title and text. + let issue = coa_core::report::is_new_issue_url(&url); let chars_ok = url.chars().all(|c| c.is_ascii_alphanumeric() || "/:._-?=#%".contains(c) || (issue && c == '&')); // the GitHub page of a module that is in the bundled catalog (some are not ours) let catalog = coa_core::modules::catalog().iter().any(|e| e.repo == url); @@ -1286,6 +1285,16 @@ struct ReportContext { /// "new" for a server the Manager installed, "imported" for one that was added. install_kind: String, server_version: Option, + /// Where the form should start: the bot system that is switched on, else the Manager. + suggested_target: String, + /// The release of whichever bot system is on, for a report that goes to its repository. + bots_version: Option, +} + +/// The places a report can go, each with its GitHub repository. +#[tauri::command] +fn report_targets() -> Vec { + coa_core::report::targets() } /// "Windows 11 (build 26200)" from `ver`; empty if it cannot be read. @@ -1312,11 +1321,15 @@ async fn report_context(state: State<'_, AppState>, id: String) -> std::result:: let root = path_of(&state, &id)?; blocking(move || { let (_, meta) = install_meta(&root)?; + let bots = coa_core::report::bots(&root); + let companions = [meta.bots.version.clone(), meta.bots.commit.as_ref().map(|c| c.chars().take(8).collect())].into_iter().flatten().collect::>().join(" · "); Ok(ReportContext { manager_version: coa_core::MANAGER_VERSION.to_string(), windows: windows_version(), install_kind: if meta.kind == coa_core::registry::InstallKind::New { "new".into() } else { "imported".into() }, server_version: meta.core.version.clone(), + suggested_target: bots.suggested.to_string(), + bots_version: if bots.suggested == "squid" { bots.squid_version } else if bots.suggested == "companions" && !companions.is_empty() { Some(companions) } else { None }, }) }) .await @@ -1470,6 +1483,8 @@ async fn export_diagnostics(state: State<'_, AppState>, id: String) -> std::resu let report = coa_core::diag::run(&root, &meta); let out = coa_core::diag::desktop_or_temp().join(format!("CoA-Diagnostics-{}.zip", coa_core::diag::stamp())); coa_core::diag::export_package(&root, &dir, &data_dir().join("logs").join("manager.log"), &meta, &report, &out)?; + // Show the file in its folder so nobody has to look for it; failing to open the folder is not a failure. + let _ = tauri_plugin_opener::reveal_item_in_dir(&out); Ok(out.to_string_lossy().into_owned()) }) .await @@ -1579,6 +1594,7 @@ pub fn run() { companions_delete_all, companions_despawn_some, open_link, + report_targets, companion_sizes, add_companions, remote_connection, diff --git a/src/dev/mock.ts b/src/dev/mock.ts index e3ac63f..cba1688 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -87,7 +87,8 @@ export {}; return (S[args.module]??[]).map(s => ({...s, value: moduleEdits[args.module]?.[s.key] ?? s.value})); } if(cmd==="module_save_settings") { moduleEdits[args.module] = {...moduleEdits[args.module], ...args.changes}; return Object.keys(args.changes); } - if(cmd==="report_context") return {manager_version:"0.3.1",windows:"Windows 11 (build 26200)",install_kind:"new",server_version:"0.261001.10"}; + if(cmd==="report_context") return {manager_version:"0.3.1",windows:"Windows 11 (build 26200)",install_kind:"new",server_version:"0.261001.10",suggested_target:"companions",bots_version:"0.2.1 · 1a2b3c4d"}; + if(cmd==="report_targets") return [{id:"manager",repo:"Corfirean/coa-server-manager",ours:true},{id:"companions",repo:"Corfirean/mod-coa-playerbots",ours:true},{id:"squid",repo:"Zyth45/mod-playerbots",ours:false}]; if(cmd==="open_link"){(window as any).__lastLink=args.url;return null;} if(cmd==="export_diagnostics") return "C:\\Users\\you\\Desktop\\CoA-Diagnostics-20261001-140000.zip"; if(cmd==="install_preflight") return {ok:true,problems:[],free_bytes:210*2**30}; diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index e825ce1..09ffffe 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -702,9 +702,9 @@ const de: Partial> = { "rep.expectedHint": "Beschreibe das erwartete Verhalten.", "rep.steps": "Schritte zum Nachstellen", "rep.attachTitle": "Logs und Screenshots", - "rep.attachText": "Erstelle eine Diagnosedatei (Einstellungen und Logs ohne Passwörter und Adressen) und ziehe sie zusammen mit Screenshots oder Videos auf die GitHub-Seite, sobald sie offen ist.", + "rep.attachText": "Ein Klick sammelt die Diagnose: Logs des Managers und des Servers, Absturzberichte, Windows-Absturzeinträge und Update-Protokolle, ohne Passwörter und Adressen. Der Ordner mit der Datei wird geöffnet; ziehe die Datei zusammen mit Screenshots oder Videos auf die GitHub-Seite.", "rep.makeFile": "Diagnosedatei erstellen", - "rep.fileSaved": "Gespeichert unter {path}. Ziehe diese Datei in das GitHub-Issue.", + "rep.fileSaved": "Gespeichert unter {path}. Der Ordner wurde geöffnet. Ziehe diese Datei in das GitHub-Issue.", "rep.privacy": "Bitte entferne Passwörter, Tokens, private IP-Angaben und andere sensible Daten, bevor du Logs veröffentlichst.", "rep.open": "Bericht auf GitHub öffnen", "rep.copy": "Text kopieren", @@ -714,6 +714,17 @@ const de: Partial> = { "rep.opened": "GitHub wurde im Browser geöffnet. Prüfe den Text, hänge Dateien an und klicke auf „Submit new issue“.", "rep.openedLong": "Der Bericht ist für einen Link zu lang und wurde deshalb in die Zwischenablage kopiert. GitHub ist geöffnet: Füge ihn (Strg+V) in die Beschreibung ein, hänge Dateien an und klicke auf „Submit new issue“.", "rep.copied": "In die Zwischenablage kopiert.", + "rep.targetTitle": "Worum geht es bei dem Problem?", + "rep.target.manager": "CoA Server Manager, der Server oder andere Module", + "rep.target.companions": "CoA Companions (Bots und das CoABotUI-Addon)", + "rep.target.squid": "SQUID Playerbots", + "rep.targetPublic": "Der Bericht wird öffentlich auf GitHub in {repo} veröffentlicht.", + "rep.botsVersion": "Bot-Version", + "rep.withDiag": "Diagnose für mich sammeln (empfohlen)", + "rep.collectOpen": "Diagnose sammeln und Bericht öffnen", + "rep.collecting": "Diagnose wird gesammelt…", + "overview.reportHint": "Ein Dienst wurde von selbst beendet?", + "overview.reportBtn": "Diagnose sammeln und melden", // Realmlist switcher and modules page "realm.profileLabel": "Realm", diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index d63d4b4..0ffc0c8 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -735,9 +735,9 @@ const en = { "rep.expectedHint": "Describe the expected behaviour.", "rep.steps": "Steps to reproduce", "rep.attachTitle": "Logs and screenshots", - "rep.attachText": "Create a diagnostics file (settings and logs with passwords and addresses removed) and drag it, together with any screenshot or video, into the GitHub page once it is open.", + "rep.attachText": "One click collects the diagnostics: the Manager's and the server's logs, crash reports, Windows crash records and update journals, with passwords and addresses removed. The file's folder opens; drag the file, together with any screenshot or video, into the GitHub page.", "rep.makeFile": "Create the diagnostics file", - "rep.fileSaved": "Saved to {path}. Drag this file into the GitHub issue.", + "rep.fileSaved": "Saved to {path}. The folder was opened. Drag this file into the GitHub issue.", "rep.privacy": "Please remove passwords, tokens, private IP information or other sensitive data before posting logs.", "rep.open": "Open the report on GitHub", "rep.copy": "Copy the text", @@ -747,6 +747,17 @@ const en = { "rep.opened": "GitHub was opened in your browser. Check the text, attach files and press Submit new issue.", "rep.openedLong": "The report is too long for a link, so it was copied to the clipboard. GitHub is open: paste it (Ctrl+V) into the description, attach files and press Submit new issue.", "rep.copied": "Copied to the clipboard.", + "rep.targetTitle": "What is the problem about?", + "rep.target.manager": "CoA Server Manager, the server or other modules", + "rep.target.companions": "CoA Companions (bots and the CoABotUI addon)", + "rep.target.squid": "SQUID Playerbots", + "rep.targetPublic": "The report will be public on GitHub in {repo}.", + "rep.botsVersion": "Bot release", + "rep.withDiag": "Collect the diagnostics for me (recommended)", + "rep.collectOpen": "Collect diagnostics and open the report", + "rep.collecting": "Collecting diagnostics…", + "overview.reportHint": "A service stopped on its own?", + "overview.reportBtn": "Collect diagnostics and report", // Realmlist switcher and modules page "realm.label": "Realm", diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index c68bcfa..6348432 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -702,9 +702,9 @@ const es: Partial> = { "rep.expectedHint": "Describe el comportamiento esperado.", "rep.steps": "Pasos para reproducirlo", "rep.attachTitle": "Registros y capturas", - "rep.attachText": "Crea un archivo de diagnóstico (ajustes y registros sin contraseñas ni direcciones) y arrástralo, junto con capturas o vídeos, a la página de GitHub cuando se abra.", + "rep.attachText": "Un clic reúne el diagnóstico: registros del Manager y del servidor, informes de fallos, registros de fallos de Windows y diarios de actualización, sin contraseñas ni direcciones. Se abre la carpeta del archivo; arrástralo, junto con capturas o vídeos, a la página de GitHub.", "rep.makeFile": "Crear el archivo de diagnóstico", - "rep.fileSaved": "Guardado en {path}. Arrastra este archivo al issue de GitHub.", + "rep.fileSaved": "Guardado en {path}. Se abrió la carpeta. Arrastra este archivo al issue de GitHub.", "rep.privacy": "Elimina contraseñas, tokens, información de IP privada y otros datos sensibles antes de publicar registros.", "rep.open": "Abrir el informe en GitHub", "rep.copy": "Copiar el texto", @@ -714,6 +714,17 @@ const es: Partial> = { "rep.opened": "GitHub se abrió en tu navegador. Revisa el texto, adjunta archivos y pulsa «Submit new issue».", "rep.openedLong": "El informe es demasiado largo para un enlace, así que se copió al portapapeles. GitHub está abierto: pégalo (Ctrl+V) en la descripción, adjunta archivos y pulsa «Submit new issue».", "rep.copied": "Copiado al portapapeles.", + "rep.targetTitle": "¿Sobre qué es el problema?", + "rep.target.manager": "CoA Server Manager, el servidor u otros módulos", + "rep.target.companions": "CoA Companions (bots y el addon CoABotUI)", + "rep.target.squid": "SQUID Playerbots", + "rep.targetPublic": "El informe será público en GitHub, en {repo}.", + "rep.botsVersion": "Versión de los bots", + "rep.withDiag": "Reunir el diagnóstico por mí (recomendado)", + "rep.collectOpen": "Reunir el diagnóstico y abrir el informe", + "rep.collecting": "Reuniendo el diagnóstico…", + "overview.reportHint": "¿Un servicio se detuvo solo?", + "overview.reportBtn": "Reunir el diagnóstico y avisar", // Realmlist switcher and modules page "realm.profileLabel": "Reino", diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 6f0ab00..53fb85e 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -702,9 +702,9 @@ const fr: Partial> = { "rep.expectedHint": "Décrivez le comportement attendu.", "rep.steps": "Étapes pour reproduire", "rep.attachTitle": "Journaux et captures d’écran", - "rep.attachText": "Créez un fichier de diagnostic (réglages et journaux sans mots de passe ni adresses) et glissez-le, avec vos captures ou vidéos, sur la page GitHub une fois ouverte.", + "rep.attachText": "Un clic rassemble le diagnostic : journaux du Manager et du serveur, rapports de plantage, enregistrements de plantage de Windows et journaux de mise à jour, sans mots de passe ni adresses. Le dossier du fichier s’ouvre ; glissez le fichier, avec vos captures ou vidéos, sur la page GitHub.", "rep.makeFile": "Créer le fichier de diagnostic", - "rep.fileSaved": "Enregistré dans {path}. Glissez ce fichier dans l’issue GitHub.", + "rep.fileSaved": "Enregistré dans {path}. Le dossier a été ouvert. Glissez ce fichier dans l’issue GitHub.", "rep.privacy": "Veuillez retirer les mots de passe, jetons, adresses IP privées et autres données sensibles avant de publier des journaux.", "rep.open": "Ouvrir le rapport sur GitHub", "rep.copy": "Copier le texte", @@ -714,6 +714,17 @@ const fr: Partial> = { "rep.opened": "GitHub s’est ouvert dans votre navigateur. Vérifiez le texte, joignez les fichiers et appuyez sur « Submit new issue ».", "rep.openedLong": "Le rapport est trop long pour un lien : il a été copié dans le presse-papiers. GitHub est ouvert : collez-le (Ctrl+V) dans la description, joignez les fichiers et appuyez sur « Submit new issue ».", "rep.copied": "Copié dans le presse-papiers.", + "rep.targetTitle": "De quoi parle le problème ?", + "rep.target.manager": "CoA Server Manager, le serveur ou d’autres modules", + "rep.target.companions": "CoA Companions (bots et addon CoABotUI)", + "rep.target.squid": "SQUID Playerbots", + "rep.targetPublic": "Le rapport sera public sur GitHub dans {repo}.", + "rep.botsVersion": "Version des bots", + "rep.withDiag": "Rassembler le diagnostic pour moi (recommandé)", + "rep.collectOpen": "Rassembler le diagnostic et ouvrir le rapport", + "rep.collecting": "Collecte du diagnostic…", + "overview.reportHint": "Un service s’est arrêté tout seul ?", + "overview.reportBtn": "Rassembler le diagnostic et signaler", // Realmlist switcher and modules page "realm.profileLabel": "Royaume", diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index bef5677..5ddfb15 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -733,9 +733,9 @@ const ru: Partial> = { "rep.expectedHint": "Опишите ожидаемое поведение.", "rep.steps": "Как воспроизвести", "rep.attachTitle": "Логи и скриншоты", - "rep.attachText": "Создайте файл диагностики (настройки и логи без паролей и адресов) и перетащите его вместе со скриншотами или видео на страницу GitHub, когда она откроется.", + "rep.attachText": "Диагностика собирается одним нажатием: логи менеджера и сервера, отчёты о падениях, записи Windows о сбоях и журналы обновлений, без паролей и адресов. Откроется папка с файлом; перетащите его вместе со скриншотами или видео на страницу GitHub.", "rep.makeFile": "Создать файл диагностики", - "rep.fileSaved": "Сохранено: {path}. Перетащите этот файл в issue на GitHub.", + "rep.fileSaved": "Сохранено: {path}. Папка открыта. Перетащите этот файл в issue на GitHub.", "rep.privacy": "Перед публикацией логов удалите пароли, токены, частные IP-адреса и другие личные данные.", "rep.open": "Открыть отчёт на GitHub", "rep.copy": "Копировать текст", @@ -745,6 +745,17 @@ const ru: Partial> = { "rep.opened": "GitHub открыт в браузере. Проверьте текст, прикрепите файлы и нажмите «Submit new issue».", "rep.openedLong": "Отчёт слишком длинный для ссылки, поэтому он скопирован в буфер обмена. GitHub открыт: вставьте текст (Ctrl+V) в описание, прикрепите файлы и нажмите «Submit new issue».", "rep.copied": "Скопировано в буфер обмена.", + "rep.targetTitle": "О чём проблема?", + "rep.target.manager": "CoA Server Manager, сервер или другие модули", + "rep.target.companions": "CoA Companions (боты и аддон CoABotUI)", + "rep.target.squid": "SQUID Playerbots", + "rep.targetPublic": "Репорт будет публичным на GitHub в {repo}.", + "rep.botsVersion": "Версия ботов", + "rep.withDiag": "Собрать диагностику за меня (рекомендуется)", + "rep.collectOpen": "Собрать диагностику и открыть репорт", + "rep.collecting": "Собираю диагностику…", + "overview.reportHint": "Служба остановилась сама?", + "overview.reportBtn": "Собрать диагностику и сообщить", // Realmlist switcher and modules page "realm.label": "Реалм", diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index 45c397a..b0965a5 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -714,9 +714,9 @@ const zh = { "rep.expectedHint": "描述你期望的正常表现。", "rep.steps": "复现步骤", "rep.attachTitle": "日志与截图附件", - "rep.attachText": "生成一份诊断包文件(已自动脱敏密码与私有 IP 等敏感信息),并在浏览器打开 GitHub 页面后,将其连同截图或录屏一起拖拽上传。", + "rep.attachText": "一键收集诊断信息:管理器与服务器日志、崩溃报告、Windows 崩溃记录和更新日志(已去除密码与地址)。文件所在文件夹会自动打开;请将该文件连同截图或录屏一起拖入 GitHub 页面。", "rep.makeFile": "生成诊断包文件", - "rep.fileSaved": "已保存至 {path}。请将该文件拖入 GitHub Issue 中。", + "rep.fileSaved": "已保存至 {path}。文件夹已打开。请将该文件拖入 GitHub Issue 中。", "rep.privacy": "上传前请注意检查并移除日志中可能包含的私有密码、Token 或其他敏感隐私信息。", "rep.open": "在 GitHub 上打开报告", "rep.copy": "复制报告文本", @@ -726,6 +726,17 @@ const zh = { "rep.opened": "已在浏览器中打开 GitHub。请检查内容、附上日志文件并点击“Submit new issue”。", "rep.openedLong": "报告内容较长超出 URL 长度限制,已自动复制到剪贴板。请在已打开的 GitHub 页面中按 Ctrl+V 粘贴描述,附上文件后提交。", "rep.copied": "已复制到剪贴板。", + "rep.targetTitle": "问题与什么有关?", + "rep.target.manager": "CoA Server Manager、服务器或其他模块", + "rep.target.companions": "CoA Companions(机器人与 CoABotUI 插件)", + "rep.target.squid": "SQUID Playerbots", + "rep.targetPublic": "该报告将公开发布在 GitHub 的 {repo}。", + "rep.botsVersion": "机器人版本", + "rep.withDiag": "替我收集诊断信息(推荐)", + "rep.collectOpen": "收集诊断信息并打开报告", + "rep.collecting": "正在收集诊断信息…", + "overview.reportHint": "某个服务自己停止了?", + "overview.reportBtn": "收集诊断信息并反馈", // Realmlist switcher and modules page "realm.label": "服务器列表", diff --git a/src/lib/api.ts b/src/lib/api.ts index c3f239d..773a0ba 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -234,6 +234,19 @@ export interface ReportContext { windows: string; install_kind: "new" | "imported"; server_version: string | null; + /** where the form starts: the bot system that is switched on, else the Manager */ + suggested_target: ReportTargetId; + /** the release of the bot system that is on */ + bots_version: string | null; +} + +export type ReportTargetId = "manager" | "companions" | "squid"; + +/** A place a problem report can go: its GitHub repository as `owner/name`. */ +export interface ReportTarget { + id: ReportTargetId; + repo: string; + ours: boolean; } export interface InstallRequirements { @@ -419,6 +432,7 @@ export const api = { allSettings: (id: string) => invoke("all_settings", { id }), allSettingsSave: (id: string, changes: Record) => invoke("all_settings_save", { id, changes }), reportContext: (id: string) => invoke("report_context", { id }), + reportTargets: () => invoke("report_targets"), listAccounts: (id: string) => invoke("list_accounts", { id }), accountSetPassword: (id: string, name: string, password: string) => invoke("account_set_password", { id, name, password }), accountSetAccess: (id: string, name: string, level: number) => invoke("account_set_access", { id, name, level }), diff --git a/src/lib/report.ts b/src/lib/report.ts index aca699f..b3669b3 100644 --- a/src/lib/report.ts +++ b/src/lib/report.ts @@ -1,9 +1,14 @@ +import type { ReportTarget, ReportTargetId } from "./api"; + /** The text of a problem report, always in English so whoever reads it on GitHub can follow it; the person's own words go in as typed. */ export interface ReportInput { managerVersion: string; windows: string; installKind: "new" | "imported"; serverVersion: string | null; + /** where the report goes; a bot repository is told which Manager and bot release it came from */ + target: ReportTargetId; + botsVersion: string | null; what: string; expected: string; steps: string; @@ -11,7 +16,10 @@ export interface ReportInput { diagnostics: boolean; } -export const NEW_ISSUE_URL = "https://github.com/Corfirean/coa-server-manager/issues/new"; +/** The "new issue" page of a repository given as `owner/name`. */ +export function newIssueUrl(repo: string): string { + return `https://github.com/${repo}/issues/new`; +} const PRIVACY = "> Please remove passwords, tokens, private IP information or other sensitive data before posting logs."; export function reportBody(r: ReportInput): string { @@ -23,6 +31,7 @@ export function reportBody(r: ReportInput): string { `**Windows version:** ${r.windows || "unknown"} `, `**Fresh install or imported server:** ${r.installKind === "new" ? "Fresh install" : "Imported server"} `, ...(r.serverVersion ? [`**Server version:** ${r.serverVersion} `] : []), + ...(r.target !== "manager" ? [`**Bot system:** ${r.target === "squid" ? "SQUID Playerbots" : "CoA Companions"}${r.botsVersion ? ` ${r.botsVersion}` : ""} `] : []), "", "**What happened?** ", text(r.what, "Describe the problem."), @@ -54,9 +63,9 @@ export function encodeQuery(s: string): string { .join(""); } -/** A link that opens GitHub's "new issue" page with the title and text filled in. */ -export function issueUrl(title: string, body: string): string { - return `${NEW_ISSUE_URL}?labels=bug&title=${encodeQuery(title)}&body=${encodeQuery(body)}`; +/** A link that opens GitHub's "new issue" page of `target` with the title and text filled in. The bug label is only asked for in our own repositories. */ +export function issueUrl(target: Pick, title: string, body: string): string { + return `${newIssueUrl(target.repo)}?${target.ours ? "labels=bug&" : ""}title=${encodeQuery(title)}&body=${encodeQuery(body)}`; } /** Links longer than this are not reliable in every browser; the full text is then copied to the clipboard instead. */ diff --git a/src/screens/Overview.tsx b/src/screens/Overview.tsx index 0dbae98..a288bb7 100644 --- a/src/screens/Overview.tsx +++ b/src/screens/Overview.tsx @@ -64,7 +64,7 @@ function Row({ label, s }: { label: string; s: ServiceStatus }) { ); } -export function Overview({ server, companions = true, onForget, onOpenUpdates, onRealmChanged }: { server: ServerSummary; /** the companions module is on */ companions?: boolean; onForget: () => Promise; onOpenUpdates: () => void; onRealmChanged: () => void }) { +export function Overview({ server, companions = true, onForget, onOpenUpdates, onRealmChanged, onReport }: { server: ServerSummary; /** the companions module is on */ companions?: boolean; onForget: () => Promise; onOpenUpdates: () => void; onRealmChanged: () => void; /** open the problem report, which collects the diagnostics */ onReport: () => void }) { const t = useT(); const human = useHuman(); const [status, setStatus] = useState(null); @@ -228,6 +228,12 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o /> {headline} + {!transitioning && !running && anyUp && ( +

+ {t("overview.reportHint")}{" "} + +

+ )}
diff --git a/src/screens/ReportPage.tsx b/src/screens/ReportPage.tsx index 65da14e..07fe1ab 100644 --- a/src/screens/ReportPage.tsx +++ b/src/screens/ReportPage.tsx @@ -1,22 +1,36 @@ -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useState } from "react"; import { Loader2 } from "lucide-react"; -import { api, asUiError, type ReportContext, type UiError } from "@/lib/api"; +import { api, asUiError, type ReportContext, type ReportTarget, type ReportTargetId, type UiError } from "@/lib/api"; import { MAX_LINK, issueUrl, reportBody } from "@/lib/report"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; -import { useHuman, useT } from "@/i18n"; +import { useHuman, useT, type Key } from "@/i18n"; const field = "mt-1 block w-full rounded-md border border-line bg-bg px-3 py-2.5 text-[15px] outline-none focus:border-gold"; -/** A problem report that becomes a prefilled GitHub issue. Nothing is sent from here: the person reviews and submits it on GitHub. */ +const TARGET_LABEL: Record = { + manager: "rep.target.manager", + companions: "rep.target.companions", + squid: "rep.target.squid", +}; + +const FALLBACK: ReportTarget = { id: "manager", repo: "Corfirean/coa-server-manager", ours: true }; + +/** + * A problem report that becomes a prefilled GitHub issue in the repository of whatever it is about. One button collects + * the diagnostics (and shows the file in its folder) and opens the issue; the person reviews it and submits it on GitHub. + */ export function ReportPage({ serverId }: { serverId: string }) { const t = useT(); const human = useHuman(); const [ctx, setCtx] = useState(null); + const [targets, setTargets] = useState([]); + const [targetId, setTargetId] = useState(null); const [title, setTitle] = useState(""); const [what, setWhat] = useState(""); const [expected, setExpected] = useState(""); const [steps, setSteps] = useState(""); + const [withDiag, setWithDiag] = useState(true); const [file, setFile] = useState(null); const [busy, setBusy] = useState(false); const [note, setNote] = useState(null); @@ -25,30 +39,44 @@ export function ReportPage({ serverId }: { serverId: string }) { useEffect(() => { void api.reportContext(serverId).then(setCtx).catch(() => setCtx(null)); + void api.reportTargets().then(setTargets).catch(() => setTargets([])); }, [serverId]); - const body = useMemo( - () => - reportBody({ - managerVersion: ctx?.manager_version ?? "", - windows: ctx?.windows ?? "", - installKind: ctx?.install_kind ?? "new", - serverVersion: ctx?.server_version ?? null, - what, - expected, - steps, - diagnostics: file !== null, - }), - [ctx, what, expected, steps, file], - ); - const issueTitle = `[Bug] ${title.trim()}`; + // start on the bot system that is switched on, until the person picks one + const chosen: ReportTargetId = targetId ?? ctx?.suggested_target ?? "manager"; + const shown = targets.length ? targets : [FALLBACK]; + const target = shown.find((x) => x.id === chosen) ?? shown[0]; + + function bodyFor(hasFile: boolean): string { + return reportBody({ + managerVersion: ctx?.manager_version ?? "", + windows: ctx?.windows ?? "", + installKind: ctx?.install_kind ?? "new", + serverVersion: ctx?.server_version ?? null, + target: target.id, + botsVersion: ctx?.bots_version ?? null, + what, + expected, + steps, + diagnostics: hasFile, + }); + } + const issueTitle = target.ours ? `[Bug] ${title.trim()}` : title.trim(); const ready = title.trim().length > 0 && what.trim().length > 0; - async function makeFile() { + /** Collects the diagnostics once; the Manager shows the file in its folder. */ + async function collect(): Promise { + if (file) return file; + const path = await api.exportDiagnostics(serverId); + setFile(path); + return path; + } + + async function collectOnly() { setBusy(true); setError(null); try { - setFile(await api.exportDiagnostics(serverId)); + await collect(); } catch (e) { setError(asUiError(e)); } finally { @@ -56,26 +84,32 @@ export function ReportPage({ serverId }: { serverId: string }) { } } + /** One button: collect the diagnostics (if asked), then open the issue with everything filled in. */ async function openIssue() { + setBusy(true); setError(null); setNote(null); try { - const full = issueUrl(issueTitle, body); + const path = withDiag ? await collect() : null; + const body = bodyFor(path !== null); + const full = issueUrl(target, issueTitle, body); if (full.length <= MAX_LINK) { await api.openLink(full); setNote(t("rep.opened")); } else { await navigator.clipboard.writeText(body); - await api.openLink(issueUrl(issueTitle, "Paste the report text here (it was copied to the clipboard by CoA Server Manager).")); + await api.openLink(issueUrl(target, issueTitle, "Paste the report text here (it was copied to the clipboard by CoA Server Manager).")); setNote(t("rep.openedLong")); } } catch (e) { setError(asUiError(e)); + } finally { + setBusy(false); } } async function copy() { - await navigator.clipboard.writeText(`${issueTitle}\n\n${body}`); + await navigator.clipboard.writeText(`${issueTitle}\n\n${bodyFor(file !== null)}`); setNote(t("rep.copied")); } @@ -85,6 +119,22 @@ export function ReportPage({ serverId }: { serverId: string }) {

{t("q.report")}

{t("rep.intro")}

+ +

{t("rep.targetTitle")}

+
+ {shown.map((x) => ( + + ))} +
+

{t("rep.targetPublic", { repo: target.repo })}

+
+

{t("rep.autoTitle")}

@@ -100,6 +150,12 @@ export function ReportPage({ serverId }: { serverId: string }) {
{ctx.server_version}
)} + {target.id !== "manager" && ctx?.bots_version && ( + <> +
{t("rep.botsVersion")}
+
{ctx.bots_version}
+ + )}
@@ -125,16 +181,20 @@ export function ReportPage({ serverId }: { serverId: string }) {

{t("rep.attachTitle")}

{t("rep.attachText")}

- + {file &&

{t("rep.fileSaved", { path: file })}

}

{t("rep.privacy")}

- + +
); } diff --git a/src/screens/Shell.tsx b/src/screens/Shell.tsx index ff81391..aa4a804 100644 --- a/src/screens/Shell.tsx +++ b/src/screens/Shell.tsx @@ -127,7 +127,7 @@ export function Shell(props: {
{page === "overview" ? ( - props.onForget(server.id)} onOpenUpdates={() => setPage("settings")} onRealmChanged={reloadModules} /> + props.onForget(server.id)} onOpenUpdates={() => setPage("settings")} onRealmChanged={reloadModules} onReport={() => setPage("report")} /> ) : page === "bots" || page === "server" ? ( ) : page === "console" ? (