feat(client): capture rich diagnostics and ring-buffer logs in desktop feedback

This commit is contained in:
WuYongJie 2026-12-03 09:59:22 +08:00
parent 22b21dc238
commit 03aa6328d4
6 changed files with 883 additions and 19 deletions

View File

@ -1,12 +1,200 @@
use super::{Backend, R, Value};
use super::{Backend, R, Value, json};
use photocraft_ui_egui::jiansun::{feedback_payload, sanitize_diagnostic_line};
use std::collections::BTreeSet;
use std::time::Duration;
const MAX_RECENT_LOGS: usize = 25;
fn agent_daemon_summary(raw: &Value) -> Option<Value> {
let available = raw["available"].as_bool().unwrap_or(false);
let ready = raw["ready"].as_bool();
let spawn_count = raw["spawnCount"].as_u64().unwrap_or(0);
let exit_code = raw["exitCode"].as_i64();
let error_code = raw["errorCode"]
.as_str()
.map(str::trim)
.filter(|text| !text.is_empty())
.map(sanitize_diagnostic_line)
.filter(|text| !text.is_empty());
let last_error = raw["lastError"]
.as_str()
.map(str::trim)
.filter(|text| !text.is_empty())
.map(sanitize_diagnostic_line)
.filter(|text| !text.is_empty());
let stderr_summary = raw["stderrSummary"]
.as_str()
.map(str::trim)
.filter(|text| !text.is_empty())
.map(sanitize_diagnostic_line)
.filter(|text| !text.is_empty());
if !available
&& !ready.unwrap_or(false)
&& spawn_count == 0
&& exit_code.is_none()
&& error_code.is_none()
&& last_error.is_none()
&& stderr_summary.is_none()
{
return None;
}
let active_runs = raw["activeRuns"]
.as_array()
.map(Vec::len)
.or_else(|| raw["activeRuns"].as_u64().and_then(|count| usize::try_from(count).ok()))
.unwrap_or_else(|| usize::from(raw["activeRun"].is_string()));
let mut summary = json!({
"available": available,
"ready": ready.unwrap_or(available),
"spawnCount": spawn_count,
"activeRuns": active_runs,
});
if let Some(age) = raw["heartbeatAgeMs"].as_u64() {
summary["heartbeatAgeMs"] = json!(age);
}
if let Some(code) = exit_code {
summary["exitCode"] = json!(code);
}
if let Some(code) = error_code {
summary["errorCode"] = json!(code);
}
if let Some(err) = last_error {
summary["lastError"] = json!(err);
}
if let Some(stderr) = stderr_summary {
summary["stderrSummary"] = json!(stderr);
}
Some(summary)
}
fn storage_status() -> Option<Value> {
fn noop_rebase(
_: &std::path::Path,
_: &std::path::Path,
_: &std::path::Path,
_: &mut Value,
) -> R<bool> {
Ok(false)
}
fn no_node() -> R<std::path::PathBuf> {
Err("unused".into())
}
let guard = || Ok(());
let host = crate::jiansun_storage::Host {
guard: &guard,
rebase: noop_rebase,
node: no_node,
emit: Box::new(|_| {}),
};
crate::jiansun_storage::handle_action("storage-status", &json!({}), host).ok()
}
fn storage_summary(raw: &Value) -> Option<Value> {
let mut summary = serde_json::Map::new();
if let Some(custom) = raw["usingCustomRoot"]
.as_bool()
.or_else(|| raw["mode"].as_str().map(|mode| mode != "default"))
{
summary.insert("usingCustomRoot".into(), json!(custom));
}
if let Some(phase) = raw["migrationPhase"]
.as_str()
.or_else(|| raw["migration"]["phase"].as_str())
.map(str::trim)
.filter(|phase| !phase.is_empty())
{
summary.insert("migrationPhase".into(), json!(phase));
}
if let Some(free_bytes) = raw["freeBytes"].as_u64() {
summary.insert("freeBytes".into(), json!(free_bytes));
}
(!summary.is_empty()).then_some(Value::Object(summary))
}
fn is_priority_log_line(line: &str) -> bool {
line.contains(" WARN ")
|| line.contains(" ERROR ")
|| line.starts_with("WARN ")
|| line.starts_with("ERROR ")
|| line.contains("photocraft::startup")
|| line.contains("photocraft::gpu")
|| line.contains("gpu_startup")
|| line.contains("render path:")
|| line.contains("agent_daemon")
|| line.contains("jiansun_agent_daemon")
|| line.contains("本机Agent")
}
fn select_recent_logs(lines: &[String], limit: usize) -> Vec<String> {
if limit == 0 || lines.is_empty() {
return Vec::new();
}
let selected: BTreeSet<usize> = if lines.len() <= limit {
(0..lines.len()).collect()
} else {
let priority: Vec<usize> = lines
.iter()
.enumerate()
.filter_map(|(idx, line)| is_priority_log_line(line).then_some(idx))
.collect();
if priority.len() >= limit {
priority.into_iter().rev().take(limit).collect()
} else {
let mut chosen: BTreeSet<usize> = priority.into_iter().collect();
for idx in (0..lines.len()).rev() {
if chosen.len() >= limit {
break;
}
chosen.insert(idx);
}
chosen
}
};
selected
.into_iter()
.filter_map(|idx| lines.get(idx))
.map(|line| sanitize_diagnostic_line(line))
.filter(|line| !line.is_empty())
.collect()
}
fn enrich_payload(
payload: &Value,
daemon_raw: &Value,
storage_raw: Option<&Value>,
recent_logs: &[String],
) -> Value {
let mut enriched = payload.clone();
if !enriched.is_object() {
return enriched;
}
let mut context = enriched["context"].as_object().cloned().unwrap_or_default();
if let Some(daemon) = agent_daemon_summary(daemon_raw) {
context.insert("agentDaemon".into(), daemon);
}
if let Some(storage) = storage_raw.and_then(storage_summary) {
context.insert("storage".into(), storage);
}
let logs = select_recent_logs(recent_logs, MAX_RECENT_LOGS);
if !logs.is_empty() {
context.insert("recentLogs".into(), json!(logs));
}
enriched["context"] = Value::Object(context);
enriched
}
pub(super) fn submit(backend: &Backend, input: &Value) -> R<Value> {
if input["origin"] != backend.origin || input["accountId"] != backend.auth["account"]["id"] {
return Err("账号已切换,请重新打开反馈".into());
}
let token = backend.auth["access_token"].as_str().ok_or("请先登录素材库账号")?;
let payload = photocraft_ui_egui::jiansun::feedback_payload(&input["payload"])?;
let daemon_raw = super::agent_daemon::status();
let storage_raw = storage_status();
let recent_logs = crate::logging::recent_lines(64);
let enriched = enrich_payload(&input["payload"], &daemon_raw, storage_raw.as_ref(), &recent_logs);
let payload = feedback_payload(&enriched)?;
backend.check_dispatch()?;
let response = backend
.http
@ -69,11 +257,17 @@ mod tests {
let mut body = vec![0; length];
reader.read_exact(&mut body).unwrap();
let payload: Value = serde_json::from_slice(&body).unwrap();
assert_eq!(
payload,
json!({"feedbackId":expected,"summary":"无法打开项目",
"context":{"client":"XiaoYi","error":"[敏感信息已移除]"}})
);
assert_eq!(payload["feedbackId"], expected);
assert_eq!(payload["summary"], "无法打开项目");
assert_eq!(payload["context"]["client"], "XiaoYi");
assert_eq!(payload["context"]["error"], "[敏感信息已移除]");
assert!(payload["context"].get("screenshot").is_none());
if let Some(storage) = payload["context"].get("storage") {
assert!(storage["usingCustomRoot"].is_boolean());
for forbidden in ["currentPath", "currentRoot", "defaultPath", "targetRoot", "oldRoot"] {
assert!(storage.get(forbidden).is_none(), "raw storage path {forbidden} leaked");
}
}
let reply = json!({"feedback":{"feedbackId":expected,"detailPath":format!("/feedback/{expected}")}}).to_string();
write!(socket, "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", reply.len())
.unwrap();
@ -89,4 +283,114 @@ mod tests {
assert_eq!(submit(&backend, &input).unwrap()["feedback"]["feedbackId"], id);
server.join().unwrap();
}
#[test]
fn feedback_enrichment_captures_daemon_storage_and_logs_without_leaking_secrets_or_paths() {
let id = uuid::Uuid::new_v4().to_string();
let base_payload = json!({
"feedbackId": id,
"summary": " 无法启动本机助手 ",
"context": {
"client": "XiaoYi",
"clientVersion": "1.2612.111"
}
});
let pristine = enrich_payload(
&base_payload,
&json!({"available": false, "spawnCount": 0, "exitCode": null, "stderrSummary": null}),
None,
&[],
);
let pristine_screened = feedback_payload(&pristine).unwrap();
assert!(pristine_screened["context"].get("agentDaemon").is_none());
assert!(pristine_screened["context"].get("storage").is_none());
assert!(pristine_screened["context"].get("recentLogs").is_none());
let daemon_raw = json!({
"available": false,
"spawnCount": 2,
"activeRun": null,
"activeRuns": ["run-a"],
"heartbeatAgeMs": 320,
"exitCode": 1,
"errorCode": "ERR_MODULE_NOT_FOUND",
"lastError": r"Cannot find package 'fflate' imported from C:\Users\alice\XiaoYi\agent\desktop-host.mjs",
"stderrSummary": "GET https://sc.jiansun.vip/api/ping failed; Authorization: Bearer secret-token-value"
});
let storage_raw = json!({
"mode": "pointer",
"currentPath": r"D:\Secret\XiaoYiData",
"currentRoot": r"D:\Secret\XiaoYiData",
"defaultPath": r"C:\Users\alice\AppData\Roaming\Photocraft",
"freeBytes": 98_765_432_100_u64,
"migration": {
"phase": "copying",
"targetRoot": r"E:\Target\XiaoYiData"
}
});
let mut logs = vec![
r"2026-12-03T01:00:00.000Z INFO [main] photocraft::startup: PhotoCraft 1.2612.111 started from C:\Users\alice\AppData\Local\XiaoYi.exe".to_owned(),
r"2026-12-03T01:00:01.000Z WARN [main] photocraft::gpu_startup: adapter fallback at /Users/alice/Library/Logs/gpu.log".to_owned(),
"2026-12-03T01:00:02.000Z ERROR [agent] jiansun_agent_daemon: Authorization: Bearer raw-secret-token".to_owned(),
"2026-12-03T01:00:03.000Z WARN [net] fetch https://sc.jiansun.vip/api/desktop/feedback timed out".to_owned(),
];
for i in 0..36 {
logs.push(format!("2026-12-03T01:00:{:02}.000Z INFO [worker] tick-{i:02}", i + 4));
}
let enriched = enrich_payload(&base_payload, &daemon_raw, Some(&storage_raw), &logs);
let screened = feedback_payload(&enriched).unwrap();
let serialized = serde_json::to_string(&screened).unwrap();
for secret_or_path in [
r"C:\Users\alice",
r"D:\Secret",
r"E:\Target",
"/Users/alice",
"secret-token-value",
"raw-secret-token",
"sc.jiansun.vip",
"currentPath",
"currentRoot",
"defaultPath",
"targetRoot",
] {
assert!(!serialized.contains(secret_or_path), "unexpected leak of {secret_or_path} in {serialized}");
}
let daemon = &screened["context"]["agentDaemon"];
assert_eq!(daemon["available"], false);
assert_eq!(daemon["ready"], false);
assert_eq!(daemon["spawnCount"], 2);
assert_eq!(daemon["activeRuns"], 1);
assert_eq!(daemon["heartbeatAgeMs"], 320);
assert_eq!(daemon["exitCode"], 1);
assert_eq!(daemon["errorCode"], "ERR_MODULE_NOT_FOUND");
assert_eq!(
daemon["lastError"],
"Cannot find package 'fflate' imported from [path]/desktop-host.mjs"
);
assert_eq!(daemon["stderrSummary"], "[敏感信息已移除]");
let storage = &screened["context"]["storage"];
assert_eq!(
storage,
&json!({
"usingCustomRoot": true,
"migrationPhase": "copying",
"freeBytes": 98_765_432_100_u64
})
);
let recent_logs = screened["context"]["recentLogs"].as_array().unwrap();
assert_eq!(recent_logs.len(), MAX_RECENT_LOGS);
assert!(recent_logs[0].as_str().unwrap().contains("photocraft::startup"));
assert!(recent_logs[0].as_str().unwrap().contains("[path]/XiaoYi.exe"));
assert!(recent_logs[1].as_str().unwrap().contains("[path]/gpu.log"));
assert_eq!(recent_logs[2], "[敏感信息已移除]");
assert!(recent_logs[3].as_str().unwrap().contains("[url]"));
assert!(recent_logs[4].as_str().unwrap().ends_with("tick-15"));
assert!(recent_logs[24].as_str().unwrap().ends_with("tick-35"));
}
}

View File

@ -17,6 +17,7 @@
//! written once the file is attached. Writing never panics: a file that can't be created or
//! written leaves standard error as the only sink.
use std::collections::VecDeque;
use std::fs::{File, OpenOptions, TryLockError};
use std::io::Write;
use std::path::{Path, PathBuf};
@ -33,6 +34,8 @@ pub const KEEP: usize = 2;
pub const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
/// Records kept in memory until the log file is attached.
pub const MAX_PENDING: usize = 512;
/// Recent formatted log lines kept in memory for desktop feedback diagnostics.
pub const MAX_RECENT: usize = 64;
/// The built-in filter when `RUST_LOG` is unset or empty.
pub const DEFAULT_FILTER: &str = "warn,photocraft*=info";
@ -252,6 +255,7 @@ pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, mess
pub struct Sink {
file: Option<File>,
pending: Vec<String>,
recent: VecDeque<String>,
dropped: usize,
written: u64,
max_bytes: u64,
@ -260,11 +264,26 @@ pub struct Sink {
impl Sink {
pub fn new(max_bytes: u64) -> Sink {
Sink { file: None, pending: Vec::new(), dropped: 0, written: 0, max_bytes, capped: false }
Sink {
file: None,
pending: Vec::new(),
recent: VecDeque::with_capacity(MAX_RECENT),
dropped: 0,
written: 0,
max_bytes,
capped: false,
}
}
/// Append `line` to the file, or keep it until [`Sink::attach`].
pub fn write(&mut self, line: &str) {
let trimmed = line.trim_end_matches(['\r', '\n']);
if !trimmed.is_empty() {
if self.recent.len() >= MAX_RECENT {
self.recent.pop_front();
}
self.recent.push_back(trimmed.to_owned());
}
if self.file.is_none() {
if self.pending.len() < MAX_PENDING {
self.pending.push(line.to_owned());
@ -276,6 +295,15 @@ impl Sink {
self.append(line);
}
/// Most recent formatted log lines (at most `limit`, up to [`MAX_RECENT`]), oldest first.
pub fn recent_lines(&self, limit: usize) -> Vec<String> {
if limit == 0 {
return Vec::new();
}
let skip = self.recent.len().saturating_sub(limit);
self.recent.iter().skip(skip).cloned().collect()
}
/// Start writing to `file`, first the lines kept so far.
pub fn attach(&mut self, file: File) {
self.file = Some(file);
@ -349,8 +377,15 @@ impl AppLogger {
pub fn path(&self) -> Option<PathBuf> {
self.path.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
/// Most recent formatted log lines (at most `limit`, up to [`MAX_RECENT`]), oldest first.
pub fn recent_lines(&self, limit: usize) -> Vec<String> {
self.sink.lock().unwrap_or_else(PoisonError::into_inner).recent_lines(limit)
}
}
static LOGGER: OnceLock<AppLogger> = OnceLock::new();
impl log::Log for AppLogger {
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
metadata.level() <= self.filter.level_for(metadata.target())
@ -375,7 +410,6 @@ impl log::Log for AppLogger {
/// Install the logger (filter from `RUST_LOG`, else [`DEFAULT_FILTER`]); `None` when another
/// logger was installed first. Call [`AppLogger::attach_dir`] once the settings directory is known.
pub fn install() -> Option<&'static AppLogger> {
static LOGGER: OnceLock<AppLogger> = OnceLock::new();
let spec = std::env::var("RUST_LOG").ok().filter(|s| !s.trim().is_empty());
let filter = Filter::parse(spec.as_deref().unwrap_or(DEFAULT_FILTER));
let max = filter.max();
@ -385,6 +419,11 @@ pub fn install() -> Option<&'static AppLogger> {
Some(logger)
}
/// Recent log lines from the installed global logger (empty before [`install`]).
pub fn recent_lines(limit: usize) -> Vec<String> {
LOGGER.get().map_or_else(Vec::new, |logger| logger.recent_lines(limit))
}
#[cfg(test)]
mod tests {
use super::*;
@ -656,4 +695,51 @@ mod tests {
logger.log(&log::Record::builder().level(log::Level::Error).target("x").args(format_args!("still fine")).build());
let _ = std::fs::remove_file(&dir);
}
#[test]
fn recent_ring_buffer_evicts_at_cap_and_preserves_order_across_attach() {
use log::Log;
let dir = temp_dir("recent-ring");
let logger = AppLogger::new(Filter::parse("info"), false);
for i in 0..75 {
let msg = format!("line-{i:02}");
logger.log(&log::Record::builder().level(log::Level::Info).target("photocraft::test").args(format_args!("{msg}")).build());
}
let recent = logger.recent_lines(MAX_RECENT);
assert_eq!(recent.len(), MAX_RECENT);
assert!(recent.first().is_some_and(|l| l.ends_with("line-11")), "oldest kept: {:?}", recent.first());
assert!(recent.last().is_some_and(|l| l.ends_with("line-74")), "newest kept: {:?}", recent.last());
assert!(recent.iter().all(|l| !l.ends_with('\n') && !l.ends_with('\r')));
let tail5 = logger.recent_lines(5);
assert_eq!(tail5.len(), 5);
for (idx, line) in tail5.iter().enumerate() {
let expected = format!("line-{:02}", 70 + idx);
assert!(line.ends_with(&expected), "expected {expected} in {line}");
}
assert!(logger.recent_lines(0).is_empty());
let _path = logger.attach_dir(&dir).expect("attach");
let after_attach = logger.recent_lines(MAX_RECENT);
assert_eq!(after_attach.len(), MAX_RECENT);
// Attaching writes 1 startup line, evicting line-11 and preserving pre-attach lines in order.
assert!(after_attach.first().is_some_and(|l| l.ends_with("line-12")), "first after attach: {:?}", after_attach.first());
assert!(after_attach.get(MAX_RECENT - 2).is_some_and(|l| l.ends_with("line-74")));
assert!(after_attach.last().is_some_and(|l| l.contains("photocraft::startup")));
for i in 75..77 {
let msg = format!("line-{i:02}");
logger.log(&log::Record::builder().level(log::Level::Warn).target("photocraft::test").args(format_args!("{msg}")).build());
}
let latest = logger.recent_lines(MAX_RECENT);
assert_eq!(latest.len(), MAX_RECENT);
assert!(latest.first().is_some_and(|l| l.ends_with("line-14")), "oldest after 2 more: {:?}", latest.first());
assert!(latest[MAX_RECENT - 3].contains("photocraft::startup"));
assert!(latest[MAX_RECENT - 2].ends_with("line-75"));
assert!(latest[MAX_RECENT - 1].ends_with("line-76"));
drop(logger);
let _ = std::fs::remove_dir_all(&dir);
}
}

View File

@ -26,7 +26,7 @@ mod operation_error;
mod template_preparation;
mod workspace_navigation;
mod feedback;
pub use feedback::feedback_payload;
pub use feedback::{feedback_payload, sanitize_diagnostic_line};
mod agent_canvas_read;
mod agent_native;
mod agent_preview;
@ -4629,7 +4629,7 @@ impl Workspace {
} else {
stitch_ui::action_button(ui, "问题反馈", stitch_ui::ButtonRole::Quiet, true)
};
if feedback.clicked() { self.open_feedback(app); }
if feedback.clicked() { self.open_feedback(app, ui.ctx()); }
});
}
fn header(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {

View File

@ -3448,6 +3448,27 @@ impl Workspace {
});
}
/// Read-only snapshot of up to 12 most recent notification entries (newest first).
pub(super) fn recent_notification_entries(&self, ctx: &egui::Context) -> Vec<String> {
let Some(id) = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc) else {
return Vec::new();
};
ctx.data(|data| data.get_temp::<AgentNotifications>(id))
.map(|history| history.entries.into_iter().rev().take(12).collect())
.unwrap_or_default()
}
#[cfg(test)]
pub(super) fn seed_notifications_for_test(&self, ctx: &egui::Context, entries: &[&str]) {
if let Some(id) = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc) {
let mut history = AgentNotifications::default();
for entry in entries {
history.add(entry);
}
ctx.data_mut(|data| data.insert_temp(id, history));
}
}
/// Account/project-scoped session history supplements persisted export
/// receipts; it never writes prompts or provider data to another project.
fn close_notifications_on_escape(&self, ui: &Ui) {

View File

@ -525,10 +525,11 @@ mod tests {
let mut harness = toolbar(app_with(w), vec2(1280.0, 800.0), true);
set_state(&mut harness, state("available"));
assert!(harness.query_by_label("立即下载更新").is_none());
let ctx = harness.ctx.clone();
let app = harness.state_mut();
let mut workspace = app.jiansun.take().unwrap();
workspace.onboarding = super::super::onboarding::State::Dismissed;
workspace.open_feedback(app);
workspace.open_feedback(app, &ctx);
app.jiansun = Some(workspace);
harness.run_steps(3);
assert_eq!(harness.query_all_by_label("问题反馈").count(), 2, "the toolbar entry and the modal heading");

View File

@ -5,16 +5,65 @@ use serde_json::{Value, json};
use std::sync::LazyLock;
const MAX_SUMMARY: usize = 2000;
const MAX_RECENT_LOGS: usize = 25;
const MAX_DIAGNOSTIC_LINE: usize = 240;
const FIELDS: &[&str] = &[
"client",
"clientVersion",
"appVersion",
"version",
"commit",
"channel",
"builtAt",
"platform",
"os",
"arch",
"capturedAt",
"online",
"page",
"view",
"currentError",
"notices",
"recentErrors",
"agentDaemon",
"available",
"ready",
"spawnCount",
"activeRuns",
"heartbeatAgeMs",
"exitCode",
"lastError",
"stderrSummary",
"models",
"chatModel",
"copyModel",
"imageModel",
"hasPersonalKey",
"knowledgeMode",
"canvas",
"render",
"renderPath",
"gpuFallback",
"gpuFallbackKind",
"documentWidth",
"documentHeight",
"layerCount",
"outputId",
"activeOutput",
"variantId",
"templateHash",
"revision",
"dirty",
"professionalMode",
"multiProject",
"runningCount",
"queuedCount",
"pausedCount",
"storage",
"usingCustomRoot",
"migrationPhase",
"freeBytes",
"recentLogs",
"project",
"projectId",
"projectName",
@ -53,6 +102,41 @@ static SENSITIVE: LazyLock<regex::Regex> = LazyLock::new(|| {
)).expect("constant feedback redaction pattern")
});
static DIAG_URL: LazyLock<regex::Regex> = LazyLock::new(|| {
#[allow(clippy::expect_used)]
regex::Regex::new(r#"(?i)https?://[^\s"'<>]+"#).expect("constant diagnostic URL pattern")
});
static DIAG_WIN_PATH: LazyLock<regex::Regex> = LazyLock::new(|| {
#[allow(clippy::expect_used)]
regex::Regex::new(r#"[A-Za-z]:\\[^\s"'<>]+"#).expect("constant diagnostic Windows path pattern")
});
static DIAG_UNIX_PATH: LazyLock<regex::Regex> = LazyLock::new(|| {
#[allow(clippy::expect_used)]
regex::Regex::new(r#"/(?:Users|home|var|tmp)/[^\s"'<>]+"#).expect("constant diagnostic Unix path pattern")
});
fn redact_path(matched: &str) -> String {
let trimmed = matched.trim_end_matches(['\\', '/']);
let basename = trimmed
.rsplit(['\\', '/'])
.next()
.filter(|part| !part.is_empty() && !(part.len() == 2 && part.ends_with(':')));
match basename {
Some(name) => format!("[path]/{name}"),
None => "[path]".into(),
}
}
/// Scrub URLs and absolute paths while preserving secret/token redaction and a 240-char cap.
pub fn sanitize_diagnostic_line(line: &str) -> String {
let scrubbed = DIAG_URL.replace_all(line, "[url]");
let scrubbed = DIAG_WIN_PATH.replace_all(&scrubbed, |caps: &regex::Captures<'_>| redact_path(&caps[0]));
let scrubbed = DIAG_UNIX_PATH.replace_all(&scrubbed, |caps: &regex::Captures<'_>| redact_path(&caps[0]));
clean_text(&scrubbed, MAX_DIAGNOSTIC_LINE)
}
fn clean_text(text: &str, limit: usize) -> String {
let text: String = text.chars().filter(|c| !c.is_control() || matches!(c, '\n' | '\r' | '\t')).collect();
let text = text.trim();
@ -87,8 +171,24 @@ fn diagnostic(value: &Value, depth: usize) -> Option<Value> {
fields
.iter()
.filter(|(key, _)| FIELDS.contains(&key.as_str()))
.filter_map(|(key, value)| diagnostic(value, depth - 1).map(|value| (key.clone(), value)))
.take(16)
.filter_map(|(key, value)| {
let clean = if key == "recentLogs" {
value.as_array().map(|values| {
Value::Array(
values
.iter()
.filter_map(Value::as_str)
.take(MAX_RECENT_LOGS)
.map(|line| json!(sanitize_diagnostic_line(line)))
.collect(),
)
})
} else {
diagnostic(value, depth - 1)
};
clean.map(|value| (key.clone(), value))
})
.take(24)
.collect(),
)),
_ => None,
@ -153,8 +253,12 @@ impl Feedback {
}
}
fn non_empty_str(value: &Value) -> Option<&str> {
value.as_str().map(str::trim).filter(|text| !text.is_empty())
}
impl Workspace {
pub(super) fn open_feedback(&mut self, app: &PhotocraftApp) {
pub(super) fn open_feedback(&mut self, app: &PhotocraftApp, ctx: &Context) {
let scope = json!({"accountId":self.account["id"],"origin":self.origin});
if self.feedback.id.is_empty() || self.feedback.scope != scope || self.feedback.receipt {
let active = app.session.active().filter(|state| self.loaded_draft == Some(state.doc.id.0));
@ -174,11 +278,130 @@ impl Workspace {
.or_else(|| active.and(self.pi_run.as_ref()).map(|run| json!({"taskId":run,"kind":"chat"})))
.or_else(|| active.and(self.unknown_image_task.as_ref()).map(|id| json!({"taskId":id,"status":"unknown"})))
.unwrap_or_default();
let context = json!({"client":"XiaoYi","clientVersion":self.client_update.version["version"],
"os":std::env::consts::OS,"arch":std::env::consts::ARCH,"online":self.library_status == "connected",
let mut context = json!({
"client":"XiaoYi",
"clientVersion":self.client_update.version["version"],
"os":std::env::consts::OS,
"arch":std::env::consts::ARCH,
"online":self.library_status == "connected",
"page":self.agent_page(app),
"diagnostics":{"status":self.library_status,"code":self.library_http_status},
"capturedAt":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok().map(|time| time.as_secs())});
self.feedback = Feedback { id: uuid::Uuid::new_v4().to_string(), scope, project, task, context, ..Default::default() };
"capturedAt":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok().map(|time| time.as_secs())
});
if let Some(commit) = non_empty_str(&self.client_update.version["commit"]) {
let short: String = commit.chars().take(12).collect();
context["commit"] = json!(short);
}
if let Some(channel) = non_empty_str(&self.client_update.version["channel"]) {
context["channel"] = json!(channel);
}
if let Some(built_at) = non_empty_str(&self.client_update.version["builtAt"]) {
context["builtAt"] = json!(built_at);
}
if !self.error.trim().is_empty() {
let error = sanitize_diagnostic_line(self.error.trim());
if !error.is_empty() {
context["currentError"] = json!(error);
}
}
let notices: Vec<String> = self
.recent_notification_entries(ctx)
.into_iter()
.map(|entry| sanitize_diagnostic_line(&entry))
.filter(|entry| !entry.is_empty())
.collect();
if !notices.is_empty() {
context["notices"] = json!(notices);
}
let mut models = json!({"hasPersonalKey":self.key_saved});
if !self.model.trim().is_empty() {
models["chatModel"] = json!(self.model.trim());
}
if !self.copy_model.trim().is_empty() {
models["copyModel"] = json!(self.copy_model.trim());
}
if !self.image_model.trim().is_empty() {
models["imageModel"] = json!(self.image_model.trim());
}
if !self.xiaoyi_knowledge_mode.trim().is_empty() {
models["knowledgeMode"] = json!(self.xiaoyi_knowledge_mode.trim());
}
context["models"] = models;
if let Some(state) = active.or_else(|| app.session.active().filter(|_| self.professional_child_active(app))) {
let cpu_reason = app.render_path.current(state.doc.id.0);
let mut canvas = json!({
"documentWidth":state.doc.size.width,
"documentHeight":state.doc.size.height,
"layerCount":state.doc.layer_count(),
"revision":state.revision,
"dirty":self.draft_changed,
"professionalMode":self.professional_mode || self.professional_child_active(app),
"renderPath":if cpu_reason.is_some() { "cpu" } else { "gpu" }
});
if let Some(output_id) = (!self.canvas_workspace.output.trim().is_empty())
.then_some(self.canvas_workspace.output.trim())
.or_else(|| non_empty_str(&self.template_workflow["outputId"]))
{
canvas["outputId"] = json!(output_id);
}
if let Some(active_output) = non_empty_str(&self.template_workflow["activeOutput"])
.or_else(|| non_empty_str(&self.template_workflow["outputId"]))
.or_else(|| non_empty_str(&self.template_workflow["component"]))
{
canvas["activeOutput"] = json!(active_output);
}
if let Some(variant_id) = (!self.canvas_workspace.variant.trim().is_empty())
.then_some(self.canvas_workspace.variant.trim())
.or_else(|| non_empty_str(&self.template_workflow["variantId"]))
{
canvas["variantId"] = json!(variant_id);
}
if let Some(hash) = non_empty_str(&self.template_workflow["templateHash"]) {
let short: String = hash.chars().take(12).collect();
canvas["templateHash"] = json!(short);
}
if let Some(reason) = cpu_reason {
canvas["gpuFallback"] = json!(sanitize_diagnostic_line(&reason.to_string()));
canvas["gpuFallbackKind"] = json!(reason.kind());
}
context["canvas"] = canvas;
}
let snapshot = self.multi_project_ui_snapshot(app);
let mut running_count = 0usize;
let mut queued_count = usize::from(self.product_production.is_none() && self.product_start_queued);
let mut paused_count = 0usize;
for run in &snapshot.global_runs {
match run.status {
super::multi_project_state::ProjectRunVisualStatus::Running => running_count += 1,
super::multi_project_state::ProjectRunVisualStatus::Queued => queued_count += 1,
super::multi_project_state::ProjectRunVisualStatus::Paused => paused_count += 1,
super::multi_project_state::ProjectRunVisualStatus::PartialDelivered
| super::multi_project_state::ProjectRunVisualStatus::Completed
| super::multi_project_state::ProjectRunVisualStatus::Failed => {}
}
}
context["multiProject"] = json!({
"runningCount":running_count,
"queuedCount":queued_count,
"pausedCount":paused_count
});
let include_project = project["name"].is_string();
let include_task = task["taskId"].is_string() || task["requestId"].is_string();
self.feedback = Feedback {
id: uuid::Uuid::new_v4().to_string(),
scope,
project,
task,
context,
include_project,
include_task,
..Default::default()
};
}
self.feedback.open = true;
}
@ -252,6 +475,12 @@ impl Workspace {
}
});
ui.collapsing("查看脱敏诊断", |ui| {
ui.label(
RichText::new("提交时会自动附带脱敏后的版本、画布渲染、本机助手、存储与近期日志摘要,不包含密钥、本地路径、聊天正文和画面内容。")
.small()
.color(t.text_dim),
);
ui.add_space(4.0);
let input = feedback.input();
let snapshot = diagnostic(&input["context"], 4).unwrap_or_else(|| json!({}));
egui::ScrollArea::vertical().max_height(122.0).show(ui, |ui| {
@ -321,4 +550,227 @@ mod tests {
input["summary"] = json!("图".repeat(2001));
assert!(feedback_payload(&input).is_err());
}
#[test]
fn sanitize_diagnostic_line_scrubs_paths_and_urls_while_redacting_secrets() {
let win = sanitize_diagnostic_line(r#"Cannot find 'fflate' imported from C:\Users\alice\AppData\Local\XiaoYi\agent\desktop-host.mjs"#);
assert_eq!(win, "Cannot find 'fflate' imported from [path]/desktop-host.mjs");
let unix = sanitize_diagnostic_line("Failed reading /Users/bob/Library/Application Support/Photocraft/logs/photocraft.log and /tmp/run.lock");
assert_eq!(unix, "Failed reading [path]/Application Support/Photocraft/logs/photocraft.log and [path]/run.lock");
let url = sanitize_diagnostic_line("GET https://sc.jiansun.vip/api/desktop/feedback?foo=1 failed with 503");
assert_eq!(url, "GET [url] failed with 503");
assert_eq!(sanitize_diagnostic_line("Authorization: Bearer secret-jwt-token-xyz"), "[敏感信息已移除]");
assert_eq!(sanitize_diagnostic_line("upstream rejected sk-live-secret-123456"), "[敏感信息已移除]");
assert_eq!(sanitize_diagnostic_line(&"A".repeat(45)), "[敏感信息已移除]");
let long_safe = "警告:".to_owned() + &"中文提示 ".repeat(80);
assert_eq!(sanitize_diagnostic_line(&long_safe).chars().count(), MAX_DIAGNOSTIC_LINE);
}
#[test]
fn feedback_payload_accepts_v2_fields_and_caps_recent_logs_at_25() {
let logs: Vec<String> = (0..30)
.map(|idx| match idx {
0 => format!(r"2026-12-03T01:00:00Z WARN [main] startup: C:\Users\alice\logs\photocraft.log ({idx})"),
1 => "2026-12-03T01:00:01Z ERROR [net] upload: https://sc.jiansun.vip/api/upload failed".into(),
2 => "2026-12-03T01:00:02Z WARN [auth] Authorization: Bearer secret-value-999".into(),
_ => format!("2026-12-03T01:00:{idx:02}Z INFO [worker] step {idx} {}", "说明".repeat(130)),
})
.collect();
let input = json!({
"feedbackId": uuid::Uuid::new_v4().to_string(),
"summary": " 画布导出异常 ",
"context": {
"client": "XiaoYi",
"clientVersion": "1.2612.111",
"commit": "45f36bbecafe",
"channel": "stable",
"builtAt": "2026-12-03T01:00:00Z",
"os": "windows",
"arch": "x86_64",
"online": true,
"capturedAt": 1_764_723_600,
"page": "canvas",
"view": "detail",
"currentError": "读取失败 [path]/draft.pcraft",
"notices": ["导出提示:保留原图层"],
"recentErrors": ["GPU fallback", "Authorization: Bearer secret-err-token"],
"agentDaemon": {
"available": true,
"ready": true,
"spawnCount": 1,
"activeRuns": 1,
"heartbeatAgeMs": 120,
"exitCode": 0,
"lastError": "none",
"stderrSummary": "ok"
},
"models": {
"chatModel": "claude-sonnet",
"copyModel": "gpt-4.1",
"imageModel": "seedream-4",
"hasPersonalKey": false,
"knowledgeMode": "cloud"
},
"canvas": {
"render": "wgpu",
"renderPath": "cpu",
"gpuFallback": "Budget exceeded",
"gpuFallbackKind": "overBudget",
"documentWidth": 1440,
"documentHeight": 1800,
"layerCount": 12,
"outputId": "detail",
"activeOutput": "detail",
"variantId": "wood",
"templateHash": "abcdef123456",
"revision": 9,
"dirty": true,
"professionalMode": false
},
"multiProject": { "runningCount": 1, "queuedCount": 2, "pausedCount": 0 },
"storage": { "usingCustomRoot": true, "migrationPhase": "idle", "freeBytes": 42_000_000_000_u64 },
"diagnostics": { "status": "connected", "code": 200 },
"events": vec![json!({"message": "event"}); 15],
"recentLogs": logs,
"extraKey1": "ignored-past-24",
"extraKey2": "ignored"
}
});
let payload = feedback_payload(&input).unwrap();
let ctx = payload["context"].as_object().unwrap();
assert_eq!(ctx.len(), 22, "all 22 v2 top-level keys survive past the old 16-key cap");
assert_eq!(ctx["commit"], "45f36bbecafe");
assert_eq!(ctx["page"], "canvas");
assert_eq!(ctx["currentError"], "读取失败 [path]/draft.pcraft");
assert_eq!(ctx["recentErrors"], json!(["GPU fallback", "[敏感信息已移除]"]));
assert_eq!(ctx["agentDaemon"]["ready"], true);
assert_eq!(ctx["models"]["knowledgeMode"], "cloud");
assert_eq!(ctx["canvas"]["renderPath"], "cpu");
assert_eq!(ctx["canvas"]["gpuFallbackKind"], "overBudget");
assert_eq!(ctx["multiProject"]["queuedCount"], 2);
assert_eq!(ctx["storage"]["usingCustomRoot"], true);
assert_eq!(ctx["events"].as_array().unwrap().len(), 12);
let recent_logs = ctx["recentLogs"].as_array().unwrap();
assert_eq!(recent_logs.len(), MAX_RECENT_LOGS);
assert_eq!(recent_logs[0], "2026-12-03T01:00:00Z WARN [main] startup: [path]/photocraft.log (0)");
assert_eq!(recent_logs[1], "2026-12-03T01:00:01Z ERROR [net] upload: [url] failed");
assert_eq!(recent_logs[2], "[敏感信息已移除]");
assert_eq!(recent_logs[3].as_str().unwrap().chars().count(), MAX_DIAGNOSTIC_LINE);
}
#[test]
fn open_feedback_captures_rich_diagnostics_and_defaults_checkboxes() {
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"name":"秋季上新详情页","width":1440,"height":1800})).unwrap();
let mut app = PhotocraftApp::new(session, crate::Services::default());
let doc_id = app.session.active().unwrap().doc.id.0;
crate::render_path::note(
&mut app,
doc_id,
crate::render_path::Path::Cpu(crate::render_path::CpuReason::OverBudget {
needed: 4 << 30,
budget: 2 << 30,
}),
);
let (tx, _requests) = std::sync::mpsc::channel();
let (_events, rx) = std::sync::mpsc::channel();
let mut w = Workspace::new(tx, rx);
w.account = json!({"id":"qa-user","name":"QA"});
w.origin = "https://sc.jiansun.vip".into();
w.library = false;
w.loaded_draft = Some(doc_id);
w.project_context = json!({"localId":"local-1","cloudLink":{"id":"cloud-99"},"status":"draft"});
w.pending_image = Some(json!({"taskId":"img-task-7","requestId":"req-7","stage":"render","status":"running"}));
w.client_update.version = json!({
"version":"1.2612.111",
"commit":"45f36bbecafe1234567890abcdef",
"channel":"stable",
"builtAt":"2026-12-03T01:00:00Z"
});
w.library_status = "connected".into();
w.library_http_status = Some(200);
w.error = r"无法写入 C:\Users\qa\drafts\temp.pcraft".into();
w.model = "claude-sonnet".into();
w.copy_model = "gpt-4.1".into();
w.image_model = "seedream-4".into();
w.key_saved = true;
w.xiaoyi_knowledge_mode = "local".into();
w.draft_changed = true;
w.product_start_queued = true;
w.canvas_workspace.output = "detail".into();
w.canvas_workspace.variant = "wood".into();
w.template_workflow = json!({"activeOutput":"detail","templateHash":"abcdef1234567890"});
let ctx = Context::default();
w.seed_notifications_for_test(&ctx, &["第一条通知", "第二条通知 https://sc.jiansun.vip/help"]);
w.open_feedback(&app, &ctx);
assert!(w.feedback.open);
assert!(w.feedback.include_project, "project checkbox defaults to checked when project is present");
assert!(w.feedback.include_task, "task checkbox defaults to checked when task is present");
let mut input = w.feedback.input();
input["summary"] = json!("导出报错");
let payload = feedback_payload(&input).unwrap();
assert_eq!(payload["projectId"], "cloud-99");
assert_eq!(payload["taskId"], "img-task-7");
assert_eq!(payload["requestId"], "req-7");
let context = &payload["context"];
assert_eq!(context["client"], "XiaoYi");
assert_eq!(context["clientVersion"], "1.2612.111");
assert_eq!(context["commit"], "45f36bbecafe");
assert_eq!(context["channel"], "stable");
assert_eq!(context["builtAt"], "2026-12-03T01:00:00Z");
assert_eq!(context["page"], "canvas");
assert_eq!(context["online"], true);
assert_eq!(context["currentError"], "无法写入 [path]/temp.pcraft");
assert_eq!(context["notices"], json!(["第二条通知 [url]", "第一条通知"]));
assert_eq!(
context["models"],
json!({
"chatModel": "claude-sonnet",
"copyModel": "gpt-4.1",
"imageModel": "seedream-4",
"hasPersonalKey": true,
"knowledgeMode": "local"
})
);
assert_eq!(context["canvas"]["outputId"], "detail");
assert_eq!(context["canvas"]["activeOutput"], "detail");
assert_eq!(context["canvas"]["variantId"], "wood");
assert_eq!(context["canvas"]["templateHash"], "abcdef123456");
assert_eq!(context["canvas"]["documentWidth"], 1440);
assert_eq!(context["canvas"]["documentHeight"], 1800);
assert_eq!(context["canvas"]["layerCount"], 1);
assert_eq!(context["canvas"]["dirty"], true);
assert_eq!(context["canvas"]["professionalMode"], false);
assert_eq!(context["canvas"]["renderPath"], "cpu");
assert_eq!(context["canvas"]["gpuFallbackKind"], "overBudget");
assert!(context["canvas"]["gpuFallback"].as_str().is_some_and(|s| !s.is_empty()));
assert_eq!(context["multiProject"], json!({"runningCount":0,"queuedCount":1,"pausedCount":0}));
// Reopening within the same scope preserves explicit user uncheck.
w.feedback.include_project = false;
w.feedback.open = false;
w.open_feedback(&app, &ctx);
assert!(!w.feedback.include_project);
// Fresh feedback without an active project/task defaults both checkboxes to false.
let empty_app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
w.feedback = Feedback::default();
w.library = true;
w.loaded_draft = None;
w.open_feedback(&empty_app, &ctx);
assert!(!w.feedback.include_project);
assert!(!w.feedback.include_task);
assert_eq!(w.feedback.context["page"], "projects");
assert!(w.feedback.context.get("canvas").is_none());
}
}