feat(xiaoyi): 扩充问题反馈诊断并优化弹窗
This commit is contained in:
parent
f66f4f131e
commit
a0571c009a
@ -1,9 +1,9 @@
|
||||
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;
|
||||
const MAX_RECENT_LOGS: usize = 80;
|
||||
const MAX_RECENT_ERRORS: usize = 20;
|
||||
|
||||
fn agent_daemon_summary(raw: &Value) -> Option<Value> {
|
||||
let available = raw["available"].as_bool().unwrap_or(false);
|
||||
@ -13,29 +13,11 @@ fn agent_daemon_summary(raw: &Value) -> Option<Value> {
|
||||
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()
|
||||
{
|
||||
.filter(|text| !text.is_empty() && text.len() <= 80 && text.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"_-".contains(&byte)))
|
||||
.map(sanitize_diagnostic_line);
|
||||
let has_error = raw["lastError"].as_str().is_some_and(|text| !text.trim().is_empty());
|
||||
let has_stderr = raw["stderrSummary"].as_str().is_some_and(|text| !text.trim().is_empty());
|
||||
if !available && !ready.unwrap_or(false) && spawn_count == 0 && exit_code.is_none() && error_code.is_none() && !has_error && !has_stderr {
|
||||
return None;
|
||||
}
|
||||
|
||||
@ -50,6 +32,7 @@ fn agent_daemon_summary(raw: &Value) -> Option<Value> {
|
||||
"ready": ready.unwrap_or(available),
|
||||
"spawnCount": spawn_count,
|
||||
"activeRuns": active_runs,
|
||||
"hasStderr": has_stderr,
|
||||
});
|
||||
if let Some(age) = raw["heartbeatAgeMs"].as_u64() {
|
||||
summary["heartbeatAgeMs"] = json!(age);
|
||||
@ -60,11 +43,8 @@ fn agent_daemon_summary(raw: &Value) -> Option<Value> {
|
||||
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);
|
||||
if has_error {
|
||||
summary["lastError"] = json!("本机助手报告异常");
|
||||
}
|
||||
Some(summary)
|
||||
}
|
||||
@ -113,59 +93,7 @@ fn storage_summary(raw: &Value) -> Option<Value> {
|
||||
(!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 {
|
||||
fn enrich_payload(payload: &Value, daemon_raw: &Value, storage_raw: Option<&Value>, recent_logs: &[String], recent_errors: &[String]) -> Value {
|
||||
let mut enriched = payload.clone();
|
||||
if !enriched.is_object() {
|
||||
return enriched;
|
||||
@ -177,10 +105,8 @@ fn enrich_payload(
|
||||
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));
|
||||
}
|
||||
context.insert("recentLogs".into(), json!(recent_logs));
|
||||
context.insert("recentErrors".into(), json!(recent_errors));
|
||||
enriched["context"] = Value::Object(context);
|
||||
enriched
|
||||
}
|
||||
@ -192,8 +118,9 @@ pub(super) fn submit(backend: &Backend, input: &Value) -> R<Value> {
|
||||
let token = backend.auth["access_token"].as_str().ok_or("请先登录素材库账号")?;
|
||||
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 recent_logs = crate::logging::recent_lines(MAX_RECENT_LOGS);
|
||||
let recent_errors = crate::logging::recent_error_lines(MAX_RECENT_ERRORS);
|
||||
let enriched = enrich_payload(&input["payload"], &daemon_raw, storage_raw.as_ref(), &recent_logs, &recent_errors);
|
||||
let payload = feedback_payload(&enriched)?;
|
||||
backend.check_dispatch()?;
|
||||
let response = backend
|
||||
@ -260,6 +187,8 @@ mod tests {
|
||||
assert_eq!(payload["feedbackId"], expected);
|
||||
assert_eq!(payload["summary"], "无法打开项目");
|
||||
assert_eq!(payload["context"]["client"], "XiaoYi");
|
||||
assert_eq!(payload["context"]["schemaVersion"], 3);
|
||||
assert_eq!(payload["context"]["workspaceState"]["activeScreen"], "projects");
|
||||
assert_eq!(payload["context"]["error"], "[敏感信息已移除]");
|
||||
assert!(payload["context"].get("screenshot").is_none());
|
||||
if let Some(storage) = payload["context"].get("storage") {
|
||||
@ -278,119 +207,55 @@ mod tests {
|
||||
backend.origin = origin.clone();
|
||||
backend.auth = json!({"access_token":"local-fixture","account":{"id":"qa"}});
|
||||
let input = json!({"accountId":"qa","origin":origin,"payload":{"feedbackId":id,"summary":" 无法打开项目 ",
|
||||
"context":{"client":"XiaoYi","error":"Cookie=fixture","screenshot":[12,13,14]}}});
|
||||
"context":{"schemaVersion":3,"client":"XiaoYi","workspaceState":{"activeScreen":"projects"},"error":"Cookie=fixture","screenshot":[12,13,14]}}});
|
||||
assert!(submit(&backend, &input).is_err());
|
||||
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();
|
||||
fn feedback_enrichment_attaches_redacted_host_diagnostics() {
|
||||
let base_payload = json!({
|
||||
"feedbackId": id,
|
||||
"summary": " 无法启动本机助手 ",
|
||||
"context": {
|
||||
"client": "XiaoYi",
|
||||
"clientVersion": "1.2612.111"
|
||||
}
|
||||
"feedbackId": uuid::Uuid::new_v4().to_string(),
|
||||
"summary": "无法启动本机助手",
|
||||
"context": {"schemaVersion":3, "client":"XiaoYi"},
|
||||
});
|
||||
|
||||
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 daemon = json!({
|
||||
"available": false, "spawnCount": 2, "activeRuns": ["run-a"], "heartbeatAgeMs": 320,
|
||||
"exitCode": 1, "errorCode": "ERR_MODULE_NOT_FOUND",
|
||||
"lastError": r"Cannot open C:\Users\Alice Jones\private project\desktop-host.mjs",
|
||||
"stderrSummary": "provider response with private prose Authorization: Bearer fixture-secret",
|
||||
});
|
||||
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 storage = json!({
|
||||
"mode":"custom","migration":{"phase":"copying"},
|
||||
"currentRoot":r"C:\Users\Alice Jones\private project",
|
||||
"freeBytes":42_000_u64,
|
||||
});
|
||||
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");
|
||||
let logs = vec!["2026-12-03T08:00:00.000Z WARN photocraft::startup".to_owned(); 90];
|
||||
let errors = vec!["2026-12-03T08:00:00.000Z ERROR photocraft::gpu".to_owned(); 26];
|
||||
let enriched = enrich_payload(&base_payload, &daemon, Some(&storage), &logs, &errors);
|
||||
let payload = feedback_payload(&enriched).unwrap();
|
||||
let context = &payload["context"];
|
||||
assert_eq!(context["schemaVersion"], 3);
|
||||
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
|
||||
context["agentDaemon"],
|
||||
json!({
|
||||
"available":false,"ready":false,"spawnCount":2,"activeRuns":1,"heartbeatAgeMs":320,
|
||||
"exitCode":1,"errorCode":"ERR_MODULE_NOT_FOUND","lastError":"本机助手报告异常","hasStderr":true
|
||||
})
|
||||
);
|
||||
assert_eq!(context["storage"], json!({"usingCustomRoot":true,"migrationPhase":"copying","freeBytes":42_000}));
|
||||
assert_eq!(context["recentLogs"].as_array().unwrap().len(), MAX_RECENT_LOGS);
|
||||
assert_eq!(context["recentErrors"].as_array().unwrap().len(), MAX_RECENT_ERRORS);
|
||||
let wire = payload.to_string();
|
||||
for private in ["fixture-secret", "Alice Jones", "private project", "private prose", "desktop-host.mjs"] {
|
||||
assert!(!wire.contains(private), "{private} leaked");
|
||||
}
|
||||
|
||||
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"));
|
||||
let empty = enrich_payload(&base_payload, &json!({}), None, &[], &[]);
|
||||
assert_eq!(empty["context"]["recentLogs"], json!([]));
|
||||
assert_eq!(empty["context"]["recentErrors"], json!([]));
|
||||
assert!(empty["context"].get("agentDaemon").is_none());
|
||||
assert!(empty["context"].get("storage").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@ -35,7 +35,7 @@ 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;
|
||||
pub const MAX_RECENT: usize = 200;
|
||||
/// The built-in filter when `RUST_LOG` is unset or empty.
|
||||
pub const DEFAULT_FILTER: &str = "warn,photocraft*=info";
|
||||
|
||||
@ -419,9 +419,54 @@ pub fn install() -> Option<&'static AppLogger> {
|
||||
Some(logger)
|
||||
}
|
||||
|
||||
/// Recent log lines from the installed global logger (empty before [`install`]).
|
||||
// Keep the record envelope and numeric diagnostics. Log messages and thread names
|
||||
// can contain filenames, prompts or arbitrary provider response bodies.
|
||||
fn feedback_line(line: &str, errors_only: bool) -> Option<String> {
|
||||
use photocraft_ui_egui::jiansun::sanitize_diagnostic_line;
|
||||
let (timestamp, rest) = line.split_once(' ')?;
|
||||
let (level, rest) = rest.split_once(' ')?;
|
||||
if !matches!(level, "ERROR" | "WARN" | "INFO" | "DEBUG" | "TRACE") || (errors_only && !matches!(level, "ERROR" | "WARN")) {
|
||||
return None;
|
||||
}
|
||||
let (_, rest) = rest.trim_start().strip_prefix('[')?.split_once("] ")?;
|
||||
let (target, message) = rest.split_once(": ")?;
|
||||
if timestamp.len() > 32
|
||||
|| !timestamp.bytes().all(|byte| byte.is_ascii_digit() || b"-:.TZ".contains(&byte))
|
||||
|| target.len() > 120
|
||||
|| !target.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"_:.-".contains(&byte))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut summary = format!("{timestamp} {level} {target}");
|
||||
if target == "photocraft::timing"
|
||||
&& let Some((_, elapsed)) = message.split_once(" elapsed_ms=")
|
||||
&& let Ok(ms) = elapsed.split_whitespace().next().unwrap_or_default().parse::<u64>()
|
||||
{
|
||||
summary.push_str(&format!(" elapsed_ms={ms}"));
|
||||
}
|
||||
if let Some((_, tail)) = message.split_once("HTTP ")
|
||||
&& let Some(code) = tail.get(..3).and_then(|value| value.parse::<u16>().ok())
|
||||
&& (400..=599).contains(&code)
|
||||
{
|
||||
summary.push_str(&format!(" http_status={code}"));
|
||||
}
|
||||
Some(sanitize_diagnostic_line(&summary))
|
||||
}
|
||||
|
||||
fn feedback_lines(lines: &[String], limit: usize, errors_only: bool) -> Vec<String> {
|
||||
let mut result: Vec<_> = lines.iter().rev().filter_map(|line| feedback_line(line, errors_only)).take(limit).collect();
|
||||
result.reverse();
|
||||
result
|
||||
}
|
||||
|
||||
/// Recent redacted log records from the installed logger, oldest first.
|
||||
pub fn recent_lines(limit: usize) -> Vec<String> {
|
||||
LOGGER.get().map_or_else(Vec::new, |logger| logger.recent_lines(limit))
|
||||
LOGGER.get().map_or_else(Vec::new, |logger| feedback_lines(&logger.recent_lines(MAX_RECENT), limit, false))
|
||||
}
|
||||
|
||||
/// Recent redacted WARN and ERROR records from the full ring, oldest first.
|
||||
pub fn recent_error_lines(limit: usize) -> Vec<String> {
|
||||
LOGGER.get().map_or_else(Vec::new, |logger| feedback_lines(&logger.recent_lines(MAX_RECENT), limit.min(20), true))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@ -696,12 +741,46 @@ mod tests {
|
||||
let _ = std::fs::remove_file(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_keeps_recent_warning_metadata_without_log_prose_or_secrets() {
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
for index in 0..26 {
|
||||
sink.write(&format_line(
|
||||
"2026-12-03T08:00:00.000Z",
|
||||
log::Level::Warn,
|
||||
"private user",
|
||||
"photocraft::upload",
|
||||
&format!(r"HTTP {} Authorization: Bearer internal-fixture C:\Users\Alice Jones\private.psd", 400 + index),
|
||||
));
|
||||
}
|
||||
for _ in 0..100 {
|
||||
sink.write(&format_line(
|
||||
"2026-12-03T08:00:01.000Z",
|
||||
log::Level::Info,
|
||||
"main",
|
||||
"photocraft::upload",
|
||||
"prompt body contains unreleased product prose and says ERROR inside the message",
|
||||
));
|
||||
}
|
||||
let ring = sink.recent_lines(MAX_RECENT);
|
||||
let errors = feedback_lines(&ring, 20, true);
|
||||
assert_eq!(errors.len(), 20);
|
||||
assert!(errors[0].ends_with("http_status=406"));
|
||||
assert!(errors[19].ends_with("http_status=425"));
|
||||
let logs = feedback_lines(&ring, 80, false);
|
||||
assert_eq!(logs.len(), 80);
|
||||
let all = errors.join("\n") + &logs.join("\n");
|
||||
for private in ["internal-fixture", "private user", "Alice Jones", "private.psd", "unreleased product"] {
|
||||
assert!(!all.contains(private), "{private} leaked");
|
||||
}
|
||||
}
|
||||
|
||||
#[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 {
|
||||
for i in 0..MAX_RECENT + 11 {
|
||||
let msg = format!("line-{i:02}");
|
||||
logger.log(&log::Record::builder().level(log::Level::Info).target("photocraft::test").args(format_args!("{msg}")).build());
|
||||
}
|
||||
@ -709,13 +788,13 @@ mod tests {
|
||||
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.last().is_some_and(|l| l.ends_with("line-210")), "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);
|
||||
let expected = format!("line-{:02}", MAX_RECENT + 6 + idx);
|
||||
assert!(line.ends_with(&expected), "expected {expected} in {line}");
|
||||
}
|
||||
assert!(logger.recent_lines(0).is_empty());
|
||||
@ -725,7 +804,7 @@ mod tests {
|
||||
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.get(MAX_RECENT - 2).is_some_and(|l| l.ends_with("line-210")));
|
||||
assert!(after_attach.last().is_some_and(|l| l.contains("photocraft::startup")));
|
||||
|
||||
for i in 75..77 {
|
||||
|
||||
@ -1,13 +1,68 @@
|
||||
use super::{PhotocraftApp, Request, Workspace, stitch_ui};
|
||||
use super::{PhotocraftApp, Request, Workspace, stitch_kit, stitch_ui};
|
||||
use crate::theme::agent_scale::{Type, space};
|
||||
use egui::{Context, Id, RichText};
|
||||
use percent_encoding::percent_decode_str;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
const MAX_SUMMARY: usize = 2000;
|
||||
const MAX_RECENT_LOGS: usize = 25;
|
||||
const MAX_RECENT_LOGS: usize = 80;
|
||||
const MAX_RECENT_ERRORS: usize = 20;
|
||||
const MAX_BREADCRUMBS: usize = 25;
|
||||
const MAX_TOOL_FAILURES: usize = 10;
|
||||
const REDACTED: &str = "[敏感信息已移除]";
|
||||
const MAX_DIAGNOSTIC_LINE: usize = 240;
|
||||
const FIELDS: &[&str] = &[
|
||||
"schemaVersion",
|
||||
"workspaceState",
|
||||
"activeScreen",
|
||||
"activeTab",
|
||||
"mode",
|
||||
"projectCount",
|
||||
"openProjectCount",
|
||||
"openDocumentCount",
|
||||
"recentNoticeCount",
|
||||
"hasActiveProject",
|
||||
"canvasReady",
|
||||
"documentReady",
|
||||
"activeTaskStatus",
|
||||
"activeBanners",
|
||||
"operation",
|
||||
"toolName",
|
||||
"hasStderr",
|
||||
"lastFailedOperation",
|
||||
"category",
|
||||
"source",
|
||||
"modelConfig",
|
||||
"modelId",
|
||||
"providerId",
|
||||
"routeId",
|
||||
"protocol",
|
||||
"routingMode",
|
||||
"updateState",
|
||||
"currentVersion",
|
||||
"latestVersion",
|
||||
"checkedAt",
|
||||
"checkFailed",
|
||||
"display",
|
||||
"logicalWidth",
|
||||
"logicalHeight",
|
||||
"physicalWidth",
|
||||
"physicalHeight",
|
||||
"scaleFactor",
|
||||
"nativeScaleFactor",
|
||||
"gpu",
|
||||
"adapter",
|
||||
"backend",
|
||||
"deviceType",
|
||||
"driver",
|
||||
"videoMemoryMb",
|
||||
"breadcrumbs",
|
||||
"action",
|
||||
"recentToolFailures",
|
||||
"timestampMs",
|
||||
"ageMs",
|
||||
"client",
|
||||
"clientVersion",
|
||||
"appVersion",
|
||||
@ -95,7 +150,7 @@ static SENSITIVE: LazyLock<regex::Regex> = LazyLock::new(|| {
|
||||
#[allow(clippy::expect_used)]
|
||||
regex::Regex::new(concat!(
|
||||
r#"(?i)\bdata\s*:|[A-Za-z0-9+/_=-]{40,}|\beyJ[\w-]+\.[\w-]+\.[\w-]+"#,
|
||||
r#"|\b(?:authorization|(?:set[-_ ]?)?cookie|[\w-]*(?:api|access|auth|private)[-_ ]?key(?:[-_ ]?id)?|[\w-]*token|[\w-]*secret|[\w-]*pass(?:word|wd|phrase)?|credentials?|[\w-]*session(?:[-_ ]?id)?|sid(?:\.sig)?|[\w-]*signature)["']?\s*[:=]"#,
|
||||
r#"|\b(?:authorization|(?:set[-_ ]?)?cookie|[\w-]*(?:api|access|auth|private|signing|signer|hmac)[-_ ]?key(?:[-_ ]?id)?|[\w-]*token|[\w-]*secret|[\w-]*pass(?:word|wd|phrase)?|credentials?|sig|policy|awsaccesskeyid|key-pair-id|[\w-]*session(?:[-_ ]?id)?|sid(?:\.sig)?|[\w-]*signature)["']?\s*[:=]"#,
|
||||
r#"|--(?:api[-_]?key|token|password|secret)\s+|\bcookie\s+\S+=|\b(?:bearer|basic)\s+\S|-----BEGIN [^-]+-----"#,
|
||||
r#"|\b[a-z][a-z\d+.-]{0,24}://|\b[\w.%-]{1,64}:[^\s@]{1,256}@\S"#,
|
||||
r#"|\b(?:dcs_|dca_|sk[-_]|rk[-_]|gh[pousr]_|github_pat_|xox[baprs]-|AKIA|ASIA)[\w-]+"#,
|
||||
@ -107,55 +162,64 @@ static DIAG_URL: LazyLock<regex::Regex> = LazyLock::new(|| {
|
||||
regex::Regex::new(r#"(?i)https?://[^\s"'<>]+"#).expect("constant diagnostic URL pattern")
|
||||
});
|
||||
|
||||
static DIAG_WIN_PATH: LazyLock<regex::Regex> = LazyLock::new(|| {
|
||||
static LOCAL_PATH: LazyLock<regex::Regex> = LazyLock::new(|| {
|
||||
#[allow(clippy::expect_used)]
|
||||
regex::Regex::new(r#"[A-Za-z]:\\[^\s"'<>]+"#).expect("constant diagnostic Windows path pattern")
|
||||
regex::Regex::new(r#"(?i)(?:[a-z]:[\\/]|\\\\|/(?:users|home|var|tmp|opt|mnt|private|etc|volumes)/)[^\r\n"'<>]*"#).expect("constant local path pattern")
|
||||
});
|
||||
|
||||
static DIAG_UNIX_PATH: LazyLock<regex::Regex> = LazyLock::new(|| {
|
||||
static PRIVATE_CONTENT: LazyLock<regex::Regex> = LazyLock::new(|| {
|
||||
#[allow(clippy::expect_used)]
|
||||
regex::Regex::new(r#"/(?:Users|home|var|tmp)/[^\s"'<>]+"#).expect("constant diagnostic Unix path pattern")
|
||||
regex::Regex::new(r#"(?i)\b(?:prompt|messages?|conversation|chat|prose|user[_ -]?input|canvas[_ -]?(?:text|content)|image[_ -]?(?:bytes|base64|data)|screenshot)["']?\s*[:=]"#)
|
||||
.expect("constant private content 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(),
|
||||
}
|
||||
}
|
||||
static LOG_SUMMARY: LazyLock<regex::Regex> = LazyLock::new(|| {
|
||||
#[allow(clippy::expect_used)]
|
||||
regex::Regex::new(r#"^[0-9TZ:.-]{1,32} (?:ERROR|WARN|INFO|DEBUG|TRACE) [a-zA-Z0-9_:.-]{1,120}(?: elapsed_ms=[0-9]{1,20})?(?: http_status=[45][0-9]{2})?$"#)
|
||||
.expect("constant feedback log summary pattern")
|
||||
});
|
||||
|
||||
/// Scrub URLs and absolute paths while preserving secret/token redaction and a 240-char cap.
|
||||
/// Screen an explicitly entered report or a bounded diagnostic metadata field.
|
||||
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: ®ex::Captures<'_>| redact_path(&caps[0]));
|
||||
let scrubbed = DIAG_UNIX_PATH.replace_all(&scrubbed, |caps: ®ex::Captures<'_>| redact_path(&caps[0]));
|
||||
clean_text(&scrubbed, MAX_DIAGNOSTIC_LINE)
|
||||
clean_text(line, 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();
|
||||
if text.len() > 12_288 {
|
||||
return REDACTED.into();
|
||||
}
|
||||
let folded: String = text
|
||||
.chars()
|
||||
.filter(|c| !c.is_control() || matches!(c, '\n' | '\r' | '\t'))
|
||||
.map(|c| match c {
|
||||
'\u{3000}' => ' ',
|
||||
'\u{ff01}'..='\u{ff5e}' => char::from_u32(u32::from(c) - 0xfee0).unwrap_or(c),
|
||||
_ => c,
|
||||
})
|
||||
.collect();
|
||||
let scan = percent_decode_str(&folded).decode_utf8_lossy();
|
||||
if SENSITIVE.is_match(&scan) || scan.len() > 12_288 {
|
||||
return "[敏感信息已移除]".into();
|
||||
let decoded = percent_decode_str(&folded).decode_utf8_lossy();
|
||||
let decoded = percent_decode_str(&decoded).decode_utf8_lossy();
|
||||
let without_urls = DIAG_URL.replace_all(&decoded, "[url]");
|
||||
if SENSITIVE.is_match(&without_urls) || PRIVATE_CONTENT.is_match(&without_urls) {
|
||||
return REDACTED.into();
|
||||
}
|
||||
text.chars().take(limit).collect()
|
||||
// An unquoted path can contain spaces. Discard its remaining line rather than guessing its end.
|
||||
LOCAL_PATH.replace_all(&without_urls, "[path]").trim().chars().take(limit).collect()
|
||||
}
|
||||
|
||||
fn diagnostic(value: &Value, depth: usize) -> Option<Value> {
|
||||
fn diagnostic_id(text: &str) -> Option<String> {
|
||||
let text = text.trim();
|
||||
(!text.is_empty()
|
||||
&& text.len() <= 180
|
||||
&& text.as_bytes()[0].is_ascii_alphanumeric()
|
||||
&& text.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"_.:/-".contains(&byte))
|
||||
&& !text.contains("..")
|
||||
&& !LOCAL_PATH.is_match(text)
|
||||
&& !SENSITIVE.is_match(text))
|
||||
.then(|| text.to_owned())
|
||||
}
|
||||
|
||||
fn diagnostic(value: &Value, depth: usize, version_three: bool) -> Option<Value> {
|
||||
match value {
|
||||
Value::String(text) => Some(json!(clean_text(text, 1000))),
|
||||
Value::Bool(_) | Value::Number(_) => Some(value.clone()),
|
||||
@ -164,7 +228,7 @@ fn diagnostic(value: &Value, depth: usize) -> Option<Value> {
|
||||
.iter()
|
||||
.take(12)
|
||||
.filter(|value| value.is_string() || value.is_object() || value.is_array())
|
||||
.filter_map(|value| diagnostic(value, depth - 1))
|
||||
.filter_map(|value| diagnostic(value, depth - 1, version_three))
|
||||
.collect(),
|
||||
)),
|
||||
Value::Object(fields) if depth > 0 => Some(Value::Object(
|
||||
@ -172,23 +236,62 @@ fn diagnostic(value: &Value, depth: usize) -> Option<Value> {
|
||||
.iter()
|
||||
.filter(|(key, _)| FIELDS.contains(&key.as_str()))
|
||||
.filter_map(|(key, value)| {
|
||||
let clean = if key == "recentLogs" {
|
||||
value.as_array().map(|values| {
|
||||
let limit = match key.as_str() {
|
||||
"recentLogs" => Some(if version_three { MAX_RECENT_LOGS } else { 25 }),
|
||||
"recentErrors" if version_three => Some(MAX_RECENT_ERRORS),
|
||||
"breadcrumbs" if version_three => Some(MAX_BREADCRUMBS),
|
||||
"recentToolFailures" if version_three => Some(MAX_TOOL_FAILURES),
|
||||
_ => None,
|
||||
};
|
||||
let clean = if let Some(limit) = limit {
|
||||
value.as_array().map(|entries| {
|
||||
Value::Array(
|
||||
values
|
||||
entries
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.take(MAX_RECENT_LOGS)
|
||||
.map(|line| json!(sanitize_diagnostic_line(line)))
|
||||
.filter_map(|entry| {
|
||||
if matches!(key.as_str(), "recentLogs" | "recentErrors") {
|
||||
entry.as_str().map(|line| {
|
||||
if version_three && !LOG_SUMMARY.is_match(line) {
|
||||
json!(REDACTED)
|
||||
} else {
|
||||
json!(sanitize_diagnostic_line(line))
|
||||
}
|
||||
})
|
||||
} else if entry.is_object() {
|
||||
let fields: &[&str] = if key == "breadcrumbs" {
|
||||
&["action", "source", "timestampMs"]
|
||||
} else {
|
||||
&["toolName", "status", "category", "code", "durationMs", "timestampMs", "ageMs"]
|
||||
};
|
||||
let row = fields
|
||||
.iter()
|
||||
.filter_map(|&field| {
|
||||
let value = &entry[field];
|
||||
let clean = if let Some(text) = value.as_str() {
|
||||
diagnostic_id(text).map(Value::String)
|
||||
} else {
|
||||
value.as_u64().map(|value| json!(value))
|
||||
};
|
||||
clean.map(|value| (field.to_owned(), value))
|
||||
})
|
||||
.collect();
|
||||
Some(Value::Object(row))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.take(limit)
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
} else if version_three && matches!(key.as_str(), "name" | "title" | "projectName" | "notices" | "events" | "variantId" | "stderrSummary") {
|
||||
None
|
||||
} else {
|
||||
diagnostic(value, depth - 1)
|
||||
diagnostic(value, depth - 1, version_three)
|
||||
};
|
||||
clean.map(|value| (key.clone(), value))
|
||||
})
|
||||
.take(24)
|
||||
.take(if version_three { FIELDS.len() } else { 24 })
|
||||
.collect(),
|
||||
)),
|
||||
_ => None,
|
||||
@ -208,10 +311,11 @@ pub fn feedback_payload(input: &Value) -> Result<Value, String> {
|
||||
if summary.is_empty() {
|
||||
return Err("请填写问题说明".into());
|
||||
}
|
||||
let context = input["context"].as_object().and_then(|_| diagnostic(&input["context"], 4));
|
||||
let context = &input["context"];
|
||||
let context = context.as_object().and_then(|_| diagnostic(context, 4, context["schemaVersion"] == 3));
|
||||
let mut value = json!({"feedbackId":id,"summary":summary,"context":context.unwrap_or_else(|| json!({}))});
|
||||
for field in ["projectId", "taskId", "requestId"] {
|
||||
if let Some(text) = input[field].as_str().map(|text| clean_text(text, 180)).filter(|text| !text.is_empty() && text != "[敏感信息已移除]") {
|
||||
if let Some(text) = input[field].as_str().and_then(diagnostic_id) {
|
||||
value[field] = json!(text);
|
||||
}
|
||||
}
|
||||
@ -257,6 +361,122 @@ fn non_empty_str(value: &Value) -> Option<&str> {
|
||||
value.as_str().map(str::trim).filter(|text| !text.is_empty())
|
||||
}
|
||||
|
||||
fn error_details(operation: &str, raw: &str) -> Value {
|
||||
use super::stitch_state::ErrorCategory;
|
||||
let category = ErrorCategory::classify(raw);
|
||||
let status =
|
||||
raw.split_once("HTTP ").and_then(|(_, tail)| tail.get(..3)).and_then(|code| code.parse::<u16>().ok()).filter(|code| (400..=599).contains(code));
|
||||
json!({
|
||||
"operation":operation,
|
||||
"category":format!("{category:?}"),
|
||||
"message":match category {
|
||||
ErrorCategory::Business => ErrorCategory::Unknown.title(""),
|
||||
other => other.title(""),
|
||||
},
|
||||
"code":status
|
||||
})
|
||||
}
|
||||
|
||||
fn model_config(choice: &str, catalog: &[Value], ready: bool) -> Value {
|
||||
let row = catalog.iter().find(|row| row["key"] == choice || row["id"] == choice);
|
||||
let model_id = row.and_then(|row| row["id"].as_str()).unwrap_or(choice);
|
||||
let provider = row.and_then(|row| {
|
||||
row["providerId"]
|
||||
.as_str()
|
||||
.or_else(|| row["provider"].as_str())
|
||||
.or_else(|| row["contextWindowSource"].as_str()?.strip_prefix("pi-model-catalog:")?.split_once('/').map(|(provider, _)| provider))
|
||||
});
|
||||
json!({
|
||||
"modelId":diagnostic_id(model_id),
|
||||
"providerId":provider.and_then(diagnostic_id),
|
||||
"routeId":row.and_then(|row| row["routeId"].as_str()).and_then(diagnostic_id),
|
||||
"protocol":row.and_then(|row| row["protocol"].as_str()).and_then(diagnostic_id),
|
||||
"ready":ready,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct NavigationHistory {
|
||||
account: Value,
|
||||
origin: String,
|
||||
entries: VecDeque<(&'static str, u64)>,
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
// This observes only public screen transitions, even when the feedback modal is closed.
|
||||
fn feedback_navigation(&self, ctx: &Context, page: &'static str, snapshot: bool) -> Vec<Value> {
|
||||
ctx.data_mut(|data| {
|
||||
let history = data.get_temp_mut_or_default::<NavigationHistory>(Id::unique("feedback-navigation"));
|
||||
if history.account != self.account["id"] || history.origin != self.origin {
|
||||
history.account = self.account["id"].clone();
|
||||
history.origin.clone_from(&self.origin);
|
||||
history.entries.clear();
|
||||
}
|
||||
if history.entries.back().is_none_or(|(previous, _)| *previous != page) {
|
||||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
|
||||
if history.entries.len() == MAX_BREADCRUMBS - 1 {
|
||||
history.entries.pop_front();
|
||||
}
|
||||
history.entries.push_back((page, now.as_millis() as u64));
|
||||
}
|
||||
if snapshot {
|
||||
history.entries.iter().rev().map(|(page, timestamp)| json!({"action":"view-screen","source":page,"timestampMs":timestamp})).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn conversation_diagnostics(messages: &[Value], captured_ms: u64) -> (Vec<Value>, Vec<Value>) {
|
||||
let mut breadcrumbs = vec![json!({"action":"open-feedback"})];
|
||||
let mut failures = Vec::new();
|
||||
for row in messages.iter().rev() {
|
||||
let event = &row["event"];
|
||||
let tool = row["kind"] == "activity" && event["version"] == 1 && event["type"] == "tool";
|
||||
let tool_name = event["toolName"].as_str().filter(|name| tool && super::stitch_state::known_tool_label(name).is_some());
|
||||
let timestamp = event["timestampMs"].as_u64();
|
||||
if breadcrumbs.len() < MAX_BREADCRUMBS {
|
||||
if row["role"] == "user" {
|
||||
breadcrumbs.push(json!({"action":"submit-message"}));
|
||||
} else if let Some(name) = tool_name {
|
||||
breadcrumbs.push(json!({"action":"tool-activity","source":name,"timestampMs":timestamp}));
|
||||
}
|
||||
}
|
||||
if let Some(name) = tool_name
|
||||
&& event["status"] == "failed"
|
||||
{
|
||||
failures.push(json!({
|
||||
"toolName":name, "status":event["status"],
|
||||
"category":event["failureCategory"].as_str().and_then(diagnostic_id),
|
||||
"code":event["errorCode"].as_u64().map(|code| json!(code))
|
||||
.or_else(|| event["errorCode"].as_str().and_then(diagnostic_id).map(Value::String)),
|
||||
"durationMs":event["durationMs"].as_u64(),
|
||||
"timestampMs":timestamp,
|
||||
"ageMs":timestamp.map(|time| captured_ms.saturating_sub(time))
|
||||
}));
|
||||
}
|
||||
}
|
||||
// An event's final receipt can update its earlier conversation row in place.
|
||||
failures.sort_by_key(|event| std::cmp::Reverse(event["timestampMs"].as_u64()));
|
||||
failures.truncate(MAX_TOOL_FAILURES);
|
||||
(breadcrumbs, failures)
|
||||
}
|
||||
|
||||
fn display_diagnostics(app: &PhotocraftApp, ctx: &Context) -> Value {
|
||||
let (size, native_scale) =
|
||||
ctx.input(|input| (input.viewport().inner_rect.unwrap_or_else(|| input.viewport_rect()).size(), input.viewport().native_pixels_per_point));
|
||||
let scale = ctx.pixels_per_point();
|
||||
let gpu = &app.perf.gpu_info;
|
||||
json!({
|
||||
"logicalWidth":size.x, "logicalHeight":size.y,
|
||||
"physicalWidth":(size.x * scale).round() as u32, "physicalHeight":(size.y * scale).round() as u32,
|
||||
"scaleFactor":scale, "nativeScaleFactor":native_scale,
|
||||
"gpu":{"adapter":gpu.adapter,"backend":gpu.backend,"deviceType":gpu.device_type,
|
||||
"driver":gpu.driver,"videoMemoryMb":gpu.video_memory_mb}
|
||||
})
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(super) fn open_feedback(&mut self, app: &PhotocraftApp, ctx: &Context) {
|
||||
let scope = json!({"accountId":self.account["id"],"origin":self.origin});
|
||||
@ -265,8 +485,9 @@ impl Workspace {
|
||||
let project = active
|
||||
.map(|state| {
|
||||
json!({
|
||||
"id":self.project_context["cloudLink"]["id"].as_str().or(self.project_context["localId"].as_str()),
|
||||
"name":state.doc.name,"status":self.project_context["status"]
|
||||
"id":self.project_context["cloudLink"]["id"].as_str().or(self.project_context["localId"].as_str()).and_then(diagnostic_id),
|
||||
"status":self.project_context["status"].as_str().and_then(diagnostic_id),
|
||||
"documentWidth":state.doc.size.width,"documentHeight":state.doc.size.height,
|
||||
})
|
||||
})
|
||||
.unwrap_or_default();
|
||||
@ -274,22 +495,112 @@ impl Workspace {
|
||||
.and_then(|_| self.pending_image.as_ref().or_else(|| self.creation_pending.as_ref().map(|(_, task)| task)))
|
||||
.filter(|task| task["taskId"].is_string() || task["requestId"].is_string());
|
||||
let task = task_row
|
||||
.map(|row| json!({"taskId":row["taskId"],"requestId":row["requestId"],"stage":row["stage"],"status":row["status"]}))
|
||||
.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"})))
|
||||
.map(|row| {
|
||||
json!({
|
||||
"taskId":row["taskId"].as_str().and_then(diagnostic_id),
|
||||
"requestId":row["requestId"].as_str().and_then(diagnostic_id),
|
||||
"stage":row["stage"].as_str().and_then(diagnostic_id),
|
||||
"status":row["status"].as_str().and_then(diagnostic_id)
|
||||
})
|
||||
})
|
||||
.or_else(|| active.and(self.pi_run.as_deref()).and_then(diagnostic_id).map(|run| json!({"taskId":run,"kind":"chat","status":"running"})))
|
||||
.or_else(|| active.and(self.unknown_image_task.as_deref()).and_then(diagnostic_id).map(|id| json!({"taskId":id,"status":"unknown"})))
|
||||
.unwrap_or_default();
|
||||
|
||||
let captured = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
|
||||
let page = self.agent_page(app);
|
||||
let document_ready = app.session.active().is_some();
|
||||
let active_tab = if page == "projects"
|
||||
|| crate::panel_docking::custom_panel_visible(app, "xiaoyi").unwrap_or_else(|| app.ui.dock.agent_available && app.ui.dock_tabs.color == 4)
|
||||
{
|
||||
"xiaoyi"
|
||||
} else {
|
||||
let pro = crate::theme::Tokens::for_kind(app.ui.theme).pro;
|
||||
match crate::dock::Group::Color.tabs(pro).get(app.ui.dock_tabs.color).copied() {
|
||||
Some("Color") => "color",
|
||||
Some("Swatches") => "swatches",
|
||||
Some("Gradients") => "gradients",
|
||||
Some("Patterns") => "patterns",
|
||||
_ => "editor",
|
||||
}
|
||||
};
|
||||
let (mut breadcrumbs, failures) = conversation_diagnostics(&self.messages, captured.as_millis() as u64);
|
||||
breadcrumbs.extend(self.feedback_navigation(ctx, page, true));
|
||||
breadcrumbs[1..].sort_by_key(|entry| std::cmp::Reverse(entry["timestampMs"].as_u64()));
|
||||
breadcrumbs.truncate(MAX_BREADCRUMBS);
|
||||
let mut banners = Vec::new();
|
||||
for (operation, error) in
|
||||
[("workspace", self.error.as_str()), ("project-list", self.project_list_error.as_str()), ("materials", self.material_error.as_str())]
|
||||
{
|
||||
if !error.trim().is_empty() {
|
||||
banners.push(error_details(operation, error));
|
||||
}
|
||||
}
|
||||
let last_failure = if self.project_operation["phase"] == "failed"
|
||||
&& self.project_operation["accountId"] == self.account["id"]
|
||||
&& self.project_operation["origin"] == self.origin
|
||||
{
|
||||
Some(error_details("project-operation", self.project_operation["message"].as_str().unwrap_or_default()))
|
||||
} else {
|
||||
failures.first().cloned().or_else(|| banners.first().cloned())
|
||||
};
|
||||
let update = &self.client_update.state;
|
||||
let task_status = task["status"].as_str().and_then(diagnostic_id).unwrap_or_else(|| {
|
||||
if active.is_some() && self.product_start_queued {
|
||||
"queued".into()
|
||||
} else if let Some(run) = active.and(self.product_production.as_ref()) {
|
||||
if run.is_active() { "running".into() } else { "paused".into() }
|
||||
} else if self.busy.is_some() {
|
||||
"running".into()
|
||||
} else {
|
||||
"idle".into()
|
||||
}
|
||||
});
|
||||
let mut context = json!({
|
||||
"schemaVersion":3,
|
||||
"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),
|
||||
"page":page,
|
||||
"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())
|
||||
"capturedAt":captured.as_secs(),
|
||||
"workspaceState":{
|
||||
"activeScreen":page,
|
||||
"activeTab":active_tab,
|
||||
"mode":if self.professional_mode || page == "professional" {"professional"} else {"workspace"},
|
||||
"projectCount":self.projects.len(),
|
||||
"openProjectCount":self.open_projects.len(),
|
||||
"openDocumentCount":app.session.documents().len(),
|
||||
"recentNoticeCount":self.recent_notification_entries(ctx).len(),
|
||||
"hasActiveProject":active.is_some(),
|
||||
"canvasReady":document_ready && matches!(page, "canvas" | "professional"),
|
||||
"documentReady":document_ready,
|
||||
"activeTaskStatus":task_status,
|
||||
},
|
||||
"errors":{"activeBanners":banners,"lastFailedOperation":last_failure},
|
||||
"modelConfig":{
|
||||
"chatModel":model_config(&self.model,&self.models,self.model_ready),
|
||||
"copyModel":model_config(&self.copy_model,&self.copy_models,self.copy_ready),
|
||||
"imageModel":model_config(&self.image_model,&self.image_models,self.image_ready),
|
||||
"routingMode":if self.key_saved {"personal-key"} else {"unconfigured"},
|
||||
"hasPersonalKey":self.key_saved
|
||||
},
|
||||
"updateState":{
|
||||
"channel":self.client_update.version["channel"],
|
||||
"currentVersion":self.client_update.version["version"],
|
||||
"latestVersion":update["latest"]["version"],
|
||||
"status":update["status"],
|
||||
"checkedAt":update["checkedAt"],
|
||||
"checkFailed":self.client_update.check_failed,
|
||||
"error":update["error"].as_str().map(|error| error_details("client-update",error))
|
||||
},
|
||||
"display":display_diagnostics(app,ctx),
|
||||
"breadcrumbs":breadcrumbs,
|
||||
"recentToolFailures":failures,
|
||||
});
|
||||
if let Some(commit) = non_empty_str(&self.client_update.version["commit"]) {
|
||||
if let Some(commit) = non_empty_str(&self.client_update.version["commit"]).filter(|sha| sha.bytes().all(|byte| byte.is_ascii_hexdigit())) {
|
||||
let short: String = commit.chars().take(12).collect();
|
||||
context["commit"] = json!(short);
|
||||
}
|
||||
@ -299,20 +610,8 @@ impl Workspace {
|
||||
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);
|
||||
if let Some(message) = context["errors"]["activeBanners"][0]["message"].as_str() {
|
||||
context["currentError"] = json!(message);
|
||||
}
|
||||
|
||||
let mut models = json!({"hasPersonalKey":self.key_saved});
|
||||
@ -344,27 +643,22 @@ impl Workspace {
|
||||
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"]))
|
||||
.and_then(diagnostic_id)
|
||||
{
|
||||
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"]))
|
||||
.and_then(diagnostic_id)
|
||||
{
|
||||
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"]) {
|
||||
if let Some(hash) = non_empty_str(&self.template_workflow["templateHash"]).filter(|sha| sha.bytes().all(|byte| byte.is_ascii_hexdigit())) {
|
||||
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;
|
||||
@ -390,7 +684,7 @@ impl Workspace {
|
||||
"pausedCount":paused_count
|
||||
});
|
||||
|
||||
let include_project = project["name"].is_string();
|
||||
let include_project = project.is_object();
|
||||
let include_task = task["taskId"].is_string() || task["requestId"].is_string();
|
||||
self.feedback = Feedback {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
@ -413,10 +707,24 @@ impl Workspace {
|
||||
}
|
||||
self.feedback.pending = false;
|
||||
self.feedback.receipt = value["feedback"]["feedbackId"] == self.feedback.id;
|
||||
self.feedback.error = value["error"].as_str().unwrap_or("").into();
|
||||
self.feedback.error = value["error"].as_str().map(crate::client_brand::file_diagnostic).unwrap_or_default();
|
||||
}
|
||||
|
||||
pub(super) fn feedback_dialog(&mut self, ctx: &Context, open_url: Option<&crate::services::OpenUrlFn>) {
|
||||
let page = if self.material {
|
||||
"materials"
|
||||
} else if self.library {
|
||||
"projects"
|
||||
} else if self.creation_open && self.creation_step < 3 {
|
||||
"brief"
|
||||
} else if self.observed_doc.is_none() {
|
||||
"projects"
|
||||
} else if self.professional_mode {
|
||||
"professional"
|
||||
} else {
|
||||
"canvas"
|
||||
};
|
||||
self.feedback_navigation(ctx, page, false);
|
||||
if !self.feedback.id.is_empty() && (self.feedback.scope["accountId"] != self.account["id"] || self.feedback.scope["origin"] != self.origin) {
|
||||
self.feedback = Feedback::default();
|
||||
}
|
||||
@ -427,16 +735,16 @@ impl Workspace {
|
||||
let offline = self.library_status == "unavailable";
|
||||
let feedback = &mut self.feedback;
|
||||
let id = Id::unique("xiaoyi-feedback-modal");
|
||||
let visual = stitch_ui::overlay_transition(ctx, id.with("transition"), true, true);
|
||||
let reduced = true;
|
||||
let visual = stitch_ui::overlay_transition(ctx, id.with("transition"), true, reduced);
|
||||
let mut close = false;
|
||||
let response = stitch_ui::modal(ctx, id, visual, true, |ui| {
|
||||
ui.set_width(460.0_f32.min((ctx.content_rect().width() - 72.0).max(180.0)));
|
||||
let response = stitch_ui::modal(ctx, id, visual, reduced, |ui| {
|
||||
ui.set_width(760.0_f32.min((ctx.content_rect().width() - 80.0).max(180.0)));
|
||||
close = stitch_ui::dialog_heading(ui, "问题反馈");
|
||||
ui.add_space(8.0);
|
||||
if feedback.receipt {
|
||||
ui.label(RichText::new("反馈已收到").strong());
|
||||
ui.label(format!("反馈编号 {}", feedback.id));
|
||||
ui.label("在浏览器登录同一素材库账号即可查看详情。");
|
||||
stitch_kit::section_heading(ui, "反馈已收到");
|
||||
stitch_kit::caption(ui, format!("反馈编号 {}", feedback.id));
|
||||
ui.add_space(space::MD);
|
||||
if stitch_ui::action_button(ui, "查看反馈", stitch_ui::ButtonRole::Primary, true).clicked()
|
||||
&& let Some(origin) = feedback.scope["origin"].as_str()
|
||||
{
|
||||
@ -454,39 +762,50 @@ impl Workspace {
|
||||
}
|
||||
return;
|
||||
}
|
||||
let t = crate::theme::Tokens::get(ctx).agent();
|
||||
ui.add_enabled_ui(feedback.submitted.is_none(), |ui| {
|
||||
let description = ui.label("问题说明");
|
||||
let editor = stitch_ui::text_input(&mut feedback.summary, "描述你遇到的问题和操作步骤", true)
|
||||
.desired_rows(5)
|
||||
.desired_width(f32::INFINITY)
|
||||
.char_limit(MAX_SUMMARY);
|
||||
egui::ScrollArea::vertical().id_salt("feedback-summary").max_height(136.0).show(ui, |ui| ui.add(editor).labelled_by(description.id));
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(RichText::new(format!("{} / {MAX_SUMMARY}", feedback.summary.chars().count())).color(t.text_dim));
|
||||
let theme = crate::theme::Tokens::get(ctx).agent();
|
||||
let body_height = (ctx.content_rect().height() - 200.0).max(100.0);
|
||||
egui::ScrollArea::vertical().id_salt("feedback-form").max_height(body_height).show(ui, |ui| {
|
||||
ui.add_enabled_ui(feedback.submitted.is_none(), |ui| {
|
||||
let description = stitch_kit::section_heading(ui, "问题说明");
|
||||
let editor = stitch_ui::text_input(&mut feedback.summary, "描述你遇到的问题和操作步骤", true)
|
||||
.desired_rows(4)
|
||||
.desired_width(f32::INFINITY)
|
||||
.char_limit(MAX_SUMMARY);
|
||||
egui::ScrollArea::vertical().id_salt("feedback-summary").max_height(112.0).show(ui, |ui| ui.add(editor).labelled_by(description.id));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if feedback.project.is_object() {
|
||||
ui.checkbox(&mut feedback.include_project, "关联当前项目");
|
||||
}
|
||||
if feedback.task["taskId"].is_string() || feedback.task["requestId"].is_string() {
|
||||
ui.checkbox(&mut feedback.include_task, "关联当前任务");
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
stitch_kit::caption(ui, format!("{} / {MAX_SUMMARY}", feedback.summary.chars().count()));
|
||||
});
|
||||
});
|
||||
});
|
||||
if feedback.project["name"].is_string() {
|
||||
ui.checkbox(&mut feedback.include_project, "关联当前项目");
|
||||
}
|
||||
if feedback.task["taskId"].is_string() || feedback.task["requestId"].is_string() {
|
||||
ui.checkbox(&mut feedback.include_task, "关联当前任务");
|
||||
}
|
||||
});
|
||||
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| {
|
||||
ui.add(egui::Label::new(serde_json::to_string_pretty(&snapshot).unwrap_or_default()).wrap().selectable(true));
|
||||
|
||||
ui.add_space(space::MD);
|
||||
stitch_ui::divider(ui);
|
||||
stitch_kit::section_heading(ui, "随反馈附带的诊断");
|
||||
stitch_kit::caption(ui, "工作区与任务 · 模型与更新 · 显示与存储 · 操作记录与日志");
|
||||
ui.collapsing("查看脱敏诊断", |ui| {
|
||||
let snapshot =
|
||||
feedback.submitted.as_ref().map(|payload| payload["context"].clone()).or_else(|| diagnostic(&feedback.input()["context"], 4, true));
|
||||
let json = serde_json::to_string_pretty(&snapshot).unwrap_or_default();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
stitch_kit::caption(ui, "提交时补充本机助手、存储和近期日志摘要。");
|
||||
if stitch_ui::action_button(ui, "复制当前诊断", stitch_ui::ButtonRole::Quiet, true).clicked() {
|
||||
ctx.copy_text(json.clone());
|
||||
}
|
||||
});
|
||||
egui::ScrollArea::vertical().id_salt("feedback-diagnostics").auto_shrink([false, true]).max_height(132.0).show(ui, |ui| {
|
||||
ui.add(egui::Label::new(RichText::new(json).font(Type::Meta.font_id()).color(theme.text_dim)).wrap().selectable(true));
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(space::MD);
|
||||
stitch_ui::divider(ui);
|
||||
if !signed_in {
|
||||
stitch_ui::status_label(ui, "登录素材库后可以提交反馈。", stitch_ui::StatusTone::Neutral);
|
||||
} else if !feedback.error.is_empty() {
|
||||
@ -502,7 +821,14 @@ impl Workspace {
|
||||
} else {
|
||||
"提交反馈"
|
||||
};
|
||||
if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Primary, enabled).clicked() {
|
||||
let submit = ui
|
||||
.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let clicked = stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Primary, enabled).clicked();
|
||||
close |= stitch_ui::action_button(ui, "取消", stitch_ui::ButtonRole::Secondary, true).clicked();
|
||||
clicked
|
||||
})
|
||||
.inner;
|
||||
if submit {
|
||||
let payload = feedback.submitted.clone().map_or_else(|| feedback_payload(&feedback.input()), Ok);
|
||||
match payload {
|
||||
Ok(payload) => {
|
||||
@ -545,7 +871,7 @@ mod tests {
|
||||
let payload = feedback_payload(&input).unwrap();
|
||||
assert_eq!(payload["summary"], "图片加载失败");
|
||||
assert_eq!(payload["context"]["events"].as_array().unwrap().len(), 12);
|
||||
assert_eq!(payload["context"]["events"][0], json!({"message":"[敏感信息已移除]","error":"[敏感信息已移除]","code":503}));
|
||||
assert_eq!(payload["context"]["events"][0], json!({"message":"[敏感信息已移除]","error":"[url]","code":503}));
|
||||
assert_eq!(payload["context"]["project"]["name"], "[敏感信息已移除]");
|
||||
input["summary"] = json!("图".repeat(2001));
|
||||
assert!(feedback_payload(&input).is_err());
|
||||
@ -554,10 +880,10 @@ mod tests {
|
||||
#[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");
|
||||
assert_eq!(win, "Cannot find 'fflate' imported from [path]");
|
||||
|
||||
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");
|
||||
assert_eq!(unix, "Failed reading [path]");
|
||||
|
||||
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");
|
||||
@ -656,8 +982,8 @@ mod tests {
|
||||
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.len(), 25);
|
||||
assert_eq!(recent_logs[0], "2026-12-03T01:00:00Z WARN [main] startup: [path]");
|
||||
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);
|
||||
@ -708,7 +1034,11 @@ mod tests {
|
||||
w.template_workflow = json!({"activeOutput":"detail","templateHash":"abcdef1234567890"});
|
||||
|
||||
let ctx = Context::default();
|
||||
w.seed_notifications_for_test(&ctx, &["第一条通知", "第二条通知 https://sc.jiansun.vip/help"]);
|
||||
w.seed_notifications_for_test(&ctx, &["带用户原文的通知", "第二条通知"]);
|
||||
w.models = vec![json!({"key":"claude-sonnet","id":"claude-sonnet","provider":"anthropic","routeId":"route-a"})];
|
||||
w.client_update.state = json!({"status":"error","latest":{"version":"1.2612.120"},"error":"HTTP 503 Cookie=fixture"});
|
||||
app.perf.gpu_info.adapter = "Fixture GPU".into();
|
||||
app.perf.gpu_info.backend = "vulkan".into();
|
||||
|
||||
w.open_feedback(&app, &ctx);
|
||||
assert!(w.feedback.open);
|
||||
@ -730,8 +1060,24 @@ mod tests {
|
||||
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["schemaVersion"], 3);
|
||||
assert_eq!(context["currentError"], "这次操作没有完成");
|
||||
assert_eq!(context["errors"]["activeBanners"][0]["category"], "Business");
|
||||
assert_eq!(context["workspaceState"]["activeTaskStatus"], "running");
|
||||
assert_eq!(context["workspaceState"]["openDocumentCount"], 1);
|
||||
assert_eq!(context["workspaceState"]["canvasReady"], true);
|
||||
assert_eq!(context["breadcrumbs"][0]["action"], "open-feedback");
|
||||
assert_eq!(context["breadcrumbs"][1]["source"], "canvas");
|
||||
assert_eq!(context["modelConfig"]["chatModel"]["modelId"], "claude-sonnet");
|
||||
assert_eq!(context["modelConfig"]["chatModel"]["providerId"], "anthropic");
|
||||
assert_eq!(context["modelConfig"]["routingMode"], "personal-key");
|
||||
assert_eq!(context["updateState"]["latestVersion"], "1.2612.120");
|
||||
assert_eq!(context["updateState"]["error"]["code"], 503);
|
||||
assert_eq!(context["display"]["gpu"]["backend"], "vulkan");
|
||||
assert_eq!(context["project"].get("name"), None);
|
||||
assert_eq!(context.get("notices"), None);
|
||||
assert!(!payload.to_string().contains("带用户原文的通知"));
|
||||
assert!(!payload.to_string().contains("秋季上新详情页"));
|
||||
assert_eq!(
|
||||
context["models"],
|
||||
json!({
|
||||
@ -744,7 +1090,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(context["canvas"]["outputId"], "detail");
|
||||
assert_eq!(context["canvas"]["activeOutput"], "detail");
|
||||
assert_eq!(context["canvas"]["variantId"], "wood");
|
||||
assert!(context["canvas"].get("variantId").is_none());
|
||||
assert_eq!(context["canvas"]["templateHash"], "abcdef123456");
|
||||
assert_eq!(context["canvas"]["documentWidth"], 1440);
|
||||
assert_eq!(context["canvas"]["documentHeight"], 1800);
|
||||
@ -753,7 +1099,6 @@ mod tests {
|
||||
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.
|
||||
@ -773,4 +1118,159 @@ mod tests {
|
||||
assert_eq!(w.feedback.context["page"], "projects");
|
||||
assert!(w.feedback.context.get("canvas").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_v3_caps_sections_and_does_not_copy_conversation_content() {
|
||||
let messages: Vec<_> = (0..32)
|
||||
.flat_map(|index| {
|
||||
[
|
||||
json!({"role":"user","text":"本周未发布的产品文案"}),
|
||||
json!({"role":"assistant","kind":"activity","event":{
|
||||
"version":1,"type":"tool","toolName":"read_output_screen","status":"failed",
|
||||
"timestampMs":4_000+index,"durationMs":120,"failureCategory":"read_failed","errorCode":"E_TOOL",
|
||||
"message":"秘密模型回复","copyUpdates":{"items":[{"text":"内部画布文案"}]}
|
||||
}}),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
let (mut breadcrumbs, mut failures) = conversation_diagnostics(&messages, 5_000);
|
||||
assert_eq!(breadcrumbs.len(), MAX_BREADCRUMBS);
|
||||
assert_eq!(failures.len(), MAX_TOOL_FAILURES);
|
||||
assert_eq!(failures[0]["ageMs"], 969);
|
||||
breadcrumbs[0]["message"] = json!("a string from a private chat");
|
||||
failures[0]["screenshot"] = json!([9, 8, 7]);
|
||||
breadcrumbs.extend(vec![json!({"action":"extra"}); 5]);
|
||||
failures.extend(vec![json!({"toolName":"extra"}); 5]);
|
||||
let payload = feedback_payload(&json!({
|
||||
"feedbackId":uuid::Uuid::new_v4().to_string(),
|
||||
"summary":r"网络诊断 https://bucket.example/a?X-Amz-Signature=ff7e C:\Users\Alice Jones\Private Client\project.psd",
|
||||
"context":{
|
||||
"schemaVersion":3,"breadcrumbs":breadcrumbs,"recentToolFailures":failures,
|
||||
"recentErrors":vec!["Cookie: __Secure-session=fixture";30],
|
||||
"recentLogs":vec![r"读取失败 \\private-server\share\Original Canvas.psd";100],
|
||||
"project":{"name":"内部产品线"}
|
||||
}
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(payload["summary"], "网络诊断 [url] [path]");
|
||||
let context = &payload["context"];
|
||||
for (key, limit) in [("breadcrumbs", 25), ("recentToolFailures", 10), ("recentErrors", 20), ("recentLogs", 80)] {
|
||||
assert_eq!(context[key].as_array().unwrap().len(), limit, "{key}");
|
||||
}
|
||||
assert_eq!(context["recentErrors"][0], REDACTED);
|
||||
assert_eq!(context["recentToolFailures"][0]["code"], "E_TOOL");
|
||||
let wire = payload.to_string();
|
||||
for private in ["Alice Jones", "Original Canvas", "内部产品线", "未发布", "秘密模型", "内部画布", "private chat", "screenshot", "ff7e"]
|
||||
{
|
||||
assert!(!wire.contains(private), "{private} leaked");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_redacts_secrets_paths_and_data_before_truncating() {
|
||||
for sensitive in [
|
||||
"sk-proj-GX2J3pR1O4ZQY-U56N",
|
||||
"Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.e30.fixt",
|
||||
r#"{"Set-Cookie":"connect.sid=abcde"}"#,
|
||||
"signing_secret=sup3R-fixture",
|
||||
"signingKey: opaque-synthetic-value",
|
||||
"api_key: synthetic-key",
|
||||
"data%253Aimage%252Fpng%253Bbase64%252CiVBORw0KGgo",
|
||||
"prompt: 保密的产品正文",
|
||||
"canvas_content=商品名和排版",
|
||||
] {
|
||||
let input = format!("{}{sensitive}", "警告 ".repeat(96));
|
||||
assert_eq!(sanitize_diagnostic_line(&input), REDACTED, "{sensitive}");
|
||||
}
|
||||
for path in [
|
||||
r"C:\Users\Alice Jones\AppData\Local\Private Project.psd",
|
||||
"D:/Production/Client Project/final.psd",
|
||||
"/home/alice/Private Project/set.pcraft",
|
||||
"/Users/alice/Library/Application Support/XiaoYi/feedback.log",
|
||||
"C%3A%5CUsers%5CAlice%20Jones%5Cpersonal.txt",
|
||||
] {
|
||||
assert_eq!(sanitize_diagnostic_line(&format!("read {path}")), "read [path]");
|
||||
}
|
||||
assert_eq!(sanitize_diagnostic_line("GET https://storage.example/file?X-Amz-Credential=a&X-Amz-Signature=synthetic failed"), "GET [url] failed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "offscreen Vulkan screenshots; writes only to PHOTOCRAFT_AGENT_QA_OUT"]
|
||||
fn feedback_modal_vulkan_acceptance() {
|
||||
use eframe::{egui_wgpu, wgpu};
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"));
|
||||
for (width, height) in [(1440, 900), (960, 720)] {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"name":"测试项目","width":1440,"height":1800})).unwrap();
|
||||
let app = PhotocraftApp::new(session, crate::Services::default());
|
||||
let (tx, requests) = std::sync::mpsc::channel();
|
||||
let (_events, rx) = std::sync::mpsc::channel();
|
||||
let mut workspace = Workspace::new(tx, rx);
|
||||
workspace.account = json!({"id":"qa","name":"验收账户"});
|
||||
workspace.library_status = "connected".into();
|
||||
workspace.library = false;
|
||||
workspace.loaded_draft = Some(app.session.active().unwrap().doc.id.0);
|
||||
workspace.observed_doc = workspace.loaded_draft;
|
||||
workspace.project_context = json!({"localId":"qa-project","status":"draft"});
|
||||
workspace.pending_image = Some(json!({"taskId":"qa-task","status":"running"}));
|
||||
let mut setup = egui_wgpu::WgpuSetupCreateNew::without_display_handle();
|
||||
setup.instance_descriptor.backends = wgpu::Backends::VULKAN;
|
||||
let mut harness = Harness::builder()
|
||||
.with_context_setup(|ctx| {
|
||||
crate::cjk_fonts::install_system_provider_for_tests(ctx);
|
||||
PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium);
|
||||
})
|
||||
.with_size(egui::vec2(width as f32, height as f32))
|
||||
.with_pixels_per_point(1.0)
|
||||
.wgpu_setup(egui_wgpu::WgpuSetup::CreateNew(setup))
|
||||
.build_ui_state(
|
||||
|ui, (app, workspace): &mut (PhotocraftApp, Workspace)| {
|
||||
if stitch_ui::ui_fonts_ready(ui) {
|
||||
if workspace.feedback.id.is_empty() {
|
||||
workspace.open_feedback(app, ui.ctx());
|
||||
}
|
||||
workspace.feedback_dialog(ui.ctx(), None);
|
||||
}
|
||||
},
|
||||
(app, workspace),
|
||||
);
|
||||
harness.run_steps(8);
|
||||
let capture = |harness: &mut Harness<'_, _>, state| {
|
||||
let image = harness.render().unwrap();
|
||||
assert_eq!(image.dimensions(), (width, height));
|
||||
image.save(directory.join(format!("feedback-{width}x{height}-{state}.png"))).unwrap();
|
||||
};
|
||||
harness.get_by_label("提交反馈");
|
||||
capture(&mut harness, "empty");
|
||||
harness.state_mut().1.feedback.summary = "打开项目后,画布一直显示加载中。".into();
|
||||
harness.get_by_label("查看脱敏诊断").click();
|
||||
harness.run_steps(6);
|
||||
harness.get_by_label("复制当前诊断");
|
||||
capture(&mut harness, "preview");
|
||||
harness.get_by_label("提交反馈").click();
|
||||
harness.run_steps(6);
|
||||
let sent = requests
|
||||
.try_iter()
|
||||
.find_map(|request| match request {
|
||||
Request::Action(method, input) if method == "desktop-feedback" => Some(input),
|
||||
_ => None,
|
||||
})
|
||||
.expect("feedback submits through the native host");
|
||||
assert_eq!(sent["payload"]["context"]["schemaVersion"], 3);
|
||||
let mut reply = json!({"accountId":"qa","origin":sent["origin"],"readId":sent["readId"],"error":"反馈暂未提交,请稍后重试"});
|
||||
harness.state_mut().1.feedback_received(Ok(reply.clone()));
|
||||
harness.run_steps(6);
|
||||
capture(&mut harness, "retry");
|
||||
harness.get_by_label("重试").click();
|
||||
harness.run_steps(6);
|
||||
assert!(requests.try_iter().any(|request| matches!(request, Request::Action(method, retry) if method == "desktop-feedback" && retry == sent)));
|
||||
reply.as_object_mut().unwrap().remove("error");
|
||||
reply["feedback"] = json!({"feedbackId":sent["readId"]});
|
||||
harness.state_mut().1.feedback_received(Ok(reply));
|
||||
harness.run_steps(6);
|
||||
harness.get_by_label("查看反馈");
|
||||
capture(&mut harness, "receipt");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user