diff --git a/apps/detail-agent-pi/src/enterprise-templates.mjs b/apps/detail-agent-pi/src/enterprise-templates.mjs index d94ccc8c..3fb0a102 100644 --- a/apps/detail-agent-pi/src/enterprise-templates.mjs +++ b/apps/detail-agent-pi/src/enterprise-templates.mjs @@ -528,6 +528,16 @@ export async function xiaoyiCatalog(input, {signal,fetch = nativeKnowledgeFetch, } export async function templateRequest(input,options) { + if (input.action === 'workbench-query') { + const query = typeof input.query === 'string' ? input.query.trim() : ''; + if ([...query].length < 2 || [...query].length > 500) throw Error('请填写 2 到 500 字的规范问题'); + const client = new EnterpriseKnowledge(); + await client.call('list_libraries', {}, options); + const { result } = await client.call('query_knowledge', { query, limit: 3, maxCharacters: 4000 }, options); + const sources = (result.fragments ?? []).slice(0, 3).flatMap(({ path, text }) => + typeof path === 'string' && typeof text === 'string' ? [{ path, text }] : []); + return { sources }; + } if (input.action === 'xiaoyi-pack') return xiaoyiPacks(input,options); if (['choices','brand','catalog','resource-set','resource-component'].includes(input.action)) { return xiaoyiCatalog(input,options); diff --git a/apps/detail-photocraft/Cargo.lock b/apps/detail-photocraft/Cargo.lock index 759d2b36..a6441264 100644 --- a/apps/detail-photocraft/Cargo.lock +++ b/apps/detail-photocraft/Cargo.lock @@ -5465,6 +5465,7 @@ dependencies = [ "epaint_default_fonts", "flate2", "log", + "percent-encoding", "photocraft-algo", "photocraft-cms", "photocraft-codecs", @@ -5485,6 +5486,7 @@ dependencies = [ "photocraft-text", "photocraft-vector", "rayon", + "regex", "serde", "serde_json", "sha2", diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 11b76289..b00e5db1 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -109,6 +109,8 @@ mod slot_canvas; mod stream; #[path = "jiansun_sync.rs"] mod sync; +#[path = "jiansun_feedback.rs"] +mod feedback; #[path = "jiansun_template_cache.rs"] mod template_cache; #[cfg(test)] @@ -824,8 +826,6 @@ impl Backend { Err("项目操作账户已变化,未处理其他账户项目".to_owned()) } else { match operation["kind"].as_str() { - Some("sync") => backend.sync_project(&input), - Some("pull") => backend.open_with_recovery(&input, &events, &ctx).and_then(|_| backend.projects().map(|projects| json!({"projects":projects}))), Some("delete") => backend.delete_project(&input), _ => Err("项目操作无效".into()), } @@ -859,8 +859,14 @@ impl Backend { if Uuid::parse_str(&id).is_err() && id.parse::().is_err() { return Err("本机项目编号无效".into()); } + let brief = creation::load(&entry.path()).ok().map(|value| value["brief"].clone()).unwrap_or_default(); + let updated = v["time"].as_str().and_then(|value| value.parse::().ok()) + .and_then(|time| chrono::DateTime::from_timestamp(time, 0)) + .map(|value| value.format("%Y-%m-%d %H:%M UTC").to_string()); out.push( - json!({"id":id,"source":"native","name":v["name"],"revision":v["revision"].as_u64().unwrap_or(0),"updatedAt":v["time"],"hasDraft":v["status"]!="completed","status":v["status"].as_str().unwrap_or("draft"),"cloudLink":v["project"],"cloudPresent":false,"syncedRevision":v["syncedRevision"],"syncDirty":v["syncDirty"].as_bool().unwrap_or(true),"localPending":projects::idle(&entry.path()).is_err()}), + json!({"id":id,"source":"native","name":v["name"],"brandName":brief["brandName"], + "productModel":brief["platformFacts"]["productModel"].as_str().or(brief["identifier"].as_str().filter(|text| !text.is_empty())).or(brief["name"].as_str()), + "updatedLabel":updated,"revision":v["revision"].as_u64().unwrap_or(0),"updatedAt":v["time"],"hasDraft":v["status"]!="completed","status":v["status"].as_str().unwrap_or("draft"),"cloudLink":v["project"],"cloudPresent":false,"syncedRevision":v["syncedRevision"],"syncDirty":v["syncDirty"].as_bool().unwrap_or(true),"localPending":projects::idle(&entry.path()).is_err()}), ); } } @@ -1711,7 +1717,19 @@ impl Backend { Ok(json!({"doc":doc,"localId":local})) } "project-delete" => self.delete_project(input), - "project-sync" => self.sync_project(input), + "project-sync" if input["status"] == "completed" => self.sync_project(input), + "desktop-feedback" => feedback::submit(self, input), + "workbench-knowledge" => { + if input["accountId"] != self.auth["account"]["id"] || input["origin"] != self.origin { + return Err("账号已切换,请重新提问".into()); + } + self.check_dispatch()?; + let mut request = json!({"action":"workbench-query","query":input["query"], + "accountId":input["accountId"],"origin":input["origin"]}); + let result = self.enterprise_template_read(&mut request, |_| {})?; + self.check_dispatch()?; + Ok(result) + } "delivery-status" => self.delivery_status(input), "project-state" => self.project_state(input), "configure-xiaoyi-knowledge" => Ok(knowledge_http::configure_for_account(input)), @@ -2187,6 +2205,23 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let _ = events.send(event); } Request::Action(method, input) => { + if matches!(method.as_str(), "desktop-feedback" | "workbench-knowledge") { + let mut worker = backend.clone(); + let task_events = events.clone(); + let task_ctx = ctx.clone(); + let reference = json!({"accountId":input["accountId"],"origin":input["origin"],"readId":input["readId"]}); + let result_ref = reference.clone(); + let result_method = method.clone(); + if let Err(error) = prompt_ops.submit(move || { + let result = worker.action(&result_method, &input, &task_events, &task_ctx); + let _ = task_events.send(Event::Json(result_method, Ok(bound_material_read(result, &result_ref)))); + task_ctx.request_repaint_of(egui::ViewportId::ROOT); + }) { + let _ = events.send(Event::Json(method, Ok(bound_material_read(Err(error.into()), &reference)))); + ctx.request_repaint_of(egui::ViewportId::ROOT); + } + continue; + } if method == "client-update" { let reader = backend.clone(); let task_events = events.clone(); @@ -2360,10 +2395,10 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let result = backend.slot_action(&method, &input, &events, &ctx); let _ = events.send(Event::Json(method, result)); ctx.request_repaint_of(egui::ViewportId::ROOT); - } else if method == "project-sync" { + } else if method == "project-sync" && input["status"] == "completed" { use std::sync::atomic::Ordering; if model_busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { - let _ = events.send(Event::Json(method, Err("原任务仍在处理,未重复同步".into()))); + let _ = events.send(Event::Json(method, Err("原任务仍在处理,未重复提交成品".into()))); } else { let mut b = backend.clone(); let events = events.clone(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_feedback.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_feedback.rs new file mode 100644 index 00000000..0240fc3a --- /dev/null +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_feedback.rs @@ -0,0 +1,92 @@ +use super::{Backend, R, Value}; +use std::time::Duration; + +pub(super) fn submit(backend: &Backend, input: &Value) -> R { + 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"])?; + backend.check_dispatch()?; + let response = backend + .http + .post(format!("{}/api/desktop/feedback", backend.origin)) + .bearer_auth(token) + .timeout(Duration::from_secs(15)) + .json(&payload) + .send() + .map_err(|_| "暂时无法确认反馈结果,请联网后用同一编号重试")?; + match response.status().as_u16() { + 200..=299 => {} + 401 | 403 => return Err("授权已失效或无权限,请检查素材库账号".into()), + 404 => return Err("当前素材库暂未开放客户端反馈".into()), + 409 => return Err("反馈编号不可用,请重新打开反馈".into()), + _ => return Err("反馈暂未提交,请稍后重试".into()), + } + let value: Value = response.json().map_err(|_| "反馈回执无法读取,请用同一编号重试")?; + if value["feedback"]["feedbackId"] != payload["feedbackId"] { + return Err("反馈回执无法确认,请用同一编号重试".into()); + } + Ok(value) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::jiansun_backend::json; + use std::io::{BufRead, BufReader, Read, Write}; + use std::net::TcpListener; + + #[test] + fn feedback_sends_a_screened_bearer_request_and_reuses_the_id_on_retry() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let id = uuid::Uuid::new_v4().to_string(); + let expected = id.clone(); + let server = std::thread::spawn(move || { + for status in ["503 Unavailable", "200 OK"] { + let (mut socket, _) = listener.accept().unwrap(); + socket.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut reader = BufReader::new(&mut socket); + let mut request = String::new(); + reader.read_line(&mut request).unwrap(); + assert_eq!(request, "POST /api/desktop/feedback HTTP/1.1\r\n"); + let mut authorization = false; + let mut length = 0; + loop { + let mut header = String::new(); + reader.read_line(&mut header).unwrap(); + if header.trim().is_empty() { + break; + } + let header = header.trim().to_ascii_lowercase(); + authorization |= header == "authorization: bearer local-fixture"; + if let Some(value) = header.strip_prefix("content-length: ") { + length = value.parse().unwrap(); + } + } + assert!(authorization); + 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":"[敏感信息已移除]"}}) + ); + 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(); + } + }); + let directory = tempfile::tempdir().unwrap(); + let mut backend = Backend::new(directory.path().join("jiansun")).unwrap(); + 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]}}}); + assert!(submit(&backend, &input).is_err()); + assert_eq!(submit(&backend, &input).unwrap()["feedback"]["feedbackId"], id); + server.join().unwrap(); + } +} diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs index 405c010c..f3a9ab81 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs @@ -220,6 +220,12 @@ fn first_screen(doc: &Document) -> R { let w = (rect.width() as f32 * scale).round().max(1.0) as u32; let h = (rect.height() as f32 * scale).round().max(1.0) as u32; let image = photocraft_ui_egui::gpu_canvas::background_compose::render(doc, rect, w, h).to_rgba8(); + if let Some(first) = image.pixels.get(..4) + && (first == [255, 255, 255, 255] || first[3] == 0) + && image.pixels.chunks_exact(4).all(|pixel| pixel == first || (first[3] == 0 && pixel[3] == 0)) + { + return Err("尚无画布内容".into()); + } Ok(egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &image.pixels)) } diff --git a/apps/detail-photocraft/crates/ui-egui/Cargo.toml b/apps/detail-photocraft/crates/ui-egui/Cargo.toml index b9e56e74..c93bbd3b 100644 --- a/apps/detail-photocraft/crates/ui-egui/Cargo.toml +++ b/apps/detail-photocraft/crates/ui-egui/Cargo.toml @@ -56,6 +56,8 @@ rayon = { workspace = true } # Safe native UI-language APIs (Windows/macOS); no subprocess or web dependency. sys-locale = "=0.3.2" uuid = { version = "1", features = ["v4"] } +regex = "1" +percent-encoding = "2" # Installed RAM for the GPU memory budget (`gpu_canvas::physical_memory`) and the user's decimal # symbol (`i18n::decimal_separator`, a registry read): the safe binding the desktop app already diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index 08e7a2b1..8f12b1ac 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -25,6 +25,8 @@ mod agent_stream; mod operation_error; mod template_preparation; mod workspace_navigation; +mod feedback; +pub use feedback::feedback_payload; mod agent_canvas_read; mod agent_native; mod agent_preview; @@ -960,6 +962,8 @@ impl RecoverySchedule { } pub struct Workspace { + feedback: feedback::Feedback, + workbench: workspace_navigation::Workbench, project_files: HashMap, tx: mpsc::Sender, rx: mpsc::Receiver, @@ -1519,6 +1523,8 @@ impl Workspace { account: Value::Null, prompt_library: prompt_library_ui::PromptLibraryUi::default(), library_status: String::new(), + feedback: Default::default(), + workbench: Default::default(), library_message: String::new(), library_http_status: None, library_authorization_enabled: None, @@ -2687,6 +2693,8 @@ impl Workspace { let scope_changed = self.account["id"] != v["account"]["id"] || v["origin"].as_str().is_some_and(|origin| origin != self.origin); if scope_changed { + self.feedback = feedback::Feedback::default(); + self.workbench = workspace_navigation::Workbench::default(); self.retain_creation_ui_draft(app); self.creation_ui_scope = None; self.creation_doc = None; @@ -2740,6 +2748,8 @@ impl Workspace { } if scope_changed { self.creation_reads_tick(app); + self.refresh_workbench_scope(); + if self.busy.is_none() && self.editing_product_brief() { self.apply_workbench_seed(app); } self.xiaoyi_knowledge_mode = "unavailable".into(); self.xiaoyi_key_check = None; } @@ -2981,6 +2991,12 @@ impl Workspace { } fn receive_json_event(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, method: String, mut result: Result) { + match method.as_str() { + "desktop-feedback" => { self.feedback_received(result); return; } + "workbench-knowledge" => { self.workbench_knowledge_received(result); return; } + _ => {} + } + if method == "client-update" { if let Ok(receipt) = result { self.client_update.receive(receipt); @@ -4225,13 +4241,11 @@ impl Workspace { .map(|ch| if ch.is_ascii() { 8.0 } else { 14.0 }) .sum::() + self.update_capsule_width(); if app.session.active().is_none() { - return account_width + 166.0 + 30.0; + return account_width + 166.0 + 110.0; } - let status_width = if self.navigation_sync_status(app).is_some() { 76.0 } else { 0.0 }; let save_width = if self.saving.is_some() || self.saved.is_some() { 26.0 } else { 0.0 }; let stop_width = if self.shows_stop_automation() { 116.0 } else { 0.0 }; - // Navigation segments, divider, sync controls, and right-edge spacing. - account_width + 246.0 + 24.0 + 270.0 + status_width + save_width + stop_width + 18.0 + account_width + 246.0 + 24.0 + 172.0 + save_width + stop_width + 18.0 } fn navigation_inner(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { if self.professional_child_active(app) { @@ -4253,12 +4267,15 @@ impl Workspace { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // Keep the rightmost hit box inside the clip after fractional pixel rounding. ui.add_space(1.0); + let compact = ui.clip_rect().width() < 540.0; let account_name = self.account["name"].as_str().unwrap_or("登录"); let account_label = self.navigation_account_label(); - // The bar keeps one light action (完结); the account is an entry, not an action. - if stitch_ui::action_button(ui, &account_label, stitch_ui::ButtonRole::Quiet, true).on_hover_text(account_name).clicked() { - self.config = true; + let account_text = if compact && !self.account.is_null() { "账户" } else { &account_label }; + let account = stitch_ui::action_button(ui, account_text, stitch_ui::ButtonRole::Quiet, true).on_hover_text(account_name); + if compact { + account.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &account_label)); } + if account.clicked() { self.config = true; } self.update_capsule(app, ui); let projects = self.library || (!document_open && !self.material); let options: Vec<(&str, bool)> = if document_open { vec![("我的项目", true), ("添加素材", true), ("当前画布", true)] } else { vec![("我的项目", true), ("添加素材", true)] }; @@ -4282,7 +4299,7 @@ impl Workspace { } if document_open { stitch_ui::divider(ui); - self.sync_controls(app, ui); + self.delivery_controls(app, ui); if self.saving.is_some() { let loader_id = ui.scope_id().with("loading"); stitch_ui::ai_loader(ui, loader_id, true, self.reduce_motion); @@ -4293,10 +4310,19 @@ impl Workspace { self.handover(); } } + let feedback = if compact { + let response = stitch_ui::icon_button(ui, "message-square", 24.0, false, "问题反馈"); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "问题反馈")); + response + } else { + stitch_ui::action_button(ui, "问题反馈", stitch_ui::ButtonRole::Quiet, true) + }; + if feedback.clicked() { self.open_feedback(app); } }); } fn header(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { self.template_progress_ui(app, ui.ctx()); + self.feedback_dialog(ui.ctx(), app.services.open_url.as_ref()); let t = Tokens::get(ui.ctx()); // The normal navigation lives in the tool-options row. Keep an escape hatch // only when the user has explicitly hidden that native toolbar. @@ -4599,6 +4625,10 @@ pub(crate) fn begin_native_dock(app: &mut PhotocraftApp) { crate::panel_docking::sync_agent_tab(app); } +pub(crate) fn projects_agent_dock(app: &PhotocraftApp) -> bool { + app.jiansun.as_ref().is_some_and(|workspace| workspace.agent_page(app) == "projects") +} + pub(crate) fn agent_selected(app: &PhotocraftApp) -> bool { app.jiansun.is_some() && app.ui.dock.agent_available && app.ui.dock_tabs.color == 4 && !app.ui.dock.is_collapsed(crate::dock::Group::Color) } @@ -4752,7 +4782,7 @@ pub(crate) fn bind_workspace_rendering(app: &PhotocraftApp, ui: &Ui) { } pub fn prepare(app: &mut PhotocraftApp, ui: &mut Ui) { - let xiaoyi_open = agent_selected(app); + let xiaoyi_open = agent_selected(app) || projects_agent_dock(app); if let Some(mut w) = app.jiansun.take() { // Selecting 小壹 is also an explicit return from native editing. if w.professional_mode && w.professional_edit.is_none() && xiaoyi_open { @@ -5264,11 +5294,11 @@ fn action_impl(app: &mut PhotocraftApp, ctx: Option<&egui::Context>, method: &st "creation-attachment-import" | "creation-attachment-import-data" => Err("请使用授权的参考图导入入口".into()), name if name.starts_with("creation-") => w.creation_action(app, name, input), name if name.starts_with("slot-") => w.slot_action(app, name, input), + "project-sync" if input["status"] != "completed" => Err("工程保存在本机,请通过完结提交成品".into()), "project-sync" | "project-state" => { w.sync_action(app, method, input); Ok(Value::Null) } - "project-card-sync" => w.request_project_sync(app, &input), "agent" => { if let Some(text) = input["text"].as_str() { w.submit(app, text.to_owned()); @@ -5751,7 +5781,7 @@ mod tests { output.textures_delta.clear(); assert!(w.panel_geometry["composer"].is_null()); assert!(w.panel_geometry["subject"].is_null()); - assert!(w.panel_geometry["workspaceSearch"].is_null(), "the project page keeps one search, in the center; the dock only lists recent projects"); + assert!(w.panel_geometry["workspaceSearch"].is_array()); assert!(w.panel_geometry["workspaceReturn"].is_array(), "the dock still offers the way back to the open canvas"); assert!(requests.try_recv().is_err()); w.show_center(CenterView::Materials,true); @@ -5765,75 +5795,25 @@ mod tests { } #[test] - fn project_page_dock_lists_recent_projects_without_repeating_the_center() { - fn texts(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| texts(shape, out)), - egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), - _ => {} - } - } - let (mut w,mut app,requests,_)=slot_workspace(); - w.reduce_motion=true; - w.projects=vec![ - json!({"id":"local-old","source":"native","name":"本机旧项目","updatedAt":"2026-11-01T00:00:00Z"}), - json!({"id":"cloud-new","source":"desktop","name":"云端新项目","updatedAt":"2026-11-20T00:00:00Z"}), - json!({"id":"local-new","source":"native","name":"本机新项目","updatedAt":"2026-11-10T00:00:00Z"}), + fn workbench_finds_a_local_project_by_brand_and_omits_the_file_extension() { + use egui_kittest::{Harness, kittest::Queryable}; + let (mut w, app, requests, _) = slot_workspace(); + w.projects = vec![ + json!({"id":"local","source":"native","name":"卧室新品.pcraft","brandName":"示例品牌"}), + json!({"id":"remote","source":"desktop","name":"云端项目","brandName":"示例品牌"}), ]; - w.show_center(CenterView::Projects,true); - assert_eq!(w.agent_page(&app),"projects"); - let ctx=egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let mut seen=Vec::new(); - for _ in 0..3 { - let mut output=ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::pos2(0.0,0.0),egui::vec2(520.0,900.0))), ..Default::default() }, - |ui| w.workspace_panel(&mut app,ui)); - seen.clear(); - for clipped in &output.shapes { texts(&clipped.shape,&mut seen); } - output.textures_delta.clear(); - } - let position=|text:&str| seen.iter().position(|line| line==text); - assert!(position("最近的项目").is_some(),"{seen:?}"); - let (first,second,third)=(position("本机新项目"),position("本机旧项目"),position("云端新项目")); - assert!(matches!((first,second,third),(Some(a),Some(b),Some(c)) if a) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| texts(shape, out)), - egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), - _ => {} - } - } - let (mut w,mut app,requests,_)=slot_workspace(); - w.reduce_motion=true; - w.library_status="connected".into(); - w.projects=Vec::new(); - w.show_center(CenterView::Projects,true); - let ctx=egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let mut seen=Vec::new(); - for _ in 0..3 { - let mut output=ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::pos2(0.0,0.0),egui::vec2(250.0,900.0))), ..Default::default() }, - |ui| w.workspace_panel(&mut app,ui)); - seen.clear(); - for clipped in &output.shapes { texts(&clipped.shape,&mut seen); } - output.textures_delta.clear(); - } - // An empty dock beside the page reads as broken; it names the first step instead. - assert!(seen.iter().any(|line| line=="还没有项目"),"{seen:?}"); - assert!(seen.iter().any(|line| line.starts_with("从中间的「新建项目」开始")),"{seen:?}"); - assert!(!seen.iter().any(|line| line=="最近的项目" || line=="新建项目"),"no list to head, and the center keeps the button: {seen:?}"); - assert!(seen.iter().any(|line| line=="返回当前画布"),"{seen:?}"); + w.show_center(CenterView::Projects, true); + w.refresh_workbench_scope(); + w.workbench.input = "示例品牌".into(); + let mut harness = Harness::builder().with_size(egui::vec2(280.0, 600.0)) + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .build_ui_state(|ui, (w, app)| w.workspace_panel(app, ui), (w, app)); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); + harness.run_steps(4); + harness.get_by_label("发送").click(); + harness.run_steps(4); + harness.get_by_label("卧室新品 · 示例品牌"); + assert!(harness.query_by_label("云端项目 · 示例品牌").is_none()); assert!(requests.try_recv().is_err()); } @@ -6848,7 +6828,7 @@ mod tests { } #[test] - fn project_sync_controls_fit_inside_navigation_clip() { + fn project_actions_fit_inside_navigation_clip() { use egui_kittest::{Harness, kittest::Queryable}; for width in [960.0, 1100.0, 1280.0, 1400.0, 1440.0, 1920.0] { for name in ["222", "长账户名宽度验收"] { @@ -6866,7 +6846,7 @@ mod tests { let geometry = &harness.state().jiansun.as_ref().unwrap().navigation_geometry["clip"]; let point = |index: usize| geometry[index].as_f64().unwrap() as f32; let clip = egui::Rect::from_min_size(egui::pos2(point(0), point(1)), egui::vec2(point(2), point(3))); - for label in ["完结", "云同步", "同步对话", "我的项目", "添加素材", "当前画布", &format!("账户 · {name}")] { + for label in ["完结", "问题反馈", "我的项目", "添加素材", "当前画布", &format!("账户 · {name}")] { let rect = harness.get_by_label(label).rect(); assert!(clip.contains_rect(rect), "{label} at {width}pt, {scale}x: {rect:?} clipped by {clip:?}"); } @@ -6926,6 +6906,77 @@ mod tests { } } + #[test] + #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn workbench_and_feedback_visual_acceptance() { + 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 in [1440.0, 960.0] { + let (mut app, requests) = toolbar_fixture("验收账户"); + let workspace = app.jiansun.as_mut().unwrap(); + workspace.show_center(CenterView::Projects, true); + workspace.library_status = "connected".into(); + workspace.projects = vec![ + json!({"id":"local-1","source":"native","name":"栖木系列主卧详情页.pcraft","brandName":"栖木家居","productModel":"QIMU-301","updatedLabel":"2026-12-01 16:32","status":"draft"}), + json!({"id":"local-2","source":"native","name":"橡木餐椅.pcraft","brandName":"日常家居","productModel":"CHAIR-03","updatedLabel":"2026-11-29 10:45","status":"completed"}), + ]; + for local in ["local-1", "local-2"] { + workspace.cover_errors.insert(format!("native|{local}|null|null"), "尚无画布内容".into()); + } + let mut harness = Harness::builder() + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(egui::vec2(width, 800.0)).wgpu() + .build_ui_state(|ui, app| { + if !stitch_ui::ui_fonts_ready(ui) { return; } + crate::panels::options_bar(app, ui); + crate::panels::dock_area(app, ui); + if let Some(w) = app.jiansun.as_mut() { w.feedback_dialog(ui.ctx(), None); } + }, app); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); + harness.run_steps(8); + harness.get_by_label("工作台总助"); + let geometry = &harness.state().jiansun.as_ref().unwrap().panel_geometry; + assert!(geometry["agentTab"].is_array()); + assert!(geometry["colorTab"].is_null()); + let workspace = harness.state().jiansun.as_ref().unwrap(); + let card = &workspace.project_geometry["tiles"][0]["card"]; + assert!(card[1].as_f64().unwrap() + card[3].as_f64().unwrap() < 800.0, "coverless card metadata fits the viewport"); + harness.render().unwrap().save(directory.join(format!("projects-{width}.png"))).unwrap(); + harness.get_by_label("问题反馈").click(); + harness.run_steps(6); + harness.get_by_label("提交反馈"); + harness.state_mut().jiansun.as_mut().unwrap().feedback.summary = "在我的项目打开本机作品后,首屏封面仍显示加载中。".into(); + harness.get_by_label("查看脱敏诊断").click(); + harness.run_steps(6); + harness.render().unwrap().save(directory.join(format!("feedback-{width}.png"))).unwrap(); + harness.get_by_label("提交反馈").click(); + harness.run_steps(5); + 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"); + let mut receipt = json!({"readId":sent["readId"],"accountId":sent["accountId"],"origin":sent["origin"],"error":"暂时无法确认反馈结果,请联网后用同一编号重试"}); + harness.state_mut().jiansun.as_mut().unwrap().feedback_received(Ok(receipt.clone())); + harness.run_steps(5); + harness.get_by_label("重试").click(); + harness.run_steps(5); + assert!(requests.try_iter().any(|request| matches!(request, Request::Action(method, input) if method == "desktop-feedback" && input == sent))); + receipt.as_object_mut().unwrap().remove("error"); + receipt["feedback"] = json!({"feedbackId":sent["readId"]}); + harness.state_mut().jiansun.as_mut().unwrap().feedback_received(Ok(receipt)); + harness.run_steps(5); + harness.get_by_label("查看反馈"); + harness.render().unwrap().save(directory.join(format!("feedback-receipt-{width}.png"))).unwrap(); + harness.get_by_label("关闭").click(); + harness.state_mut().jiansun.as_mut().unwrap().show_center(CenterView::Canvas, true); + harness.run_steps(6); + let geometry = &harness.state().jiansun.as_ref().unwrap().panel_geometry; + for tab in ["agentTab", "colorTab", "swatchesTab", "gradientsTab", "patternsTab"] { + assert!(geometry[tab].is_array(), "canvas tab {tab} should be visible"); + } + } + } + #[test] fn saved_receipt_refreshes_only_the_loaded_active_project_state() { let context = json!({"cloudLink":{"id":"cloud","source":"desktop","revision":3},"syncedRevision":8,"status":"completed","document":"preserved"}); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs index 3d4cbeaa..3685f17a 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs @@ -1131,7 +1131,7 @@ pub(super) fn sync_received(w: &mut Workspace, app: &PhotocraftApp, value: &Valu } w.project_refresh_requested = true; w.creation_progress = if value["materialDelivery"]["materialId"].is_string() { - "成品已提交素材库;项目可另行云同步" + "成品已提交素材库" } else if w.sync_dirty { "云端已保存该版本,当前仍有新修改" } else { "已同步" }.into(); } pub(super) fn listing_status_received(w: &mut Workspace, app: &PhotocraftApp, value: &Value) { @@ -1181,11 +1181,6 @@ fn reference_import_activity(busy: Option<&str>) -> Option<&'static str> { } } -fn sync_status(changed: bool, busy: Option<&str>) -> Option<&'static str> { - if busy == Some("project-sync") { Some("正在同步") } - else if !changed { Some("已同步") } - else { None } -} impl Workspace { fn creation_escape(&mut self, app: &PhotocraftApp, ui: &mut Ui) { @@ -1292,13 +1287,6 @@ impl Workspace { json!({"composer":self.composer,"messages":self.messages,"creation":self.creation,"draft":self.creation_draft(),"templateWorkflow":self.template_workflow}).to_string() } pub(super) fn sync_action(&mut self, app: &PhotocraftApp, method: &str, mut input: Value) { - if method == "project-sync" && input["status"] != "completed" { - if let Err(error) = self.request_current_sync(app, input["syncChatHistory"] == true) { - self.error = error.clone(); - self.project_list_error = error; - } - return; - } if self.busy.is_some() || self.saving.is_some() || self.project_operation_pending() { self.error = "请等待当前操作完成".into(); return; @@ -1323,66 +1311,15 @@ impl Workspace { self.saving = Some((st.doc.id.0, st.revision)); self.send(method, input); } - pub(super) fn has_sync_changes(&self, app: &PhotocraftApp) -> bool { - self.sync_dirty || app.session.active().is_some_and(|s| self.project_context["syncedRevision"].as_u64() != Some(s.revision)) - } - pub(super) fn navigation_sync_status(&self, app: &PhotocraftApp) -> Option<&'static str> { - sync_status(self.has_sync_changes(app), self.busy.as_deref()) - } - pub(super) fn sync_controls(&mut self, app: &PhotocraftApp, ui: &mut Ui) { - let changed = self.has_sync_changes(app); - let visible_width = ui.available_rect_before_wrap().intersect(ui.clip_rect()).width().max(1.0); - let compact = visible_width < 220.0; + pub(super) fn delivery_controls(&mut self, app: &PhotocraftApp, ui: &mut Ui) { let idle = self.busy.is_none() && self.saving.is_none() && !self.project_operation_pending(); - let sync_failed = self.project_operation["phase"] == "failed" && self.project_operation["kind"] == "sync" - && self.project_operation["accountId"] == self.account["id"] && self.project_operation["origin"] == self.origin - && self.current_sync_item(app).is_some_and(|item| item["id"] == self.project_operation["projectId"]); - let status = self.navigation_sync_status(app); - let label = if compact && status == Some("正在同步") {"正在同步"} else if self.project_operation_pending() {"正在处理…"} - else if sync_failed {"同步失败"} else if changed {"云同步"} else {"已同步"}; - let chat_option = ui.scope_id().with(("cloud-chat-history", self.origin.as_str(), - self.account["id"].as_str(), app.session.active().map(|state| state.doc.id.0))); - let mut chat = ui.ctx().data(|data| data.get_temp::(chat_option)).unwrap_or(false); - let hint = if sync_failed { self.project_operation["message"].as_str().unwrap_or("同步未完成,请查看我的项目") } else { "备份工程和资料到当前素材库账户" }; - let chat_control = |ui: &mut Ui, chat: &mut bool| { - if ui.add_enabled(idle && changed, egui::Checkbox::new(chat, "同步对话")).changed() { - ui.ctx().data_mut(|data| data.insert_temp(chat_option, *chat)); - } - }; let delivered = self.project_context["materialDelivery"]["materialId"].is_string() && self.project_context["status"] == "completed"; - let actions = |ui: &mut Ui, height| { - let sync = stitch_ui::action_button_height(ui, label, stitch_ui::ButtonRole::Secondary, idle && changed && !self.creation_dirty, height) - .on_hover_text(hint).on_disabled_hover_text(hint).clicked(); - let (finish_label, finish_role) = if delivered { - ("上架状态", stitch_ui::ButtonRole::Secondary) - } else { - ("完结", stitch_ui::ButtonRole::Primary) - }; - let finish = stitch_ui::action_button_height(ui, finish_label, finish_role, - delivered || (idle && !self.unknown && !self.creation_dirty), height); - (sync, finish.clicked(), finish.rect) - }; - let (sync, finish, finish_rect) = if compact { - ui.allocate_ui_with_layout(egui::vec2(visible_width, 38.0), egui::Layout::top_down(egui::Align::Max), |ui| { - ui.spacing_mut().item_spacing = egui::vec2(4.0, 0.0); - ui.spacing_mut().button_padding = egui::vec2(4.0, 1.0); - ui.spacing_mut().interact_size.y = 18.0; - let buttons = ui.horizontal(|ui| actions(ui, 18.0)).inner; - chat_control(ui, &mut chat); - buttons - }).inner - } else { - if let Some(status) = status { - stitch_ui::status_label(ui, status, stitch_ui::StatusTone::Neutral); - } - chat_control(ui, &mut chat); - actions(ui, crate::theme::agent_scale::control::DEFAULT) - }; - self.navigation_geometry["delivery"] = rect_value(finish_rect); - if sync { - self.sync_action(app, "project-sync", json!({"status":"draft","syncChatHistory":chat})); - } + let (label, role) = if delivered { ("上架状态", stitch_ui::ButtonRole::Secondary) } + else { ("完结", stitch_ui::ButtonRole::Primary) }; + let button = stitch_ui::action_button(ui, label, role, delivered || (idle && !self.unknown && !self.creation_dirty)); + self.navigation_geometry["delivery"] = rect_value(button.rect); + let finish = button.clicked(); if finish { self.sync_confirm = true; self.listing_read_at = None; @@ -1404,7 +1341,7 @@ impl Workspace { let closed = stitch_ui::dialog(ui, egui::Id::unique("xiaoyi-finish-project"), title, self.sync_confirm, self.reduce_motion, 360.0, |ui| { if !delivered { - ui.label("将已完成的详情、主图和 SKU 成品提交到素材库?项目备份可另行云同步。"); + ui.label("将已完成的详情、主图和 SKU 成品提交到素材库?"); } let receipt = &self.project_context["materialDelivery"]; if let Some(id) = receipt["materialId"].as_str() { @@ -1435,7 +1372,7 @@ impl Workspace { } if !delivered && stitch_ui::action_button(ui, "完结并提交", stitch_ui::ButtonRole::Primary, idle).clicked() { self.sync_confirm = false; - self.sync_action(app, "project-sync", json!({"status":"completed","syncChatHistory":chat})); + self.sync_action(app, "project-sync", json!({"status":"completed"})); } }); }); @@ -3867,21 +3804,6 @@ mod tests { } } - #[test] - fn reference_import_and_sync_activity_only_reflect_actual_operations() { - for busy in ["creation-import", "creation-import-data"] { - assert_eq!(reference_import_activity(Some(busy)), Some("正在导入参考图")); - } - assert_eq!(reference_import_activity(Some("creation-import-library")), Some("正在读取素材库参考图")); - for busy in [None, Some("creation-read"), Some("agent"), Some("project-sync")] { - assert_eq!(reference_import_activity(busy), None); - } - assert_eq!(sync_status(false, Some("project-sync")), Some("正在同步")); - assert_eq!(sync_status(true, Some("project-sync")), Some("正在同步")); - assert_eq!(sync_status(false, None), Some("已同步")); - assert_eq!(sync_status(true, None), None); - } - #[test] fn reference_import_progress_is_visible_only_while_import_is_in_flight() { let (mut w, mut app) = setup(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/feedback.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/feedback.rs new file mode 100644 index 00000000..8ed4c2d2 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/feedback.rs @@ -0,0 +1,324 @@ +use super::{PhotocraftApp, Request, Workspace, stitch_ui}; +use egui::{Context, Id, RichText}; +use percent_encoding::percent_decode_str; +use serde_json::{Value, json}; +use std::sync::LazyLock; + +const MAX_SUMMARY: usize = 2000; +const FIELDS: &[&str] = &[ + "client", + "clientVersion", + "appVersion", + "version", + "platform", + "os", + "arch", + "capturedAt", + "online", + "project", + "projectId", + "projectName", + "task", + "taskId", + "request", + "requestId", + "id", + "name", + "title", + "kind", + "type", + "status", + "stage", + "model", + "timestamp", + "createdAt", + "durationMs", + "code", + "errorCode", + "error", + "errors", + "message", + "diagnostics", + "events", +]; + +static SENSITIVE: LazyLock = 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#"|--(?: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-]+"#, + )).expect("constant feedback redaction pattern") +}); + +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(); + let folded: String = text + .chars() + .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(); + } + text.chars().take(limit).collect() +} + +fn diagnostic(value: &Value, depth: usize) -> Option { + match value { + Value::String(text) => Some(json!(clean_text(text, 1000))), + Value::Bool(_) | Value::Number(_) => Some(value.clone()), + Value::Array(values) if depth > 0 => Some(Value::Array( + values + .iter() + .take(12) + .filter(|value| value.is_string() || value.is_object() || value.is_array()) + .filter_map(|value| diagnostic(value, depth - 1)) + .collect(), + )), + Value::Object(fields) if depth > 0 => Some(Value::Object( + fields + .iter() + .filter(|(key, _)| FIELDS.contains(&key.as_str())) + .filter_map(|(key, value)| diagnostic(value, depth - 1).map(|value| (key.clone(), value))) + .take(16) + .collect(), + )), + _ => None, + } +} + +/// Build the same screened payload for preview and the native HTTP boundary. +pub fn feedback_payload(input: &Value) -> Result { + let id = input["feedbackId"].as_str().ok_or("反馈编号无效")?; + let uuid = uuid::Uuid::parse_str(id).map_err(|_| "反馈编号无效")?; + if uuid.get_version_num() != 4 || uuid.get_variant() != uuid::Variant::RFC4122 || uuid.to_string() != id { + return Err("反馈编号无效".into()); + } + let summary = + input["summary"].as_str().map(str::trim).filter(|text| (1..=MAX_SUMMARY).contains(&text.chars().count())).ok_or("请填写 2000 字以内的问题说明")?; + let summary = clean_text(summary, MAX_SUMMARY); + if summary.is_empty() { + return Err("请填写问题说明".into()); + } + let context = input["context"].as_object().and_then(|_| diagnostic(&input["context"], 4)); + 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 != "[敏感信息已移除]") { + value[field] = json!(text); + } + } + Ok(value) +} + +#[derive(Default)] +pub(super) struct Feedback { + open: bool, + id: String, + scope: Value, + pub(super) summary: String, + project: Value, + task: Value, + context: Value, + include_project: bool, + include_task: bool, + pending: bool, + submitted: Option, + receipt: bool, + error: String, +} + +impl Feedback { + fn input(&self) -> Value { + let mut context = self.context.clone(); + let mut value = json!({"feedbackId":self.id,"summary":self.summary}); + if self.include_project { + value["projectId"] = self.project["id"].clone(); + context["project"] = self.project.clone(); + } + if self.include_task { + value["taskId"] = self.task["taskId"].clone(); + value["requestId"] = self.task["requestId"].clone(); + context["task"] = self.task.clone(); + } + value["context"] = context; + value + } +} + +impl Workspace { + pub(super) fn open_feedback(&mut self, app: &PhotocraftApp) { + 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)); + 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"] + }) + }) + .unwrap_or_default(); + let task_row = active + .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"}))) + .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", + "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() }; + } + self.feedback.open = true; + } + + pub(super) fn feedback_received(&mut self, result: Result) { + let Ok(value) = result else { return }; + if value["accountId"] != self.account["id"] || value["origin"] != self.origin || value["readId"] != self.feedback.id || !self.feedback.pending { + return; + } + self.feedback.pending = false; + self.feedback.receipt = value["feedback"]["feedbackId"] == self.feedback.id; + self.feedback.error = value["error"].as_str().unwrap_or("").into(); + } + + pub(super) fn feedback_dialog(&mut self, ctx: &Context, open_url: Option<&crate::services::OpenUrlFn>) { + if !self.feedback.id.is_empty() && (self.feedback.scope["accountId"] != self.account["id"] || self.feedback.scope["origin"] != self.origin) { + self.feedback = Feedback::default(); + } + if !self.feedback.open { + return; + } + let signed_in = self.account["id"].is_string() && !self.library_blocked(); + 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 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))); + 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("在浏览器登录同一素材库账号即可查看详情。"); + if stitch_ui::action_button(ui, "查看反馈", stitch_ui::ButtonRole::Primary, true).clicked() + && let Some(origin) = feedback.scope["origin"].as_str() + { + let url = format!("{origin}/feedback/{}", feedback.id); + if let Some(open) = open_url { + if open(&url).is_err() { + feedback.error = "无法打开浏览器,可凭反馈编号查询。".into(); + } + } else { + ctx.open_url(egui::OpenUrl::new_tab(url)); + } + } + if !feedback.error.is_empty() { + stitch_ui::status_label(ui, &feedback.error, stitch_ui::StatusTone::Error); + } + 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)); + }); + }); + 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| { + 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)); + }); + }); + if !signed_in { + stitch_ui::status_label(ui, "登录素材库后可以提交反馈。", stitch_ui::StatusTone::Neutral); + } else if !feedback.error.is_empty() { + stitch_ui::status_label(ui, &feedback.error, stitch_ui::StatusTone::Error); + } else if offline { + stitch_ui::status_label(ui, "素材库暂时离线,联网后可提交。", stitch_ui::StatusTone::Warning); + } + let enabled = signed_in && !feedback.pending && !feedback.summary.trim().is_empty(); + let label = if feedback.pending { + "提交中…" + } else if !feedback.error.is_empty() { + "重试" + } else { + "提交反馈" + }; + if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Primary, enabled).clicked() { + let payload = feedback.submitted.clone().map_or_else(|| feedback_payload(&feedback.input()), Ok); + match payload { + Ok(payload) => { + feedback.pending = self + .tx + .send(Request::Action( + "desktop-feedback".into(), + json!({ + "payload":&payload,"accountId":feedback.scope["accountId"],"origin":feedback.scope["origin"],"readId":feedback.id + }), + )) + .is_ok(); + if feedback.pending { + feedback.submitted = Some(payload); + feedback.error.clear(); + } else { + feedback.error = "本机服务已停止,请重启后提交。".into(); + } + } + Err(error) => feedback.error = error, + } + } + }); + if close || response.is_some_and(|response| response.should_close()) { + feedback.open = false; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn feedback_payload_screens_summary_and_nested_diagnostics() { + let mut input = json!({"feedbackId":uuid::Uuid::new_v4().to_string(),"summary":" 图片加载失败 ", + "context":{"events":vec![json!({"message":"data%3Aimage/png;base64,abc","image":[1,2,3], + "error":"https://me:password@private","detail":"hidden","code":503});13], + "project":{"name":"Token: abc"},"client":"XiaoYi"}}); + 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"]["project"]["name"], "[敏感信息已移除]"); + input["summary"] = json!("图".repeat(2001)); + assert!(feedback_payload(&input).is_err()); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs index 6c2b8963..a639de89 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs @@ -1,7 +1,7 @@ //! One native home for account projects and local drafts. Covers are requested only for //! visible rows; destructive actions always name their scope and require confirmation. use super::{json, Value, Tokens, Workspace, PhotocraftApp, Ui, stitch_ui, agent_panel, CenterView, RichText, agent_motion, Duration, Request}; -use crate::{icons, widgets}; +use crate::{icons, theme::agent_scale::Type, widgets}; use egui::{Align, Frame, Layout, Sense, Stroke, pos2, vec2}; fn key(item: &Value) -> String { @@ -16,14 +16,6 @@ fn cloud_present(item: &Value) -> bool { matches!(item["source"].as_str(), Some("web" | "desktop")) || item["cloudPresent"] == true } -fn sync_choice(item: &Value) -> (&'static str, Option<&'static str>) { - if item["source"] != "native" { return ("同步", Some("pull")); } - if !cloud_present(item) { return ("同步到云端", Some("sync")); } - if item["syncDirty"] != false || item["syncedRevision"] != item["revision"] { return ("同步", Some("sync")); } - if item["cloudUpdateAvailable"] == true { return ("同步", Some("pull")); } - ("已同步", None) -} - #[derive(Clone)] struct DeleteDialogContent { item: Value, @@ -48,7 +40,7 @@ fn cloud_update_block_reason(item: &Value, open: bool) -> Option<&'static str> { } else if item["localPending"] == true || item["cloudUpdateBlocked"] == "pending_request" || item["deleteBlocked"] == true { Some("原任务尚待处理,本机工程已保留") } else if item["syncDirty"] != false || item["cloudUpdateBlocked"] == "unsynced_draft" { - Some("本机还有未同步修改,暂不替换工程") + Some("本机工程有修改,暂不替换") } else if item["cloudUpdateAvailable"] != true { Some("请刷新项目后核对云端版本") } else { @@ -77,9 +69,24 @@ fn project_status(item: &Value) -> Option { } } +pub(super) fn project_title(item: &Value) -> &str { + let name = item["name"].as_str().unwrap_or("未命名项目"); + if let Some((stem, extension)) = name.rsplit_once('.') + && extension.eq_ignore_ascii_case("pcraft") && !stem.is_empty() + { + return stem; + } + name +} + +pub(super) fn project_matches_query(item: &Value, query: &str) -> bool { + [item["name"].as_str(), item["brandName"].as_str(), item["productModel"].as_str()] + .into_iter().flatten().any(|value| value.to_lowercase().contains(query)) +} + fn matches_project(item: &Value, filter: ProjectFilter, query: &str) -> bool { let status_matches = filter == ProjectFilter::All || project_status(item) == Some(filter); - status_matches && (query.is_empty() || item["name"].as_str().unwrap_or("").to_lowercase().contains(query)) + status_matches && (query.is_empty() || project_matches_query(item, query)) } fn badge(item: &Value, t: &Tokens) -> (&'static str, egui::Color32, egui::Color32) { @@ -97,32 +104,6 @@ impl Workspace { self.project_operation["phase"] == "running" && self.project_operation["accountId"] == self.account["id"] && self.project_operation["origin"] == self.origin } - fn project_sync_item(&self, app: &PhotocraftApp, item: &Value) -> Value { - let mut item = item.clone(); - if item["source"] == "native" { - let identity = self.local_identity(item["id"].as_str().unwrap_or("")); - if let Some(state) = app.session.documents().iter().find(|state| self.open_projects.get(&state.doc.id.0) == Some(&identity)) { - item["revision"] = json!(state.revision); - if self.loaded_draft == Some(state.doc.id.0) && self.sync_dirty { item["syncDirty"] = json!(true); } - } - } - item - } - - pub(super) fn current_sync_item(&self, app: &PhotocraftApp) -> Option { - let state = app.session.active()?; - let identity = self.open_projects.get(&state.doc.id.0)?; - let local = identity.rsplit('|').next()?; - let item = self.projects.iter().find(|item| item["source"] == "native" && item["id"] == local).cloned().unwrap_or_else(|| - json!({"source":"native","id":local,"revision":state.revision,"cloudPresent":self.project_context["cloudLink"]["id"].is_string(),"syncedRevision":self.project_context["syncedRevision"],"syncDirty":self.sync_dirty})); - Some(self.project_sync_item(app, &item)) - } - - pub(super) fn request_current_sync(&mut self, app: &PhotocraftApp, chat: bool) -> Result { - let item = self.current_sync_item(app).ok_or("请先保存并打开项目")?; - self.request_project_sync_with_policy(app, &item, chat) - } - fn project_action_block(&self, app: &PhotocraftApp, item: &Value) -> Option<&'static str> { if self.project_operation_pending() { return Some("项目操作正在进行,请稍候"); } let identity = self.local_identity(item["id"].as_str().unwrap_or("")); @@ -134,11 +115,11 @@ impl Workspace { None } - fn begin_project_operation(&mut self, kind: &str, item: &Value, mut input: Value) -> Result { + fn begin_project_delete(&mut self, item: &Value, mut input: Value) -> Result { if self.project_operation_pending() { return Err("项目操作正在进行,请稍候".into()); } self.project_operation_serial = self.project_operation_serial.wrapping_add(1); - self.project_operation = json!({"id":self.project_operation_serial,"kind":kind,"projectId":item["id"],"source":item["source"],"accountId":self.account["id"],"origin":self.origin,"phase":"running", - "message":match kind {"delete"=>"正在删除项目…","pull"=>"正在同步到本机…",_=>"正在同步到云端…"}}); + self.project_operation = json!({"id":self.project_operation_serial,"kind":"delete","projectId":item["id"],"source":item["source"],"accountId":self.account["id"],"origin":self.origin,"phase":"running", + "message":"正在删除项目…"}); input["operation"] = self.project_operation.clone(); if self.tx.send(Request::Action("project-operation".into(), input)).is_err() { self.project_operation["phase"] = json!("failed"); @@ -148,68 +129,22 @@ impl Workspace { Ok(json!({"submitted":true})) } - pub(super) fn request_project_sync(&mut self, app: &PhotocraftApp, item: &Value) -> Result { - self.request_project_sync_with_policy(app, item, false) - } - - fn request_project_sync_with_policy(&mut self, app: &PhotocraftApp, item: &Value, chat: bool) -> Result { - if let Some(reason) = self.project_action_block(app, item) { return Err(reason.into()); } - let item = self.project_sync_item(app, item); - let (_, action) = sync_choice(&item); - let Some(kind) = action else { return Ok(json!({"synced":true,"submitted":false})); }; - let mut input = item.clone(); - input["accountId"] = self.account["id"].clone(); - input["origin"] = json!(self.origin); - if kind == "pull" && item["source"] == "native" { - let open = self.open_project_index(app, item["id"].as_str().unwrap_or("")).is_some(); - if let Some(reason) = cloud_update_block_reason(&item, open) { return Err(reason.into()); } - input = item["cloudUpdateRef"].clone(); - } else if kind == "sync" { - input["localId"] = item["id"].clone(); - input["syncChatHistory"] = json!(chat); - input["status"] = json!("draft"); - let identity = self.local_identity(item["id"].as_str().ok_or("项目编号无效")?); - if let Some(state) = app.session.documents().iter().find(|state| self.open_projects.get(&state.doc.id.0) == Some(&identity)) { - let current = self.loaded_draft == Some(state.doc.id.0); - let meta = if current { - self.sync_request_meta = self.sync_signature(); - json!({"composer":self.composer,"messages":self.messages,"project":self.project_context,"syncDirty":self.sync_dirty,"creationDraft":self.creation_draft()}) - } else { json!({}) }; - self.tx.send(Request::Save(state.doc.clone(), state.revision, meta)).map_err(|_| "本机服务已停止,未同步")?; - if current { self.saving = Some((state.doc.id.0, state.revision)); } - input["doc"] = json!(state.doc.id.0); - input["revision"] = json!(state.revision); - } else { input.as_object_mut().ok_or("项目同步参数无效")?.remove("doc"); } - } - self.begin_project_operation(kind, &item, input) - } - pub(super) fn project_operation_received(&mut self, app: &mut PhotocraftApp, result: Result) { let Ok(reply) = result else { return }; let operation = &reply["operation"]; if !self.project_operation_pending() || operation["id"] != self.project_operation["id"] || operation["accountId"] != self.account["id"] || operation["origin"] != self.origin { return; } - let kind = operation["kind"].as_str().unwrap_or(""); if let Some(error) = reply["error"].as_str() { self.project_operation["phase"] = json!("failed"); self.project_operation["message"] = json!(error); - if kind == "delete" { self.delete_error = error.into(); } + self.delete_error = error.into(); return; } let value = &reply["value"]; self.project_read = None; self.project_refresh_requested = true; - if kind == "delete" { self.project_deleted(app, value); } - else { - if let Some(items) = value["projects"].as_array() { self.merge_project_receipt(app, items); } - if kind == "sync" { super::creation::sync_received(self, app, value); } - } + self.project_deleted(app, value); self.project_operation["phase"] = json!("done"); - self.project_operation["message"] = json!(match kind { - "delete" => "项目已删除", - "pull" => "已同步到本机", - _ if value["syncDirty"] == true => "云端已保存该版本,当前仍有新修改", - _ => "已同步到云端", - }); + self.project_operation["message"] = json!("项目已删除"); } pub(super) fn local_identity(&self, local: &str) -> String { @@ -502,26 +437,28 @@ impl Workspace { let k = key(item); let native = item["source"] == "native"; let cloud = cloud_present(item); - let preview_height = width * 1.6; - let (shell, _) = ui.allocate_exact_size(vec2(width, preview_height + 62.0), Sense::hover()); + let has_screen = native || item["screenCount"].as_u64().unwrap_or(0) > 0; + let unavailable = !self.project_covers.contains_key(&k) && (!has_screen || self.cover_errors.contains_key(&k)); + let preview_height = width * if unavailable { 0.85 } else { 1.6 }; + let (shell, _) = ui.allocate_exact_size(vec2(width, preview_height + 82.0), Sense::hover()); let rect = egui::Rect::from_min_size(shell.min, vec2(width, preview_height)); let response = ui.interact(shell, ui.scope_id().with("project-open"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); let enabled = self.busy.is_none(); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button,enabled,"打开项目")); let hover = stitch_ui::morph_value(ui.ctx(),ui.scope_id().with("project-hover"),enabled && (response.hovered() || response.has_focus()),self.reduce_motion); let stroke_width = if cloud { 2.0 / ui.ctx().pixels_per_point() } else { 1.0 / ui.ctx().pixels_per_point() }; - stitch_ui::material(ui,ui.scope_id().with("project-material"),shell,16.0,hover*0.58,background); + stitch_ui::material_over(ui, ui.scope_id().with("project-material"), shell, 16.0, hover * 0.35, background, t.card, t.card_border); if let Some(texture) = self.project_covers.get(&k) { let size = texture.size_vec2(); let factor = (rect.width()/size.x).max(rect.height()/size.y); let uv = egui::Rect::from_center_size(pos2(0.5,0.5),rect.size()/(size*factor)); egui::Image::new(texture).uv(uv).corner_radius(egui::CornerRadius {nw:16,ne:16,sw:0,se:0}).paint_at(ui,rect); } else { - let has_screen = native || item["screenCount"].as_u64().unwrap_or(0) > 0; + ui.painter().rect_filled(rect, egui::CornerRadius { nw: 16, ne: 16, sw: 0, se: 0 }, t.field); let error = self.cover_errors.get(&k); let empty = error.is_some_and(|s|s=="尚无画布内容" || s=="尚未生成页面"); let text = if self.cover_loading.contains(&k) {"加载封面…"} else if empty {"待生成"} else if error.is_some() {"封面暂不可用"} else if has_screen {"首屏预览"} else {"待生成"}; - ui.painter().text(rect.center(),egui::Align2::CENTER_CENTER,text,egui::FontId::proportional(12.0),t.text_dim); + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, text, Type::Meta.font_id(), t.text_dim); if let Some(error) = error { response.clone().on_hover_text(error); } if has_screen && error.is_none() && !self.cover_loading.contains(&k) && self.cover_loading.len() < 2 && ui.is_rect_visible(rect) { self.cover_loading.insert(k); @@ -555,20 +492,8 @@ impl Workspace { let mut delete_rect = None; let blocked = delete_block_reason(item).or_else(|| self.project_action_block(app, item)); let delete_enabled = blocked.is_none(); - let sync_item = self.project_sync_item(app, item); - let (sync_label, sync_kind) = sync_choice(&sync_item); - let open_local = self.open_project_index(app, item["id"].as_str().unwrap_or("")).is_some(); - let sync_blocked = self.project_action_block(app, item).or_else(|| - if sync_kind == Some("pull") && native { cloud_update_block_reason(item, open_local) } else { None }); - let sync_enabled = sync_kind.is_some() && sync_blocked.is_none(); - let mut syncing = false; - let mut sync_rect = None; stitch_ui::select_popup(ui,&menu,176.0,self.reduce_motion,|ui| { menu_open = stitch_ui::menu_item(ui,"打开项目",enabled).clicked(); - let sync = stitch_ui::menu_item(ui, sync_label, sync_enabled); - sync_rect = Some(sync.rect); - syncing = sync.clicked(); - if let Some(reason) = sync_blocked { sync.on_disabled_hover_text(reason); } stitch_ui::divider(ui); let delete = stitch_ui::menu_item(ui,"删除项目",delete_enabled); delete_rect = Some(delete.rect); @@ -578,32 +503,36 @@ impl Workspace { ui.add(egui::Label::new(RichText::new(reason).size(11.5).color(t.text_dim)).wrap()); } }); - if syncing { - egui::Popup::close_id(ui.ctx(),menu.id.with("popup")); - if let Err(error) = self.request_project_sync(app, item) { self.project_list_error = error; } - } if deleting { egui::Popup::close_id(ui.ctx(),menu.id.with("popup")); self.delete_error.clear();self.delete_confirm=Some(item.clone()); } - let name = item["name"].as_str().unwrap_or("未命名项目"); + let name = project_title(item); let name_rect = egui::Rect::from_min_size(pos2(rect.left()+12.0,rect.bottom()+10.0),vec2(width-24.0,22.0)); let mut label_ui = ui.new_child(egui::UiBuilder::new().id_salt("project-title").max_rect(name_rect).layout(Layout::left_to_right(Align::Center))); widgets::elided_label(&mut label_ui,name,name_rect.width()).on_hover_text(name); - let status = if item["cloudDeleted"]==true {if item["retainedReason"]=="pending_request" {"云端已删除 · 任务待核查"} else {"云端已删除 · 本机保留"}} else if native && cloud {if item["syncDirty"]==true {"本机 · 尚有未同步修改"} else {"本机 · 云端"}} else if native {"仅本机 · 未同步"} else {"云端"}; - let status_rect = egui::Rect::from_min_size(pos2(rect.left()+12.0,rect.bottom()+36.0),vec2(width-24.0,18.0)); - let status_galley = ui.painter().layout_no_wrap(status.to_owned(),egui::FontId::proportional(11.5),t.text_dim); - ui.painter_at(status_rect).galley(status_rect.min,status_galley,t.text_dim); + let brand = item["brandName"].as_str().filter(|value| !value.is_empty()).unwrap_or("品牌未填写"); + let model = item["productModel"].as_str().filter(|value| !value.is_empty()).unwrap_or("型号未填写"); + let status = if item["retainedReason"] == "pending_request" { "任务待核查" } + else if native { "本机" } else { "云端" }; + let updated = item["updatedLabel"].as_str().or_else(|| item["updatedAt"].as_str()?.get(..10)) + .unwrap_or("更新时间未知"); + for (offset, text) in [(36.0, format!("{brand} · {model}")), (56.0, format!("{updated} · {status}"))] { + let line = egui::Rect::from_min_size(pos2(rect.left() + 12.0, rect.bottom() + offset), vec2(width - 24.0, 18.0)); + let mut row = ui.new_child(egui::UiBuilder::new().id_salt(("project-meta", offset as u32)) + .max_rect(line).layout(Layout::left_to_right(Align::Center))); + row.add(egui::Label::new(RichText::new(&text).size(Type::Meta.size()).color(t.text_dim)).truncate()).on_hover_text(text); + } let on_menu = ui.input(|i|i.pointer.interact_pos().is_some_and(|p|menu_rect.contains(p))); let opening = menu_open || (response.clicked() && !on_menu && !egui::Popup::is_any_open(ui.ctx())); if update.as_ref().is_some_and(|button|button.clicked()) { if let Err(error)=self.request_cloud_update(app,item) {self.project_list_error=error;} - } else if opening && enabled && !deleting && !syncing { + } else if opening && enabled && !deleting { egui::Popup::close_id(ui.ctx(),menu.id.with("popup")); self.handover();if let Err(error)=self.request_project_open(app,item.clone()) {self.project_list_error=error;} } if let Some(tiles)=self.project_geometry["tiles"].as_array_mut() { - tiles.push(json!({"id":item["id"],"source":item["source"],"open":agent_panel::rect_value(rect),"card":agent_panel::rect_value(shell),"hover":hover,"menu":agent_panel::rect_value(menu.rect),"sync":sync_rect.map(agent_panel::rect_value),"syncLabel":sync_label,"syncEnabled":sync_enabled,"syncBlockedReason":sync_blocked,"delete":delete_rect.map(agent_panel::rect_value),"deleteEnabled":delete_enabled,"deleteBlockedReason":blocked,"hasCover":self.project_covers.contains_key(&key(item)),"cloud":cloud,"borderPhysicalPixels":if cloud {2.0} else {1.0},"state":state,"badge":agent_panel::rect_value(badge_rect),"cloudUpdate":update.as_ref().map(|b|agent_panel::rect_value(b.rect)),"cloudUpdateEnabled":update.as_ref().is_some_and(|b|b.enabled())})); + tiles.push(json!({"id":item["id"],"source":item["source"],"open":agent_panel::rect_value(rect),"card":agent_panel::rect_value(shell),"hover":hover,"menu":agent_panel::rect_value(menu.rect),"delete":delete_rect.map(agent_panel::rect_value),"deleteEnabled":delete_enabled,"deleteBlockedReason":blocked,"hasCover":self.project_covers.contains_key(&key(item)),"cloud":cloud,"borderPhysicalPixels":if cloud {2.0} else {1.0},"state":state,"badge":agent_panel::rect_value(badge_rect),"cloudUpdate":update.as_ref().map(|b|agent_panel::rect_value(b.rect)),"cloudUpdateEnabled":update.as_ref().is_some_and(|b|b.enabled())})); } } @@ -711,7 +640,7 @@ impl Workspace { .collect::>() ); self.delete_confirm = Some(request.clone()); - if let Err(error) = self.begin_project_operation("delete", &item, request) { self.delete_error = error; } + if let Err(error) = self.begin_project_delete(&item, request) { self.delete_error = error; } } }); }); @@ -728,79 +657,6 @@ mod tests { use crate::jiansun::Event; use super::*; - #[test] - fn card_sync_uses_presence_and_saved_content_to_choose_upload_download_or_disabled() { - assert_eq!(sync_choice(&json!({"source":"web","id":"remote"})), ("同步", Some("pull"))); - assert_eq!(sync_choice(&json!({"source":"native","id":"local","revision":2})), ("同步到云端", Some("sync"))); - let mut local = json!({"source":"native","id":"local","cloudPresent":true,"revision":2,"syncedRevision":2,"syncDirty":false}); - assert_eq!(sync_choice(&local), ("已同步", None)); - local["revision"] = json!(3); - assert_eq!(sync_choice(&local), ("同步", Some("sync"))); - local["syncedRevision"] = json!(3); - local["syncDirty"] = json!(true); - assert_eq!(sync_choice(&local), ("同步", Some("sync"))); - local["syncDirty"] = json!(false); - local["cloudUpdateAvailable"] = json!(true); - assert_eq!(sync_choice(&local), ("同步", Some("pull"))); - } - - #[test] - fn card_sync_targets_the_chosen_project_without_opening_or_stopping_another_agent() { - let (tx, requests) = mpsc::channel(); - let (_events, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - let _ = requests.try_iter().collect::>(); - w.account = json!({"id":"owner"}); - w.busy = Some("agent".into()); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"name":"当前项目","width":1440,"height":400})).unwrap(); - let active = app.session.active().unwrap().doc.id.0; - w.loaded_draft = Some(active); - w.open_projects.insert(active, w.local_identity("current")); - w.project_context = json!({"localId":"current"}); - let item = json!({"source":"native","id":"00000000-0000-4000-8000-000000000001","revision":7,"syncDirty":true}); - assert_eq!(w.request_project_sync(&app, &item).unwrap()["submitted"], true); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected the project operation"); }; - assert_eq!(method, "project-operation"); - assert_eq!(input["localId"], item["id"]); - assert_eq!(input["operation"]["kind"], "sync"); - assert_eq!(input["revision"], 7); - assert!(input["doc"].is_null()); - assert_eq!(w.busy.as_deref(), Some("agent")); - assert_eq!(w.project_context["localId"], "current"); - assert_eq!(app.session.active().unwrap().doc.id.0, active); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn unsaved_canvas_edits_reenable_card_sync_and_save_the_exact_document_first() { - let (tx, requests) = mpsc::channel(); - let (_events, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - let _ = requests.try_iter().collect::>(); - w.account = json!({"id":"owner"}); - w.busy = None; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width":1440,"height":400})).unwrap(); - let st = app.session.active().unwrap(); - let id = st.doc.id.0; - let revision = st.revision; - w.loaded_draft = Some(id); - w.sync_dirty = false; - w.open_projects.insert(id, w.local_identity("local")); - let item = json!({"source":"native","id":"local","revision":revision,"syncedRevision":revision,"syncDirty":false,"cloudPresent":true}); - assert_eq!(w.request_project_sync(&app, &item).unwrap()["submitted"], false); - app.session.execute("image.imageSize", json!({"width":1440,"height":800})).unwrap(); - let changed = app.session.active().unwrap().revision; - assert_eq!(w.request_project_sync(&app, &item).unwrap()["submitted"], true); - let Request::Save(doc, saved_revision, _) = requests.try_recv().unwrap() else { panic!("save must precede upload"); }; - assert_eq!(doc.id.0, id); - assert_eq!(saved_revision, changed); - let Request::Action(_, input) = requests.try_recv().unwrap() else { panic!("expected upload"); }; - assert_eq!(input["doc"], id); - assert_eq!(input["revision"], changed); - } - #[test] fn project_operation_errors_are_visible_and_late_other_account_receipts_are_ignored() { let (tx, requests) = mpsc::channel(); @@ -812,7 +668,7 @@ mod tests { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); let item = json!({"source":"desktop","id":"remote","revision":2}); assert!(w.project_action_block(&app, &item).is_none()); - w.begin_project_operation("delete", &item, item.clone()).unwrap(); + w.begin_project_delete(&item, item.clone()).unwrap(); let operation = w.project_operation.clone(); let mut other = operation.clone(); other["accountId"] = json!("another"); @@ -1007,37 +863,32 @@ mod tests { } #[test] fn closing_the_native_tab_reenables_cloud_download_even_when_its_binding_is_retained() { - for via_sync_menu in [false, true] { - let (tx, requests) = mpsc::channel(); - let (_events, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - w.busy = None; - w.account = json!({"id":"a"}); - let _ = requests.try_iter().collect::>(); - let mut item = cloud_update_item(&w.origin); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width":1440,"height":400})).unwrap(); - let doc = app.session.active().unwrap().doc.id.0; - let revision = app.session.active().unwrap().revision; - item["revision"] = json!(revision); - item["syncedRevision"] = json!(revision); - item["cloudUpdateRef"]["localRevision"] = json!(revision); - w.open_projects.insert(doc, w.local_identity(item["id"].as_str().unwrap())); - if via_sync_menu { assert!(w.request_project_sync(&app, &item).is_err()); } - else { assert!(w.request_cloud_update(&mut app, &item).is_err()); } - assert!(requests.try_recv().is_err()); - app.session.close(0).unwrap(); - assert!(w.open_projects.contains_key(&doc)); - if via_sync_menu { assert_eq!(w.request_project_sync(&app, &item).unwrap()["submitted"], true); } - else { w.request_cloud_update(&mut app, &item).unwrap(); } - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected the existing cloud update path"); }; - assert_eq!(method, if via_sync_menu { "project-operation" } else { "open" }); - assert_eq!(input["id"], item["cloudUpdateRef"]["id"]); - assert_eq!(input["revision"], 4); - assert_eq!(input["localRevision"], revision); - assert_eq!(input["updateExisting"], true); - if via_sync_menu { assert_eq!(input["operation"]["kind"], "pull"); } - } + let (tx, requests) = mpsc::channel(); + let (_events, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + w.busy = None; + w.account = json!({"id":"a"}); + let _ = requests.try_iter().collect::>(); + let mut item = cloud_update_item(&w.origin); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width":1440,"height":400})).unwrap(); + let doc = app.session.active().unwrap().doc.id.0; + let revision = app.session.active().unwrap().revision; + item["revision"] = json!(revision); + item["syncedRevision"] = json!(revision); + item["cloudUpdateRef"]["localRevision"] = json!(revision); + w.open_projects.insert(doc, w.local_identity(item["id"].as_str().unwrap())); + assert!(w.request_cloud_update(&mut app, &item).is_err()); + assert!(requests.try_recv().is_err()); + app.session.close(0).unwrap(); + assert!(w.open_projects.contains_key(&doc)); + w.request_cloud_update(&mut app, &item).unwrap(); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected the existing cloud update path"); }; + assert_eq!(method, "open"); + assert_eq!(input["id"], item["cloudUpdateRef"]["id"]); + assert_eq!(input["revision"], 4); + assert_eq!(input["localRevision"], revision); + assert_eq!(input["updateExisting"], true); } #[test] fn deletion_block_state_is_explicit_and_never_inferred_from_names_or_age() { @@ -1235,7 +1086,7 @@ mod tests { let mut w = Workspace::new(tx, rx); w.busy = None; w.projects = vec![ - json!({"id":"one","source":"web","name":"很长的中文项目名称用于验证首屏预览与删除按钮不会互相挤压","revision":1,"hasDraft":true,"screenCount":0}), + json!({"id":"one","source":"web","name":"很长的中文项目名称用于验证首屏预览与删除按钮不会互相挤压","revision":1,"hasDraft":true,"screenCount":1}), json!({"id":"two","source":"web","name":"第二个项目","revision":1,"hasDraft":true,"screenCount":0}), json!({"id":"three","source":"web","name":"第三个项目","revision":1,"hasDraft":true,"screenCount":0}), ]; @@ -1254,7 +1105,12 @@ mod tests { } for tile in w.project_geometry["tiles"].as_array().unwrap() { let preview = tile["open"].as_array().unwrap(); - assert!(preview[3].as_f64().unwrap() > preview[2].as_f64().unwrap() * 1.5, "preview stays portrait"); + let aspect = preview[3].as_f64().unwrap() / preview[2].as_f64().unwrap(); + if tile["id"] == "one" { + assert!(aspect > 1.5, "leave room for the portrait cover"); + } else { + assert!(aspect < 1.0, "keep coverless project details near the top"); + } for action in ["open", "menu"] { let r = tile[action].as_array().unwrap(); let x = r[0].as_f64().unwrap(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workspace_navigation.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workspace_navigation.rs index b2915c2a..b4914b37 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workspace_navigation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workspace_navigation.rs @@ -1,11 +1,30 @@ -use super::{CenterView, Workspace, agent_panel, stitch_ui}; -use crate::{PhotocraftApp, theme::Tokens}; +use super::{CenterView, Request, Workspace, agent_panel, project_browser, stitch_ui}; +use crate::{ + PhotocraftApp, + theme::{Tokens, agent_scale::Type}, +}; use egui::{Id, RichText, Ui}; use serde_json::{Value, json}; -/// How many of the center grid's first rows the project page repeats as a -/// quick jump from the dock. -const RECENT_PROJECTS: usize = 6; +#[derive(Clone, Copy, Default, PartialEq, Eq)] +enum Intent { + #[default] + Find, + Spu, + Brief, + Knowledge, +} + +#[derive(Default)] +pub(super) struct Workbench { + scope: Value, + intent: Intent, + pub(super) input: String, + turns: Vec<(String, String)>, + matches: Vec, + pending: Option, + seed: Option<(u64, Intent, String)>, +} impl Workspace { pub(super) fn agent_page(&self, app: &PhotocraftApp) -> &'static str { @@ -26,62 +45,219 @@ impl Workspace { !self.library && !self.material && self.creation_open && self.creation_step < 3 } - /// The right-hand companion of a center destination. On the project page - /// the center owns the title, filters, search and "新建项目"; this panel - /// adds only what helps beside it, so nothing on screen exists twice. + fn workbench_scope(&self) -> Value { + json!({"accountId":self.account["id"],"origin":self.origin}) + } + + pub(super) fn refresh_workbench_scope(&mut self) { + let scope = self.workbench_scope(); + if self.workbench.scope != scope { + self.workbench = Workbench { scope, ..Default::default() }; + } + } + + pub(super) fn apply_workbench_seed(&mut self, app: &mut PhotocraftApp) { + let Some((doc, intent, text)) = self.workbench.seed.take() else { return }; + if app.session.active().map(|state| state.doc.id.0) != Some(doc) || self.creation_doc != Some(doc) { + self.workbench.seed = Some((doc, intent, text)); + return; + } + if intent == Intent::Spu { + self.creation_brief["identifierType"] = json!("spu"); + self.creation_brief["identifier"] = json!(text); + self.creation_dirty = true; + if let Err(error) = self.creation_action(app, "creation-product-platform", json!({"spu":text})) { + self.error = error; + } + } else { + self.creation_brief["note"] = json!(text); + self.creation_dirty = true; + } + } + + fn submit_workbench(&mut self, app: &mut PhotocraftApp) { + let query = self.workbench.input.trim().to_owned(); + let intent = self.workbench.intent; + self.workbench.matches.clear(); + let result = match intent { + Intent::Find => { + let query = query.to_lowercase(); + self.workbench.matches = self + .projects + .iter() + .filter(|item| item["source"] == "native" && project_browser::project_matches_query(item, &query)) + .take(12) + .cloned() + .collect(); + if self.workbench.matches.is_empty() { + "本机没有匹配的项目。".into() + } else { + "点击下方匹配的本机项目即可打开。".into() + } + } + Intent::Spu | Intent::Brief => { + if intent == Intent::Spu && !self.account["id"].is_string() { + "登录素材库后可以按 SPU 导入商品资料。".into() + } else { + match self.creation_action(app, "creation-new", Value::Null) { + Ok(_) => { + if let Some(doc) = app.session.active() { + self.workbench.seed = Some((doc.doc.id.0, intent, query.clone())); + } + "已打开新项目的产品资料页。".into() + } + Err(error) => error, + } + } + } + Intent::Knowledge => { + let id = uuid::Uuid::new_v4().to_string(); + if !self.account["id"].is_string() { + "登录素材库后可以查询企业知识库。".into() + } else if self + .tx + .send(Request::Action( + "workbench-knowledge".into(), + json!({ + "accountId":self.account["id"],"origin":self.origin,"readId":id,"query":query + }), + )) + .is_ok() + { + self.workbench.pending = Some(id); + "正在查阅企业知识库…".into() + } else { + "知识库读取服务暂不可用,请稍后重试。".into() + } + } + }; + self.workbench.input.clear(); + if self.workbench.turns.len() >= 12 { + self.workbench.turns.remove(0); + } + self.workbench.turns.push((query, result)); + } + + pub(super) fn workbench_knowledge_received(&mut self, result: Result) { + let Ok(value) = result else { return }; + if self.workbench.scope != self.workbench_scope() + || value["accountId"] != self.account["id"] + || value["origin"] != self.origin + || value["readId"].as_str() != self.workbench.pending.as_deref() + || self.workbench.pending.is_none() + { + return; + } + self.workbench.pending = None; + if let Some((_, reply)) = self.workbench.turns.last_mut() { + *reply = if let Some(error) = value["error"].as_str() { + error.to_owned() + } else { + let excerpts = value["sources"] + .as_array() + .into_iter() + .flatten() + .filter_map(|source| Some(format!("{}\n来源:{}", source["text"].as_str()?, source["path"].as_str()?))) + .collect::>(); + if excerpts.is_empty() { + "知识库没有返回相关规范,可补充品牌、品类或模板名称再问。".into() + } else { + excerpts.join("\n\n") + } + }; + } + } + + fn workbench_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + self.refresh_workbench_scope(); + let t = Tokens::get(ui.ctx()).agent(); + ui.label(RichText::new("工作台总助").size(Type::TitleLg.size()).strong().color(t.text)); + ui.add_space(6.0); + if self.workbench.turns.is_empty() { + ui.label(RichText::new("查找本机项目、用商品资料新建项目,或查询企业模板和规范。").color(t.text_dim)); + } + ui.add_space(10.0); + egui::ScrollArea::vertical().id_salt("workbench-turns").max_height((ui.available_height() - 220.0).max(60.0)).stick_to_bottom(true).show(ui, |ui| { + for (index, (query, answer)) in self.workbench.turns.iter().enumerate() { + ui.label(RichText::new(query).strong().color(t.text)); + stitch_ui::streaming_reply(ui, ui.scope_id().with(index), answer, false, self.reduce_motion); + ui.add_space(8.0); + } + for item in self.workbench.matches.clone() { + let name = project_browser::project_title(&item); + let label = item["brandName"].as_str().filter(|name| !name.is_empty()).map_or_else(|| name.to_owned(), |brand| format!("{name} · {brand}")); + if stitch_ui::menu_item(ui, &label, self.busy.is_none()).on_hover_text(&label).clicked() + && let Err(error) = self.request_project_open(app, item) + { + self.project_list_error = error; + } + } + }); + let modes = [(Intent::Find, "找项目"), (Intent::Spu, "按 SPU 新建"), (Intent::Brief, "用资料新建"), (Intent::Knowledge, "问规范")]; + ui.horizontal_wrapped(|ui| { + for (intent, label) in modes { + if ui.add_enabled_ui(self.workbench.pending.is_none(), |ui| ui.selectable_label(self.workbench.intent == intent, label)).inner.clicked() { + self.workbench.intent = intent; + } + } + }); + let (hint, limit, minimum) = match self.workbench.intent { + Intent::Find => ("输入项目名称、品牌或型号", 200, 1), + Intent::Spu => ("粘贴商品 SPU", 200, 1), + Intent::Brief => ("粘贴商品资料或制作要求", 2000, 1), + Intent::Knowledge => ("例如:这个品牌的详情页首屏有什么要求?", 500, 2), + }; + let pending = self.workbench.pending.is_some(); + let response = egui::ScrollArea::vertical() + .id_salt("workbench-input") + .max_height(88.0) + .show(ui, |ui| { + ui.add_enabled( + !pending, + stitch_ui::text_input(&mut self.workbench.input, hint, true).desired_width(f32::INFINITY).desired_rows(2).char_limit(limit), + ) + }) + .inner; + self.panel_geometry["workspaceSearch"] = agent_panel::rect_value(response.rect); + let count = self.workbench.input.trim().chars().count(); + let enabled = !pending && (minimum..=limit).contains(&count); + if stitch_ui::action_button(ui, if pending { "查阅中…" } else { "发送" }, stitch_ui::ButtonRole::Primary, enabled).clicked() { + self.submit_workbench(app); + } + } + pub(super) fn workspace_panel(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - let page = self.agent_page(app); - let projects = page == "projects"; + let projects = self.agent_page(app) == "projects"; let t = Tokens::get(ui.ctx()).agent(); ui.memory_mut(|memory| memory.surrender_focus(super::composer_input_id())); self.focus_composer = false; - for key in ["composer", "input", "subject", "references", "send", "conversationClip", "copywritingFields", "copywritingOptions", - "workspaceSearch", "workspaceReturn"] { - self.panel_geometry[key] = serde_json::Value::Null; + for key in [ + "composer", + "input", + "subject", + "references", + "send", + "conversationClip", + "copywritingFields", + "copywritingOptions", + "workspaceSearch", + "workspaceReturn", + ] { + self.panel_geometry[key] = Value::Null; } - if projects { - ui.add_space(6.0); - } else { - ui.add_space(18.0); + ui.add_space(if projects { 6.0 } else { 18.0 }); + if !projects { ui.horizontal(|ui| { ui.add_space(16.0); ui.add(crate::icons::image("image", 20.0, t.text_dim)); - ui.label(RichText::new("素材库").size(18.0).color(t.text)); + ui.label(RichText::new("素材库").size(Type::TitleLg.size()).color(t.text)); }); ui.add_space(20.0); } egui::Frame::NONE.inner_margin(16).show(ui, |ui| { ui.set_width(ui.available_width()); if projects { - if let Some(recent) = self.recent_projects() { - ui.label(RichText::new("最近的项目").size(12.0).color(t.text_dim)); - ui.add_space(8.0); - ui.scope(|ui| { - ui.spacing_mut().item_spacing.y = 2.0; - for item in recent { - // A list row, not a pill: names of any length share - // one left edge and one width. - let name = item["name"].as_str().unwrap_or("未命名项目"); - let response = stitch_ui::menu_item(ui, name, self.busy.is_none()); - if response.clicked() - && let Err(error) = self.request_project_open(app, item) - { - self.project_list_error = error; - } - } - }); - } else { - // Nothing to jump to yet. Say where a project starts, - // rather than leaving a blank column beside the page. - let (title, line) = if self.needs_library_login() || self.library_blocked() { - ("还没有可用的项目", "连接素材库后,这里会列出你最近的项目。") - } else { - ("还没有项目", "从中间的「新建项目」开始:填好产品资料、选好模板,就能进入画布和小壹一起制作。") - }; - ui.label(RichText::new(title).size(14.0).strong().color(t.text)); - ui.add_space(6.0); - ui.add(egui::Label::new(RichText::new(line).size(12.0).color(t.text_dim)).wrap()); - } + self.workbench_ui(app, ui); } else { ui.label(RichText::new("选择素材,预览后置入画布").color(t.text_dim)); let search = stitch_ui::search_field(ui, Id::unique("workspace-material-search"), &mut self.query, "输入产品编号"); @@ -101,7 +277,7 @@ impl Workspace { } } if let Some(state) = app.session.active() { - ui.add_space(24.0); + ui.add_space(16.0); stitch_ui::divider(ui); let label = if self.pending() { "返回当前任务" } else { "返回当前画布" }; let document = state.doc.id.0; @@ -113,22 +289,46 @@ impl Workspace { } self.panel_geometry["backgroundDocument"] = json!(document); } - // The project page shows its library notice in the center. if !projects && (self.needs_library_login() || self.library_blocked()) { ui.add_space(16.0); self.library_notice(ui); } }); } +} - /// The first rows of the center grid, in its own order: local projects - /// first, then the most recently updated. - fn recent_projects(&self) -> Option> { - let mut order: Vec<_> = self.projects.iter().enumerate() - .map(|(index, item)| (item["source"] == "native", item["updatedAt"].as_str(), index)) - .collect(); - order.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.cmp(&a.1))); - let recent: Vec = order.into_iter().take(RECENT_PROJECTS).map(|(_, _, index)| self.projects[index].clone()).collect(); - (!recent.is_empty()).then_some(recent) +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + + #[test] + fn workbench_spu_import_is_bound_to_the_new_project() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"name":"已有项目","width":800,"height":800})).unwrap(); + let previous = app.session.active().unwrap().doc.id.0; + let (tx, requests) = mpsc::channel(); + let (_events, receiver) = mpsc::channel(); + let mut workspace = Workspace::new(tx, receiver); + let _ = requests.try_iter().count(); + workspace.busy = None; + workspace.account = json!({"id":"qa"}); + workspace.workbench.intent = Intent::Spu; + workspace.workbench.input = "0003-A".into(); + workspace.creation_doc = Some(previous); + workspace.submit_workbench(&mut app); + let current = app.session.active().unwrap().doc.id.0; + assert_ne!(previous, current); + workspace.apply_workbench_seed(&mut app); + assert!(requests.try_recv().is_err(), "wait for the new document's product brief"); + workspace.creation_doc = Some(current); + workspace.apply_workbench_seed(&mut app); + let Request::Action(method, input) = requests.try_recv().unwrap() else { + panic!("expected a product lookup"); + }; + assert_eq!(method, "creation-product-platform"); + assert_eq!(input["doc"], current); + assert_eq!(input["spu"], "0003-A"); + assert!(requests.try_recv().is_err()); } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/panels/panel_docking.rs b/apps/detail-photocraft/crates/ui-egui/src/panels/panel_docking.rs index 0148a860..1bfd929a 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/panels/panel_docking.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/panels/panel_docking.rs @@ -629,14 +629,20 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { None => legacy(app), }; #[cfg(not(target_arch = "wasm32"))] - let agent_projection = crate::jiansun::agent_selected(app); + let projects_projection = crate::jiansun::projects_agent_dock(app); + #[cfg(not(target_arch = "wasm32"))] + let agent_projection = projects_projection || crate::jiansun::agent_selected(app); #[cfg(target_arch = "wasm32")] let agent_projection = false; #[cfg(not(target_arch = "wasm32"))] let layout = if agent_projection { let pro = app.ui.theme.is_pro(); - let panels: Vec = app.ui.dock.visible_tabs(Group::Color, pro).iter() - .filter_map(|(_, label)| normalize(label).map(str::to_owned)).collect(); + let panels: Vec = if projects_projection { + vec!["xiaoyi".into()] + } else { + app.ui.dock.visible_tabs(Group::Color, pro).iter() + .filter_map(|(_, label)| normalize(label).map(str::to_owned)).collect() + }; if let Some(active) = panels.iter().position(|id| id == "xiaoyi") { let range = agent_width_range(app, ui.available_width().min(ui.ctx().content_rect().width())); let width = ui.ctx().data_mut(|data| data.get_persisted::(agent_width_id())).unwrap_or(520.0).clamp(*range.start(), *range.end()); @@ -739,7 +745,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.ctx().data_mut(|data| data.insert_persisted(agent_width_id(), width.clamp(*range.start(), *range.end()))); continue; } - if !matches!(action, Action::Activate { .. }) { continue; } + if projects_projection || !matches!(action, Action::Activate { .. }) { continue; } } let result = match action { // A dock group minimizes as PhotoCraft's collapsed group, which the native dock's