diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs index 8d027f97..9e03522c 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs @@ -655,11 +655,123 @@ impl Backend { self.material_response(self.http.post(format!("{}/api/{endpoint}", self.origin)) .bearer_auth(token).json(payload).timeout(Duration::from_secs(300))) } +} + +struct UploadProgressTracker { + account_id: Value, + origin: String, + request_id: String, + total_files: usize, + total_bytes: u64, + total_chunks: u64, + uploaded_bytes: u64, + completed_chunks: u64, + session_bytes: u64, + file_index: usize, + started_at: std::time::Instant, +} + +impl UploadProgressTracker { + fn new(account_id: Value, origin: String, request_id: String, files: &[Artifact], state: &Value) -> Self { + let mut total_bytes = 0u64; + let mut total_chunks = 0u64; + let mut uploaded_bytes = 0u64; + let mut completed_chunks = 0u64; + for (index, artifact) in files.iter().enumerate() { + let chunks = artifact.size.div_ceil(CHUNK_SIZE).max(1); + total_bytes = total_bytes.saturating_add(artifact.size); + total_chunks = total_chunks.saturating_add(chunks); + let upload = &state["uploads"][index.to_string()]; + if upload["complete"] == true { + uploaded_bytes = uploaded_bytes.saturating_add(artifact.size); + completed_chunks = completed_chunks.saturating_add(chunks); + } else if let Some(next_chunk) = upload["nextChunk"].as_u64() { + let done_chunks = next_chunk.min(chunks); + completed_chunks = completed_chunks.saturating_add(done_chunks); + uploaded_bytes = uploaded_bytes.saturating_add(done_chunks.saturating_mul(CHUNK_SIZE).min(artifact.size)); + } + } + Self { + account_id, + origin, + request_id, + total_files: files.len(), + total_bytes, + total_chunks, + uploaded_bytes, + completed_chunks, + session_bytes: 0, + file_index: 0, + started_at: std::time::Instant::now(), + } + } + + fn advance_chunk(&mut self, bytes: u64) { + self.completed_chunks = (self.completed_chunks + 1).min(self.total_chunks); + self.uploaded_bytes = self.uploaded_bytes.saturating_add(bytes).min(self.total_bytes); + self.session_bytes = self.session_bytes.saturating_add(bytes); + } + + fn eta_seconds(&self) -> Option { + let remaining = self.total_bytes.saturating_sub(self.uploaded_bytes); + if remaining == 0 { + return Some(0); + } + let elapsed = self.started_at.elapsed().as_secs_f64(); + if self.session_bytes == 0 || elapsed < 0.05 { + return None; + } + let bytes_per_sec = self.session_bytes as f64 / elapsed; + if bytes_per_sec <= 1.0 { + return None; + } + Some((remaining as f64 / bytes_per_sec).ceil().clamp(1.0, 86_400.0) as u64) + } + + fn snapshot(&self, artifact: &Artifact, stage: &str) -> Value { + json!({ + "accountId": self.account_id, + "origin": self.origin, + "requestId": self.request_id, + "fileIndex": self.file_index, + "totalFiles": self.total_files, + "fileName": artifact.name, + "uploadedBytes": self.uploaded_bytes, + "totalBytes": self.total_bytes, + "completedChunks": self.completed_chunks, + "totalChunks": self.total_chunks, + "stage": stage, + "etaSeconds": self.eta_seconds(), + }) + } +} + +impl Backend { + fn emit_upload_progress(&self, payload: Value) { + if let Some((events, ctx)) = &self.access.notifications { + let _ = events.send(super::Event::Json("delivery-upload-progress".into(), Ok(payload))); + ctx.request_repaint_of(egui::ViewportId::ROOT); + } + } fn upload_material_file(&self, state_file: &Path, state: &mut Value, key: &str, artifact: &Artifact, purpose: &str, token: &str, ) -> R { - let chunks = artifact.size.div_ceil(CHUNK_SIZE); + self.upload_material_file_with_progress(state_file, state, key, artifact, purpose, token, None) + } + + #[allow(clippy::too_many_arguments)] + fn upload_material_file_with_progress( + &self, + state_file: &Path, + state: &mut Value, + key: &str, + artifact: &Artifact, + purpose: &str, + token: &str, + mut progress: Option<&mut UploadProgressTracker>, + ) -> R { + let chunks = artifact.size.div_ceil(CHUNK_SIZE).max(1); let mut repaired = false; loop { if state["uploads"][key]["uploadId"].is_null() { @@ -674,31 +786,45 @@ impl Backend { } let upload = &state["uploads"][key]; let upload_id = upload["uploadId"].as_str().ok_or("素材库未返回上传编号")?.to_owned(); - if upload["complete"] == true { return Ok(upload_id); } + if upload["complete"] == true { + if let Some(tracker) = progress.as_deref_mut() { + self.emit_upload_progress(tracker.snapshot(artifact, "uploading")); + } + return Ok(upload_id); + } let mut file = File::open(&artifact.path).map_err(|_| "成品文件无法读取")?; let start = upload["nextChunk"].as_u64().unwrap_or(0); let mut expired = false; for index in start..chunks { let offset = index * CHUNK_SIZE; - let size = (artifact.size - offset).min(CHUNK_SIZE); - file.seek(SeekFrom::Start(offset)).map_err(|_| "成品文件读取中断")?; - let mut bytes = vec![0; size as usize]; - file.read_exact(&mut bytes).map_err(|_| "成品文件读取中断")?; - let (status, value) = self.material_response(self.http.post(format!("{}/api/materials/upload/chunk", self.origin)) - .bearer_auth(token).header("Content-Type", "application/octet-stream") - .header("X-Upload-Id", &upload_id).header("X-Chunk-Index", index.to_string()) - .header("X-File-Name", &artifact.name).header("X-Chunk-Size", size.to_string()) - .timeout(Duration::from_secs(300)).body(bytes))?; - if status == 404 { - expired = true; - break; + let size = artifact.size.saturating_sub(offset).min(CHUNK_SIZE); + if size > 0 { + file.seek(SeekFrom::Start(offset)).map_err(|_| "成品文件读取中断")?; + let mut bytes = vec![0; size as usize]; + file.read_exact(&mut bytes).map_err(|_| "成品文件读取中断")?; + let (status, value) = self.material_response(self.http.post(format!("{}/api/materials/upload/chunk", self.origin)) + .bearer_auth(token).header("Content-Type", "application/octet-stream") + .header("X-Upload-Id", &upload_id).header("X-Chunk-Index", index.to_string()) + .header("X-File-Name", &artifact.name).header("X-Chunk-Size", size.to_string()) + .timeout(Duration::from_secs(300)).body(bytes))?; + if status == 404 { + expired = true; + break; + } + if status != 200 { return Err(material_error(&value)); } } - if status != 200 { return Err(material_error(&value)); } state["uploads"][key]["nextChunk"] = json!(index + 1); write_json(state_file, state)?; + if let Some(tracker) = progress.as_deref_mut() { + tracker.advance_chunk(size); + self.emit_upload_progress(tracker.snapshot(artifact, "uploading")); + } } + if !expired && let Some(tracker) = progress.as_deref_mut() { + self.emit_upload_progress(tracker.snapshot(artifact, "merging")); + } let (status, completed) = if expired { (404, json!({"error":"素材上传会话已失效"})) } else { @@ -780,13 +906,35 @@ impl Backend { let purpose = format!("xiaoyi:{cloud_id}:{request_id}"); let mut repaired = false; let result = loop { + let mut tracker = UploadProgressTracker::new( + self.auth["account"]["id"].clone(), + self.origin.clone(), + request_id.clone(), + delivery_files, + &state, + ); + if let Some(first) = delivery_files.first() { + self.emit_upload_progress(tracker.snapshot(first, "uploading")); + } let mut groups = json!({"main":[],"sku":[],"detail":[]}); for (index, artifact) in delivery_files.iter().enumerate() { - let upload_id = self.upload_material_file(&state_file, &mut state, &index.to_string(), artifact, &purpose, token)?; + tracker.file_index = index; + let upload_id = self.upload_material_file_with_progress( + &state_file, + &mut state, + &index.to_string(), + artifact, + &purpose, + token, + Some(&mut tracker), + )?; let mut file = artifact.file_info(); file["uploadId"] = json!(upload_id); groups[artifact.group].as_array_mut().ok_or("素材分组无效")?.push(file); } + if let Some(last) = delivery_files.last() { + self.emit_upload_progress(tracker.snapshot(last, "submitting")); + } if read_json(&project.join("context.json"))?["revision"].as_u64() != Some(revision) || detail_artifacts(project)? != artifacts || creation::load(project)?["brief"] != brief @@ -1068,4 +1216,48 @@ mod tests { assert_eq!(meta["specId"], "带轮款"); assert_eq!(meta["variantName"], "原木色"); } + + #[test] + fn upload_progress_tracker_tracks_resumed_chunks_and_eta() { + let art_a = Artifact { + path: PathBuf::from("a.psd"), name: "a.psd".into(), group: "detail", + size: CHUNK_SIZE * 2, sha256: "a".repeat(64), width: 100, height: 100, + sku_variant: None, sku_spec_id: None, sku_variant_name: None, sku: None, + }; + let art_b = Artifact { + path: PathBuf::from("b.jpg"), name: "b.jpg".into(), group: "main", + size: 512, sha256: "b".repeat(64), width: 100, height: 100, + sku_variant: None, sku_spec_id: None, sku_variant_name: None, sku: None, + }; + let state = json!({"uploads": {"0": {"nextChunk": 1}}}); + let mut tracker = UploadProgressTracker::new( + json!("acc-1"), + "https://sc.jiansun.vip".into(), + "req-1".into(), + &[art_a.clone(), art_b.clone()], + &state, + ); + let snap0 = tracker.snapshot(&art_a, "uploading"); + assert_eq!(snap0["totalFiles"], 2); + assert_eq!(snap0["totalChunks"], 3); + assert_eq!(snap0["completedChunks"], 1); + assert_eq!(snap0["uploadedBytes"], CHUNK_SIZE); + assert_eq!(snap0["totalBytes"], CHUNK_SIZE * 2 + 512); + assert!(snap0["etaSeconds"].is_null()); + + tracker.started_at = std::time::Instant::now() - Duration::from_secs(2); + tracker.advance_chunk(CHUNK_SIZE); + let snap1 = tracker.snapshot(&art_a, "uploading"); + assert_eq!(snap1["completedChunks"], 2); + assert_eq!(snap1["uploadedBytes"], CHUNK_SIZE * 2); + assert_eq!(snap1["etaSeconds"], 1); + + tracker.file_index = 1; + tracker.advance_chunk(512); + let snap2 = tracker.snapshot(&art_b, "submitting"); + assert_eq!(snap2["completedChunks"], 3); + assert_eq!(snap2["uploadedBytes"], CHUNK_SIZE * 2 + 512); + assert_eq!(snap2["etaSeconds"], 0); + assert_eq!(snap2["stage"], "submitting"); + } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index 3e055624..0662d43f 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -1204,6 +1204,7 @@ pub struct Workspace { listing_read_at: Option<(u64, Instant)>, listing_read_error: Option, delivery_completion: bool, + delivery_upload_progress: Option, finished_web_pending: bool, finished_web_error: Option, sync_dirty: bool, @@ -1875,6 +1876,7 @@ impl Workspace { listing_read_at: None, listing_read_error: None, delivery_completion: false, + delivery_upload_progress: None, finished_web_pending: false, finished_web_error: None, sync_dirty: true, @@ -2597,6 +2599,26 @@ impl Workspace { .chain(self.unknown_image_task.as_deref().map(|id| ("image-recover", id))) } + fn unknown_recovery_delay(&self, now: Instant) -> Option { + if !self.unknown { + return None; + } + let production = self.product_production.as_ref(); + self.original_image_recoveries() + .filter(|(_, id)| !production.is_some_and(|run| run.owns_deferred_image(id))) + .filter_map(|(_, id)| { + let keep_checking = production.is_some_and(|run| run.waiting_for_image(id)); + match self.image_recovery_schedules.get(id) { + Some(schedule) if !schedule.exhausted() || keep_checking => { + Some(schedule.due.saturating_duration_since(now)) + } + Some(_) => None, + None => Some(Duration::ZERO), + } + }) + .min() + } + fn automatic_image_recovery(&mut self, app: &PhotocraftApp, now: Instant) { if !self.unknown { return; } let Some(doc) = self.automatic_recovery_doc(app).filter(|doc| self.loaded_draft == Some(*doc)) else { return }; @@ -3624,6 +3646,18 @@ impl Workspace { } return; } + if method == "delivery-upload-progress" { + if let Ok(value) = result + && value["accountId"] == self.account["id"] + && value["origin"] == self.origin + { + self.delivery_upload_progress = Some(value); + } + return; + } + if method == "project-sync" { + self.delivery_upload_progress = None; + } if method == "delivery-status" { if let Ok(value) = result { creation::listing_status_received(self, app, &value); @@ -4178,6 +4212,7 @@ impl Workspace { self.creation_progress.clear(); self.sync_confirm = false; self.delivery_completion = false; + self.delivery_upload_progress = None; self.finished_web_pending = false; self.finished_web_error = None; self.agent_rule = Value::Null; @@ -4517,8 +4552,8 @@ impl Workspace { let interval = if self.project_refresh_requested { PROJECT_REFRESH_COOLDOWN } else { PROJECT_REFRESH_INTERVAL }; ctx.request_repaint_after(interval.saturating_sub(self.project_refresh.elapsed())); } - if self.unknown { - ctx.request_repaint_after(Duration::from_secs(1)); + if let Some(delay) = self.unknown_recovery_delay(Instant::now()) { + ctx.request_repaint_after(delay); } if self.waiting_for_external_agent() { ctx.request_repaint_after(Duration::from_secs(10).saturating_sub(self.pi_touched.elapsed())); @@ -6469,20 +6504,49 @@ mod tests { assert_eq!(w.creation_brief["name"], "已保存的资料"); } + fn module_tree_sources(stem: &str) -> Vec<(String, String)> { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/jiansun"); + let mut out = Vec::new(); + let parent = root.join(format!("{stem}.rs")); + if let Ok(src) = std::fs::read_to_string(&parent) { + out.push((stem.to_owned(), src)); + } + let dir = root.join(stem); + let mut stack = vec![dir]; + while let Some(cur) = stack.pop() { + let Ok(entries) = std::fs::read_dir(&cur) else { continue }; + let mut paths: Vec<_> = entries.filter_map(Result::ok).map(|e| e.path()).collect(); + paths.sort(); + for path in paths { + if path.is_dir() { + stack.push(path); + } else if path.extension().and_then(|s| s.to_str()) == Some("rs") { + let name = path.file_name().and_then(|s| s.to_str()).unwrap_or(""); + if name == "tests.rs" || name.ends_with("_tests.rs") { + continue; + } + if let Ok(src) = std::fs::read_to_string(&path) { + let rel = path.strip_prefix(&root).unwrap_or(&path).to_string_lossy().replace('\\', "/"); + out.push((rel, src)); + } + } + } + } + out + } + #[test] fn agent_ui_callers_use_shared_stitch_controls() { - let files = [ + let mut files: Vec<(String, String)> = [ ("jiansun", include_str!("jiansun.rs")), ("account_dialog", include_str!("jiansun/account_dialog.rs")), ("agent_canvas_read", include_str!("jiansun/agent_canvas_read.rs")), ("agent_motion", include_str!("jiansun/agent_motion.rs")), ("agent_native", include_str!("jiansun/agent_native.rs")), - ("agent_panel", include_str!("jiansun/agent_panel.rs")), ("canvas_workspace", include_str!("jiansun/canvas_workspace.rs")), ("composer_attachments", include_str!("jiansun/composer_attachments.rs")), ("composer_references", include_str!("jiansun/composer_references.rs")), ("creation_reads", include_str!("jiansun/creation_reads.rs")), - ("creation", include_str!("jiansun/creation.rs")), ("native_copy_warnings", include_str!("jiansun/native_copy_warnings.rs")), ("onboarding", include_str!("jiansun/onboarding.rs")), ("pi_bridge", include_str!("jiansun/pi_bridge.rs")), @@ -6499,7 +6563,12 @@ mod tests { ("stitch_state", include_str!("jiansun/stitch_state.rs")), ("stitch_kit", include_str!("jiansun/stitch_kit.rs")), ("stitch_timeline", include_str!("jiansun/stitch_timeline.rs")), - ]; + ] + .into_iter() + .map(|(n, s)| (n.to_owned(), s.to_owned())) + .collect(); + files.extend(module_tree_sources("agent_panel")); + files.extend(module_tree_sources("creation")); let forbidden = ["egui::Button::", "egui::Separator::", "egui::Spinner::", "egui::Window::", "egui::ComboBox::from_", ".button(", ".small_button(", ".checkbox(", ".radio(", ".selectable_", ".spinner(", ".separator("]; for (name, source) in files { let normalized = source.replace("\r\n", "\n"); @@ -6660,10 +6729,18 @@ mod tests { /// 第 3 批结束把全部归零并改成硬禁用。 #[test] fn agent_callers_never_gain_font_size_literals() { + for (stem, ceiling) in [("agent_panel", 33usize), ("creation", 23)] { + let count: usize = module_tree_sources(stem) + .into_iter() + .map(|(_, source)| size_literals(&production_of(&source))) + .sum(); + assert!( + count <= ceiling, + "{stem} grew to {count} hard-coded font sizes (ceiling {ceiling}); take the size from `theme::agent_scale::Type`" + ); + } let baseline = [ - ("agent_panel", include_str!("jiansun/agent_panel.rs"), 33usize), - ("canvas_workspace", include_str!("jiansun/canvas_workspace.rs"), 8), - ("creation", include_str!("jiansun/creation.rs"), 23), + ("canvas_workspace", include_str!("jiansun/canvas_workspace.rs"), 8usize), ("jiansun", include_str!("jiansun.rs"), 0), ("project_browser", include_str!("jiansun/project_browser.rs"), 8), ("prompt_library_ui", include_str!("jiansun/prompt_library_ui.rs"), 8), @@ -6688,9 +6765,8 @@ mod tests { /// `panel_geometry` 的字符串键是外部 QA 脚本与 `jiansun.state` 控制通道的契约,只许原样保留。 #[test] fn panel_geometry_keys_keep_their_names_for_the_external_qa_contract() { - let writers = [ + let mut writers: Vec = [ include_str!("jiansun.rs"), - include_str!("jiansun/agent_panel.rs"), include_str!("jiansun/canvas_workspace.rs"), include_str!("jiansun/composer_attachments.rs"), include_str!("jiansun/visual_preview_ui.rs"), @@ -6698,11 +6774,15 @@ mod tests { include_str!("jiansun/workflow_export.rs"), include_str!("jiansun/workspace_navigation.rs"), include_str!("jiansun/production_controls.rs"), - ]; + ] + .into_iter() + .map(str::to_owned) + .collect(); + writers.extend(module_tree_sources("agent_panel").into_iter().map(|(_, s)| s)); let marker = "panel_geometry[\""; let mut found = std::collections::BTreeSet::new(); for source in writers { - let production = production_of(source); + let production = production_of(&source); let mut rest = production.as_str(); while let Some(at) = rest.find(marker) { let tail = &rest[at + marker.len()..]; @@ -6717,6 +6797,30 @@ mod tests { assert!(found.is_empty(), "new panel_geometry keys are not registered: {found:?}"); } + /// 无头子模块(`agent_panel/`、`creation/` 下非 `*_ui.rs`)不得直接依赖 `egui::` 绘制接口。 + #[test] + fn headless_submodules_do_not_use_egui_drawing() { + for stem in ["agent_panel", "creation"] { + for (rel, source) in module_tree_sources(stem) { + if !rel.contains('/') || rel.ends_with("_ui.rs") { + continue; + } + for (idx, line) in production_of(&source).lines().enumerate() { + if !line.contains("egui::") { + continue; + } + let allowed = line.contains("ctx: &egui::Context") + || line.contains("ctx.request_repaint") + || line.contains("egui::ViewportId::ROOT") + || line.contains("egui::ColorImage") + || line.contains("egui::Id") + || line.trim() == "use egui::{Id, Rect};"; + assert!(allowed, "{rel}:{} uses disallowed egui:: in headless module: {line}", idx + 1); + } + } + } + } + /// 白标:组件库与状态模型里带中文的文案行,不得出现实现方的产品名。 #[test] fn agent_library_copy_never_names_the_implementation_products() { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs index 710afcec..a7b2bf7c 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs @@ -4,12 +4,50 @@ pub(super) mod multi_project_ui; #[path = "storage_settings_ui.rs"] pub(super) mod storage_settings_ui; -use super::stitch_timeline as timeline; -use super::stitch_state::{NoticeKind, RunState, ToolStatus, WorkerStage}; -use timeline::GoalProgressPanel; -use super::{json, Ui, Tokens, agent_motion, Value, RichText, Workspace, PhotocraftApp, Request, workflow_bridge, CenterView, LayerContent, Arc, Instant, Duration}; -use crate::icons; -use egui::{Align, Align2, Color32, FontId, Frame, Id, Layout, Rect, Response, Sense, Stroke, Vec2, vec2}; +mod artifact_preview_ui; +mod composer_actions; +mod composer_ui; +mod image_registration; +mod image_result_ui; +mod model_picker_ui; +mod model_settings; +mod models; +mod multi_project_view; +mod notifications; +mod notifications_ui; +mod processing_card_ui; +mod production_head_ui; +mod production_reply_ui; +mod reference_shelf_ui; +mod storage_events; +mod turn_ui; +mod turns; + +#[allow(unused_imports)] +use super::{ + CenterView, Document, agent_stream, canvas_workspace, composer_input_id, glow_pill, + multi_project_state, operation_error, production_controls, siri_orb, stitch_state, + stitch_timeline, stitch_ui, typing_text, +}; +use super::{PhotocraftApp, RichText, Tokens, Ui, Value, Workspace, agent_motion, json, stitch_timeline as timeline}; +use egui::{Align, Frame, Id, Rect, Response, Stroke, Vec2, vec2}; +use artifact_preview_ui::candidate_matches_message; +use turn_ui::{remember_visible_stream, turn_reply_id}; + +pub(super) use artifact_preview_ui::image_preview_button; +pub(super) use composer_ui::{copy_visible_text, insert_suggestion}; +#[cfg(test)] +pub(super) use models::ModelRole; +pub(super) use production_reply_ui::production_reply_text; +pub(super) use turns::{ConversationRows, conversation_settled, turns}; +#[cfg(test)] +pub(super) use turns::{TurnItem, TurnItemContent}; + +const CONTINUE_PRODUCTION: &str = "继续制作整套"; + +pub(super) fn rect_value(r: Rect) -> Value { + json!([r.left(), r.top(), r.width(), r.height()]) +} pub(super) fn paint_tag(ui: &Ui, rect: Rect, response: &Response, selected: bool) { let t = Tokens::get(ui.ctx()).agent(); @@ -31,1208 +69,8 @@ pub(super) fn paint_tag(ui: &Ui, rect: Rect, response: &Response, selected: bool } } -struct ProductionWorker<'a> { - row: &'a Value, - number: u64, - active: bool, - stage: WorkerStage, - step: String, - review: bool, - slot: String, - frame: Value, -} - -#[derive(Default)] -struct Turn<'a> { - user: Option<&'a str>, - user_index: Option, - target: Option<&'a Value>, - items: Vec>, - last_reply: Option<(&'a str, usize)>, -} - -enum TurnItem<'a> { - Reply(&'a str, usize), - Notice(&'a str, usize), - Thinking(&'a Value, usize), - Tools(Vec<(&'a Value, usize)>), - Images(usize, Vec<&'a Value>), - Choice(usize), -} - -impl TurnItem<'_> { - fn message_index(&self) -> usize { - match self { - Self::Reply(_, index) | Self::Notice(_, index) | Self::Thinking(_, index) - | Self::Images(index, _) | Self::Choice(index) => *index, - Self::Tools(rows) => rows[0].1, - } - } -} - -#[derive(Clone)] -enum TurnItemContent { - Reply(String), - Notice(String), - Thinking(bool), - Tools(Vec), - Images(Vec), - Choice(Value), -} - -impl TurnItemContent { - fn capture(item: &TurnItem<'_>, messages: &[Value]) -> Self { - match item { - TurnItem::Reply(text, _) => Self::Reply((*text).to_owned()), - TurnItem::Notice(text, _) => Self::Notice((*text).to_owned()), - TurnItem::Thinking(value, _) => Self::Thinking(value["active"] == true), - TurnItem::Tools(rows) => Self::Tools(rows.iter().map(|(value, _)| (*value).clone()).collect()), - TurnItem::Images(_, images) => Self::Images(images.iter().map(|value| (*value).clone()).collect()), - TurnItem::Choice(index) => Self::Choice(messages[*index].clone()), - } - } - - fn matches(&self, item: &TurnItem<'_>, messages: &[Value]) -> bool { - match (self, item) { - (Self::Reply(previous), TurnItem::Reply(text, _)) - | (Self::Notice(previous), TurnItem::Notice(text, _)) => previous.as_str() == *text, - (Self::Thinking(previous), TurnItem::Thinking(value, _)) => *previous == (value["active"] == true), - (Self::Tools(previous), TurnItem::Tools(rows)) => - previous.iter().eq(rows.iter().map(|(value, _)| *value)), - (Self::Images(previous), TurnItem::Images(_, images)) => - previous.iter().eq(images.iter().copied()), - (Self::Choice(previous), TurnItem::Choice(index)) => previous == &messages[*index], - _ => false, - } - } -} - -impl<'a> Turn<'a> { - fn images(&self) -> impl Iterator + '_ { - self.items.iter().flat_map(|item| match item { - TurnItem::Images(_, images) => images.as_slice(), - _ => &[], - }).copied() - } -} - -#[derive(Clone, Default)] -struct StreamHandoffs(Vec<(Id, String)>); - -#[derive(Clone, Copy, PartialEq, Eq)] -enum ReplyHandoff { Displayed, Append } - -const CONTINUE_PRODUCTION: &str = "继续制作整套"; - -/// A settled turn owns no request, pause or unresolved result. Follow-ups and -/// composer suggestions both wait for it. -#[derive(Clone, Default)] -struct ConversationRows { - layout: Option<(Id, usize, u32, u32, crate::theme::ThemeKind)>, - rects: Vec>, -} - -#[derive(Clone)] -struct TurnItemLayout { - content: TurnItemContent, - bounds: Rect, - advance: f32, - rail: Option, - settled_at: f64, - texture_sizes: Vec>, -} - -#[derive(Clone, Default)] -struct TurnItemLayouts { - key: Option<(u32, u32, crate::theme::ThemeKind, bool, bool)>, - #[cfg(test)] - benchmark_count: usize, - disclose_until: f64, - items: Vec>, -} - -fn conversation_settled(workspace: &Workspace, production: bool) -> bool { - !production && workspace.turn_idle() && !workspace.unknown && !workspace.pi_review - && !workspace.agent_effects_paused && workspace.error.is_empty() && workspace.stream_reply.is_empty() -} - -fn thinking_ui(ui: &mut Ui, thinking: &Value, turn_running: bool, reduced: bool) -> egui::Response { - let status = match (thinking["active"] == true, turn_running) { - (true, true) => timeline::ThinkingStatus::Active, - (true, false) => timeline::ThinkingStatus::Interrupted, - (false, _) => timeline::ThinkingStatus::Done, - }; - timeline::thinking_row(ui, ui.next_auto_id().with("thinking"), status, None, reduced) -} - -fn turn_reply_id(conversation_id: Id, user_index: Option) -> Id { - conversation_id.with(("turn-reply", user_index)) -} - -/// One caption for every image and waiting card: white 12pt on a scrim at the -/// bottom-left, one line, never wider than the card. -fn paint_image_caption(painter: &egui::Painter, rect: Rect, text: &str) { - if !(rect.width() >= 64.0 && rect.height() >= 34.0) { return; } - let mut job = egui::text::LayoutJob::simple_singleline(text.to_owned(), FontId::proportional(super::agent_stream::TEXT_META), Color32::WHITE); - job.wrap.max_width = (rect.width() - 22.0).max(1.0); - job.wrap.max_rows = 1; - let caption = painter.layout_job(job); - let pos = rect.left_bottom() + vec2(10.0, -8.0 - caption.size().y); - painter.rect_filled(Rect::from_min_size(pos, caption.size()).expand2(vec2(5.0, 3.0)), 6.0, Color32::from_black_alpha(188)); - painter.galley(pos, caption, Color32::WHITE); -} - -fn remember_visible_stream(ui: &Ui, id: Id, text: &str) { - let mut end = text.len().min(65_000); - while end > 0 && !text.is_char_boundary(end) { end -= 1; } - let text = text.get(..end).unwrap_or_default(); - ui.data_mut(|data| { - let cache = data.get_temp_mut_or_default::(Id::unique("jiansun-stream-handoffs")); - if let Some((_, previous)) = cache.0.iter_mut().find(|(candidate, _)| *candidate == id) { - if previous != text { text.clone_into(previous); } - } else { - // One public stream is at most the bridge's 65KB limit. Keep only - // recent scoped turns, never an unbounded copy of the transcript. - if cache.0.len() >= 16 { cache.0.remove(0); } - cache.0.push((id, text.to_owned())); - } - }); -} - -fn final_handoff(ui: &Ui, id: Id, text: &str) -> Option { - if text.is_empty() { return None; } - ui.data_mut(|data| { - let cache = data.get_temp_mut_or_default::(Id::unique("jiansun-stream-handoffs")); - cache.0.iter().find(|(candidate, _)| *candidate == id).and_then(|(_, stream)| { - if stream.starts_with(text) || stream.ends_with(text) { Some(ReplyHandoff::Displayed) } - else if !stream.is_empty() && text.starts_with(stream.as_str()) { Some(ReplyHandoff::Append) } - else { None } - }) - }) -} - -/// A tool's public label is constructed locally, never from its arguments, -/// output, arbitrary summary or error string. Unknown values stay unknown. -/// The name and status tables live in the kit (`stitch_state`), so a tool reads -/// the same here as in its row badge; this only assembles the legacy line. -fn is_tool_event(event: &Value) -> bool { - event["version"] == 1 && event["type"] == "tool" -} - -#[cfg(test)] -fn tool_activity_label(event: &Value) -> Option<(String, super::stitch_ui::StatusTone)> { - use super::stitch_state::{ToolStatus, tool_label}; - if !is_tool_event(event) { return None; } - let status = ToolStatus::parse(event["status"].as_str().unwrap_or("")); - let tool = tool_label(event["toolName"].as_str().unwrap_or("")); - let mut label = format!("{} · {tool}", status.label()); - // Only a terminal event with an upstream-provided duration gets a timer. - // There is no local clock estimate or implied completion percentage. - if status.timed() - && let Some(ms) = event["durationMs"].as_u64().filter(|ms| *ms <= 9_007_199_254_740_991) - { - label.push_str(&format!(" · {}", duration_text(ms))); - } - Some((label, status.tone().into())) -} - -/// People read durations coarsely: milliseconds under a second, tenths below -/// ten, whole seconds below a minute, then minutes. -fn duration_text(ms: u64) -> String { - super::stitch_state::duration_text(ms) -} - -/// Model ids are catalog keys written for machines. Known words become a -/// readable name; one unknown word leaves the whole id untouched, rather -/// than a half-translated label that matches no receipt. -fn model_display_name(id: &str) -> String { - let word = |word: &str| -> Option { - match word { - "gpt" => Some("GPT".to_owned()), - "vip" | "cl" | "2k" | "4k" => Some(word.to_ascii_uppercase()), - "image" | "nano" | "banana" | "flare" | "burst" | "sunburst" | "lite" | "fast" | "pro" => { - Some(format!("{}{}", word[..1].to_ascii_uppercase(), &word[1..])) - } - _ if !word.is_empty() && word.bytes().all(|byte| byte.is_ascii_digit() || byte == b'.') => Some(word.to_owned()), - _ => None, - } - }; - let mut words = Vec::new(); - for part in id.split('-') { - let Some(part) = word(part) else { return id.to_owned() }; - words.push(part); - } - if words.len() > 1 { words.join(" ") } else { id.to_owned() } -} - -/// Only the timestamp emitted by the active tool can start a live timer. -/// A UI mount time, a previous turn or a future/invalid clock is not evidence. -fn active_tool_elapsed(messages: &[Value], run: Option<&str>, now_ms: u64) -> Option { - let run = run.filter(|run| !run.is_empty())?; - messages.iter().rev().find_map(|message| { - let event = &message["event"]; - if event["version"] != 1 || event["type"] != "tool" || event["run"] != run || event["status"] != "started" { - return None; - } - let started = event["timestampMs"].as_u64()?; - now_ms.checked_sub(started) - }) -} - - -#[derive(Clone,Copy,Debug,Hash,PartialEq,Eq)] -enum ModelRole {Chat,Copy,Image} -impl ModelRole { - fn setting(self) -> &'static str { - match self { Self::Chat => "model", Self::Copy => "copyModel", Self::Image => "imageModel" } - } - fn geometry(self)->&'static str {match self {Self::Chat=>"chatModel",Self::Copy=>"copyModel",Self::Image=>"imageModel"}} - fn menu(self)->&'static str {match self {Self::Chat=>"chatModelMenu",Self::Copy=>"copyModelMenu",Self::Image=>"imageModelMenu"}} -} - -fn is_hidden_model(role: ModelRole, model: &Value) -> bool { - if role == ModelRole::Chat && model["productionReady"] == false { - return true; - } - let Some(id) = model["id"].as_str() else { return false }; - let id = id.to_ascii_lowercase(); - matches!(id.as_str(), - "gpt-6.2-astra" | "claude-sonnet-4-6" | "gemini-4-argon" | "gemini-4-carbon" - | "grok-4.5" | "grok-4.6" | "world-generation" | "deepseek-ocr" - ) || [ - "gpt-5.6-", "gpt-6-", "gpt-6.1-", "glm-5.3", "claude-fable-", "claude-opus-", - "claude-haiku-4-5", "gemini-3-", "gemini-3.", - ].iter().any(|prefix| id.starts_with(prefix)) -} - -const CONTEXT_UNAVAILABLE:&str="—"; -const CONTEXT_PENDING:&str="开始对话后显示使用情况"; -fn usage_count(value:&Value)->Option{value.as_u64().filter(|n|*n<=9_007_199_254_740_991)} -fn context_for_model(usage:&Value,models:&[Value],selected:&str)->Option{ - let model=models.iter().find(|model|model["key"]==selected)?; - let same=usage["version"]==1&&usage["model"]==model["id"]&&usage["modelKey"].as_str().is_none_or(|key|key==selected); - let mut current=if same {usage.clone()} else {json!({"version":1,"model":model["id"],"modelKey":selected})}; - let has_capacity=current["contextWindow"].as_u64().is_some_and(|limit|limit>0)&¤t["capacitySource"].as_str().is_some_and(|source|!source.is_empty()); - if !has_capacity&&model["contextWindow"].as_u64().is_some_and(|limit|limit>0)&&model["contextWindowSource"].as_str().is_some_and(|source|!source.is_empty()) { - current["contextWindow"]=model["contextWindow"].clone();current["capacitySource"]=model["contextWindowSource"].clone(); - } - (same||current["contextWindow"].as_u64().is_some_and(|limit|limit>0)).then_some(current) -} -fn context_tokens(value:&Value)->Option{matches!(value["contextSource"].as_str(),Some("pi-session"|"pi-last-response")).then(||usage_count(&value["contextTokens"])).flatten()} -fn context_fraction(usage:Option<&Value>)->Option{ - let value=usage?; - let limit=usage_count(&value["contextWindow"])?; - if limit==0||value["capacitySource"].as_str().is_none_or(str::is_empty){return None;} - let used=context_tokens(value)?; - if value["contextSource"]=="pi-last-response" {return Some((used as f64/limit as f64).clamp(0.0,1.0) as f32);} - let native=&value["piContextUsage"];let percent=native["percent"].as_f64()?; - (value["contextSource"]=="pi-session"&&usage_count(&native["tokens"])==Some(used)&&usage_count(&native["contextWindow"])==Some(limit)&&percent.is_finite()&&(0.0..=100.0).contains(&percent)).then_some((percent/100.0) as f32) -} -fn context_number(tokens:u64)->String {if tokens>=1_000_000 {format!("{:.0}M",tokens as f64/1_000_000.0)} else if tokens>=1_000 {format!("{:.0}K",tokens as f64/1_000.0)} else {tokens.to_string()}} -fn context_label(usage:Option<&Value>)->String{ - let Some(value)=usage else {return CONTEXT_UNAVAILABLE.into()}; - let Some(limit)=usage_count(&value["contextWindow"]).filter(|limit|*limit>0) else {return CONTEXT_UNAVAILABLE.into()}; - if value["capacitySource"].as_str().is_none_or(str::is_empty){return CONTEXT_UNAVAILABLE.into();} - let used=context_tokens(value).map_or_else(||"—".into(),context_number); - format!("{used}/{}",context_number(limit)) -} -fn context_meter(ui:&mut Ui,usage:Option<&Value>,reduced:bool,compact:bool)->Response{ - let t=Tokens::get(ui.ctx()).agent();let fraction=context_fraction(usage);let label=context_label(usage); - // The ring itself stays a dash; what it explains to a person is that the - // number is not known yet, which a bare dash cannot say. - let accessible=if label==CONTEXT_UNAVAILABLE {CONTEXT_PENDING.to_owned()}else{label.clone()}; - let response=ui.horizontal(|ui|{ - let response=super::stitch_ui::context_capacity(ui,fraction,&accessible).interact(Sense::click()); - if !compact {ui.label(RichText::new(&label).size(12.0).color(t.text));}response - }).inner; - response.widget_info(||egui::WidgetInfo::labeled(egui::Role::Button,true,accessible.as_str())); - super::stitch_ui::select_popup(ui,&response,260.0,reduced,|ui|{ - ui.label(RichText::new("当前上下文").strong().color(t.text)); - if let Some(fraction)=fraction { - super::stitch_ui::progress(ui,response.id.with("capacity"),&accessible,Some(fraction),reduced); - } else {ui.label(RichText::new(&accessible).size(12.0).color(t.text_dim));} - });response -} - -fn activity(message: &Value) -> bool { - if message["kind"] == "reply" { - return false; - } - if message["kind"] == "activity" { - return true; - } - let text = message["text"].as_str().unwrap_or(""); - ["已完成:", "图片已生成", "图片已保留", "已替换当前屏", "已置入生成", "已接手", "画布已修改", "98k图片结果"].iter().any(|prefix| text.starts_with(prefix)) -} - -/// Historical activity is not a live undo capability. Keep the original -/// journal intact while avoiding a stale promise after native undo or redo. -fn activity_history_label(text: &str) -> &str { - if text == "已采纳图片,可撤销" { "图片采纳记录" } else if text.starts_with("专业编辑已回填") { "专业编辑回填记录 · 编辑源文件保留" } else { text } -} - -#[cfg(test)] -fn activity_morph_id(conversation_id: Id, indices: &[usize]) -> Id { - conversation_id.with(("operations", indices.first().copied().unwrap_or(usize::MAX))) -} - -#[derive(Clone)] -struct AgentToast { shown_at: f64 } - -fn toast_active(toast: &AgentToast, now: f64) -> bool { - now.is_finite() && toast.shown_at.is_finite() && now >= toast.shown_at && now - toast.shown_at < 2.4 -} - -fn toast_id(origin: &str, account: &Value, project: &Value, doc: Option) -> Option { - let account = account["id"].as_str().filter(|id| !id.is_empty())?; - if origin.is_empty() { return None; } - Some(Id::unique("jiansun-draft-toast").with((origin, account, project["localId"].as_str(), doc))) -} - -/// Only called after an actual library item was inserted into the draft. -fn post_draft_toast(ui: &Ui, id: Id) { - let now = ui.input(|input| input.time); - ui.ctx().data_mut(|data| data.insert_temp(id, AgentToast { shown_at: now })); - ui.ctx().request_repaint(); -} - -fn draw_draft_toast(ui: &Ui, id: Id, anchor: Rect, reduced: bool) { - let Some(toast) = ui.ctx().data(|data| data.get_temp::(id)) else { return }; - if !ui.is_rect_visible(anchor) { return; } - let now = ui.input(|input| input.time); - let active = toast_active(&toast, now); - let visual = super::stitch_ui::overlay_transition(ui.ctx(), id.with("transition"), active, reduced); - if visual.render { - let position = egui::pos2(anchor.left() + 8.0, (anchor.top() - 36.0).max(ui.clip_rect().top())); - egui::Area::new(id.with("surface")).order(egui::Order::Foreground).fixed_pos(position).interactable(false).show(ui.ctx(), |ui| { - super::stitch_ui::overlay_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Menu, visual.opacity).show(ui, |ui| { - super::stitch_ui::overlay_contents(ui, visual, |ui| { - let t = Tokens::get(ui.ctx()).agent(); - ui.label(RichText::new("已添加到草稿").size(12.0).color(t.text)); - }); - }); - }); - } - if active { - let remaining = (2.4 - (now - toast.shown_at)).max(0.01); - ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(remaining)); - } else if !visual.render { - ui.ctx().data_mut(|data| data.remove::(id)); - } -} - -#[derive(Clone, Default)] -struct AgentNotifications { - entries: Vec, - unread: usize, - last_error: String, - last_unknown: bool, - open: bool, -} - -impl AgentNotifications { - fn add(&mut self, value: &str) { - if value.trim().is_empty() { return; } - let mut chars = value.chars(); - let mut visible = chars.by_ref().take(4000).collect::(); - if chars.next().is_some() { visible.push_str("…(内容已截断)"); } - if self.entries.iter().any(|item| item == &visible) { return; } - self.entries.push(visible); - if self.entries.len() > 40 { self.entries.remove(0); } - self.unread=(self.unread+1).min(self.entries.len()); - } - - fn observe(&mut self, error: &str, unknown: bool, warning: Option<&str>, receipts: &[Value]) { - if !error.is_empty() && error != self.last_error { self.add(error); } - self.last_error = error.to_owned(); - if unknown && !self.last_unknown && error.is_empty() { self.add("原请求结果待核查,未重复发送。"); } - self.last_unknown = unknown; - if let Some(warning) = warning { self.add(warning); } - for message in receipts { - if let Some(text) = message["text"].as_str().filter(|text| { - text.starts_with("保存副本时有导出提示:") || text.starts_with("PSD副本已导出,导出提示:") - }) { self.add(text); } - } - } -} - -fn notification_id(origin: &str, account: &Value, project: &Value, doc: Option) -> Option { - toast_id(origin, account, project, doc).map(|id| id.with("notifications")) -} - -fn turns(messages: &[Value]) -> Vec> { - let mut out = Vec::new(); - let mut current = Turn::default(); - let mut call_rows = std::collections::HashMap::<(&str, &str), (usize, usize)>::new(); - for (index, message) in messages.iter().enumerate() { - if message["role"] == "user" { - if current.user.is_some() || !current.items.is_empty() { - out.push(std::mem::take(&mut current)); - call_rows.clear(); - } - current.user = message["text"].as_str(); - current.user_index = Some(index); - } else if matches!(message["kind"].as_str(), Some("copywriting-options" | "copywriting-fields" | "pi-ui-request")) { - current.items.push(TurnItem::Choice(index)); - } else if message["kind"] == "pi-ui-decoration" { - continue; - } else if matches!(message["kind"].as_str(), Some("image" | "template-image" | "image-job")) { - if let Some(TurnItem::Images(_, images)) = current.items.last_mut() { - images.push(message); - } else { - current.items.push(TurnItem::Images(index, vec![message])); - } - } else if message["kind"] == "thinking" { - if let Some(TurnItem::Thinking(previous, previous_index)) = current.items.last_mut() { - *previous = message; - *previous_index = index; - } else { - current.items.push(TurnItem::Thinking(message, index)); - } - } else if activity(message) && is_tool_event(&message["event"]) { - let event = &message["event"]; - let identity = event["run"].as_str().zip(event["toolCallId"].as_str()); - if let Some(&(group, row)) = identity.and_then(|key| call_rows.get(&key)) - && let Some(TurnItem::Tools(tools)) = current.items.get_mut(group) - && let Some((previous, _)) = tools.get_mut(row) - { - if matches!(previous["status"].as_str(), Some("started" | "pending")) { - *previous = event; - } - continue; - } - let len = current.items.len(); - let location = if let Some(TurnItem::Tools(tools)) = current.items.last_mut() { - let row = tools.len(); - tools.push((event, index)); - (len - 1, row) - } else { - current.items.push(TurnItem::Tools(vec![(event, index)])); - (len, 0) - }; - if let Some(key) = identity { call_rows.insert(key, location); } - } else if let Some(text) = message["text"].as_str().filter(|s| !s.is_empty()) { - if activity(message) { - current.items.push(TurnItem::Notice(text, index)); - } else { - current.items.push(TurnItem::Reply(text, index)); - current.last_reply = Some((text, index)); - } - } - if current.target.is_none() { - current.target = message.get("target").filter(|target| target.is_object()); - } - } - if current.user.is_some() || !current.items.is_empty() { - out.push(current); - } - // The same status can be recorded again each time a stage resumes. The - // transcript keeps every record; the timeline shows only the latest copy. - let mut latest = std::collections::HashMap::new(); - for (turn_index, turn) in out.iter().enumerate() { - for (item_index, item) in turn.items.iter().enumerate() { - if let TurnItem::Notice(text, _) = item { latest.insert(*text, (turn_index, item_index)); } - } - } - for (turn_index, turn) in out.iter_mut().enumerate() { - let mut item_index = 0; - turn.items.retain(|item| { - let keep = match item { - TurnItem::Notice(text, _) => latest.get(text).copied() == Some((turn_index, item_index)), - _ => true, - }; - item_index += 1; - keep - }); - } - out -} - -/// Size a message to its actual shaped text, capped to the available column. -/// Manual allocation keeps the selectable label and its rounded surface in the -/// same right-aligned rectangle at all sidebar widths and DPI scales. -#[cfg(test)] -fn user_bubble(ui: &mut Ui, text: &str) -> Rect { - user_bubble_with_reveal(ui, text, None, true) -} - -/// The bubble itself lives in the kit (`stitch_ui::user_bubble_with_reveal`), together with -/// the per-character reveal and its glow. `reduced` is always passed through: reduced motion -/// shows the whole message at once and never starts the reveal or its repaint loop. -fn user_bubble_with_reveal(ui: &mut Ui, text: &str, started: Option, reduced: bool) -> Rect { - timeline::user_message(ui, text, started, reduced) -} - -fn paint_reference_thumbnail(ui: &mut Ui, texture: &egui::TextureHandle, limit: Vec2) -> Rect { - let source = texture.size_vec2(); - let size = source * (limit.x / source.x).min(limit.y / source.y); - ui.add(egui::Image::new(texture).fit_to_exact_size(size).corner_radius(6.0)).rect -} - -/// Assistant replies are laid out directly on the conversation surface; the -/// shared native label retains selectable text and its existing rich styling. -fn production_turn(command: Option<&str>) -> bool { - command.is_some_and(|command| { - matches!(command, "制作详情、主图和 SKU" | "继续整套制作" | "一键制作整套详情页") - || ["制作详情页 ·", "制作主图 ·", "制作 SKU ·"].iter().any(|prefix| command.starts_with(prefix)) - }) -} - -pub(super) fn production_reply_text(text: &str, streaming: bool, workflow: &Value) -> String { - let mut labels = std::collections::HashMap::new(); - let mut insert = |id, label| { - labels.entry(id).and_modify(|current| { - if *current != Some(label) { - *current = None; - } - }).or_insert(Some(label)); - }; - for output in workflow["outputs"].as_array().into_iter().flatten() { - if let (Some(id), Some(name)) = (output["documentId"].as_str(), output["name"].as_str()) { - insert(id, name); - } - for field in output["fields"].as_array().into_iter().flatten() { - if let (Some(id), Some(label)) = (field["fieldId"].as_str(), field["label"].as_str()) { - insert(id, label); - } - } - } - let tool_tags = [("", ""), ("", "")]; - let mut visible = String::new(); - let mut remaining = text; - while let Some((index, start, end)) = tool_tags.iter() - .filter_map(|&(start, end)| remaining.find(start).map(|index| (index, start, end))) - .min_by_key(|&(index, _, _)| index) - { - visible.push_str(&remaining[..index]); - let body = &remaining[index + start.len()..]; - remaining = body.split_once(end).map_or("", |(_, tail)| tail); - } - if streaming && let Some(index) = remaining.rfind('<') - && tool_tags.iter().any(|(tag, _)| tag.starts_with(&remaining[index..])) - { - remaining = &remaining[..index]; - } - visible.push_str(remaining); - let text = visible.as_str(); - let mut value = String::with_capacity(text.len()); - let mut chars = text.char_indices().peekable(); - while let Some((start, c)) = chars.next() { - let is_word = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'); - if !is_word(c) { - value.push(c); - continue; - } - while chars.next_if(|&(_, c)| is_word(c)).is_some() {} - let end = chars.peek().map_or(text.len(), |&(end, _)| end); - let token = &text[start..end]; - if token.len() >= 16 && token.bytes().all(|ch| ch.is_ascii_hexdigit()) && token.bytes().any(|ch| ch.is_ascii_alphabetic()) { - value.push_str("内部编号"); - continue; - } - value.push_str(labels.get(token).copied().flatten().unwrap_or(match token { - "sources" => "资料来源", - "links" => "图文对应关系", - _ => crate::client_brand::reply_word(token), - })); - } - value.replace("分句编号", "句子对应关系").replace("分句索引", "句子对应关系") -} - -fn read_delivery_manifest(ui: &Ui, path: &str) -> Option> { - let folder = std::path::Path::new(path); - if !folder.is_absolute() { return None; } - let file = folder.join("交付清单.json"); - let metadata = file.metadata().ok()?; - let stamp = (metadata.modified().ok()?, metadata.len()); - let id = ui.scope_id().with("saved-delivery-manifest"); - type Cache = (std::path::PathBuf, (std::time::SystemTime, u64), Arc); - if let Some((_, _, manifest)) = ui.data(|data| data.get_temp::(id)) - .filter(|(cached_file, cached_stamp, _)| cached_file == &file && *cached_stamp == stamp) - { - return Some(manifest); - } - let manifest: Value = serde_json::from_slice(&std::fs::read(&file).ok()?).ok()?; - manifest["allOutputsCompleted"].as_bool()?; - let manifest = Arc::new(manifest); - ui.data_mut(|data| data.insert_temp(id, (file, stamp, Arc::clone(&manifest)))); - Some(manifest) -} - -fn recover_delivery_manifest(ui: &Ui, checkpoint: &Value) -> Option<(String, Arc)> { - let root = checkpoint["deliveryDir"].as_str()?; - if let Some(manifest) = read_delivery_manifest(ui, root) - && (checkpoint["deliveryId"].is_null() || manifest["deliveryId"] == checkpoint["deliveryId"]) - { - return Some((root.to_owned(), manifest)); - } - let delivery_id = checkpoint["deliveryId"].as_str()?; - let dir = std::path::Path::new(root); - if !dir.is_absolute() { return None; } - let stamp = dir.metadata().ok()?.modified().ok()?; - let id = ui.scope_id().with(("recover-delivery-path", root, delivery_id)); - type Cache = (std::time::SystemTime, Option); - let path = if let Some((_, path)) = ui.data(|data| data.get_temp::(id)).filter(|(time, _)| *time == stamp) { - path - } else { - let path = dir.read_dir().ok()?.flatten().filter_map(|entry| { - entry.file_type().ok()?.is_dir().then(|| entry.path().into_os_string().into_string().ok()).flatten() - }).find(|path| read_delivery_manifest(ui, path).is_some_and(|manifest| manifest["deliveryId"] == delivery_id)); - ui.data_mut(|data| data.insert_temp(id, (stamp, path.clone()))); - path - }?; - let manifest = read_delivery_manifest(ui, &path)?; - (manifest["deliveryId"] == delivery_id).then_some((path, manifest)) -} - -fn production_image_cells( - app: &PhotocraftApp, workspace: &Workspace, progress: &Value, cells: &mut [super::agent_stream::Cell], -) { - use super::agent_stream::Cell; - let Some((target, workflow)) = workspace.production_canvas(app) else { return }; - let Some(variant) = progress["variantId"].as_str() else { return }; - if workflow["canvasFirst"] != true || workflow["outputId"] != progress["outputId"] || workflow["variantId"] != variant { - return; - } - let Some(slots) = workflow["slots"].as_array() else { return }; - for (row, state) in progress["pictureCells"].as_array().into_iter().flatten().zip(cells) { - let Some(slot_id) = row["slotId"].as_str() else { continue }; - let Some(id) = slots.iter().find(|slot| slot["id"] == slot_id && slot["outputId"] == progress["outputId"] - && slot["variantId"] == variant).and_then(|slot| slot["nativeLayerId"].as_u64()) else { continue }; - let id = photocraft_doc::LayerId(id); - let visible = target.doc.layer(id).is_some_and(|layer| layer.visible && match &layer.content { - photocraft_doc::LayerContent::Smart(smart) => !matches!(&smart.source, - photocraft_doc::SmartSource::Embedded { file_name, .. } if file_name == "template-empty.png"), - photocraft_doc::LayerContent::Raster(_) => true, - _ => false, - }); - *state = if visible && *state == Cell::Verified - && super::canvas_workspace::adopted(&target.doc, slot_id, variant).is_some() { - Cell::Verified - } else if visible { - Cell::Filled - } else if app.has_slot_preview(&target.doc, id) || slots.iter().any(|slot| - slot["id"] == slot_id && slot["variantId"] == variant && slot["candidates"].as_array().into_iter() - .flatten().any(|candidate| candidate["status"] == "complete")) { - Cell::Preview - } else { - Cell::Empty - }; - } -} - -#[cfg(test)] -fn assistant_reply(ui: &mut Ui, id: Id, text: &str) -> Response { - timeline::reply(ui, id, timeline::Reply { text, streaming: false, animate_final: false }, false) -} - -pub(super) fn copy_visible_text(ui: &mut Ui, text: &str, label: &str) -> Response { - let response = super::stitch_ui::icon_button(ui, "copy", 24.0, false, label); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); - if response.clicked() { ui.ctx().copy_text(text.to_owned()); } - response -} - -fn copy_reply(ui: &mut Ui, text: &str) -> Response { - copy_visible_text(ui, text, "复制这条回复") -} - -fn has_comparable_candidates(workflow: &Value, subject: &Value) -> bool { - let (Some(slot_id), Some(variant)) = (subject["slotId"].as_str().filter(|s| !s.is_empty()), subject["productVariantId"].as_str().filter(|s| !s.is_empty())) else { - return false; - }; - let mut ids = std::collections::HashSet::new(); - for slot in workflow["slots"].as_array().into_iter().flatten().filter(|slot| { - slot["id"] == slot_id && (slot["variantId"].is_null() || slot["variantId"] == variant) - }) { - for candidate in slot["candidates"].as_array().into_iter().flatten() { - let candidate_variant = candidate["variantId"].as_str().or_else(|| candidate["variant"].as_str()); - let same_variant = candidate_variant == Some(variant) || (candidate_variant.is_none() && slot["variantId"] == variant); - if same_variant && candidate["status"] == "complete" && let Some(id) = candidate["id"].as_str().filter(|id| !id.is_empty()) { - ids.insert(id); - } - } - } - ids.len() >= 2 -} - -pub(super) fn insert_suggestion(draft: &mut String, prompt: &str) { - if draft.trim().is_empty() { - *draft = prompt.to_owned(); - } else { - if !draft.ends_with('\n') { draft.push('\n'); } - draft.push_str(prompt); - } -} - -#[derive(Clone)] -struct ArtifactPreviewSnapshot { - scope: String, - key: String, - texture: egui::TextureHandle, - view: ArtifactPreviewView, -} - -#[derive(Clone)] -struct ArtifactPreviewView { - zoom: Option, - center: Vec2, - drag_position: Option, -} - -impl Default for ArtifactPreviewView { - fn default() -> Self { Self { zoom: None, center: Vec2::splat(0.5), drag_position: None } } -} - -impl ArtifactPreviewView { - fn scale(&self, viewport: Vec2, image: Vec2, pixels_per_point: f32) -> f32 { - self.zoom.map_or((viewport.x / image.x).min(viewport.y / image.y).min(1.0 / pixels_per_point), |zoom| zoom / pixels_per_point) - } - - fn zoom_at(&mut self, zoom: f32, at: Vec2, viewport: Vec2, image: Vec2, pixels_per_point: f32) { - let old = self.scale(viewport, image, pixels_per_point); - let fit = (viewport.x / image.x).min(viewport.y / image.y).min(1.0 / pixels_per_point); - self.zoom = Some(zoom.clamp(fit * pixels_per_point, 4.0)); - let new = self.scale(viewport, image, pixels_per_point); - self.center += at / image * (1.0 / old - 1.0 / new); - } -} - -pub(super) fn image_preview_button(ui: &mut Ui, rect: Rect, key: &str) -> egui::Response { - let button = Rect::from_min_size(rect.right_top() + vec2(-34.0, 6.0), vec2(28.0, 28.0)); - let response = preview_icon_at(ui, button, key, "maximize-2", "放大预览"); - if response.clicked() { - ui.data_mut(|data| data.insert_temp(Id::unique("jiansun-image-expanded"), key.to_owned())); - } - response -} - -fn preview_icon_at(ui: &mut Ui, rect: Rect, key: &str, icon: &str, label: &str) -> egui::Response { - let mut controls = ui.new_child(egui::UiBuilder::new().id_salt(("preview-control", key)).max_rect(rect) - .layout(Layout::top_down(egui::Align::Min))); - controls.set_clip_rect(ui.clip_rect().intersect(rect)); - let mut frame = egui::Frame::NONE.corner_radius(8).begin(&mut controls); - let response = super::stitch_ui::icon_action_button(&mut frame.content_ui, icon, label, true, 28.0, true); - frame.frame.fill = Color32::from_black_alpha(if response.hovered() { 230 } else { 185 }); - frame.end(&mut controls); - response.on_hover_text(label) -} - -fn preview_neighbors<'a>(workflow: &'a Value, key: &str) -> (Option<&'a str>, Option<&'a str>) { - for slot in workflow["slots"].as_array().into_iter().flatten() { - let mut keys = slot["candidates"].as_array().into_iter().flatten() - .filter(|candidate| candidate["status"] == "complete") - .filter_map(|candidate| candidate.get("taskId").unwrap_or(&candidate["id"]).as_str()); - let mut previous = None; - while let Some(candidate) = keys.next() { - if candidate == key { return (previous, keys.next()); } - previous = Some(candidate); - } - } - (None, None) -} - -fn artifact_preview_contents(ui: &mut Ui, texture: &egui::TextureHandle, view: &mut ArtifactPreviewView, rect: Rect) { - let image = texture.size_vec2(); - let viewport = rect.size(); - let pixels_per_point = ui.ctx().pixels_per_point(); - let response = ui.interact(rect, ui.scope_id().with("preview-image"), Sense::click_and_drag()); - let response = response.on_hover_text("滚轮缩放 · 拖动查看 · 双击适应窗口"); - if response.double_clicked() { *view = ArtifactPreviewView::default(); } - if response.hovered() && ui.is_enabled() { - let (scroll, pinch) = ui.input_mut(|input| { - let values = (input.smooth_scroll_delta.y, input.zoom_delta()); - input.smooth_scroll_delta = Vec2::ZERO; - values - }); - let factor = if pinch != 1.0 { pinch } else { (scroll * 0.005).exp() }; - if factor != 1.0 { - let zoom = view.scale(viewport, image, pixels_per_point) * pixels_per_point * factor; - view.zoom_at(zoom, response.hover_pos().unwrap_or(rect.center()) - rect.center(), viewport, image, pixels_per_point); - ui.ctx().request_repaint(); - } - } - let scale = view.scale(viewport, image, pixels_per_point); - if ui.is_enabled() { - ui.input(|input| { - for event in &input.events { - match event { - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } if rect.contains(*pos) => view.drag_position = Some(*pos), - egui::Event::PointerMoved(pos) => { - if let Some(previous) = view.drag_position { - view.center -= (*pos - previous) / (image * scale); - view.drag_position = Some(*pos); - } - } - egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, .. } | egui::Event::PointerGone => view.drag_position = None, - _ => {} - } - } - }); - } else { view.drag_position = None; } - let half = (viewport / (image * scale) * 0.5).min(Vec2::splat(0.5)); - view.center = view.center.clamp(half, Vec2::splat(1.0) - half); - let can_pan = image.x * scale > viewport.x + 0.5 || image.y * scale > viewport.y + 0.5; - if can_pan { - let cursor = if view.drag_position.is_some() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab }; - response.on_hover_cursor(cursor); - } - let painter = ui.painter_at(rect.intersect(ui.clip_rect())); - painter.image(texture.id(), Rect::from_min_size(rect.center() - view.center * image * scale, image * scale), - Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE); -} - -fn artifact_preview_zoom_bar(ui: &mut Ui, texture: &egui::TextureHandle, view: &mut ArtifactPreviewView, viewport: Vec2, loading: bool, reduced: bool) { - let image = texture.size_vec2(); - let pixels_per_point = ui.ctx().pixels_per_point(); - let zoom = view.scale(viewport, image, pixels_per_point) * pixels_per_point; - let fit = ArtifactPreviewView::default().scale(viewport, image, pixels_per_point) * pixels_per_point; - let t = Tokens::get(ui.ctx()).agent(); - egui::Frame::NONE.fill(t.field).stroke(Stroke::new(1.0, t.field_border)).corner_radius(18) - .inner_margin(egui::Margin::symmetric(8, 0)).show(ui, |ui| { - ui.horizontal(|ui| { - use super::stitch_ui::{ButtonRole, action_button, icon_action_button}; - ui.spacing_mut().item_spacing.x = 3.0; - ui.spacing_mut().button_padding.x = 5.0; - if action_button(ui, "适应窗口", ButtonRole::Quiet, true).clicked() { - *view = ArtifactPreviewView::default(); - } - if action_button(ui, "原始大小", ButtonRole::Quiet, true).clicked() { - view.zoom_at(1.0, Vec2::ZERO, viewport, image, pixels_per_point); - } - if icon_action_button(ui, "minus", "缩小预览", true, 28.0, zoom > fit + 0.001).on_hover_text("缩小预览").clicked() { - view.zoom_at(zoom / 1.25, Vec2::ZERO, viewport, image, pixels_per_point); - } - if icon_action_button(ui, "plus", "放大预览", true, 28.0, zoom < 4.0).on_hover_text("放大预览").clicked() { - view.zoom_at(zoom * 1.25, Vec2::ZERO, viewport, image, pixels_per_point); - } - let percent = format!("{:.0}%", view.scale(viewport, image, pixels_per_point) * pixels_per_point * 100.0); - ui.add_sized(vec2(38.0, 28.0), egui::Label::new(RichText::new(percent).weak()).truncate()); - if loading { - super::stitch_ui::ai_loader(ui, ui.scope_id().with("artifact-preview-loading"), true, reduced); - } - }); - }); -} - -pub(super) fn rect_value(r: Rect) -> Value { - json!([r.left(), r.top(), r.width(), r.height()]) -} -fn frame_image_ratio(frame: &Value) -> Option { - let width = frame["width"].as_f64()?; - let height = frame["height"].as_f64()?; - (width > 0.0 && height > 0.0).then_some((width / height) as f32).filter(|ratio| ratio.is_finite() && *ratio > 0.0) -} - -fn image_card_size(width: f32, ratio: f32) -> egui::Vec2 { - let width = width.min(340.0 * ratio); - vec2(width, width / ratio) -} -fn image_location(value: &Value, id: &str) -> Value { - let mut target = json!({"kind":"candidate","taskId":id,"candidateId":id}); - for key in ["slotId", "productVariantId", "outputId", "documentId", "nativeLayerId"] { - if let Some(field) = value.get(key).filter(|field| !field.is_null()) - .or_else(|| value["target"].get(key).filter(|field| !field.is_null())) { - target[key] = field.clone(); - } - } - if value["variantId"].is_string() && !target["productVariantId"].is_string() { - target["productVariantId"] = value["variantId"].clone(); - } - if let Some(candidate) = value["candidateId"].as_str().or_else(|| value["target"]["candidateId"].as_str()) { - target["candidateId"] = json!(candidate); - } - target -} - -fn image_reference_target(value: &Value, id: &str, label: &str, original: bool) -> Value { - let mut target = json!({"taskId":id,"label":label}); - for key in ["documentId", "nativeLayerId", "slotId", "fieldId", "candidateId", "outputId", - "productVariantId", "pageId", "status", "source"] { - let field = value.get(key).filter(|field| !field.is_null()) - .or_else(|| if original { None } else { value["target"].get(key) }); - if let Some(field) = field { target[key] = field.clone(); } - } - if target["productVariantId"].is_null() { - target["productVariantId"] = value["variantId"].clone(); - } - target["kind"] = json!(if original { "template-image" } - else if target["slotId"].is_string() || target["candidateId"].is_string() { "candidate" } - else { "image" }); - if target["kind"] == "candidate" && target["candidateId"].is_null() { - target["candidateId"] = json!(id); - } - target -} - -fn activate_reference(ui: &mut Ui, reference: &Value, preview: Option<&str>) -> Option { - if reference["slotId"].is_string() || reference["nativeLayerId"].is_number() { - return Some(reference.clone()); - } - if let Some(id) = preview.or_else(|| reference["taskId"].as_str()) { - ui.data_mut(|data| data.insert_temp(Id::unique("jiansun-image-expanded"), id.to_owned())); - } - None -} - -/// Match explicit identities only: a reused slot or a similar label alone is -/// never enough to identify an earlier response. -fn candidate_matches_message(target: &Value, image: &Value) -> bool { - let saved = &image["target"]; - let mut identity = false; - for key in ["candidateId", "taskId", "run"] { - let requested = target[key].as_str().filter(|value| !value.is_empty()); - let recorded = image[key].as_str().or_else(|| saved[key].as_str()).filter(|value| !value.is_empty()); - if let Some(requested) = requested { - if let Some(recorded) = recorded { - if requested != recorded { return false; } - if key != "run" { identity = true; } - } else if key == "run" { return false; } - } - } - if !identity { return false; } - for key in ["slotId", "productVariantId", "outputId"] { - if let (Some(requested), Some(recorded)) = (target[key].as_str(), image[key].as_str().or_else(|| saved[key].as_str())) - && requested != recorded { return false; } - } - identity -} - -fn composer_galley(ui: &Ui, text: &str, width: f32) -> Arc { - let mut job = egui::text::LayoutJob::simple(text.to_owned(), FontId::proportional(14.0), Tokens::get(ui.ctx()).agent().text, width); - for section in &mut job.sections { section.format.line_height = Some(24.0); } - ui.fonts_mut(|fonts| fonts.layout_job(job)) -} - -const REFERENCE_WIDTH: f32 = 132.0; -const REFERENCE_GAP: f32 = 4.0; - -fn reference_columns(width: f32) -> usize { - ((width + REFERENCE_GAP) / (REFERENCE_WIDTH + REFERENCE_GAP)).floor().max(1.0) as usize -} - -fn reference_shelf_height(count: usize, width: f32) -> f32 { - if count == 0 { return 0.0; } - let rows = count.div_ceil(reference_columns(width)).min(3); - rows as f32 * (24.0 + REFERENCE_GAP) - REFERENCE_GAP + 6.0 -} - -/// Read the submit key before TextEdit consumes it. IME confirmation belongs to -/// the editor, never to the model request; repeats are consumed without dispatch. -fn composer_enter(ui: &mut Ui, id: Id) -> bool { - let state_id = id.with("ime-submit-guard"); - if !ui.memory(|memory| memory.has_focus(id)) { - ui.data_mut(|data| data.remove::<(bool, u64)>(state_id)); - return false; - } - let frame = ui.ctx().cumulative_frame_nr(); - let (mut composing, mut confirmed) = ui.data(|data| data.get_temp::<(bool, u64)>(state_id)).unwrap_or((false, u64::MAX)); - let mut ime_event = false; - ui.input(|input| { - for event in &input.events { - match event { - egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) => { - composing = !text.is_empty(); - ime_event = true; - confirmed = frame; - } - egui::Event::Ime(egui::ImeEvent::Commit(_)) => { - composing = false; - ime_event = true; - confirmed = frame; - } - _ => {} - } - } - }); - ui.data_mut(|data| data.insert_temp(state_id, (composing, confirmed))); - let blocked = composing || ime_event || confirmed != u64::MAX && frame.saturating_sub(confirmed) <= 1; - let mut submit = false; - ui.input_mut(|input| { - input.events.retain(|event| { - if let egui::Event::Key { key: egui::Key::Enter, pressed: true, repeat, modifiers, .. } = event - && !modifiers.shift - && !modifiers.alt - { - submit |= !blocked && !repeat; - false - } else { - true - } - }); - }); - submit -} - -fn icon(ui: &mut Ui, name: &str, tint: Color32) { - ui.add(icons::image(name, 14.0, tint)); -} - -/// Candidate numbers are the actual canvas order, never the message order. -/// If either identity is absent or ambiguous, show no invented ordinal. -fn candidate_ordinal(subject: &Value, workflow: &Value) -> Option { - let slot_id = subject["slotId"].as_str().filter(|id| !id.is_empty())?; - let candidate_id = subject["candidateId"].as_str().filter(|id| !id.is_empty())?; - let mut slots = workflow["slots"].as_array()?.iter().filter(|slot| slot["id"].as_str() == Some(slot_id)); - let slot = slots.next()?; - if slots.next().is_some() { return None; } - let mut matches = slot["candidates"].as_array()?.iter().enumerate() - .filter(|(_, candidate)| candidate["id"].as_str() == Some(candidate_id)); - let (index, _) = matches.next()?; - if matches.next().is_some() { return None; } - Some(index + 1) -} - -fn subject_label(subject: &Value, workflow: &Value) -> String { - if subject["kind"] == "selection" { - let count = subject["selectedLayerIds"].as_array().map_or_else(|| subject["targets"].as_array().map_or(0, Vec::len), Vec::len); - return format!("已选 {count} 个对象"); - } - let mut parts = Vec::::new(); - for field in ["pageId", "label", "variantLabel"] { - if let Some(text) = subject[field].as_str().filter(|text| !text.trim().is_empty()) { - let text = text.chars().take(160).collect::(); - if !parts.iter().any(|part| part == &text || part.starts_with(&format!("{text} ·"))) { - parts.push(text); - } - } - } - if subject["kind"] == "candidate" { - let ordinal = candidate_ordinal(subject, workflow); - parts.push( - subject["candidateLabel"] - .as_str() - .map(str::to_owned) - .unwrap_or_else(|| ordinal.map_or_else(|| "候选".into(), |index| format!("候选 {index}"))), - ); - } - if parts.is_empty() { "当前项目".into() } else { parts.join(" · ") } -} - -fn image_result_labels(target: &Value, workflow: &Value, brief: &Value) -> (String, String, String) { - let short = candidate_ordinal(target, workflow).map_or_else(|| "候选图片".to_owned(), |ordinal| format!("候选 {ordinal}")); - let slot = workflow["slots"].as_array().into_iter().flatten() - .find(|slot| target["slotId"].as_str().is_some_and(|id| !id.is_empty() && slot["id"].as_str() == Some(id))); - let page = slot.and_then(|slot| slot["documentId"].as_str()).unwrap_or(""); - let slot_label = slot.and_then(|slot| slot["label"].as_str()).unwrap_or(""); - let variant = brief["variants"].as_array().into_iter().flatten() - .find(|variant| target["productVariantId"].as_str().is_some_and(|id| !id.is_empty() && variant["id"].as_str() == Some(id))) - .and_then(|variant| variant["name"].as_str()).unwrap_or(""); - let title = subject_label(target, workflow); - let full = [page, slot_label, variant, title.as_str()].into_iter().filter(|part| !part.is_empty()).collect::>().join(" · "); - (page.to_owned(), short, full) -} - -fn notice_kind(text: &str) -> NoticeKind { - if text.contains("失败") { NoticeKind::Failed } - else if text.contains("核查") || text.contains("无法确认") || text.contains("未执行") { NoticeKind::NeedsCheck } - else if text.starts_with("正在") { NoticeKind::Waiting } - else if text.starts_with("图片已生成") { NoticeKind::Produced } - else if ["已完成", "已替换", "已置入", "已采用", "已回填", "已导出"] - .iter().any(|prefix| text.starts_with(prefix)) { NoticeKind::Saved } - else { NoticeKind::Info } -} - -fn workflow_scope(proposal: &Value, workflow: &Value) -> String { - if matches!(proposal["intent"].as_str(), Some("export" | "export_psd")) { - return "当前画布".into(); - } - if !matches!(proposal["intent"].as_str(), Some("fill_output" | "review_candidates" | "generate_candidate")) { - return String::new(); - } - let output = match proposal["outputId"].as_str() { - Some("main_images") => "主图", - Some("sku_images") => "SKU", - _ => "详情", - }; - let target = if let Some(slot_id) = proposal["slotId"].as_str() { - workflow["slots"] - .as_array() - .into_iter() - .flatten() - .find(|slot| slot["id"] == slot_id) - .and_then(|slot| if proposal["intent"] == "generate_candidate" { slot["fieldId"].as_str() } else { slot["documentId"].as_str() }) - .unwrap_or("图位已变化") - } else { - "全组" - }; - if proposal["intent"] == "generate_candidate" { - format!("{output} · {target} · {}", proposal["variant"].as_str().unwrap_or("候选已变化")) - } else { - format!("{output} · {target}") - } -} impl Workspace { - pub(super) fn trace_canvas_candidate(&mut self, app: &PhotocraftApp, target: Value) { - self.pending_candidate_trace = None; - let Some((doc, revision)) = app.session.active().map(|state| (state.doc.id.0, state.revision)) else { return }; - let matching: Vec<_> = turns(&self.messages).into_iter().filter(|turn| - turn.images().any(|image| candidate_matches_message(&target, image))) - .map(|turn| turn.user_index).collect(); - if matching.len() != 1 { return; } - self.pending_candidate_trace = Some(json!({ - "scope":[self.origin,self.account["id"],self.project_context["localId"],doc,self.loaded_draft,revision], - "turn":matching.first().copied().flatten(),"target":target - })); - } - - pub(super) fn track_worker_image(&mut self, value: &Value) { - let Some(op) = self.workflow.worker_image_progress(value) else { return; }; - let Some(task) = op["candidateId"].as_str().filter(|_| op["imageFrame"].is_object()) else { return; }; - if let Some(message) = self.messages.iter_mut().rev().find(|message| message["taskId"] == task - && matches!(message["kind"].as_str(), Some("image-job" | "image"))) - { - if message["kind"] == "image-job" { - message["step"] = op["imageStep"].clone(); - } - return; - } - self.messages.push(json!({ - "role":"assistant", "kind":"image-job", "taskId":task, "run":op["run"], "workerNumber":op["workerNumber"], - "width":op["imageFrame"]["width"], "height":op["imageFrame"]["height"], - "slotLabel":op["slotLabel"], "step":op["imageStep"], - "target":{"slotId":op["slotId"],"outputId":op["outputId"],"productVariantId":op["productVariantId"],"candidateId":task} - })); - self.draft_changed = true; - } - - pub(super) fn register_image(&mut self, task: Value) { - let Some(id) = task["taskId"].as_str() else { - return; - }; - if !self.messages.iter().any(|m| m["kind"] == "image" && m["taskId"] == id) { - let mut message = json!({"role":"assistant","kind":"image","taskId":id,"target":image_location(&task, id)}); - for key in ["slotId", "outputId"] { - if task[key].is_string() { - message[key] = task[key].clone(); - } - } - if task["variantId"].is_string() { - message["productVariantId"] = task["variantId"].clone(); - } - if let Some(job) = self.messages.iter_mut().rev().find(|item| item["kind"] == "image-job" && item["taskId"] == id) { - for key in ["width", "height", "workerNumber", "slotLabel"] { - message[key] = job[key].clone(); - } - *job = message; - } else { - self.messages.push(message); - } - self.draft_changed = true; - } - if self.requested_previews.insert(id.to_owned()) { - let _ = self.tx.send(Request::Action("agent-image-preview".into(), json!({"doc":task["doc"],"taskId":id}))); - } - } - /// Content-only viewport for workflow-card unit tests. Production uses the - /// real PhotoCraft dock; its tab switching is tested below. - #[cfg(test)] - pub(super) fn right(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - self.panel_geometry = json!({}); - egui::Panel::right("agent-workflow-fixture").exact_size(360.0).show(ui, |ui| self.agent_body(app, ui)); - } - pub(super) fn agent_body(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { let page=self.agent_page(app); let pulse=agent_motion::subject_change(ui,Id::unique("agent-workspace-transition"),page,self.reduce_motion); @@ -1593,9116 +431,39 @@ impl Workspace { app.perf.stage.ui_regions.conversation += crate::gpu_canvas::now_ms() - conversation_start; } - /// Only render request-owned snapshots; the currently selected canvas - /// object is not a reliable target once an asynchronous request is sent. - pub(super) fn processing_target(&self, app: &PhotocraftApp) -> Option { - let doc = app.session.active().map(|state| state.doc.id.0)?; - match self.busy.as_deref() { - Some("slot-append" | "slot-generate") => self.running_workflow_generation(doc) - .map(|op| { - let label = self.template_workflow["slots"].as_array().into_iter().flatten() - .find(|slot| slot["id"] == op["slotId"] && slot["outputId"] == op["outputId"]) - .map(|slot| &slot["label"]); - let kind = if op["candidateId"].is_string() { "candidate" } else { "slot" }; - json!({"kind":kind,"slotId":op["slotId"],"outputId":op["outputId"],"label":label, - "productVariantId":op["productVariantId"],"candidateId":op["candidateId"]}) - }) - .or_else(|| self.canvas_workspace.submitted_generation_target(&self.account["id"], &self.origin, Some(doc)).cloned()), - Some("agent" | "pi-agent") - if self.owner_doc == Some(doc) - && self.pi_request_scope["project"]["documentId"].as_u64() == Some(doc) - && self.pi_request_scope["account"]["id"] == self.account["id"] - && self.pi_request_scope["account"]["origin"] == self.origin - && self.pi_request_scope["project"]["localId"] - .as_str() - .is_none_or(|local| self.open_projects.get(&doc).is_some_and(|current| current == local)) => - { - self.pi_request_scope.get("subject").filter(|target| target.is_object()).cloned() - } - _ => None, - } - } - - pub(super) fn processing_card_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui) { - super::glow_pill::bind(ui, app.gpu_render_state.as_ref()); - if self.batch_progress_visible() { return; } - let reduced = self.reduce_motion || agent_motion::hidden(ui, ui.available_rect_before_wrap().intersect(ui.clip_rect())) - || self.owner_doc.is_some_and(|owner| app.session.active().is_none_or(|state| state.doc.id.0 != owner)); - let pending = self.pending(); - let running = self.canvas_workspace.adoption_preparing() || (pending && !self.agent_effects_paused); - let processing_id = Id::unique("jiansun-processing-card"); - let image_task = matches!(self.busy.as_deref(), Some("image" | "slot-generate" | "slot-append" | "image-recover" | "slot-recover")) - || self.pending_image.is_some(); - // Conversation status uses AI Loader, never the image-generation - // surface. Reset a preceding image remnant before another task starts. - if pending && (!image_task || self.canvas_workspace.adoption_preparing()) { - let _ = agent_motion::task_visibility(ui, processing_id, false, true); - self.agent_status_ui(ui, running); - return; - } - let visibility = agent_motion::task_visibility(ui, processing_id, pending && image_task, reduced); - if visibility <= 0.0 { - ui.data_mut(|data|data.remove::<(Id,f64,f64)>(Id::unique("glow-pill-image-clock"))); - return; - } - let mut card_ui = ui.new_child(egui::UiBuilder::new().id_salt("task-card-content").max_rect(ui.available_rect_before_wrap())); - card_ui.set_opacity(visibility); - let parent_ui = ui; - let ui = &mut card_ui; - let t = Tokens::get(ui.ctx()).agent(); - let waiting_for_image = pending && matches!(self.busy.as_deref(), Some("image" | "slot-generate" | "slot-append")) - && self.pending_image.is_none() - && !self.agent_effects_paused; - // Keep the neutral placeholder only long enough to fade out. Its - // visual lifetime does not change the underlying task state or title. - // The submitted user message stays at the same index while tool and - // result records append. Selection, hover and viewport coordinates do - // not define the identity or restart the waiting mark. - let waiting_id = Id::unique(("jiansun-result-waiting", &self.origin, self.account["id"].as_str(), - self.owner_doc, self.messages.iter().rposition(|message| message["role"] == "user"))); - let waiting_visibility = ui.ctx().animate_bool_with_time( - waiting_id.with("visibility"), - waiting_for_image, - if reduced { 0.0 } else { 0.16 }, - ); - let active = running; - let title = if !pending { - "处理已结束" - } else if !active { - "已停止本地操作 · 原请求保留" - } else if waiting_for_image { - if self.image_progress.is_empty() { "正在生成图片…" } else { super::stitch_ui::processing_label(&self.image_progress) } - } else if matches!(self.busy.as_deref(), Some("recover" | "image-recover" | "slot-recover")) { - "正在核查原结果…" - } else if !self.queue.is_empty() || self.pending_image.is_some() { - "正在更新画布…" - } else if self.busy.as_deref() == Some("slot-copy") { - "正在生成图位文案…" - } else { - self.workflow_waiting.as_ref().and_then(|value| value["label"].as_str()).unwrap_or("正在回复…") - }; - let title = title.to_owned(); - let target = self.processing_target(app).filter(|target| target["kind"].as_str().is_some_and(|kind| !kind.is_empty() && kind != "project")); - // The conversation frame has its own margins. Size the task surface - // from the actual dock/clip rather than compounding those margins. - let dock_width = self.panel_geometry["panel"][2].as_f64().map(|width| width as f32).unwrap_or(ui.clip_rect().width()); - let desired_card_width = (dock_width - 32.0).max(0.0).min((ui.clip_rect().right() - ui.cursor().left()).max(0.0)); - let ratio = (waiting_visibility > 0.0).then(|| { - let slot = target.as_ref()?; - self.template_workflow["slots"].as_array()?.iter() - .find(|value| value["id"] == slot["slotId"] - && (slot["outputId"].is_null() || slot["outputId"] == value["outputId"]) - && (slot["productVariantId"].is_null() || value["variantId"].is_null() || slot["productVariantId"] == value["variantId"])) - .and_then(|value| frame_image_ratio(&value["frame"])) - }).flatten().unwrap_or(16.0 / 9.0); - let image_size = image_card_size(desired_card_width, ratio); - let elapsed_ms = if active { - std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok() - .and_then(|now| u64::try_from(now.as_millis()).ok()) - .and_then(|now| active_tool_elapsed(&self.messages, self.pi_run.as_deref(), now)) - } else { None }; - ui.add_space(10.0); - let card = super::stitch_ui::surface(ui, super::stitch_ui::SurfaceRole::Task, |ui| { - let waiting_background = agent_motion::reserve_background(ui); - let content_width = ((if waiting_visibility > 0.0 { image_size.x } else { desired_card_width }) - 26.0).max(0.0); - ui.set_width(content_width); - if waiting_visibility > 0.0 { - ui.set_min_height((image_size.y - 26.0).max(0.0)); - } - ui.horizontal(|ui| { - if waiting_visibility > 0.0 { - let (rect, _) = ui.allocate_exact_size(vec2(26.0, 26.0), egui::Sense::hover()); - let motion=if waiting_for_image {super::siri_orb::Motion::Thinking} else {super::siri_orb::Motion::Still}; - if let Some(orb) = super::siri_orb::paint(ui,waiting_id.with("identity"),rect,motion,reduced) { - self.panel_geometry["processingBlob"] = rect_value(rect); - self.panel_geometry["processingBlobPhase"] = json!(orb.phase); - self.panel_geometry["processingBlobMoving"] = json!(!reduced && waiting_for_image); - self.panel_geometry["processingIdentity"] = json!("siri-orb"); - } - } else { - super::stitch_ui::ai_loader(ui, processing_id.with("loader"), active, reduced); - } - let reserve = if active { 26.0 + ui.spacing().item_spacing.x } else { 0.0 }; - let label_width = (ui.available_width() - reserve).max(0.0); - let label = egui::Label::new(RichText::new(title).size(13.0).color(t.text)).truncate(); - if waiting_visibility > 0.0 { - ui.allocate_ui_with_layout(vec2(label_width, 26.0), Layout::left_to_right(Align::Center), |ui| { - ui.set_width(label_width); - ui.add(label); - }); - } else { - ui.add_sized(vec2(label_width, 26.0), label); - } - if active { - let stop = super::stitch_ui::icon_button(ui, "square", 26.0, false, "停止本地自动操作,保留原请求"); - self.panel_geometry["taskStop"] = rect_value(stop.rect); - if stop.clicked() { self.abort_chat_run(); } - } - }); - if let Some(ms) = elapsed_ms { - let seconds = ms / 1_000; - let response = ui.label(RichText::new(format!("工具已运行 {}:{:02}", seconds / 60, seconds % 60)).size(super::agent_stream::TEXT_META).color(t.text_dim)); - if !agent_motion::hidden(ui, response.rect) { ui.ctx().request_repaint_after(Duration::from_millis(1_000 - ms % 1_000)); } - } - if let Some(target) = &target { - ui.add_space(5.0); - let label = subject_label(target, &self.template_workflow); - ui.add(egui::Label::new(RichText::new(label).size(12.0).color(t.text_dim)).wrap()); - } - waiting_background - }); - self.panel_geometry["processing"] = rect_value(card.response.rect); - if waiting_visibility > 0.0 { - self.panel_geometry["processingPlaceholder"] = rect_value(card.response.rect); - } - let now=ui.input(|input|input.time); - let elapsed=ui.data_mut(|data|{ - let id=Id::unique("glow-pill-image-clock"); - let mut clock=data.get_temp::<(Id,f64,f64)>(id).filter(|clock|clock.0==waiting_id).unwrap_or((waiting_id,now,0.0)); - if active && !reduced {clock.2=(now-clock.1)*0.55;} - data.insert_temp(id,clock);clock.2 - }); - let activity=ui.ctx().animate_bool_with_time(processing_id.with("working"),active,if reduced || agent_motion::hidden(ui, card.response.rect) {0.0} else {0.16}); - let mut pulse=if reduced {super::glow_pill::Pulse::default()} else {super::glow_pill::waiting(elapsed)}; - pulse.surge*=activity; - pulse.warp*=activity; - super::glow_pill::paint(ui,super::glow_pill::Surface {id:processing_id,rect:card.response.rect,radius:t.radius, - time:if reduced {2.4} else {elapsed},pulse,opacity:visibility,background:Some(card.inner),text_range:None,flanks:0.0}); - if active && !reduced { agent_motion::schedule(ui, card.response.rect, agent_motion::Pace::Idle); } - self.panel_geometry["processingLightMode"] = json!(if active {"glow-pill"} else {"paused"}); - self.panel_geometry["processingOpacity"] = json!(visibility); - parent_ui.advance_cursor_after_rect(ui.min_rect()); - } - - fn agent_status_ui(&mut self, ui: &mut Ui, running: bool) { - let t = Tokens::get(ui.ctx()).agent(); - let id = Id::unique(("jiansun-agent-status", &self.origin, self.account["id"].as_str(), self.owner_doc, - self.messages.iter().rposition(|message| message["role"] == "user"))); - let preparing = self.canvas_workspace.adoption_preparing(); - let title = if preparing { "准备采纳…" } - else if self.pi_ui_waiting() { "等待你的回复…" } - else if !running { "已停止本地操作 · 原请求保留" } - else if self.busy.as_deref() == Some("recover") { "正在核查原结果…" } - else if !self.queue.is_empty() { "正在更新画布…" } - else { self.workflow_waiting.as_ref().and_then(|value| value["label"].as_str()).unwrap_or("正在处理…") }.to_owned(); - // A stable, unframed row remains throughout the turn, including the - // genuine network waits between tools. No glow, panel or target repeat. - let shown = ui.allocate_ui_with_layout(vec2(ui.available_width(), 26.0), Layout::right_to_left(Align::Center), |ui| { - ui.set_min_height(26.0); - // Reserve the stop target first. Generic shared field rows use a - // 32pt interaction height; this status has its own compact 26pt - // geometry and cannot inherit that minimum through horizontal(). - if running && !preparing { - let stop = super::stitch_ui::icon_button(ui, "square", 26.0, false, "停止本地自动操作,保留原请求"); - self.panel_geometry["taskStop"] = rect_value(stop.rect); - if stop.clicked() { self.abort_chat_run(); } - } - ui.allocate_ui_with_layout(vec2(ui.available_width(), 26.0), Layout::left_to_right(Align::Center), |ui| { - super::stitch_ui::ai_loader(ui, id.with("loader"), running, true); - ui.add(egui::Label::new(RichText::new(title).size(12.0).color(t.text_dim)).truncate()); - }); - }); - self.panel_geometry["agentStatus"] = rect_value(shown.response.rect); - self.panel_geometry["processingLightMode"] = json!("inactive"); - } - - fn production_outcome_ui(&mut self, ui: &mut Ui, production: bool, app: &PhotocraftApp) { - use timeline::RunOutcome; - self.finish_delivery_hint(app, ui); - if production { - return; - } - let receipt = self.messages.iter().rev().take_while(|row| row["role"] != "user") - .find(|row| row["productionSummary"].is_object()); - let checkpoint = &self.product_checkpoint; - let delivery = receipt.map_or(&checkpoint["productionDelivery"], |row| &row["productionDelivery"]); - let path = delivery["path"].as_str(); - let saved = path.and_then(|path| read_delivery_manifest(ui, path).map(|manifest| (path.to_owned(), manifest))) - .or_else(|| (path.is_none() && !delivery["error"].is_string()) - .then(|| recover_delivery_manifest(ui, checkpoint)).flatten()); - if let Some((path, manifest)) = saved { - if self.delivery_completion { - self.sync_confirm = false; - self.delivery_completion = false; - } - let label = if manifest["allOutputsCompleted"] == true { - "本地已落盘" - } else { - "部分成品已落盘" - }; - let count = manifest["completedOutputs"].as_u64().zip(manifest["totalOutputs"].as_u64()) - .map_or_else(|| label.to_owned(), |(done, total)| format!("{label} · {done}/{total} 份")); - let outcome = if manifest["allOutputsCompleted"] == true { - RunOutcome::Completed { summary: &count, path: &path } - } else { - RunOutcome::PartialDelivery { summary: &count, path: &path } - }; - let mut open = false; - timeline::run_outcome_card(ui, outcome, None, |_| open = true, |ui| { - self.delivery_receipts_ui(app, ui, &manifest); - }); - if open && app.services.open_folder.as_ref() - .is_none_or(|open| open(std::path::Path::new(&path)).is_err()) - { - self.error = "无法打开文件夹,请检查目录是否仍可访问".into(); - } - return; - } - - let producing = self.pi_product_production; - let outcome = if producing && self.agent_effects_paused { - Some(RunOutcome::Stopped { request_kept: self.pending() || self.unknown }) - } else if producing && self.result_needs_check() { - Some(RunOutcome::NeedsCheck) - } else if self.pending() { - None - } else if let Some(error) = delivery["error"].as_str() { - Some(RunOutcome::Failed { category: super::stitch_state::ErrorCategory::classify(error) }) - } else if path.is_some() || receipt.is_some() { - Some(RunOutcome::Waiting { reason: "成品交付尚未确认" }) - } else { - None - }; - if let Some(outcome) = outcome { - timeline::run_outcome_card(ui, outcome, None, |_| {}, |_| {}); - } - } - - fn delivery_receipts_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui, manifest: &Value) { - use super::stitch_ui::{self as kit, ButtonRole::Quiet, StatusTone::{Error, Neutral}}; - let doc = app.session.active().map(|doc| doc.doc.id.0); - let receipt = &self.project_context["materialDelivery"]; - let same_delivery = receipt["deliveryId"].as_str().map_or( - self.project_context["status"] == "completed", |id| manifest["deliveryId"] == id); - let material = receipt["materialId"].as_str().filter(|_| same_delivery); - let listing = &receipt["listingStatus"]; - let withdrawn = material.is_some() && receipt["state"] == "removed"; - let pending = self.busy.as_deref() == Some("project-sync") - || (same_delivery && matches!(receipt["state"].as_str(), Some("pending" | "uploading"))); - let upload_error = same_delivery.then(|| receipt["error"].as_str()).flatten() - .or_else(|| self.error.strip_prefix("素材库提交失败:")); - let (library_label, library_tone) = if withdrawn { - ("已撤回", Neutral) - } else if material.is_some() { - ("已建档", Neutral) - } else if upload_error.is_some() { - ("提交失败", Error) - } else if pending { - ("正在提交", Neutral) - } else if manifest["allOutputsCompleted"] == true { - ("待入库", Neutral) - } else { - ("待补齐成品", Neutral) - }; - let (listing_label, listing_tone) = match (material.is_some() && !withdrawn, listing["state"].as_str()) { - (false, _) => ("未触发", Neutral), - (true, Some("pending")) => ("等待上架", Neutral), - (true, Some("listing")) => ("上架中", Neutral), - (true, Some("listed")) => ("已上架", Neutral), - (true, Some("failed")) => ("上架失败", Error), - (true, _) => ("待查询", Neutral), - }; - let now = Instant::now(); - let mut refresh = material.is_some() && !withdrawn && doc.is_some_and(|doc| - self.listing_read_at.is_none_or(|(last_doc, next)| last_doc != doc || now >= next)); - let mut submit = false; - let mut open_listing = false; - let mut jump = None; - kit::status_label(ui, &format!("素材库 · {library_label}"), library_tone); - kit::status_label(ui, &format!("外部自动上架 · {listing_label}"), listing_tone); - if upload_error.is_some() || listing_tone == Error || self.listing_read_error.is_some() || self.finished_web_error.is_some() { - kit::disclosure(ui, ui.scope_id().with("delivery-details"), "查看提交与上架详情", false, self.reduce_motion, |ui| { - for error in [upload_error, self.listing_read_error.as_deref(), self.finished_web_error.as_deref(), - (listing_tone == Error).then(|| listing["message"].as_str()).flatten()].into_iter().flatten() { - super::operation_error::details(ui, ui.next_auto_id(), error, self.reduce_motion, None); - } - if self.listing_read_error.is_some() && kit::action_button(ui, "重新查询", Quiet, doc.is_some()).clicked() { - refresh = true; - } - if listing_tone == Error && kit::action_button(ui, "打开上架工作台", Quiet, !self.finished_web_pending).clicked() { - open_listing = true; - } - }); - } - if material.is_none() && manifest["allOutputsCompleted"] == true && !pending { - let ready = doc.is_some() && self.busy.is_none() && self.saving.is_none() - && !self.project_operation_pending() && !self.creation_dirty && !self.unknown; - let label = if upload_error.is_some() { "重试入库" } else { "提交素材库" }; - submit = kit::action_button(ui, label, Quiet, ready).clicked(); - } - - if let Some(hints) = manifest["reviewHints"].as_array().filter(|hints| !hints.is_empty()) { - kit::disclosure(ui, ui.scope_id().with("delivery-review"), &format!("人工核对({})", hints.len()), false, self.reduce_motion, |ui| { - for hint in hints { - let Some(message) = hint.as_str().or_else(|| hint["message"].as_str()) else { continue }; - ui.label(crate::client_brand::user_error(message, "有一项成品需要人工核对")); - let output = hint["outputId"].as_str().or_else(|| { - [("详情页:", "detail"), ("主图:", "main_images"), ("SKU 图:", "sku_images"), ("SKU:", "sku_images")] - .into_iter().find_map(|(prefix, output)| message.starts_with(prefix).then_some(output)) - }); - let Some(output) = output else { continue }; - let exact = hint["slotId"].is_string() || !hint["layerId"].is_null() || hint["nativeLayerId"].is_u64() - || !hint["screenId"].is_null() || !hint["pageId"].is_null() || hint["screenIndex"].is_u64(); - let label = if exact { "定位到画布" } else { "查看成品" }; - if kit::action_button(ui, label, Quiet, doc.is_some()).clicked() { - jump = Some((output.to_owned(), hint.clone())); - } - } - }); - } - - if refresh && let Some(doc) = doc { - self.listing_read_at = Some((doc, now + Duration::from_secs(15))); - if self.tx.send(Request::Action("delivery-status".into(), json!({"doc":doc}))).is_err() { - self.listing_read_error = Some("本机服务已停止,请重启后查看".into()); - } - } - if material.is_some() && !withdrawn { - ui.ctx().request_repaint_after(Duration::from_secs(15)); - } - if open_listing && let Some((doc, material)) = doc.zip(material) { - self.finished_web_error = None; - self.finished_web_pending = self.tx.send(Request::Action("finished-web-open".into(), - json!({"doc":doc,"materialId":material}))).is_ok(); - if !self.finished_web_pending { - self.finished_web_error = Some("本机服务已停止,请重启后重试".into()); - } - } - if submit { - self.sync_action(app, "project-sync", json!({"status":"completed","deliveryId":manifest["deliveryId"]})); - } - if let Some((output, hint)) = jump { - self.locate_delivery_hint(app, ui, &output, hint); - } - } - - fn locate_delivery_hint(&mut self, app: &PhotocraftApp, ui: &Ui, output: &str, hint: Value) { - let target = json!({"outputId":output,"variantId":hint["variantId"]}); - if let Err(error) = self.slot_action(app, "slot-skeleton", target) { - self.error = error; - return; - } - ui.data_mut(|data| data.insert_temp(self.delivery_hint_id(), (output.to_owned(), hint))); - self.show_center(CenterView::Canvas, app.session.active().is_some()); - self.creation_open = false; - ui.ctx().request_repaint(); - } - - fn delivery_hint_id(&self) -> Id { - Id::unique(("delivery-review-locate", &self.origin, self.account["id"].as_str(), self.owner_doc)) - } - - fn finish_delivery_hint(&mut self, app: &PhotocraftApp, ui: &Ui) { - if self.product_view_pending() || self.busy.as_deref() == Some("slot-skeleton") { - return; - } - let Some((output, hint)) = ui.data_mut(|data| data.remove_temp::<(String, Value)>(self.delivery_hint_id())) else { return }; - let workflow = &self.template_workflow; - if workflow["outputId"] != output || hint["variantId"].is_string() && hint["variantId"] != workflow["variantId"] { - self.error = "未能打开这条提示对应的成品".into(); - return; - } - let variant = workflow["variantId"].as_str(); - let native_id = hint["nativeLayerId"].as_u64().or(hint["layerId"].as_u64()) - .or_else(|| hint["layerId"].as_str().and_then(|id| id.strip_prefix('L').unwrap_or(id).parse().ok())) - .filter(|&id| app.session.active().is_some_and(|state| state.doc.layer(photocraft_doc::LayerId(id)).is_some())); - let pages = || workflow["outputs"].as_array().into_iter().flatten().filter(|page| page["outputId"] == output); - let page = hint["pageId"].as_str().or(hint["screenId"].as_str()) - .or_else(|| hint["screenIndex"].as_u64().and_then(|index| pages().nth(index as usize)?["documentId"].as_str())); - let slot = workflow["slots"].as_array().into_iter().flatten() - .filter(|slot| slot["outputId"] == output && (slot["variantId"].is_null() || slot["variantId"].as_str() == variant)) - .find(|slot| match hint["slotId"].as_str() { - Some(id) => slot["id"] == id, - None => page.is_some_and(|page| slot["documentId"] == page), - }) - .and_then(|slot| slot["id"].as_str()); - if native_id.is_some() || slot.is_some() { - self.canvas_locate(json!({"kind":"selection","outputId":output,"productVariantId":variant, - "targets":[{"nativeLayerId":native_id,"slotId":slot,"locateImageSlot":page.is_none() && native_id.is_none()}]})); - ui.ctx().request_repaint(); - } else if ["slotId", "layerId", "nativeLayerId", "pageId", "screenId", "screenIndex"] - .iter().any(|key| !hint[*key].is_null()) - { - self.error = "当前成品中已找不到该核对位置".into(); - } - } - - fn workflow_card_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - let receipt_id = Id::unique(("workflow-approved", &self.origin, self.account["id"].as_str(), self.project_context["localId"].as_str(), self.owner_doc)); - let receipt = ui.data(|data| data.get_temp::<(Value, usize)>(receipt_id)); - let proposal = match self.workflow.proposal().cloned() { Some(proposal) => proposal, None => match &receipt { Some((proposal, _)) => proposal.clone(), None => return } }; - let resolved = receipt.as_ref().filter(|(previous, _)| previous == &proposal).map(|(_, chosen)| *chosen); - let intent = proposal["intent"].as_str().unwrap_or(""); - let label = match intent { - "analyze" => "开始分析", - "selling_points" => "生成一批", - "plan" => "生成方案", - "review_plan" => "查看方案", - "install_template" => "载入模板", - "slot_copy" => "生成文案", - "apply_copy" => "回填文案", - "generate_candidate" => "生成此候选", - "review_candidates" => "查看候选", - "fill_output" => "回填画布", - "export" => "导出…", - "export_psd" => "导出 PSD…", - _ => return, - }; - let running = self.busy.is_some() || self.pi_run.is_some() || self.saving.is_some() || !self.queue.is_empty() || self.pending_image.is_some(); - let current = workflow_bridge::proposal_current(self, app); - let unknown = - self.unknown && matches!(intent, "analyze" | "selling_points" | "plan" | "install_template" | "slot_copy" | "apply_copy" | "generate_candidate"); - let ready = !running && current && !unknown; - self.panel_geometry["workflowReady"] = json!(ready); - let scope = workflow_scope(&proposal, &self.template_workflow); - ui.add_space(10.0); - let state = if let Some(choice) = resolved { timeline::ApprovalState::Decided(choice) } - else if unknown { timeline::ApprovalState::Blocked("结果待核查") } - else if !current { timeline::ApprovalState::Blocked("内容已更新") } - else { timeline::ApprovalState::Awaiting }; - let card = timeline::approval_card(ui, receipt_id.with(proposal.to_string()), timeline::ApprovalCard { - title: proposal["title"].as_str().unwrap_or(label), scope: (!scope.is_empty()).then_some(scope.as_str()), - instruction: proposal["instruction"].as_str().filter(|s| !s.trim().is_empty()), - action: label, opt_out: "暂不处理", state, - }, ready, self.reduce_motion); - if resolved.is_none() { - if ready && ui.clip_rect().contains_rect(card.action.rect) { - self.panel_geometry["workflowAccept"] = rect_value(card.action.rect); - } - if card.action.clicked() { - match self.accept_workflow(app) { - Ok(_) => { ui.data_mut(|data| data.insert_temp(receipt_id, (proposal.clone(), 0_usize))); } - Err(error) => self.error = error, - } - } - if let Some(response) = card.opt_out { - if ui.clip_rect().contains_rect(response.rect) { self.panel_geometry["workflowDismiss"] = rect_value(response.rect); } - if response.clicked() { - self.workflow_dismiss(); - ui.data_mut(|data| data.insert_temp(receipt_id, (proposal, 1_usize))); - } - } - } - if running { - ui.horizontal(|ui| { - super::stitch_ui::ai_loader(ui, ui.scope_id().with("workflow-saving"), true, self.reduce_motion); - if self.saving.is_some() { ui.label("正在保存…"); } - }); - } - self.panel_geometry["workflowCard"] = rect_value(card.rect); - if !running && self.workflow.take_card_reveal() { - ui.scroll_to_rect_animation(card.rect, Some(Align::BOTTOM), egui::style::ScrollAnimation::none()); - } - } - - fn user_reveal_id(&self,index:Option)->Id { - Id::unique(("user-text-arrival",&self.origin,self.account["id"].as_str(),self.project_context["localId"].as_str(),self.observed_doc,index)) - } - fn reveal_sent_user_text(&self,ui:&Ui,after:usize) { - if self.reduce_motion {return;} - let now=ui.input(|input|input.time); - for (index,_) in self.messages.iter().enumerate().skip(after).filter(|(_,message)|message["role"]=="user") { - ui.data_mut(|data|data.insert_temp(self.user_reveal_id(Some(index)),now)); - } - } - fn sent_references(&self, ui: &mut Ui, message: &Value) -> Option { - let references = message["requestScope"]["references"].as_array().filter(|items| !items.is_empty())?; - let mut locate = None; - let available = ui.available_width().max(1.0); - let width = available.min(120.0); - let spacing = ui.spacing().item_spacing.x; - let columns = (((available + spacing) / (width + spacing)).floor() as usize).max(1); - let caption_color = Tokens::get(ui.ctx()).agent().text_dim; - for (row, items) in references.chunks(columns).enumerate() { - ui.allocate_ui_with_layout(vec2(available, 1.0), Layout::right_to_left(Align::Min), |ui| { - for (column, reference) in items.iter().enumerate().rev() { - let index = row * columns + column; - let detail = &message["referenceContent"][index]; - ui.allocate_ui_with_layout(vec2(width, 1.0), Layout::top_down(Align::Max), |ui| { - ui.set_width(width); - let label = reference["label"].as_str().filter(|label| !label.is_empty()) - .map(str::to_owned).unwrap_or_else(|| subject_label(reference, &self.template_workflow)); - let image_size = vec2(width, 110.0); - let image_area = Rect::from_min_size(ui.max_rect().min, image_size); - if let Some(id) = detail["imageId"].as_str().or_else(|| reference["taskId"].as_str()) { - if ui.is_rect_visible(image_area) { - self.agent_images.mark_visible(id); - } - // Keep the transcript height independent of the scroll clip. - if let Some(image) = self.agent_images.peek(id) { - let rect = paint_reference_thumbnail(ui, image, image_size); - let preview = ui.interact(rect, ui.scope_id().with(("sent-reference-image", index)), Sense::click()) - .on_hover_text(label.as_str()); - if preview.clicked() { locate = activate_reference(ui, reference, Some(id)); } - } - } - let caption = ui.add(egui::Label::new(RichText::new(label).size(12.0).color(caption_color)) - .truncate().sense(Sense::click())); - if caption.clicked() { locate = activate_reference(ui, reference, detail["imageId"].as_str()); } - if let Some(text) = detail["text"].as_str().filter(|text| !text.is_empty()) { - ui.add(egui::Label::new(RichText::new(text.chars().take(96).collect::()).size(12.0)).wrap()); - } - }); - } - }); - } - locate - } - - fn turn_ui(&self, ui: &mut Ui, turn: Turn<'_>, conversation_id: Id, count: usize, current_turn: bool, tracing: bool, doc: Option<&super::Document>) -> Option { - let t = Tokens::get(ui.ctx()).agent(); - let batch_progress = self.batch_progress_visible(); - let product = production_turn(turn.user) - || (current_turn && self.pi_product_production); - let live_reply = if self.pi_product_production { - self.stream_reply.as_str() - } else if batch_progress && self.workflow.production_progress().is_object() { - "" - } else if batch_progress { - self.stream_reply.splitn(3, '\n').nth(2).unwrap_or("") - } else { - self.stream_reply.as_str() - }; - let stream = current_turn.then_some(live_reply).filter(|text| !text.is_empty()); - let turn_running = current_turn && self.pending() && !self.agent_effects_paused - && (self.pi_run.is_some() || matches!(self.busy.as_deref(), Some("agent" | "pi-agent"))); - let projected = if current_turn && batch_progress { self.projected_worker_jobs() } else { Vec::new() }; - let merged_images = matches!(turn.items.last(), Some(TurnItem::Images(..))); - let last_position = turn.items.len().saturating_sub(1); - let mut locate = None; - let mut flow = super::agent_stream::Flow::default(); - if let Some(text) = turn.user { - let enter = agent_motion::message_enter(ui, conversation_id, turn.user_index.unwrap_or(usize::MAX), count, self.reduce_motion); - let reveal_id = self.user_reveal_id(turn.user_index); - let now = ui.input(|input| input.time); - let started = if self.reduce_motion {ui.data_mut(|data|data.remove::(reveal_id));None} else { - ui.data_mut(|data| { - if enter < 1.0 { data.get_temp_mut_or_insert_with(reveal_id, || now); } - data.get_temp::(reveal_id) - }) - }; - let response = agent_motion::message_visual(ui, enter, |ui| { - if let Some(index) = turn.user_index { - if let Some(reference) = self.sent_references(ui, &self.messages[index]) { - locate = Some(reference); - } - } - user_bubble_with_reveal(ui, text, started, self.reduce_motion); - if turn.user_index.is_some_and(|index| self.messages[index]["kind"] == "steer" && self.messages[index]["delivered"] == true) { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.label(RichText::new("已插话").size(11.0).color(t.text_dim)); - }); - } - }); - agent_motion::message_repaint(ui, response.response.rect, enter); - ui.add_space(18.0); - } - if !turn.items.is_empty() || stream.is_some() { - if let Some(target) = turn.target.filter(|target| target["kind"] != "project") { - let label = subject_label(target, &self.template_workflow); - let row = timeline::target_row(ui, conversation_id.with(("turn-target", turn.user_index)), &label, self.reduce_motion); - if row.clicked() { locate = Some(target.clone()); } - } - let reply_id = turn_reply_id(conversation_id, turn.user_index); - let latest_reply = turn.items.iter().rev().find_map(|item| match item { - TurnItem::Reply(_, index) => Some(*index), - _ => None, - }); - let tail_reply = match turn.items.last() { - Some(TurnItem::Reply(text, index)) => Some((*text, *index)), - _ => None, - }; - let stream_is_persisted = stream.is_some_and(|stream| tail_reply.is_some_and(|(text, _)| - text == stream || text.starts_with(stream) || (!turn_running && final_handoff(ui, reply_id, text).is_some()))); - let stream_extends_receipt = !stream_is_persisted && stream.is_some_and(|stream| - tail_reply.is_some_and(|(text, _)| !text.is_empty() && stream.starts_with(text))); - let paint_stream = |ui: &mut Ui, text: &str| { - remember_visible_stream(ui, reply_id, text); - ui.push_id(reply_id, |ui| { - let display = product.then(|| production_reply_text(text, turn_running, &self.template_workflow)); - timeline::reply(ui, reply_id, timeline::Reply { text: display.as_deref().unwrap_or(text), streaming: turn_running, animate_final: false }, self.reduce_motion); - }); - ui.add_space(8.0); - }; - let layouts_id = reply_id.with("turn-item-layouts"); - let virtualized = current_turn && turn.items.len() >= 32; - #[cfg(test)] - let virtualized = virtualized && !ui.data(|data| - data.get_temp::(Id::unique("benchmark-full-transcript")).unwrap_or(false)); - let mut layouts = TurnItemLayouts::default(); - let now = ui.input(|input| input.time); - if virtualized { - layouts = ui.data_mut(|data| data.remove_temp(layouts_id)).unwrap_or_default(); - #[cfg(test)] - { - let reset_on_append = ui.data(|data| - data.get_temp::(Id::unique("benchmark-reset-on-append")).unwrap_or(false)); - if reset_on_append && layouts.benchmark_count != count { - layouts.items.clear(); - } - layouts.benchmark_count = count; - } - let key = Some((ui.available_width().to_bits(), ui.pixels_per_point().to_bits(), - Tokens::get(ui.ctx()).kind, self.reduce_motion, turn_running)); - if layouts.key.is_some_and(|(_, _, _, _, running)| running) && !turn_running { - layouts.disclose_until = now + super::stitch_ui::TOOL_DISCLOSURE_SETTLE_SECONDS; - } - if layouts.key != key { - layouts.key = key; - layouts.items.clear(); - } - layouts.items.resize(count, None); - } - let viewport = ui.clip_rect().expand2(vec2(0.0, 240.0)); - let focused_rect = virtualized.then(|| { - ui.memory(|memory| memory.focused()).and_then(|id| ui.ctx().read_response(id)).map(|r| r.rect) - }).flatten(); - - for (position, item) in turn.items.into_iter().enumerate() { - let use_layout = virtualized && position != last_position; - let item_index = item.message_index(); - let mut cached = if use_layout { layouts.items[item_index].take() } else { None }; - let origin = ui.next_widget_position().to_vec2(); - let mut texture_sizes = Vec::new(); - if use_layout { - let live = match &item { - TurnItem::Thinking(value, _) => turn_running && value["active"] == true, - TurnItem::Tools(rows) => now < layouts.disclose_until || turn_running && rows.iter().any(|(event, _)| - ToolStatus::parse(event["status"].as_str().unwrap_or("")).running()), - TurnItem::Images(_, images) => { - let mut live = false; - for image in images { - let id = image["taskId"].as_str().or_else(|| image["id"].as_str()).unwrap_or(""); - texture_sizes.push(self.agent_images.peek(id).map(egui::TextureHandle::size)); - live |= turn_running && image["kind"] == "image-job" && image["finished"].is_null() - && self.pi_run.as_deref().is_some_and(|run| image["run"] == run); - live |= self.canvas_workspace.preview_arrival(id).is_some_and(|started| - agent_motion::image_enter(now - started, 1.0, self.reduce_motion).0 < 1.0); - } - live - } - TurnItem::Reply(_, index) => latest_reply == Some(*index) && stream.is_some() - || agent_motion::message_enter(ui, conversation_id, *index, count, self.reduce_motion) < 1.0, - _ => false, - }; - cached = cached.filter(|layout| - layout.texture_sizes == texture_sizes && layout.content.matches(&item, &self.messages)); - if !live && !tracing - && let Some(layout) = &cached - && layout.settled_at <= now - { - let bounds = layout.bounds.translate(origin); - if !bounds.intersects(viewport) && !ui.rect_contains_pointer(bounds) - && focused_rect.is_none_or(|focus| !bounds.intersects(focus)) - { - ui.expand_to_include_rect(bounds); - ui.add_space(layout.advance); - ui.skip_ahead_auto_ids(1); - flow.restore_anchor(layout.rail.map(|rail| rail.translate(origin))); - layouts.items[item_index] = cached; - continue; - } - } - } - // Each cached item owns stable widget IDs even when earlier - // items are replaced by their layout. - let content = use_layout.then(|| { - let previous = cached.take(); - let settled = previous.as_ref().map(|layout| (layout.advance, layout.settled_at)); - let content = previous.map_or_else(|| TurnItemContent::capture(&item, &self.messages), |layout| layout.content); - (content, settled) - }); - let mut item_ui = use_layout.then(|| ui.new_child(egui::UiBuilder::new().id_salt(("turn-item", item_index)))); - { - let ui = item_ui.as_mut().unwrap_or(&mut *ui); - match item { - TurnItem::Thinking(thinking, _) => { - let row = thinking_ui(ui, thinking, turn_running, self.reduce_motion); - flow.connect(ui, row.rect); - } - TurnItem::Notice(text, _) => { - let text = activity_history_label(text); - let display = crate::client_brand::user_error( - &production_reply_text(text, false, &self.template_workflow), "本轮操作有一条更新"); - let row = timeline::notice_row(ui, ui.next_auto_id().with("notice"), timeline::Notice { - kind: notice_kind(text), text: &display, hint: None, - }, self.reduce_motion); - flow.connect(ui, row.rect); - } - TurnItem::Tools(tasks) => { - let Some((_, first)) = tasks.first() else { continue }; - let id = conversation_id.with(("public-reasoning", first)); - let elapsed: Vec<_> = tasks.iter().map(|(event, _)| { - let status = ToolStatus::parse(event["status"].as_str().unwrap_or("")); - status.timed().then(|| usage_count(&event["durationMs"]).map(duration_text)).flatten() - }).collect(); - let rows: Vec<_> = tasks.iter().zip(&elapsed).map(|((event, _), elapsed)| { - let tool = event["toolName"].as_str().unwrap_or(""); - let status = ToolStatus::parse(event["status"].as_str().unwrap_or("")); - timeline::ToolRow { tool, name: super::stitch_state::tool_label(tool), - status: if status == ToolStatus::Started && !turn_running { ToolStatus::Unknown } else { status }, - elapsed: elapsed.as_deref(), summary:event["summary"].as_str(), - failure_category:event["failureCategory"].as_str(), - failure_detail:event["failureDetail"]["message"].as_str(), - copy_updates: super::pi_bridge::copy_updates(event) } - }).collect(); - let row = timeline::tool_group(ui, id, timeline::ToolGroupHead { - total: rows.len(), - completed: rows.iter().filter(|row| row.status == ToolStatus::Completed).count(), - failed: rows.iter().filter(|row| row.status == ToolStatus::Failed).count(), - active: turn_running && rows.iter().any(|row| row.status.running()), - turn_running, - }, &rows, self.reduce_motion); - flow.connect(ui, row.rect); - ui.add_space(8.0); - } - TurnItem::Reply(text, index) => { - flow.break_run(); - let is_last_reply = tail_reply.is_some_and(|(_, last)| index == last); - if is_last_reply && stream_extends_receipt && let Some(text) = stream { - paint_stream(ui, text); - continue; - } - let handoff = (current_turn && latest_reply == Some(index)) - .then(|| final_handoff(ui, reply_id, text)).flatten(); - let arrival = agent_motion::message_enter(ui, conversation_id, index, count, self.reduce_motion); - let anchor = reply_id.with(index); - let clean = production_reply_text(text, false, &self.template_workflow); - let text = clean.as_str(); - let copy_id = anchor.with("copy"); - // The copy action keeps its row but shows only while the - // reply is pointed at or the button itself holds focus. - let previous = ui.data(|data| data.get_temp::(copy_id.with("shown"))); - let (reply_rect, copy_focused) = ui.data(|data| ( - data.get_temp::(copy_id.with("reply-rect")), - data.get_temp::(copy_id.with("focus")).unwrap_or(false), - )); - let shown = copy_focused || reply_rect.is_some_and(|rect| ui.rect_contains_pointer(rect)); - if previous != Some(shown) { - ui.ctx().request_repaint(); - ui.data_mut(|data| data.insert_temp(copy_id.with("shown"), shown)); - } - let response = ui.push_id(anchor, |ui| { - if let Some(handoff) = handoff - && super::stitch_ui::move_response_arrival(ui, reply_id, anchor) - && handoff == ReplyHandoff::Displayed - { - super::stitch_ui::prepare_final_handoff(ui, anchor, text); - } - timeline::reply(ui, anchor, timeline::Reply { text, streaming: false, animate_final: arrival < 1.0 }, self.reduce_motion); - ui.allocate_ui_with_layout(vec2(ui.available_width(), 24.0), Layout::right_to_left(Align::Center), |ui| { - ui.set_opacity(if shown { 1.0 } else { 0.0 }); - let focused = copy_reply(ui, text).has_focus(); - ui.data_mut(|data| data.insert_temp(copy_id.with("focus"), focused)); - }); - }); - ui.data_mut(|data| data.insert_temp(copy_id.with("reply-rect"), response.response.rect)); - ui.add_space(8.0); - } - TurnItem::Images(first, images) => { - let images = images.into_iter().chain(projected.iter().filter(|_| position == last_position)).collect::>(); - if let Some(target) = self.timeline_images(ui, conversation_id.with(("image-results", first)), &images, &mut flow, doc) { - locate = Some(target); - } - } - TurnItem::Choice(index) => { - flow.break_run(); - let action = match self.messages.get(index).and_then(|message| message["kind"].as_str()) { - Some("pi-ui-request") => self.pi_ui_render(ui, index), - kind => timeline::interaction_card(ui, timeline::InteractionCard { title: None, note: None }, |ui| { - if kind == Some("copywriting-fields") { self.copy_fields_ui(ui, index) } - else { self.copy_options_ui(ui, index) } - }).inner, - }; - if let Some(action) = action { locate = Some(action); } - ui.add_space(8.0); - } - } - } - if let (Some(child), Some((content, previous))) = (item_ui, content) { - let bounds = child.min_rect().translate(-origin); - let advance = child.next_widget_position().y - origin.y; - let rail = flow.anchor().map(|anchor| anchor.translate(-origin)); - let settled_at = previous.filter(|(height, _)| *height == advance) - .map_or(now + 0.25, |(_, settled_at)| settled_at); - ui.expand_to_include_rect(child.min_rect()); - ui.add_space(advance); - layouts.items[item_index] = Some(TurnItemLayout { content, bounds, advance, rail, settled_at, texture_sizes }); - } - } - if virtualized { - ui.data_mut(|data| data.insert_temp(layouts_id, layouts)); - } - if let Some(text) = stream.filter(|_| !stream_is_persisted && !stream_extends_receipt) { - flow.break_run(); - paint_stream(ui, text); - } - if stream.is_some() && self.unknown && !batch_progress { - ui.label(RichText::new("输出未完成").small().color(t.warning)); - } - } - if !projected.is_empty() && !merged_images { - let images: Vec<_> = projected.iter().collect(); - self.timeline_images(ui, conversation_id.with(("worker-jobs", turn.user_index)), &images, &mut flow, doc); - } - locate - } - - fn timeline_images(&self, ui: &mut Ui, id: Id, images: &[&Value], flow: &mut super::agent_stream::Flow, doc: Option<&super::Document>) -> Option { - let heading = if images.iter().any(|image| image["kind"] == "template-image") { "图片来源" } else { "生成图片" }; - let count = images.len().to_string(); - ui.add_space(2.0); - let (row, results) = timeline::image_set(ui, id, timeline::ImageSet::conversation(heading, Some(&count), images.len()), - self.reduce_motion, |ui, index, width| self.image_result(ui, images[index], width, doc)); - flow.connect(ui, row.rect); - flow.break_run(); - results.into_iter().flatten().last() - } - - fn image_result(&self, ui: &mut Ui, value: &Value, cell_width: f32, doc: Option<&super::Document>) -> Option { - let t = Tokens::get(ui.ctx()).agent(); - let id = value["taskId"].as_str().or_else(|| value["id"].as_str()).filter(|id| !id.is_empty())?; - let now = ui.input(|input| input.time); - let enter = self.canvas_workspace.preview_arrival(id).map_or(1.0, |started| agent_motion::image_enter(now - started, 1.0, self.reduce_motion).0); - let mut locate = None; - let target = image_location(value, id); - let original = value["kind"] == "template-image" || value["original"] == true; - let (page_label, short_label, label) = if original { - let field = self.template_workflow["outputs"].as_array().into_iter().flatten() - .filter(|output| value["outputId"].is_null() || output["outputId"] == value["outputId"]) - .flat_map(|output| output["fields"].as_array().into_iter().flatten()) - .find(|field| field["kind"] == "image" && field["fieldId"] == value["fieldId"]) - .and_then(|field| field["label"].as_str()) - .or_else(|| value["fieldId"].as_str()).unwrap_or(""); - let label = if field.is_empty() { "模板原图".into() } else { format!("{field} · 模板原图") }; - (String::new(), "模板原图".into(), label) - } else if value["slotId"].is_null() && value["candidateId"].is_null() - && let Some(label) = value["label"].as_str().filter(|label| !label.is_empty()) - { - (String::new(), label.to_owned(), label.to_owned()) - } else { - image_result_labels(&target, &self.template_workflow, &self.creation_brief) - }; - let ratio_id = ui.scope_id().with(("result-image-ratio", id)); - let ratio = ui.data_mut(|data| { - if let Some(texture) = self.agent_images.peek(id) { - let size = texture.size_vec2(); - data.insert_temp(ratio_id, size.x / size.y.max(1.0)); - } - data.get_temp::(ratio_id).or_else(|| frame_image_ratio(value)).unwrap_or(1.0) - }); - let size = image_card_size(cell_width, ratio); - if value["kind"] == "image-job" { - let active = !self.agent_effects_paused && value["finished"].is_null() - && (value["projected"] == true || self.pi_run.as_deref().is_some_and(|run| value["run"] == run)); - let text = value["slotLabel"].as_str().unwrap_or("").to_owned(); - if !active { - // A queued slot keeps its cell and its place in order; it grows - // into the image card only once its own generation starts. - super::agent_stream::queued_job(ui, cell_width, &text, value["finished"].as_str().unwrap_or("等待结果")); - return None; - } - let step = value["step"].as_str().unwrap_or("正在生成图片…"); - let (rect, response) = ui.allocate_ui_with_layout( - vec2(cell_width, size.y), Layout::centered_and_justified(egui::Direction::TopDown), - |ui| ui.allocate_exact_size(size, Sense::empty()), - ).inner; - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{text} · {step}"))); - if ui.is_rect_visible(rect) { - let id = ui.scope_id().with(("timeline-image-job", id)); - let painter = ui.painter_at(rect); - painter.rect_filled(rect, t.radius_sm, t.canvas); - painter.rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); - let background = ui.painter().add(egui::Shape::Noop); - super::glow_pill::background(ui, id, rect, t.radius_sm, 0.56, background); - painter.text(rect.center(), Align2::CENTER_CENTER, step, FontId::proportional(super::agent_stream::TEXT_TITLE), t.text); - paint_image_caption(&painter, rect, &text); - } - return None; - } - let slot = self.template_workflow["slots"].as_array().into_iter().flatten().find(|slot| - target["slotId"].is_string() && slot["id"] == target["slotId"] && slot["outputId"] == target["outputId"] - && slot["variantId"] == target["productVariantId"]); - let candidate = slot.and_then(|slot| slot["candidates"].as_array()?.iter() - .find(|candidate| candidate["id"] == target["candidateId"])); - let live = doc.zip(target["slotId"].as_str().zip(target["productVariantId"].as_str())) - .filter(|(doc, _)| target["documentId"].as_u64().is_none_or(|id| doc.id.0 == id) - && self.canvas_workspace.output == target["outputId"] && self.canvas_workspace.variant == target["productVariantId"]); - let adopted = live.and_then(|(doc, (slot, variant))| super::canvas_workspace::adopted(doc, slot, variant)); - let manual = live.is_some_and(|(doc, (slot, variant))| super::canvas_workspace::manual_image(doc, slot, variant).is_some()); - let is_adopted = adopted.is_some() && adopted == target["candidateId"].as_str(); - let show_adopt = live.is_some() && !is_adopted && candidate.is_some_and(|candidate| candidate["status"] == "complete") - && self.can_start_turn() && self.saving.is_none(); - ui.push_id(id, |ui| ui.vertical(|ui| { - ui.set_width(cell_width); - ui.allocate_ui_with_layout(vec2(cell_width, size.y), Layout::centered_and_justified(egui::Direction::TopDown), |ui| { - if let Some(texture) = self.agent_images.peek(id) { - let (rect, response) = ui.allocate_exact_size(size, Sense::click()); - // Blur and fade in place: geometry, the rounded mask, the hit - // target and selection outline all remain at the final crop. - // The parent UI clip still bounds the image when scrolling. - if ui.is_rect_visible(rect) { - self.agent_images.mark_visible_existing(id); - let _ = self.agent_images.get(id); - if enter < 1.0 { - ui.painter().add(agent_motion::rounded_image_entry_blur(texture.id(), rect, enter, t.radius_sm)); - } else { - egui::Image::new(texture).fit_to_exact_size(rect.size()).corner_radius(t.radius_sm).paint_at(ui, rect); - } - } - agent_motion::message_repaint(ui, rect, enter); - let selected = !original && self.canvas_workspace.context.as_ref().is_some_and(|current| current["candidateId"] == target["candidateId"]); - if selected { - agent_motion::role_light(ui, agent_motion::Surface::new(response.id.with("selection-light"), rect.expand(1.0), t.radius_sm), self.reduce_motion, agent_motion::LightRole::CanvasTarget); - } else if response.hovered() { - ui.painter().rect_stroke(rect.expand(1.0), t.radius_sm, Stroke::new(1.0, t.text_dim), egui::StrokeKind::Outside); - } - let slot_label = slot.and_then(|slot| slot["label"].as_str()).or_else(|| value["slotLabel"].as_str()).unwrap_or(""); - let caption = [slot_label, page_label.as_str(), short_label.as_str()].into_iter() - .filter(|part| !part.is_empty()).collect::>().join(" · "); - paint_image_caption(&ui.painter_at(rect), rect, &caption); - let review = &self.workflow.production_progress()["candidateReviews"][id]; - let decision = candidate.and_then(|candidate| candidate["reviewDecision"].as_str()) - .or_else(|| value["reviewDecision"].as_str()).or_else(|| review["status"].as_str()); - let badge = if is_adopted { Some(("已采纳", t.agent_semantic().success)) } - else if manual { Some(("图位已手动编辑", t.text_faint)) } - else { match decision { - Some("passed" | "pass") => Some(("验图通过", t.agent_semantic().success)), - Some("not_selected") => Some(("未选用", t.text_faint)), - Some("rejected" | "revise" | "missing") => Some(("已退回", t.danger)), - Some("pending") => Some(("待核查", t.warning)), - _ if !original && target["slotId"].is_string() => Some(("待采纳", t.warning)), - _ => None, - }}; - if let Some((status, color)) = badge && rect.width() >= 112.0 && rect.height() >= 52.0 { - let painter = ui.painter_at(rect); - let font = crate::theme::agent_scale::Type::Meta.font_id(); - let text = painter.layout_no_wrap(status.to_owned(), font, Color32::WHITE); - let tag = Rect::from_min_size(rect.left_top() + vec2(8.0, 8.0), vec2(text.size().x + 21.0, 22.0)); - painter.rect_filled(tag, 6.0, Color32::from_black_alpha(188)); - painter.circle_filled(egui::pos2(tag.left() + 8.0, tag.center().y), 3.0, color); - painter.galley(egui::pos2(tag.left() + 15.0, tag.center().y - text.size().y * 0.5), text, Color32::WHITE); - } - let expand = (rect.width() >= 42.0 && rect.height() >= 42.0).then(|| image_preview_button(ui, rect, id)); - let response = response.on_hover_text(format!("{label} · 右键引用到小壹或查看大图")); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("定位 {label}"))); - if response.clicked() && !expand.is_some_and(|button| button.clicked()) { - if original { - ui.data_mut(|data| data.insert_temp(Id::unique("jiansun-image-expanded"), id.to_owned())); - } else { - locate = Some(image_location(value, id)); - } - } - self.image_reference_menu(ui, &response, value, id, &label, original, show_adopt); - } else { - let placeholder = if original { "模板原图加载中" } else { "定位图片" }; - let (rect, response) = ui.allocate_exact_size(size, Sense::click()); - let response = response.on_hover_cursor(egui::CursorIcon::PointingHand) - .on_hover_text(format!("{label} · 右键引用到小壹或查看大图")); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, placeholder)); - if ui.is_rect_visible(rect) { - ui.painter().rect_filled(rect, t.radius_sm, if response.hovered() { t.hover } else { t.field }); - let icon_size = rect.width().min(rect.height()).min(16.0); - crate::icons::paint(ui, Rect::from_center_size(rect.center(), vec2(icon_size, icon_size)), "image", icon_size, t.text_dim); - if response.has_focus() { - ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.text_dim), egui::StrokeKind::Inside); - } - } - if ui.is_rect_visible(response.rect) && matches!(value["status"].as_str(), None | Some("complete")) { - self.agent_images.mark_visible(id); - } - self.image_reference_menu(ui, &response, value, id, &label, original, show_adopt); - if response.clicked() && !original { - locate = Some(image_location(value, id)); - } - } - }); - })); - locate - } - - fn image_reference_menu(&self, ui: &mut Ui, response: &Response, value: &Value, id: &str, label: &str, original: bool, show_adopt: bool) { - egui::Popup::context_menu(response).frame(super::stitch_ui::menu_frame(ui.ctx())).show(|ui| { - super::stitch_ui::scope_with_motion(ui, self.reduce_motion, |ui| { - // menu_item fills its available width; constrain the - // popup rather than letting it inherit the whole canvas. - let width = 176.0_f32.min((ui.ctx().content_rect().width() - 32.0).max(1.0)); - ui.set_min_width(width); - ui.set_max_width(width); - ui.spacing_mut().item_spacing.y = 2.0; - if show_adopt && super::stitch_ui::menu_item(ui, "采纳", true).clicked() { - ui.data_mut(|data| data.insert_temp(Id::unique("xiaoyi-adopt-candidate"), image_location(value, id))); - ui.close(); - } - if super::stitch_ui::menu_item(ui, "引用到小壹", true).clicked() { - let target = image_reference_target(value, id, label, original); - ui.data_mut(|data| data.insert_temp(Id::unique("xiaoyi-image-reference"), target)); - ui.close(); - } - let preview = super::stitch_ui::menu_item(ui, "查看大图", true); - if preview.clicked() { - ui.data_mut(|d| d.insert_temp(Id::unique("jiansun-image-expanded"), id.to_owned())); - ui.close(); - } - }); - }); - } - - pub(super) fn artifact_window(&self, ui: &mut Ui) { - let id = Id::unique("jiansun-image-expanded"); - let snapshot_id = id.with("exit-snapshot"); - let transition_id = id.with("transition"); - let scope = json!([self.origin, self.account["id"], self.project_context["localId"], self.owner_doc]).to_string(); - let selected = ui.data(|d| d.get_temp::(id)); - let mut snapshot = ui.data(|d| d.get_temp::(snapshot_id)); - if snapshot.as_ref().is_some_and(|old| old.scope != scope) { - ui.data_mut(|d| { d.remove::(snapshot_id); d.remove::(id); }); - super::stitch_ui::overlay_transition(ui.ctx(), transition_id, false, true); - return; - } - if let Some(selected) = selected.as_ref() { - self.agent_images.mark_visible(selected); - if let Some(texture) = self.agent_images.get(selected) { - let view = snapshot.as_ref().filter(|old| old.key == *selected).map(|old| old.view.clone()).unwrap_or_default(); - let current = ArtifactPreviewSnapshot { scope, key: selected.clone(), texture: texture.clone(), view }; - ui.data_mut(|d| d.insert_temp(snapshot_id, current.clone())); - snapshot = Some(current); - } else if snapshot.is_none() { - if ui.input(|input| input.key_pressed(egui::Key::Escape)) { - ui.data_mut(|data| data.remove::(id)); - } - super::stitch_ui::overlay_transition(ui.ctx(), transition_id, false, true); - return; - } - } - let visual = super::stitch_ui::overlay_transition(ui.ctx(), transition_id, selected.is_some(), self.reduce_motion); - if !visual.render { - ui.data_mut(|d| d.remove::(snapshot_id)); - return; - } - if let Some(saved) = snapshot.as_mut() { - self.agent_images.mark_visible_existing(&saved.key); - let texture = &saved.texture; - let screen = ui.ctx().content_rect(); - let image = texture.size_vec2(); - let available = (screen.size() - vec2(104.0, 112.0)).max(Vec2::splat(1.0)); - let viewport = image * ArtifactPreviewView::default().scale(available, image, ui.ctx().pixels_per_point()); - let (previous, next) = preview_neighbors(&self.template_workflow, &saved.key); - let loading = selected.as_ref().is_some_and(|key| *key != saved.key); - let mut close = false; - let mut switch = None; - let modal = egui::Modal::new(id.with("lightbox")) - .frame(egui::Frame::NONE) - .backdrop_color(Color32::from_black_alpha((208.0 * visual.opacity) as u8)) - .show(ui.ctx(), |ui| { - let size = vec2((viewport.x + 80.0).max(260.0), viewport.y + 84.0); - let (body, _) = ui.allocate_exact_size(size, Sense::hover()); - super::stitch_ui::overlay_contents(ui, visual, |ui| { - let photo = Rect::from_center_size(egui::pos2(body.center().x, body.top() + 36.0 + viewport.y / 2.0), viewport); - artifact_preview_contents(ui, texture, &mut saved.view, photo); - let close_rect = Rect::from_min_size(body.right_top() - vec2(28.0, 0.0), Vec2::splat(28.0)); - close = preview_icon_at(ui, close_rect, "close", "x", "关闭预览").clicked(); - for (key, x, icon, label, shortcut) in [ - (previous, photo.left() - 24.0, "chevron-left", "上一张", egui::Key::ArrowLeft), - (next, photo.right() + 24.0, "chevron-right", "下一张", egui::Key::ArrowRight), - ] { - if let Some(key) = key { - let rect = Rect::from_center_size(egui::pos2(x, photo.center().y), Vec2::splat(28.0)); - if preview_icon_at(ui, rect, icon, icon, label).clicked() - || (ui.is_enabled() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, shortcut))) { - switch = Some(key); - } - } - } - let width = if loading { 274.0 } else { 252.0 }; - let bar = Rect::from_center_size(egui::pos2(photo.center().x, photo.bottom() + 29.0), vec2(width, 38.0)); - let mut controls = ui.new_child(egui::UiBuilder::new().id_salt("zoom-bar").max_rect(bar) - .layout(Layout::top_down(egui::Align::Min))); - artifact_preview_zoom_bar(&mut controls, texture, &mut saved.view, viewport, loading, self.reduce_motion); - }); - }); - ui.data_mut(|d| d.insert_temp(snapshot_id, saved.clone())); - if visual.interactive && (close || modal.should_close()) { - ui.data_mut(|d| d.remove::(id)); - ui.ctx().request_repaint(); - } else if let Some(key) = switch { - ui.data_mut(|d| d.insert_temp(id, key.to_owned())); - ui.ctx().request_repaint(); - } - } - } - - /// What the canvas holds for the suggestion row: selected text, and a - /// selected object. - fn suggestion_scope(&self, app: &PhotocraftApp) -> (bool, bool) { - let has_text = app - .session - .active() - .is_some_and(|s| s.selected_layers().iter().any(|id| matches!(s.doc.layer(*id).map(|l| &l.content), Some(LayerContent::Text(_))))); - let selected = self.canvas_workspace.context.as_ref().is_some_and(|context| context["kind"] != "project"); - (has_text, selected) - } - - /// Suggestions follow what the canvas holds: selected text, a selected - /// object, or nothing. Choosing one only fills the composer. - fn suggestion_prompts(&self, has_text: bool, selected: bool) -> [(&'static str, &'static str); 2] { - let suggestions = if has_text { - [("精简文案", "请精简当前选中的文字,保留原有事实和语气。"), ("检查排版", "请检查当前文字的层级和间距,先讨论调整建议。")] - } else if selected { - let compare = self.canvas_workspace.context.as_ref().is_some_and(|subject| has_comparable_candidates(&self.template_workflow, subject)); - [ - ("讨论选中对象", "请结合当前选中的对象讨论可以改进的地方,先不要自动生成或替换。"), - if compare { - ("比较候选", "请比较当前图位的已有候选,说明各自特点,不自动采纳。") - } else { - ("讨论调整方向", "请结合选中对象和项目资料,先讨论可以调整的方向。") - }, - ] - } else { - [ - ("梳理资料", "请读取当前项目资料,梳理已有事实和需要补充的内容。"), - ("讨论页面", "请结合项目模板和产品资料,和我讨论页面的重点与安排。"), - ] - }; - suggestions - } - - fn suggestion_row(&mut self, app: &PhotocraftApp, ui: &mut Ui, key: &str, suggestions: [(&'static str, &'static str); 2], resume_production: Option, size: super::agent_stream::SuggestionSize, wrap: bool) { - use super::agent_stream::{SUGGESTION_CHIP_HEIGHT, SUGGESTION_GAP, suggestion_chip}; - let mut rects = Vec::new(); - let draft_ready = self.composer_draft_ready(app); - let layout = egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(wrap); - ui.allocate_ui_with_layout(vec2(ui.available_width(), SUGGESTION_CHIP_HEIGHT), layout, |ui| { - ui.spacing_mut().item_spacing = vec2(SUGGESTION_GAP, SUGGESTION_GAP); - if let Some(enabled) = resume_production { - let hint = "按图位完成剩余图片,保留已采纳结果和现有图层"; - let response = suggestion_chip(ui, "sparkles", CONTINUE_PRODUCTION, enabled, self.reduce_motion, size) - .on_hover_text(hint).on_disabled_hover_text(hint); - rects.push(json!({"label":CONTINUE_PRODUCTION,"rect":rect_value(response.rect)})); - if response.clicked() { - self.resume_product_production(app); - ui.ctx().request_repaint(); - } - } - let items = suggestions.map(|(label, _)| ("sparkles", label)); - let responses = timeline::suggestion_row(ui, &items, draft_ready, self.reduce_motion, size); - for ((label, prompt), response) in suggestions.into_iter().zip(responses) { - let response = response.on_hover_text(prompt); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, response.enabled(), format!("填入输入框:{label}"))); - rects.push(json!({"label":label,"rect":rect_value(response.rect)})); - if response.clicked() { - self.fill_prompt(prompt); - ui.ctx().request_repaint(); - } - } - }); - // Leave space between the shortcuts and the input surface. - ui.add_space(6.0); - self.panel_geometry[key] = json!(rects); - } - - /// Nothing has been said yet: a few lines say what 小壹 does here and - /// where to start. They name only what this client's tools can do. - fn empty_conversation_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - let t = Tokens::get(ui.ctx()).agent(); - let document_open = app.session.active().is_some(); - ui.add_space(24.0); - ui.add(egui::Label::new(RichText::new("小壹可以帮你").size(14.0).strong().color(t.text))); - ui.add_space(6.0); - for line in ["为图位生成候选图,采纳后放进画布", "写详情页文案,并核对卖点依据", "整套制作详情、主图和 SKU"] { - ui.horizontal_top(|ui| { - ui.add_space(1.0); - ui.add(egui::Label::new(RichText::new("·").size(12.0).color(t.text_faint))); - ui.add(egui::Label::new(RichText::new(line).size(12.0).color(t.text_dim)).wrap()); - }); - } - ui.add_space(8.0); - let start = if document_open { "在下面的输入框里写下需求,或点一条建议开始。" } else { "打开一个项目后,在下面的输入框里写下需求。" }; - ui.add(egui::Label::new(RichText::new(start).size(12.0).color(t.text_faint)).wrap()); - if !document_open && super::stitch_ui::action_button(ui, "我的项目", super::stitch_ui::ButtonRole::Secondary, true).clicked() { - self.show_center(CenterView::Projects, false); - } - } - - /// Follow-ups close a settled reply. They name the next step from the - /// reply's own receipt and never send anything by themselves. - fn followup_prompts(&self, production: bool) -> Option<[(&'static str, &'static str); 2]> { - if !conversation_settled(self, production) { return None; } - let index = self.messages.iter().rposition(|message| message["text"].as_str().is_some_and(|text| !text.is_empty()))?; - if turns(&self.messages).last().and_then(|turn| turn.last_reply.map(|(_, last)| last)) != Some(index) { return None; } - let summary = &self.messages[index]["productionSummary"]; - Some(if summary.is_object() { - if summary["exported"] == summary["total"] { - [("验收整套", "请检查本轮详情、主图和 SKU 的导出结果,逐项指出需要调整的地方。"), - ("核对卖点和配图", "请核对整页的卖点与配图是否对应,列出证据不足的地方。")] - } else { - [("查看未完成项", "请梳理这轮未完成的文案、图位和输出,说明每项卡在哪里。"), - ("核对已有结果", "请检查目前已保留的文案和配图,指出需要调整的地方。")] - } - } else { - [("展开下一步", "请把上一条建议展开为具体的下一步和验收标准。"), - ("核对依据", "请结合当前项目资料,核对上一条回复中的判断和依据。")] - }) - } - - fn fill_prompt(&mut self, prompt: &str) { - insert_suggestion(&mut self.composer, prompt); - self.canvas_workspace.composer_edited(); - self.image_mode = "chat".into(); - self.focus_composer = true; - self.draft_changed = true; - self.touched = Instant::now(); - } - - pub(super) fn pending(&self) -> bool { - matches!( - self.busy.as_deref(), - Some( - "agent" - | "agent-stopping" - | "pi-agent" - | "recover" - | "image" - | "image-recover" - | "image-use" - | "slot-generate" - | "slot-append" - | "slot-recover" - | "slot-copy" - ) - ) || self.pi_run.is_some() - || self.canvas_workspace.adoption_preparing() - || !self.queue.is_empty() - || self.pending_image.is_some() - || (self.workflow_waiting.is_some() && self.busy.is_some()) - } - - fn result_needs_check(&self) -> bool { - // A dispatched request is protected from replay while it is still - // running. That protection is not a terminal unknown-result message. - self.unknown && !self.pending() && self.product_production.is_none() && !self.product_start_queued - } - - fn batch_progress_visible(&self) -> bool { - !self.agent_effects_paused && (self.product_start_queued || self.product_production.is_some() - || self.pi_product_production && self.pending()) - } - - fn production_workers(&self) -> Vec> { - let progress = self.workflow.production_progress(); - let jobs = self.pi_run.as_deref().map_or_else(Vec::new, |run| self.workflow.worker_generations(run)); - let mut used = std::collections::HashSet::new(); - let rows = progress["workers"].as_array().into_iter().flatten().map(|row| (row, false)) - .chain(progress["reviews"].as_array().into_iter().flatten().map(|row| (row, true))); - let rows: Vec<_> = rows.filter(|(row, review)| row["active"] == true || (!review && row["step"] != "已交验图")).collect(); - let reserved: std::collections::HashSet<_> = rows.iter().filter_map(|(row, _)| row["number"].as_u64().filter(|n| *n > 0)).collect(); - let mut next = (1_u64..).filter(|n| !reserved.contains(n)); - rows.into_iter().map(|(row, review)| { - let number = row["number"].as_u64().filter(|n| *n > 0 && used.insert(*n)) - .unwrap_or_else(|| next.next().unwrap()); - let active = row["active"] == true; - let job = (!review && active && row["slotId"].is_string()).then(|| jobs.iter().rev().find(|job| - job["slotId"] == row["slotId"] && job["phase"] == "submitted" - && (row["number"].is_null() || job["workerNumber"] == row["number"]))).flatten(); - let image_step = job.and_then(|job| job["imageStep"].as_str()); - let step = image_step.or_else(|| row["step"].as_str()).unwrap_or(""); - let stage = WorkerStage::infer(step, review, image_step.is_some()); - ProductionWorker { - row, number, active, stage, step: step.to_owned(), review, - slot: row["label"].as_str().unwrap_or("").to_owned(), - frame: job.map(|job| job["imageFrame"].clone()).unwrap_or_default(), - } - }).collect() - } - - fn projected_worker_jobs(&self) -> Vec { - if self.product_start_queued || self.product_production.as_ref().is_some_and(|run| !run.showing_agent_progress()) { - return Vec::new(); - } - let progress = self.workflow.production_progress(); - let current = self.messages.iter().rposition(|row| row["role"] == "user").map_or(&self.messages[..], |i| &self.messages[i..]); - self.production_workers().into_iter().filter_map(|worker| { - if !worker.active || worker.stage != WorkerStage::Generating { return None; } - let slot_id = &worker.row["slotId"]; - if current.iter().any(|image| image["kind"] == "image-job" && image["finished"].is_null() - && self.pi_run.as_deref().is_some_and(|run| image["run"] == run) - && if slot_id.is_string() && image["target"]["slotId"].is_string() { - image["target"]["slotId"] == *slot_id - && (worker.row["number"].is_null() || image["workerNumber"].is_null() || image["workerNumber"] == worker.row["number"]) - && (image["target"]["outputId"].is_null() || progress["outputId"].is_null() || image["target"]["outputId"] == progress["outputId"]) - && (image["target"]["productVariantId"].is_null() || progress["variantId"].is_null() - || image["target"]["productVariantId"] == progress["variantId"]) - } else { - image["workerNumber"] == worker.number - }) { return None; } - let frame = [Some(&worker.frame), Some(worker.row), worker.row.get("imageFrame"), - self.template_workflow["slots"].as_array().into_iter().flatten().find(|slot| - slot["id"] == *slot_id && (progress["outputId"].is_null() || slot["outputId"] == progress["outputId"]) - && (progress["variantId"].is_null() || slot["variantId"].is_null() || slot["variantId"] == progress["variantId"])) - .map(|slot| &slot["frame"])] - .into_iter().flatten().find(|frame| frame_image_ratio(frame).is_some()); - Some(json!({ - "kind":"image-job", "taskId":format!("worker-preview-{}", worker.number), "projected":true, - "workerNumber":worker.number, "slotLabel":worker.slot, - "width":frame.map(|frame| &frame["width"]), "height":frame.map(|frame| &frame["height"]), - })) - }).collect() - } - - fn production_head_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui) { - use super::agent_stream::Cell; - use timeline::{GoalBudget, GoalSlot, GoalStage, StagePhase, WorkerState}; - - let id = Id::unique(("jiansun-production-head", &self.origin, self.account["id"].as_str(), self.owner_doc)); - let run = self.product_production.as_ref(); - let preparing = self.product_start_queued.then(|| super::template_preparation::state(&self.template_progress)); - let waiting = run.is_some_and(|run| run.waiting_to_resume()) || self.template_progress["phase"] == "waiting" && preparing.is_some(); - let use_stream = preparing.is_none() && run.is_none_or(|run| run.showing_agent_progress()); - let progress = self.workflow.production_progress(); - let title = use_stream.then(|| progress["heading"].as_str().or_else(|| self.stream_reply.lines().next())).flatten() - .filter(|line| !line.is_empty()).map(str::to_owned) - .or_else(|| preparing.as_ref().map(|(label, _)| label.clone())) - .or_else(|| run.and_then(|run| run.progress_label())) - .unwrap_or_else(|| "正在准备详情页".into()); - let title = title.trim_start_matches("小壹").trim_start_matches([' ', '·']); - let show_work = use_stream || run.is_some_and(|run| run.waiting_for_originals()); - let source = |key: &str| progress[key].as_array().filter(|_| show_work).map(Vec::as_slice).unwrap_or_default(); - let image_source = source("pictureCells"); - let copy_source = source("copyCells"); - let cells_of = |rows: &[Value]| rows.iter().map(|cell| match cell["state"].as_str() { - Some("verified") => Cell::Verified, - Some("filled") => Cell::Filled, - Some("preview") => Cell::Preview, - _ => Cell::Empty, - }).collect::>(); - let mut image_cells = cells_of(image_source); - production_image_cells(app, self, progress, &mut image_cells); - let copy_cells = cells_of(copy_source); - let workers = if show_work { self.production_workers() } else { Vec::new() }; - let worker_states: Vec<_> = workers.iter().map(|worker| WorkerState { - number: worker.number, stage: worker.stage, slot: &worker.slot, active: worker.active, - }).collect(); - let filled = image_cells.iter().filter(|cell| cell.filled()).count(); - let current_counts = (if image_cells.is_empty() { progress["rendered"].as_u64().unwrap_or(0) as usize } else { filled }, - if image_cells.is_empty() { progress["total"].as_u64().unwrap_or(0) as usize } else { image_cells.len() }); - let fraction = preparing.as_ref().and_then(|(_, fraction)| *fraction).or_else(|| - (show_work && current_counts.1 > 0).then(|| current_counts.0 as f32 / current_counts.1 as f32)); - let working = run.and_then(|run| run.working_output()); - let current = working.as_ref().and_then(|row| row["outputId"].as_str()) - .or_else(|| show_work.then(|| progress["outputId"].as_str()).flatten()) - .or_else(|| (preparing.is_some() || self.pi_product_production && fraction.is_some()).then_some("detail")); - let requested = run.map(|run| run.requested_outputs()); - let pending = run.map(|run| run.pending_outputs()); - let contains = |value: &Option, output: &str| value.as_ref().and_then(Value::as_array) - .is_some_and(|rows| rows.iter().any(|row| row["outputId"] == output)); - let outputs = [("detail", "详情"), ("main_images", "主图"), ("sku_images", "SKU")]; - let pipeline: Vec<_> = outputs.iter().filter(|(output, _)| requested.is_none() || contains(&requested, output)) - .map(|(output, name)| (*name, if current == Some(*output) { StagePhase::Current(fraction.unwrap_or(0.0)) } - else if contains(&requested, output) && !contains(&pending, output) { StagePhase::Done } - else { StagePhase::Queued })).collect(); - let slots = || image_source.iter().zip(&image_cells).map(|(row, cell)| GoalSlot { - label: row["label"].as_str().unwrap_or("图位"), - state: match workers.iter().find(|worker| worker.active && worker.row["slotId"] == row["slotId"]).map(|worker| worker.stage) { - Some(WorkerStage::Generating) => timeline::SlotState::Generating, - Some(WorkerStage::Reviewing) => timeline::SlotState::Reviewing, - _ if row["state"] == "failed" => timeline::SlotState::Failed, - _ if cell.filled() => timeline::SlotState::Done, - _ => timeline::SlotState::Queued, - }, - }).collect(); - let stages: Vec<_> = outputs.iter().filter(|(_, name)| pipeline.iter().any(|(shown, _)| shown == name)) - .map(|(output, name)| { - let selected = current == Some(*output); - let (done, total, unit) = if selected && show_work { (current_counts.0, current_counts.1, "图位") } - else { (usize::from(pipeline.contains(&(*name, StagePhase::Done))), 1, "份") }; - GoalStage { name, done, total, unit, elapsed: None, tokens: None, - waiting_canvas: self.workflow.waiting_canvas(output), - slots: if selected && show_work { slots() } else { Vec::new() } } - }).collect(); - let head = super::production_controls::HeadControls::read(&self.production_control_state()); - let resume_ready = self.can_resume_product(); - let budget = if let Some(run) = run { - GoalBudget::Time { elapsed: run.elapsed(), limit: None } - } else if let Some(used) = usage_count(&progress["tokensUsed"]) { - GoalBudget::Tokens { used, limit: usage_count(&progress["tokenBudget"]) } - } else { - GoalBudget::Unreported - }; - let clock_paused = run.is_some_and(|run| run.clock_paused()); - let mut controls = head.view(resume_ready); - if clock_paused && matches!(controls.stop, timeline::StopPhase::Idle | timeline::StopPhase::Delivered) { - controls.stop = timeline::StopPhase::Paused; - } - let state = if clock_paused { RunState::WaitingResume } - else if self.pi_ui_waiting() { RunState::WaitingUser } - else if waiting { RunState::WaitingResume } else { RunState::Running }; - ui.add_space(10.0); - let full = ui.available_rect_before_wrap(); - let inner = Rect::from_min_max(full.left_top() + vec2(16.0, 0.0), full.right_bottom() - vec2(16.0, 0.0)); - let mut column = ui.new_child(egui::UiBuilder::new().id_salt(id).max_rect(inner).layout(Layout::top_down(Align::Min))); - column.spacing_mut().item_spacing.y = 4.0; - let result = timeline::goal_progress_panel(&mut column, id, GoalProgressPanel { - title, state, budget, pipeline: &pipeline, image_cells: &image_cells, copy_cells: ©_cells, - workers: &worker_states, roadmap: Some(&stages), controls: run.is_some().then_some(controls), - }, self.reduce_motion || self.product_view_detached(), |index| { - let row = &image_source[index]; - let status = match image_cells[index] { Cell::Verified => "已核验", Cell::Filled => "已上画布", Cell::Preview => "有候选待采纳", Cell::Empty => "待填" }; - format!("图片 {} · {} · {status}", index + 1, row["label"].as_str().unwrap_or("图位")) - }); - if let GoalBudget::Time { elapsed, .. } = budget - && !clock_paused - && !agent_motion::hidden(ui, result.rect) - { - // 首分钟显示秒,之后只在分钟数变化时刷新。 - let seconds = elapsed.as_secs(); - let next = if seconds < 60 { 1 } else { 60 - seconds % 60 }; - ui.ctx().request_repaint_after(Duration::from_secs(next)); - } - let worker_geometry = result.workers.into_iter().map(|mut row| { - if let Some(worker) = workers.iter().find(|worker| row["worker"] == worker.number) { - row["step"] = json!(worker.step); - row["review"] = json!(worker.review); - } - row - }).collect::>(); - let located = result.slot_clicked.and_then(|index| image_source.get(index)).filter(|row| row["slotId"].is_string()) - .map(|row| json!({"kind":"slot","slotId":row["slotId"],"outputId":progress["outputId"],"productVariantId":progress["variantId"]})); - self.panel_geometry["productionProgressTag"] = rect_value(result.toggle.rect); - self.panel_geometry["productionTitle"] = rect_value(result.title); - self.panel_geometry["productionProgress"] = rect_value(result.rect); - self.panel_geometry["productionShelf"] = rect_value(result.rect); - self.panel_geometry["productionProgressRail"] = result.rail.map_or(Value::Null, rect_value); - self.panel_geometry["productionImageCells"] = result.image_cells; - self.panel_geometry["productionCopyCells"] = result.copy_cells; - self.panel_geometry["productionWorkers"] = json!(worker_geometry); - if let Some(target) = located { self.canvas_locate(target); } - if let Some(stop) = result.stop { - self.panel_geometry["taskStop"] = rect_value(stop.rect); - if stop.clicked() { self.abort_chat_run(); } - } - if let Some(controls) = &result.controls { - use timeline::StopMode; - // "停止"沿用外部脚本已在读的 taskStop,点开是停止菜单;"只暂停"直接执行,另外两项先确认。 - let choice = |mode| controls.choices.iter().find(|(shown, _)| *shown == mode).map_or(Value::Null, |(_, rect)| rect_value(*rect)); - self.panel_geometry["taskStop"] = rect_value(controls.stop.rect); - self.panel_geometry["productionResume"] = controls.resume.as_ref().map_or(Value::Null, |resume| rect_value(resume.rect)); - self.panel_geometry["productionStopPause"] = choice(StopMode::Pause); - self.panel_geometry["productionStopEnd"] = choice(StopMode::End); - self.panel_geometry["productionStopDeliver"] = choice(StopMode::Deliver); - self.panel_geometry["productionStopStatus"] = controls.status.map_or(Value::Null, rect_value); - self.panel_geometry["productionBudget"] = controls.budget.map_or(Value::Null, rect_value); - if controls.resume.as_ref().is_some_and(Response::clicked) { - self.resume_product_production(app); - } - match controls.chosen { - Some(StopMode::Pause) => super::production_controls::queue_action(ui.ctx(), "production-stop", - super::production_controls::stop_input(StopMode::Pause)), - Some(mode) => super::production_controls::open_stop_confirm(ui.ctx(), mode), - None => {} - } - } - self.stop_confirm_ui(ui, head.phase().ready()); - ui.advance_cursor_after_rect(column.min_rect()); - ui.add_space(2.0); - } - - pub(super) fn production_assets(&self) -> impl Iterator { - let mut seen = std::collections::HashSet::new(); - self.messages.iter().filter(move |message| - matches!(message["kind"].as_str(), Some("image" | "template-image")) - && message["taskId"].as_str().is_some_and(|task| seen.insert(task))) - } - - fn open_generated_folder(&mut self, doc: u64) { - let action = json!({"doc":doc,"accountId":self.account["id"],"origin":self.origin}); - let result = self.tx.send(Request::Action("open-generated-folder".into(), action)); - self.canvas_workspace.generated_folder_status = Some((doc, if result.is_ok() { - "正在查找本地生成图…".into() - } else { - "本机服务暂不可用,请稍后再试。".into() - })); - } - - pub(super) fn production_assets_ui(&mut self, ui: &mut Ui, doc: u64) { - if super::stitch_ui::action_button(ui, "打开本地文件夹", super::stitch_ui::ButtonRole::Quiet, true).clicked() { - self.open_generated_folder(doc); - } - if let Some((id, message)) = &self.canvas_workspace.generated_folder_status - && *id == doc - { - super::stitch_ui::status_label(ui, message, super::stitch_ui::StatusTone::Neutral); - } - let mut locate = None; - egui::ScrollArea::vertical().id_salt("returned-assets").show(ui, |ui| { - let width = ui.available_width(); - let columns = ((width + 8.0) / 128.0).floor().max(1.0) as usize; - let cell = ((width + 8.0) / columns as f32 - 8.0).min(144.0); - egui::Grid::new("returned-assets-grid").num_columns(columns) - .min_col_width(cell).max_col_width(cell).spacing(vec2(8.0, 8.0)) - .show(ui, |ui| { - for (index, image) in self.production_assets().enumerate() { - if let Some(target) = self.image_result(ui, image, cell, None) { locate = Some(target); } - if (index + 1) % columns == 0 { ui.end_row(); } - } - }); - }); - if let Some(target) = locate { self.canvas_locate(target); } - } - - fn composer_surface_height(&self, app: &PhotocraftApp, ui: &Ui, width: f32, progress: f32) -> f32 { - let references = reference_shelf_height(self.composer_reference_list(app).len(), (width - 28.0).max(1.0)); - if progress == 0.0 { - return 56.0 + references; - } - let attachment = if self.composer_text_send_allowed_for(app) { 0.0 } else { self.composer_attachments_extra_height() }; - let wrap_width = (width - 32.0).max(1.0); - let layout_key = (wrap_width, ui.pixels_per_point(), Tokens::get(ui.ctx()).kind); - let height_id = ui.scope_id().with("composer-draft-height"); - type DraftHeight = ((f32, f32, crate::theme::ThemeKind), String, f32); - let cached = ui.data_mut(|data| data.remove_temp::>(height_id)).flatten(); - let (key, draft, text_height) = cached - .filter(|(key, draft, _)| *key == layout_key && draft == &self.composer) - .unwrap_or_else(|| (layout_key, self.composer.clone(), - composer_galley(ui, &self.composer, wrap_width).size().y.max(24.0))); - ui.data_mut(|data| data.insert_temp(height_id, Some((key, draft, text_height)))); - let expanded = (text_height + 74.0 + attachment).max(168.0) - .min((ui.ctx().content_rect().height() * 0.5 - references).max(168.0)); - 56.0 + references + (expanded - 56.0) * progress - } - - fn composer_notice_height(&self, ui: &Ui) -> f32 { - let gap = 6.0; - let row = ui.spacing().interact_size.y; - let button = 34.0_f32.max(row); - let mut height = 0.0; - if self.pi_review && self.busy.is_none() { height += button + 16.0 + gap; } - if self.result_needs_check() || (!self.pending() && self.ready_image.is_some()) { height += button + 16.0 + gap; } - if !self.error.is_empty() && self.error != self.library_message { height += super::operation_error::inline_height(ui,&self.error,(ui.available_width()-20.0).max(1.0)) + gap; } - if !self.needs_library_login() && !self.library_blocked() && !self.key_saved { height += button + gap; } - height + self.steering_queue_height() - } - - fn steering_queue_height(&self) -> f32 { - if self.pi_run.is_none() || self.agent_effects_paused || self.loaded_draft != self.owner_doc { return 0.0; } - let groups = usize::from(!self.pi_queued_steering.is_empty()) + usize::from(!self.pi_queued_followup.is_empty()); - if groups == 0 { 0.0 } else { (groups as f32 * 19.0).max(26.0) + 6.0 } - } - - fn steering_queue_ui(&mut self, ui: &mut Ui) { - let height = self.steering_queue_height(); - if height == 0.0 { return; } - let tint = Tokens::get(ui.ctx()).agent().text_dim; - ui.allocate_ui_with_layout(vec2(ui.available_width(), height - 6.0), Layout::right_to_left(Align::Center), |ui| { - let clear = super::stitch_ui::icon_button(ui, "x", 26.0, false, "清空待发送消息"); - if clear.clicked() { self.clear_steer_queue(); } - ui.vertical(|ui| { - ui.spacing_mut().item_spacing.y = 0.0; - for (title, messages) in [ - ("待插话 · 当前步骤后注入", &self.pi_queued_steering), - ("已排队 · 本轮结束后发送", &self.pi_queued_followup), - ] { - if messages.is_empty() { continue; } - let preview = messages.join(" / ").replace('\n', " "); - ui.add(egui::Label::new(RichText::new(format!("{title} {preview}")).size(12.0).color(tint)).truncate()) - .on_hover_text(format!("{title}\n{}", messages.join("\n"))); - } - }); - }); - } - - fn can_send(&self, app: &PhotocraftApp) -> bool { - self.can_send_with(app, self.image_mode != "chat") - } - - fn can_send_with(&self, app: &PhotocraftApp, image: bool) -> bool { - if !image && self.can_steer(app) { return true; } - if !image && self.has_paused_production() && self.turn_idle() { - return self.can_resume_product() && self.composer_draft_ready(app) - && !self.library_blocked() && !self.composer.trim().is_empty(); - } - let target_ready = !image - || self.template_workflow["canvasFirst"] != true - || (self.template_workflow["capabilities"]["imageDispatchAllowed"] == true - && self.canvas_workspace.context.as_ref().is_some_and(|target| { - target["kind"] != "selection" - && target["productVariantId"] == self.canvas_workspace.variant - && target["slotId"] - .as_str() - .filter(|id| !id.is_empty()) - .is_some_and(|id| self.template_workflow["slots"].as_array().into_iter().flatten().any(|slot| slot["id"] == id)) - })); - !self.professional_child_active(app) && self.composer_draft_ready(app) - && !self.library_blocked() - && (image || self.composer_text_send_allowed_for(app)) - && target_ready - && self.can_start_turn() - && !self.pi_review - && (if image { self.image_ready } else { self.model_ready }) - && !self.composer.trim().is_empty() - } - - fn send_discussion(&mut self, app: &PhotocraftApp) { - if !self.can_steer(app) && !self.has_paused_production() && !self.composer_text_send_allowed_for(app) { - self.error = "当前对话模型暂不支持图片,请先移除附件或使用生图".into(); - return; - } - if self.can_send_with(app, false) { - self.image_mode = "chat".into(); - self.send_composer(app); - } - } - - fn send_image_once(&mut self, app: &PhotocraftApp) { - if self.can_send_with(app, true) { - if self.template_workflow["canvasFirst"] == true { - // The canvas-first workspace owns its immutable candidate - // append and ACK. Never route this to the legacy replacement. - if let Err(error) = self.canvas_generate_selected(app) { - self.error = error; - } - return; - } - // This is an explicit one-shot action. Ordinary Send/Ctrl+Enter - // always discuss through Pi; a previous image action is not a mode - // that can silently turn the next user message into a paid image. - if self.image_mode != "regenerate" { - self.image_mode = "generate".into(); - } - self.send_composer(app); - self.image_mode = "chat".into(); - } - } - - fn send_composer(&mut self, app: &PhotocraftApp) { - if !self.can_send(app) { - return; - } - let text = self.composer.clone(); - if self.image_mode == "chat" { - if self.can_steer(app) { - if self.steer(app, text, "steer") { - self.composer.clear(); - self.draft_changed = true; - } - return; - } - if self.has_paused_production() && self.turn_idle() { - self.resume_product_production_with(app, Some(text)); - if !self.has_paused_production() { - self.composer.clear(); - self.draft_changed = true; - } - return; - } - self.submit(app, text); - } else { - self.generate(app, text, &self.image_mode.clone()); - } - // Preflight errors keep the user's draft available to correct and resubmit deliberately. - if matches!(self.busy.as_deref(), Some("agent" | "pi-agent" | "image")) { - self.composer.clear(); - self.draft_changed = true; - } - } - - fn composer_escape(&mut self, ui: &mut Ui) { - let input_id = super::composer_input_id(); - let ime_composing = ui.data(|data| data.get_temp::<(bool, u64)>(input_id.with("ime-submit-guard"))) - .is_some_and(|(composing, _)| composing) - || ui.input(|input| input.events.iter().any(|event| matches!(event, egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) if !text.is_empty()))); - let owns_focus = ui.memory(|memory| memory.has_focus(input_id) - || (memory.focused().is_none() && memory.had_focus_last_frame(input_id))); - if !self.model_settings && !self.prompt_library.is_open() - && !ime_composing && ui.memory(|memory| memory.top_modal_layer().is_none()) - && owns_focus - && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { - let mut selection = egui::text_edit::TextEditState::load(ui.ctx(), input_id); - let range = selection.as_ref().and_then(|state| state.cursor.char_range()); - if let Some(range) = range.filter(|range| range.primary != range.secondary) { - if let Some(state) = selection.as_mut() { - state.cursor.set_char_range(Some(egui::text::CCursorRange::one(range.primary))); - } - if let Some(state) = selection { state.store(ui.ctx(), input_id); } - } else if self.composer.is_empty() { - self.focus_composer = false; - ui.memory_mut(|memory| memory.surrender_focus(input_id)); - } - if !self.composer.is_empty() { ui.memory_mut(|memory| memory.request_focus(input_id)); } - } - } - - fn composer_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - super::glow_pill::bind(ui, app.gpu_render_state.as_ref()); - let messages_before_send = self.messages.len(); - let mut prompt_anchor = None; - self.composer_reference_sync(app); - if self.notifications_ui(ui) { self.show_center(CenterView::Canvas, app.session.active().is_some()); } - self.composer_escape(ui); - let input_id = super::composer_input_id(); - let t = Tokens::get(ui.ctx()).agent(); - ui.spacing_mut().item_spacing = vec2(6.0, 6.0); - self.panel_geometry["productionProgress"] = Value::Null; - self.panel_geometry["productionProgressRail"] = Value::Null; - self.panel_geometry["productionWorkers"] = Value::Null; - self.panel_geometry["productionShelf"] = Value::Null; - self.panel_geometry["productionWorkersTag"] = Value::Null; - self.panel_geometry["productionProgressTag"] = Value::Null; - self.panel_geometry["productionImageCells"] = Value::Null; - self.panel_geometry["productionCopyCells"] = Value::Null; - self.panel_geometry["productionResume"] = Value::Null; - self.panel_geometry["productionStopPause"] = Value::Null; - self.panel_geometry["productionStopEnd"] = Value::Null; - self.panel_geometry["productionStopDeliver"] = Value::Null; - self.panel_geometry["productionStopStatus"] = Value::Null; - self.panel_geometry["productionBudget"] = Value::Null; - if self.pi_review && self.busy.is_none() { - self.status_row(ui, "info", "原建议未执行", t.warning, |this, ui| { - if super::stitch_ui::action_button(ui, "放弃原建议", super::stitch_ui::ButtonRole::Secondary, true).on_hover_text("保留原响应和已完成的修改;不重新运行模型或工具").clicked() { - this.send("pi-review", json!({"doc":app.session.active().map(|s|s.doc.id.0)})); - } - }); - } - self.panel_geometry["recoverResult"] = Value::Null; - if self.result_needs_check() { - let title = if self.original_image_recoveries().next().is_some() { - if self.original_image_recoveries().all(|(_, id)| { - self.image_recovery_schedules.get(id).is_some_and(|schedule| schedule.exhausted()) - }) { - "原图片暂未取回,已保留请求" - } else { - "图片结果待自动核查" - } - } - else if self.unknown_image { "有一张图片未确认结果" } - else { "有一项操作未确认结果" }; - self.status_row(ui, "info", title, t.warning, |this, ui| { - let action = super::stitch_ui::action_button(ui, "核查结果", super::stitch_ui::ButtonRole::Secondary, this.busy.is_none()) - .on_hover_text("只读取原请求结果,不重新生成"); - this.panel_geometry["recoverResult"] = rect_value(action.rect); - if action.clicked() { this.recover(app); } - }); - } else if !self.pending() && self.ready_image.is_some() { - self.status_row(ui, "image", "图片已就绪", t.text_dim, |this, ui| { - if super::stitch_ui::action_button(ui, "应用到画布", super::stitch_ui::ButtonRole::Primary, this.busy.is_none()).clicked() { - this.use_image(app); - } - }); - } - self.panel_geometry["reconnect"] = Value::Null; - self.error_notice_ui(ui); - self.steering_queue_ui(ui); - self.panel_geometry["send"] = Value::Null; - self.panel_geometry["stop"] = Value::Null; - let shortcut = composer_enter(ui, input_id); - let morph = self.panel_geometry["composerMorph"].as_f64().unwrap_or(1.0) as f32; - let can_stop = self.pending() && !self.batch_progress_visible() && !self.agent_effects_paused; - let compact_stop = can_stop && morph < 0.95; - let surface_height = self.composer_surface_height(app, ui, ui.available_width(), morph); - let (surface_rect, surface_response) = ui.allocate_exact_size(vec2(ui.available_width(), surface_height), Sense::hover()); - let radius = 28.0 - 4.0 * morph; - let material = super::stitch_ui::surface_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Composer); - ui.painter().rect_filled(surface_rect, radius, material.fill); - ui.painter().rect_stroke(surface_rect, radius, material.stroke, egui::StrokeKind::Inside); - let drop_active = self.panel_geometry["composerExpanded"].as_bool().unwrap_or(false); - self.composer_attachment_drop_surface(app, ui, surface_rect, radius, drop_active); - let light = agent_motion::reserve_background(ui); - let send_background = agent_motion::reserve_background(ui); - let mut content = ui.new_child(egui::UiBuilder::new().id_salt("composer-stable-surface") - .max_rect(surface_rect.shrink2(vec2(14.0, 12.0))).layout(Layout::top_down(Align::Min))); - content.set_clip_rect(surface_rect.shrink(2.0).intersect(ui.clip_rect())); - let parent_ui = ui; - let ui = &mut content; - let references = self.composer_reference_list(app); - self.panel_geometry["references"] = json!(references); - let reference_height = reference_shelf_height(references.len(), ui.max_rect().width()); - if reference_height > 0.0 { - let shelf = Rect::from_min_size(ui.max_rect().min, vec2(ui.max_rect().width(), reference_height - 6.0)); - let mut reference_ui = ui.new_child(egui::UiBuilder::new().id_salt("composer-references").max_rect(shelf)); - self.reference_shelf(app, &mut reference_ui, &references, shelf.height()); - } - let header_rect = ui.max_rect().translate(vec2(0.0, reference_height)); - let mut header = ui.new_child(egui::UiBuilder::new().id_salt("composer-header").max_rect(header_rect)); - header.set_opacity(morph * morph); - if morph < 0.95 { header.disable(); } - if morph > 0.001 { - self.composer_attachment_previews(app, &mut header); - } - let header_height = if header.min_rect().height() > 0.0 { header.min_rect().height() + 6.0 } else { 0.0 }; - let stop_space = if compact_stop { 36.0 } else { 0.0 }; - let mini_input = Rect::from_min_size( - egui::pos2(surface_rect.left() + 54.0, surface_rect.top() + reference_height + 17.0), - vec2((surface_rect.width() - 72.0 - stop_space).max(1.0), 24.0), - ); - let full_input = Rect::from_min_max( - egui::pos2(surface_rect.left() + 16.0, surface_rect.top() + 14.0 + reference_height + header_height), - egui::pos2(surface_rect.right() - 16.0, surface_rect.bottom() - 60.0)); - let input_rect = Rect::from_min_max(mini_input.min.lerp(full_input.min, morph), mini_input.max.lerp(full_input.max, morph)); - let typing_owner=Id::unique((&self.origin,self.account["id"].as_str(),self.observed_doc,self.loaded_draft)); - let reduced=self.reduce_motion; - let mut layouter = |ui: &Ui, text: &dyn egui::TextBuffer, wrap_width: f32| { - let mut galley=composer_galley(ui,text.as_str(),wrap_width); - super::typing_text::edit(ui,typing_owner,&mut galley,reduced); - galley - }; - let mut input_ui = ui.new_child(egui::UiBuilder::new().id_salt("composer-input-region").max_rect(input_rect)); - input_ui.set_clip_rect(input_rect.intersect(ui.clip_rect())); - input_ui.spacing_mut().scroll.fade.strength=0.0; - input_ui.visuals_mut().text_cursor.stroke=Stroke::new(1.5,t.text); - let draft_ready = self.composer_draft_ready(app); - if !draft_ready { input_ui.disable(); } - let text_start=ui.ctx().graphics(|graphics|graphics.get(ui.layer_id()).map_or(0,|list|list.next_idx().0)); - let resized=ui.data_mut(|data|{let id=input_id.with("viewport-size");let previous=data.get_temp::(id);data.insert_temp(id,input_rect.size());previous!=Some(input_rect.size())}); - let editor = egui::ScrollArea::vertical().id_salt("agent-input-scroll").animated(false) - .max_height(input_rect.height().max(24.0)).min_scrolled_height(input_rect.height().max(24.0)) - .content_margin(egui::Margin::ZERO).auto_shrink([false, false]) - .show(&mut input_ui, |ui| { - let hint = if !draft_ready { "正在加载项目草稿…" } - else if self.steering_available(app) { "继续补充要求,将在当前步骤后插话…" } - else { "告诉小壹,你想怎么改…" }; - let editor=super::stitch_ui::text_input(&mut self.composer, hint, true) - .layouter(&mut layouter).id(input_id).return_key(egui::KeyboardShortcut::new(egui::Modifiers::SHIFT, egui::Key::Enter)) - .font(FontId::proportional(14.0)).desired_rows(1).desired_width(f32::INFINITY) - .min_size(vec2(0.0, input_rect.height().max(24.0))).margin(egui::Margin::ZERO).frame(Frame::NONE).show(ui); - if resized&&editor.response.response.has_focus()&&let Some(range)=editor.cursor_range { - let caret=editor.galley.pos_from_cursor(range.primary).translate(editor.galley_pos.to_vec2()); - if !ui.clip_rect().contains_rect(caret){ui.scroll_to_rect_animation(caret,None,egui::style::ScrollAnimation::none());} - } - editor - }); - self.panel_geometry["inputScrollOffset"]=json!(editor.state.unclamped_offset().y); - let editor=editor.inner; - self.panel_geometry["inputContentHeight"]=json!(editor.galley.size().y); - if let Some(row)=editor.galley.rows.first(){self.panel_geometry["inputFirstRow"]=rect_value(Rect::from_min_size(editor.galley_pos+vec2(0.0,row.pos.y),vec2(input_rect.width(),row.size.y)));} - if let Some(range) = editor.cursor_range { - self.panel_geometry["inputCaret"] = rect_value(editor.galley.pos_from_cursor(range.primary).translate(editor.galley_pos.to_vec2())); - } - self.panel_geometry["inputHitRect"] = rect_value(editor.response.rect); - let response = editor.response.response.accessible_name("小壹消息输入"); - let text_end = ui.ctx().graphics(|graphics|graphics.get(ui.layer_id()).map_or(text_start, |list| list.next_idx().0)); - // 输入框的逐字柔光画在光涌玻璃上面、文字光标下面(见 `typing_text::paint_glow`)。 - super::typing_text::paint_glow(ui,typing_owner,editor.galley_pos); - let input_focused = response.has_focus(); - self.panel_geometry["input"] = rect_value(input_rect); - if self.focus_composer && draft_ready { response.request_focus(); self.focus_composer = false; } - if response.changed() { - self.canvas_workspace.composer_edited(); self.draft_changed = true; self.touched = Instant::now(); - } - let typing = input_focused && !self.composer.trim().is_empty() && !self.pending(); - let orb_id = Id::unique("composer-identity"); - let orb_progress = super::stitch_ui::morph_value(ui.ctx(), orb_id.with("size"), typing, self.reduce_motion); - let orb_center = egui::pos2(surface_rect.left() + 29.0, surface_rect.center().y + reference_height / 2.0) - .lerp(egui::pos2(surface_rect.left() + 35.0, surface_rect.bottom() - 33.0), morph); - let orb = Rect::from_center_size(orb_center, Vec2::splat(34.0 - 10.0 * morph + 16.0 * orb_progress)); - let typing_animation = typing && super::typing_text::is_animating(ui, typing_owner); - let background_canvas = self.product_view_detached() - || self.owner_doc.is_some_and(|owner| app.session.active().is_none_or(|state| state.doc.id.0 != owner)); - let working = !background_canvas && !self.agent_effects_paused && !self.pi_ui_waiting() - && (self.pending() || self.batch_progress_visible() && !self.has_paused_production()); - let motion = super::siri_orb::Motion::composer(self.reduce_motion, typing_animation, working); - let freeze = self.reduce_motion || background_canvas && !typing_animation; - let animation = super::siri_orb::paint(ui, orb_id, orb, motion, freeze); - self.panel_geometry["composerOrb"] = rect_value(orb); - self.panel_geometry["composerOrbTyping"] = json!(typing); - self.panel_geometry["composerOrbMotion"] = json!(if self.reduce_motion { "reduced" } else { motion.label() }); - self.panel_geometry["composerOrbPhase"] = animation.map_or(Value::Null, |a| json!(a.phase)); - self.panel_geometry["composerOrbSpeed"] = animation.map_or(Value::Null, |a| json!(a.speed)); - let toolbar_rect = Rect::from_min_max(egui::pos2(surface_rect.left() + 14.0, surface_rect.bottom() - 54.0), - egui::pos2(surface_rect.right() - 14.0, surface_rect.bottom() - 12.0)); - let mut toolbar = ui.new_child(egui::UiBuilder::new().id_salt("composer-toolbar").max_rect(toolbar_rect)); - toolbar.set_opacity(((morph - 0.3) / 0.7).clamp(0.0, 1.0)); - if morph < 0.95 { toolbar.disable(); } - let can = self.can_send_with(app, false); - let connect = (self.needs_library_login() || self.library_blocked()) - && draft_ready && self.busy.is_none() && !self.composer.trim().is_empty(); - let mut send_clicked = false; - if morph > 0.3 { - let ui = &mut toolbar; - // One responsive toolbar. Narrow docks retain every action with - // an accessible icon; only labels collapse, never controls. - ui.horizontal(|ui| { - let narrow = ui.available_width() < 260.0; - let ultra = ui.available_width() < if can_stop { 175.0 } else { 145.0 }; - let action_size = if narrow { 24.0 } else { 28.0 }; - ui.spacing_mut().item_spacing.x = if narrow { 1.0 } else { 3.0 }; - ui.spacing_mut().button_padding.x = 4.0; - let right_width = 30.0 - + if can_stop { 30.0 + ui.spacing().item_spacing.x } else { 0.0 } - + if ultra { 0.0 } else { action_size + ui.spacing().item_spacing.x }; - let left_width = (ui.available_width() - right_width - ui.spacing().item_spacing.x).max(1.0); - let mut compact_settings_anchor = None; - ui.allocate_ui_with_layout(vec2(left_width, 42.0), Layout::left_to_right(Align::Center), |ui| { - ui.allocate_exact_size(vec2(if ultra { 34.0 } else { 42.0 }, 42.0), Sense::hover()); - let add = super::stitch_ui::icon_button(ui, "plus", action_size, false, "添加"); - add.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "添加")); - self.panel_geometry["composerMore"] = rect_value(add.rect); - self.panel_geometry["referenceImage"] = Value::Null; - self.panel_geometry["promptLibrary"] = Value::Null; - prompt_anchor = Some(add.rect); - if ultra { compact_settings_anchor = Some(add.clone()); } - egui::Popup::menu(&add).id(Id::unique("jiansun-composer-more-popup")).style(super::stitch_ui::scoped_popup_style(ui)) - .frame(super::stitch_ui::command_menu_frame(ui.ctx())).show(|ui| { - ui.set_width(180.0); - let selected = self.canvas_subject(app)["kind"] != "project" && self.composer_draft_ready(app); - let reference = super::stitch_ui::command_menu_item(ui, "layers", "引用选中画布对象", selected); - self.panel_geometry["referenceAdd"] = rect_value(reference.rect); - if reference.clicked() { - match self.composer_reference_add(app) { Ok(()) => self.focus_composer = true, Err(error) => self.error = error } - ui.close(); - } - self.composer_attachment_menu_item(app, ui); - if super::stitch_ui::command_menu_item(ui, "folder-open", "常用提示词", true).clicked() { - self.close_model_settings(); - self.prompt_library.toggle(&self.account, &self.origin, &self.tx); ui.close(); - } - if ultra { - if super::stitch_ui::command_menu_item(ui, "sparkles", "生图", self.can_send_with(app, true)).clicked() { self.send_image_once(app); ui.close(); } - if super::stitch_ui::command_menu_item(ui, "sliders-horizontal", "连接设置、通知与警告", true).clicked() { - self.open_model_settings(); - ui.close(); - } - } - }); - if !ultra { - let image_action = super::stitch_ui::icon_action_button(ui, "sparkles", "生图", true, action_size, self.can_send_with(app, true)) - .on_hover_text("使用生图模型提交当前要求;普通发送仍是对话"); - self.panel_geometry["imageGenerate"] = rect_value(image_action.rect); - if image_action.clicked() { self.send_image_once(app); } - if left_width >= 120.0 { - let usage = context_for_model(&self.pi_context_usage, &self.models, &self.model); - if usage.as_ref().is_some_and(|value|value["contextWindow"].as_u64().is_some_and(|limit|limit>0)) { - let meter = context_meter(ui, usage.as_ref(), self.reduce_motion, true); - self.panel_geometry["contextIndicator"] = rect_value(meter.rect); - self.panel_geometry["contextPercent"] = context_fraction(usage.as_ref()).map_or(Value::Null,|fraction|json!(fraction*100.0)); - } - } - } - }); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - let response = ui - .add_enabled_ui(can || connect, |ui| super::stitch_ui::send_action_button(ui, Id::unique("composer-send"), self.reduce_motion)) - .inner - .on_hover_text(if connect { "连接素材库后发送" } - else if self.can_steer(app) { "Enter 插话 · Shift+Enter 换行" } - else { "Enter 发送 · Shift+Enter 换行" }) - .on_disabled_hover_text(if self.unknown { "先核查原请求结果" } - else if !self.composer_text_send_allowed_for(app) { "当前对话模型暂不支持图片,请先移除附件或使用生图" } - else { "打开项目、连接模型并输入要求后发送" }); - self.panel_geometry["send"] = rect_value(response.rect); - send_clicked = response.clicked(); - if compact_stop { - ui.allocate_exact_size(vec2(30.0,30.0), Sense::hover()); - } else if can_stop { - let stop = super::stitch_ui::icon_button(ui, "square", 30.0, false, "停止小壹,保留原请求"); - self.panel_geometry["stop"] = rect_value(stop.rect); - if stop.clicked() { self.abort_chat_run(); } - } - if !ultra { - let response = super::stitch_ui::icon_button(ui, "sliders-horizontal", action_size, self.model_settings, "连接设置、通知与警告"); - let unread=notification_id(&self.origin,&self.account,&self.project_context,self.owner_doc) - .and_then(|id|ui.data(|data|data.get_temp::(id))).is_some_and(|history|history.unread>0); - if unread { - let dot=Rect::from_center_size(response.rect.right_top()+vec2(-3.0,3.0),vec2(8.0,8.0)); - super::stitch_ui::paint_badge(ui,response.id.with("unread"),dot,super::stitch_ui::BadgeKind::Unread,"",self.reduce_motion); - } - self.panel_geometry["settings"] = rect_value(response.rect); - if response.clicked() { - if self.model_settings { - self.close_model_settings(); - } else { - self.open_model_settings(); - } - } - self.model_settings_popup(ui, &response); - } - }); - if let Some(anchor) = compact_settings_anchor { self.model_settings_popup(ui, &anchor); } - }); - } - if send_clicked || (shortcut && (can || connect)) { - if connect { self.open_library_login(); } - else { self.send_discussion(app); } - } - // 设置浮层里点的"检查更新"在这里派发:浮层本身拿不到 app。 - self.flush_client_update_request(app); - let compact_stop_rect = Id::unique("jiansun-composer-compact-stop-rect"); - if compact_stop { - let compact_center = egui::pos2(surface_rect.right() - 27.0, mini_input.center().y); - let expanded_center = egui::pos2(toolbar_rect.right() - 48.0, toolbar_rect.center().y); - let rect = Rect::from_center_size(compact_center.lerp(expanded_center,morph),vec2(30.0,30.0)); - let mut control = ui.new_child(egui::UiBuilder::new().id_salt("composer-compact-stop").max_rect(rect)); - let stop = super::stitch_ui::icon_button(&mut control, "square", 30.0, false, "停止小壹,保留原请求"); - self.panel_geometry["stop"] = rect_value(stop.rect); - ui.data_mut(|data| data.insert_temp(compact_stop_rect, stop.rect)); - if stop.clicked() { self.abort_chat_run(); } - } else { - ui.data_mut(|data| data.remove::(compact_stop_rect)); - } - let ui = parent_ui; - let frame = egui::InnerResponse { inner: light, response: surface_response }; - self.panel_geometry["composer"] = rect_value(frame.response.rect); - ui.ctx().data_mut(|data| data.insert_temp(Id::unique("jiansun-composer-previous-rect"), frame.response.rect)); - self.panel_geometry["composerFocused"] = json!(input_focused); - // Only a submission accepted by the native path can launch the pulse. - // Loading history, repainting bubbles and failed preflight never do. - let sent = matches!(self.busy.as_deref(), Some("agent" | "pi-agent" | "image" | "slot-append" | "slot-generate")) - && self.messages.get(messages_before_send..).is_some_and(|messages| - messages.iter().any(|message| message["role"] == "user")); - if sent { - self.reveal_sent_user_text(ui,messages_before_send); - self.flush_document_draft(ui.ctx(), self.observed_doc, false); - } - super::stitch_ui::sent_glow(ui, Id::unique("composer-sent-glow"), super::stitch_ui::SendSurface {rect:frame.response.rect,radius,background:Some(send_background),text_range:Some(text_start..text_end),flanks:morph}, sent, self.reduce_motion); - - if self.prompt_library.show(ui, &self.account, &self.origin, &mut self.composer, &self.tx, - super::prompt_library_ui::PromptPanelPlacement { can_insert:draft_ready, reduced:self.reduce_motion, anchor:prompt_anchor, composer:frame.response.rect }) { - self.canvas_workspace.composer_edited(); - self.draft_changed = true; - self.touched = Instant::now(); - if let Some(id) = toast_id(&self.origin, &self.account, &self.project_context, self.owner_doc) { post_draft_toast(ui, id); } - } - if let Some(id) = toast_id(&self.origin, &self.account, &self.project_context, self.owner_doc) { - draw_draft_toast(ui, id, frame.response.rect, self.reduce_motion); - } - self.panel_geometry["composerLightMode"] = json!(super::stitch_ui::composer_glow_mode(ui,self.reduce_motion)); - if !self.needs_library_login() && !self.library_blocked() && !self.key_saved && super::stitch_ui::action_button(ui, "连接个人模型", super::stitch_ui::ButtonRole::Quiet, true).clicked() { - self.open_model_settings(); - self.key_settings = true; - ui.ctx().request_repaint(); - } - } - - fn error_notice_ui(&mut self,ui:&mut Ui) { - self.panel_geometry["errorNotice"]=Value::Null; - if self.error.is_empty() || self.error==self.library_message {return;} - if self.result_needs_check() && (self.error.contains("素材库请求失败(HTTP 503)") - || self.error.contains("结果未知;不会重发") || self.error.contains("原请求结果待核查")) { return; } - let error=self.error.clone(); - let details=super::operation_error::inline(ui,&error); - self.panel_geometry["errorNotice"]=json!({"title":super::operation_error::public_title(&error),"details":rect_value(details.rect)}); - if details.clicked() - && let Some(id)=notification_id(&self.origin,&self.account,&self.project_context,self.owner_doc) { - ui.ctx().data_mut(|data| { - let history=data.get_temp_mut_or_default::(id); - history.add(&error);history.open=true; - }); - } - } - - fn status_row(&mut self, ui: &mut Ui, name: &str, text: &str, tint: Color32, action: impl FnOnce(&mut Self, &mut Ui)) { - let frame=super::stitch_ui::surface_frame(ui.ctx(),super::stitch_ui::SurfaceRole::Task).stroke(Stroke::NONE).inner_margin(8); - super::stitch_ui::material_frame(ui,frame, |ui| { - ui.horizontal(|ui| { - icon(ui, name, tint); - ui.label(RichText::new(text).size(12.0).color(tint)); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| action(self, ui)); - }); - }); - } - - /// Read-only snapshot of up to 12 most recent notification entries (newest first). - pub(super) fn recent_notification_entries(&self, ctx: &egui::Context) -> Vec { - let Some(id) = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc) else { - return Vec::new(); - }; - ctx.data(|data| data.get_temp::(id)) - .map(|history| history.entries.into_iter().rev().take(12).collect()) - .unwrap_or_default() - } - - #[cfg(test)] - pub(super) fn seed_notifications_for_test(&self, ctx: &egui::Context, entries: &[&str]) { - if let Some(id) = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc) { - let mut history = AgentNotifications::default(); - for entry in entries { - history.add(entry); - } - ctx.data_mut(|data| data.insert_temp(id, history)); - } - } - - fn notifications_ui(&mut self, ui: &mut Ui)->bool { - self.panel_geometry["notificationCandidates"]=Value::Null; - let marker = Id::unique("jiansun-notification-last-scope"); - let current = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc); - let scope = current.unwrap_or_else(|| Id::unique("jiansun-notification-no-account")); - let previous = ui.ctx().data(|data| data.get_temp::(marker)); - let switched = previous.is_some_and(|old| old != scope); - if switched { - ui.ctx().data_mut(|data| { - if let Some(old) = previous { data.get_temp_mut_or_default::(old).open = false; } - if current.is_some() { data.get_temp_mut_or_default::(scope).open = false; } - }); - } - ui.ctx().data_mut(|data| data.insert_temp(marker, scope)); - let Some(id) = current else { return false }; - let mut history = ui.ctx().data(|data| data.get_temp::(id)).unwrap_or_default(); - let unknown = self.result_needs_check(); - if switched { - // Do not attribute an old in-memory error to the newly selected account. - history.last_error = self.error.clone(); history.last_unknown = unknown; - } - let identity_prefix = self.local_identity(""); - let project_id = self.owner_doc.filter(|doc| self.loaded_draft == Some(*doc)) - .and_then(|doc| self.open_projects.get(&doc)) - .and_then(|identity| identity.strip_prefix(&identity_prefix)) - .filter(|project| !project.is_empty()); - let receipts = if project_id.is_some() { self.messages.as_slice() } else { &[] }; - let diagnostics = super::operation_error::DiagnosticContext { - version: &self.client_update.version, - project_id, - messages: receipts, - }; - let warning = self.prompt_library.warning(); - history.observe(&self.error, unknown, warning.as_deref(), receipts); - let visual = super::stitch_ui::overlay_transition(ui.ctx(), id.with("transition"), history.open, self.reduce_motion); - if visual.interactive {history.unread=0;} - let mut view_candidates=false; - if visual.render { - let t = Tokens::get(ui.ctx()).agent(); - let screen = ui.ctx().content_rect(); - let width = (screen.width() - 64.0).clamp(1.0, 360.0); - let list_height = (screen.height() - 200.0).clamp(1.0, 260.0); - let mut bounds = Rect::NOTHING; - let closed = super::stitch_ui::dialog(ui, id.with("window"), "通知与警告", history.open, self.reduce_motion, width, |ui| { - ui.label(RichText::new("本次会话的通知;导出提示也保留在项目对话中。").size(12.0).color(t.text_dim)); - if history.entries.is_empty() { ui.label("暂无通知"); } - egui::ScrollArea::vertical().id_salt(id.with("entries")).max_height(list_height).show(ui, |ui| { - for (index,entry) in history.entries.iter().enumerate().rev() { - super::stitch_ui::divider(ui); - let active=!self.error.is_empty() && entry==&self.error; - ui.label(RichText::new(if active {"当前问题"} else {"历史通知"}).size(super::agent_stream::TEXT_META).color(t.text_dim)); - let has_candidates=self.template_workflow["slots"].as_array().into_iter().flatten() - .any(|slot|slot["candidates"].as_array().into_iter().flatten().any(|candidate|candidate["status"]=="complete")); - if active && super::operation_error::message(entry).image_read && has_candidates { - let button=super::stitch_ui::action_button(ui,"查看已有候选",super::stitch_ui::ButtonRole::Secondary,true); - self.panel_geometry["notificationCandidates"]=rect_value(button.rect); - if button.clicked() {view_candidates=true;} - } - super::operation_error::details(ui,id.with(("error-details",index)),entry,self.reduce_motion,Some(&diagnostics)); - } - }); - bounds = ui.min_rect(); - }); - if bounds.is_positive() { self.panel_geometry["notifications"] = rect_value(bounds); } - if closed || view_candidates { history.open = false; ui.ctx().request_repaint(); } - } - self.panel_geometry["notificationsOpen"] = json!(history.open); - ui.ctx().data_mut(|data| data.insert_temp(id, history)); - view_candidates - } - - fn reference_shelf(&mut self, app: &PhotocraftApp, ui: &mut Ui, references: &[Value], height: f32) { - let mut detach = None; - let mut target = None; - let mut rects = Vec::new(); - let columns = reference_columns(ui.available_width()); - egui::ScrollArea::vertical().id_salt("composer-reference-scroll").max_height(height) - .auto_shrink([false, true]).show(ui, |ui| { - let width = REFERENCE_WIDTH.min(ui.available_width()).max(1.0); - ui.spacing_mut().item_spacing = vec2(REFERENCE_GAP, REFERENCE_GAP); - ui.spacing_mut().interact_size.y = 24.0; - for (row, items) in references.chunks(columns).enumerate() { - ui.horizontal(|ui| { - for (column, reference) in items.iter().enumerate() { - let index = row * columns + column; - ui.push_id(index, |ui| { - let label = subject_label(reference, &self.template_workflow); - let glyph = if super::composer_references::image_reference(reference) { "image" } - else if matches!(reference["component"].as_str(), Some("pixelMask" | "vectorMask")) { "layer-mask" } - else if reference["layerKind"] == "Type" { "type" } else { "layers" }; - let task = reference["taskId"].as_str(); - let thumbnail = task.and_then(|id| self.agent_images.peek(id)).cloned(); - let (body, remove) = super::stitch_ui::reference_chip_with_preview(ui, glyph, &label, &label, 0.0, width, thumbnail.as_ref()); - let enter = |response: &Response| response.clicked() || response.has_focus() - && ui.input(|i| i.key_pressed(egui::Key::Enter) || i.key_pressed(egui::Key::Space)); - if enter(&remove) { detach = Some(index); } - if enter(&body) { target = activate_reference(ui, reference, None); } - if ui.is_rect_visible(body.rect) { - if let Some(task) = task { self.agent_images.mark_visible(task); } - let rect = body.rect.union(remove.rect); - rects.push(rect_value(rect)); - if index == 0 { - self.panel_geometry["subject"] = rect_value(rect); - self.panel_geometry["referenceRemove"] = rect_value(remove.rect); - } - } - if body.hovered() || body.has_focus() { - let thumbnail = thumbnail.or_else(|| super::reference_media::hover_image(app, ui.ctx(), reference)); - let mut tooltip = egui::Tooltip::for_widget(&body); - tooltip.popup = tooltip.popup.style(super::stitch_ui::scoped_popup_style(ui)); - if let Some(texture) = &thumbnail { - tooltip.popup = tooltip.popup - .align(egui::RectAlign::TOP_START) - .gap(6.0) - .width(148.0) - .frame(Frame::NONE); - tooltip.show(|ui| { - let rect = paint_reference_thumbnail(ui, texture, vec2(148.0, 144.0)); - self.panel_geometry["subjectTooltip"] = rect_value(rect); - }); - } else { - tooltip.popup = tooltip.popup.frame(super::stitch_ui::surface_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Menu).inner_margin(egui::Margin::same(8))); - tooltip.show(|ui| { - ui.set_max_width(148.0); - ui.add(egui::Label::new(RichText::new(label).size(12.0)).wrap()); - }); - } - } - }); - } - }); - } - }); - self.panel_geometry["referenceChips"] = json!(rects); - if let Some(index) = detach { - if let Err(error) = self.composer_reference_remove(app, index) { self.error = error; } - self.focus_composer = true; - } else if let Some(target) = target - && let Err(error) = self.locate_composer_reference(app, target) - { - self.error = error; - } - } - - pub(super) fn receive_chat_context_usage(&mut self,usage:&Value) { - if usage["version"]==1&&self.models.iter().any(|model|model["key"]==self.model&&model["id"]==usage["model"])&&usage["modelKey"].as_str().is_none_or(|key|key==self.model){self.pi_context_usage=usage.clone();} - } - - fn model_picker(&mut self, ui: &mut Ui, role: ModelRole, width: f32, compact: bool) -> Response { - let t = Tokens::get(ui.ctx()).agent(); - let current = match role {ModelRole::Chat=>&self.model,ModelRole::Copy=>&self.copy_model,ModelRole::Image=>&self.image_model}; - let models = match role {ModelRole::Chat=>&self.models,ModelRole::Copy=>&self.copy_models,ModelRole::Image=>&self.image_models}; - let label = models.iter().find(|m| m["key"] == *current).and_then(|m| m["id"].as_str()).map(model_display_name).unwrap_or_else(|| "选择模型".to_owned()); - let display = label.clone(); - let mut selected = current.clone(); - let enabled = self.busy.is_none() && !self.account.is_null(); - let old_selection = selected.clone(); - let mut show_all_models = self.show_all_models; - let mut menu_rect = None; - // A native ComboBox owns its popup lifetime and keyboard semantics. - // Bind that popup to the current workspace identity and close the old - // one before switching scope or disabling selection. - let model_scope = json!([self.origin, self.account["id"], self.project_context["localId"], self.owner_doc]).to_string(); - let response = ui - .add_enabled_ui(enabled, |ui| { - super::stitch_ui::scope_with_motion(ui, self.reduce_motion, |ui| { - let response = ui.push_id(("agent-model", role, compact, &model_scope), |ui| { - super::stitch_ui::select_trigger(ui, &display, width, enabled) - }).inner; - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, enabled, &display)); - let popup_id = response.id.with("popup"); - let last_id = Id::unique(("agent-model-last-popup", role, compact)); - if let Some(previous) = ui.data(|d| d.get_temp::(last_id)) - && (previous != popup_id || !enabled) { - egui::Popup::close_id(ui.ctx(), previous); - } - if !enabled { egui::Popup::close_id(ui.ctx(), popup_id); } - ui.data_mut(|d| d.insert_temp(last_id, popup_id)); - let show_toggle = models.iter().any(|model| is_hidden_model(role, model)); - let showing_all = show_all_models; - let visible = models.iter().filter(|model| { - showing_all || model["key"] == old_selection || !is_hidden_model(role, model) - }); - let longest = visible.clone().filter_map(|model| model["id"].as_str()).map(|name| { - ui.painter().layout_no_wrap(model_display_name(name), FontId::proportional(13.0), t.text).size().x + 76.0 - }).fold(width, f32::max); - let limit = (ui.ctx().content_rect().width() * 0.52).clamp(240.0, 560.0).min((ui.ctx().content_rect().width() - 32.0).max(160.0)); - let popup_width = longest.min(limit).max(width.min(limit)); - let shown = super::stitch_ui::select_popup_with_behavior(ui, &response, popup_width, self.reduce_motion, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| { - ui.set_width((popup_width - 16.0).max(128.0)); - ui.set_max_width((popup_width - 16.0).max(128.0)); - ui.spacing_mut().item_spacing.y = 2.0; - ui.label(RichText::new(match role {ModelRole::Chat=>"对话模型",ModelRole::Copy=>"文案模型",ModelRole::Image=>"生图模型"}).size(12.0).strong().color(t.text_dim)); - ui.add_space(4.0); - egui::ScrollArea::vertical().id_salt(("agent-model-list", role, compact)).max_height(280.0).show(ui, |ui| { - let mut option = |ui: &mut Ui, key: &str, name: &str, allowed: bool| { - let is_selected = selected == key; - let label = if allowed { name.to_owned() } else { format!("{name} · Key未开放") }; - let item = super::stitch_ui::select_option(ui, &label, is_selected, allowed); - if item.clicked() { selected = key.to_owned(); ui.close(); } - }; - option(ui, "", "未选择", true); - for model in visible { - if let (Some(key), Some(id)) = (model["key"].as_str(), model["id"].as_str()) { - let name = model_display_name(id); - let label = match (role, model["productionReady"].as_bool(), model["imageInputStatus"].as_str()) { - (ModelRole::Chat, Some(true), _) if model["productionVerified"] != true => format!("{name} · 制作待实测"), - (ModelRole::Chat, Some(true), _) => format!("{name} · 可制作"), - (ModelRole::Chat, _, Some("disabled")) => format!("{name} · 仅文本"), - (ModelRole::Chat, Some(false), _) => format!("{name} · 制作待核验"), - _ => name, - }; - option(ui, key, &label, self.available(id)); - } - } - }); - if show_toggle { - super::stitch_ui::divider(ui); - super::stitch_ui::switch(ui, ui.scope_id().with("show-all-models"), &mut show_all_models, - "显示历史/全部模型", enabled, self.reduce_motion); - } - }); - if let Some(shown) = shown { - let rect = ui.ctx().layer_transform_to_global(shown.response.layer_id).map_or(shown.response.rect, |transform| transform * shown.response.rect); - menu_rect = Some(rect); - } - response - }) - .inner - }) - .inner; - self.show_all_models = show_all_models; - if let Some(rect) = menu_rect { - self.panel_geometry[role.menu()] = rect_value(rect); - } - if compact { - let rect = ui.ctx().layer_transform_to_global(response.layer_id).map_or(response.rect, |transform| transform * response.rect); - self.panel_geometry["model"] = rect_value(rect); - self.panel_geometry[role.geometry()] = rect_value(rect); - } - if selected != old_selection { - self.choose_model(role, selected); - } - response - } - - fn choose_model(&mut self, role: ModelRole, selected: String) { - if self.key_saved && self.api_key.is_empty() { - self.send("select-model", json!({"field":role.setting(),"selection":selected, - "accountId":self.account["id"],"origin":self.origin})); - } else { - match role { - ModelRole::Chat => self.model = selected, - ModelRole::Copy => self.copy_model = selected, - ModelRole::Image => self.image_model = selected, - } - self.model_ready = false; - self.copy_ready = false; - self.image_ready = false; - if !self.onboarding.is_open() { - self.open_model_settings(); - self.key_settings = true; - } - } - } - - pub(super) fn onboarding_model_options(&mut self, ui: &mut Ui) { - use crate::theme::agent_scale::Type; - let roles = [(ModelRole::Chat, "对话模型", !self.models.is_empty()), - (ModelRole::Copy, "文案模型", !self.copy_models.is_empty()), - (ModelRole::Image, "生图模型", !self.image_models.is_empty())]; - let available = roles.into_iter().filter(|(_, _, available)| *available); - let count = available.clone().count(); - if count == 0 { - ui.horizontal_wrapped(|ui| { - super::stitch_ui::status_label(ui, "模型目录未加载", super::stitch_ui::StatusTone::Warning); - if super::stitch_ui::action_button(ui, "重试", super::stitch_ui::ButtonRole::Quiet, self.busy.is_none()).clicked() { - self.send("restore", json!({})); - } - }); - return; - } - ui.label(RichText::new("至少选择一个模型").font(Type::Meta.font_id()).color(Tokens::get(ui.ctx()).agent().text_dim)); - ui.horizontal_top(|ui| { - let width = (ui.available_width() - (count - 1) as f32 * ui.spacing().item_spacing.x) / count as f32; - for (role, label, _) in available { - ui.vertical(|ui| { - ui.set_width(width); - ui.label(label); - self.model_picker(ui, role, width, true); - }); - } - }); - } - - pub(super) fn model_key_editor(&mut self, ui: &mut Ui, scope: &str, open: bool, focus: bool) { - let enabled = open && self.busy.is_none() && !self.account.is_null(); - ui.add_enabled_ui(enabled, |ui| { - let key_id = ui.make_persistent_id((scope, "personal-key", &self.origin, self.account["id"].as_str().unwrap_or_default())); - let input = super::stitch_ui::halo_field(ui, key_id.with("field"), None, self.reduce_motion, |ui| ui.add( - super::stitch_ui::text_input( - &mut self.api_key, - if self.key_saved { "输入新的个人 Key" } else { "输入个人 Key" }, - false, - ) - .id(key_id).password(true).desired_width(f32::INFINITY).frame(Frame::NONE), - ).accessible_name("模型 API Key")); - if focus && enabled { input.request_focus(); } - input.on_hover_text("只保存在本机系统凭据库"); - if super::stitch_ui::action_button(ui, "保存连接", super::stitch_ui::ButtonRole::Primary, - !self.api_key.trim().is_empty() && (!self.model.is_empty() || !self.copy_model.is_empty() || !self.image_model.is_empty())) - .clicked() - { - self.model_ready = false; - self.image_ready = false; - self.copy_ready = false; - self.send("configure", json!({"key":self.api_key,"model":self.model,"copyModel":self.copy_model,"imageModel":self.image_model})); - } - }); - } - - pub(super) fn receive_model_preference(&mut self, value: &Value) { - if value["field"] == "thinkingLevel" { - self.thinking_by_model = value["thinkingByModel"].clone(); - return; - } - let (selected, models, ready) = match value["field"].as_str() { - Some("model") => (&mut self.model, &self.models, &mut self.model_ready), - Some("copyModel") => (&mut self.copy_model, &self.copy_models, &mut self.copy_ready), - Some("imageModel") => (&mut self.image_model, &self.image_models, &mut self.image_ready), - _ => return, - }; - let Some(choice) = value["selection"].as_str() else { return; }; - *selected = choice.into(); - *ready = self.key_saved && self.available_models.as_ref().is_some_and(|available| { - models.iter().find(|model| model["key"] == choice).and_then(|model| model["id"].as_str()) - .is_some_and(|id| available.iter().any(|entry| entry == id)) - }); - } - - fn thinking_picker(&mut self, ui: &mut Ui) { - let Some(model) = self.models.iter().find(|model| model["key"] == self.model && model["reasoning"] == true) else { - return; - }; - let label = |level: &str| match level { - "off" => "关闭", - "minimal" => "最少", - "low" => "低", - "medium" => "中", - "high" => "高", - "xhigh" => "很高", - "max" => "最高", - _ => "自动", - }; - let current = self.thinking_by_model.get(self.model.as_str()).and_then(Value::as_str).unwrap_or(""); - let mut selected = current; - let levels = model["reasoningEfforts"].as_array().into_iter().flatten().filter_map(Value::as_str); - let width = ui.available_width(); - let tokens = Tokens::get(ui.ctx()).agent(); - ui.push_id("xiaoyi-thinking-effort", |ui| { - ui.label(RichText::new("思考档位").size(12.0).color(tokens.text_dim)); - let trigger = super::stitch_ui::select_trigger(ui, label(current), width, self.model_ready && self.busy.is_none()); - self.panel_geometry["thinkingLevel"] = rect_value(trigger.rect); - super::stitch_ui::select_popup(ui, &trigger, width, self.reduce_motion, |ui| { - for level in ["", "off"].into_iter().chain(levels) { - if super::stitch_ui::select_option(ui, label(level), current == level, true).clicked() { - selected = level; - ui.close(); - } - } - }); - }); - if selected != current { - self.send("select-model", json!({"field":"thinkingLevel","selection":selected,"model":self.model, - "accountId":self.account["id"],"origin":self.origin})); - } - } - - fn xiaoyi_key_input(&mut self, ui: &mut Ui) { - use super::stitch_ui::{self, ButtonRole}; - let id = ui.make_persistent_id("xiaoyi-knowledge-key"); - let hint = if self.xiaoyi_key_saved { "输入新的制作 Key" } else { "输入制作 Key" }; - stitch_ui::halo_field(ui, id.with("field"), None, self.reduce_motion, |ui| ui.add( - stitch_ui::text_input(&mut self.xiaoyi_key, hint, false) - .id(id).password(true).desired_width(f32::INFINITY).frame(Frame::NONE), - )); - if stitch_ui::action_button(ui, "校验并保存", ButtonRole::Secondary, !self.xiaoyi_key.trim().is_empty()).clicked() { - let key = std::mem::take(&mut self.xiaoyi_key); - self.send("configure-xiaoyi-knowledge", json!({"key":key})); - } - } - - fn knowledge_settings(&mut self, ui: &mut Ui) { - use super::stitch_ui::{self, ButtonRole, StatusTone, status_label}; - use crate::theme::agent_scale::Type; - let t = Tokens::get(ui.ctx()).agent(); - ui.label(RichText::new("小壹知识库").size(Type::Title.size()).color(t.text)); - let checking = self.busy.as_deref() == Some("configure-xiaoyi-knowledge"); - if self.xiaoyi_knowledge_mode == "manual" { - knowledge_connection_status(ui, self.xiaoyi_key_saved, self.xiaoyi_key_check.as_ref(), checking); - } else { - let (status, tone) = match (checking, self.xiaoyi_key_check.as_ref(), self.xiaoyi_knowledge_mode.as_str()) { - (true, _, _) => ("正在连接", StatusTone::Neutral), - (false, Some(Err(_)), _) => ("连接失败", StatusTone::Error), - (false, _, "automatic") => ("素材库自动连接", StatusTone::Neutral), - _ if self.account.is_null() => ("登录后自动连接", StatusTone::Neutral), - _ => ("未连接", StatusTone::Neutral), - }; - status_label(ui, status, tone); - if let Some(Err(error)) = self.xiaoyi_key_check.as_ref().filter(|_| !checking) { - status_label(ui, error, StatusTone::Error); - } - } - ui.add_enabled_ui(self.busy.is_none(), |ui| { - if self.xiaoyi_knowledge_mode == "manual" && !self.xiaoyi_key_saved { - self.xiaoyi_key_input(ui); - } else { - if stitch_ui::action_button(ui, "检测连接", ButtonRole::Secondary, true).clicked() { - self.send("configure-xiaoyi-knowledge", json!({"key":""})); - } - if self.xiaoyi_knowledge_mode == "manual" { - let id = ui.make_persistent_id("replace-xiaoyi-knowledge-key"); - stitch_ui::disclosure(ui, id, "更换制作 Key", false, self.reduce_motion, |ui| { - self.xiaoyi_key_input(ui); - }); - } - } - }); - } - - pub(super) fn open_model_settings(&mut self) { - if !self.model_settings { - self.model_settings = true; - self.prompt_library.close(); - self.maybe_check_update_on_settings_open(); - } - } - - fn clear_settings_key_draft(&mut self) { - if !self.onboarding.is_open() { - self.api_key.clear(); - } - } - - pub(super) fn close_model_settings(&mut self) { - if self.model_settings || self.key_settings { - self.model_settings = false; - self.key_settings = false; - self.clear_settings_key_draft(); - self.xiaoyi_key.clear(); - } - } - - pub(super) fn workspace_settings_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui, corner: egui::Pos2) { - // The brief's buttons disappear when the models are ready. Anchor the - // popup and its exit animation to the workspace instead. - let inset = crate::theme::agent_scale::space::MD; - let anchor = ui.interact( - Rect::from_min_size(corner + vec2(inset, -inset), Vec2::ZERO), - ui.make_persistent_id("workspace-settings-anchor"), - Sense::hover(), - ); - if self.notifications_ui(ui) { - self.show_center(super::CenterView::Canvas, app.session.active().is_some()); - } - self.model_settings_popup(ui, &anchor); - self.flush_client_update_request(app); - } - - pub(super) fn model_settings_popup(&mut self, ui: &mut Ui, anchor: &Response) { - let retained = ui.ctx().read_response(egui::Popup::default_response_id(anchor)).is_some(); - if self.model_settings || self.key_settings || retained { - self.settings_popup(ui, anchor); - } - } - - fn settings_popup(&mut self, ui: &mut Ui, anchor: &Response) { - // The dock layout can change mid-pass. A mounted popup claims the pass - // so another host cannot draw a second copy during the handoff. - let host = Id::unique(("jiansun-settings-host", ui.ctx().viewport_id())); - let pass = ui.ctx().cumulative_pass_nr(); - if ui.data(|data| data.get_temp::(host)) == Some(pass) { - return; - } - let open = self.model_settings || self.key_settings; - let open_id = host.with("open"); - let was_open = ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(open_id), open)); - if was_open && !open { - self.clear_settings_key_draft(); - self.xiaoyi_key.clear(); - } - let t = Tokens::get(ui.ctx()).agent(); - let (visual, transform) = super::stitch_ui::floating_panel_motion(ui.ctx(), anchor.id.with("popup"), anchor, open, self.reduce_motion); - self.panel_geometry["settingsMotion"] = json!({"opacity":visual.opacity,"scale":transform.scaling,"interactive":visual.interactive}); - ui.ctx().data_mut(|data| data.insert_temp(Id::unique("jiansun-settings-retained"), visual.render)); - if !visual.render { - return; - } - ui.data_mut(|data| data.insert_temp(host, pass)); - let frame = super::stitch_ui::overlay_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Dialog, visual.opacity).inner_margin(18); - let global_anchor = ui.ctx().layer_transform_to_global(anchor.layer_id).map_or(anchor.rect, |transform| transform * anchor.rect); - let body_height = super::stitch_ui::floating_body_height(ui.ctx().content_rect(), global_anchor); - let glass = settings_glass_supported(ui.ctx()); - self.panel_geometry["settingsGlass"] = json!(glass); - // A model menu can extend beyond this surface. Its click or Escape - // belongs to that child menu, not to the settings dismissal handler. - let nested_open = [ModelRole::Chat,ModelRole::Copy,ModelRole::Image].into_iter().any(|role| { - ui.data(|data| data.get_temp::(Id::unique(("agent-model-last-popup", role, true)))) - .is_some_and(|id| egui::Popup::is_id_open(ui.ctx(), id)) - }); - let mut popup_visible = true; - egui::Popup::from_response(anchor) - .frame(egui::Frame::NONE) - .open_bool(&mut popup_visible) - .close_behavior(if visual.interactive && !nested_open { egui::PopupCloseBehavior::CloseOnClickOutside } else { egui::PopupCloseBehavior::IgnoreClicks }) - .show(|ui| { - let contents = |ui: &mut Ui| super::stitch_ui::overlay_contents(ui, visual, |ui| super::stitch_ui::scope_with_motion(ui, self.reduce_motion, |ui| { - ui.set_width(360.0_f32.min((ui.ctx().content_rect().width() - 32.0).max(180.0))); - ui.spacing_mut().item_spacing = vec2(8.0, 10.0); - ui.spacing_mut().scroll.floating = false; - ui.horizontal(|ui| { - ui.label(RichText::new("小壹设置").size(14.0).strong().color(t.text)); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - if super::stitch_ui::icon_button(ui, "x", 26.0, false, "关闭模型设置").clicked() { - self.close_model_settings(); - } - }); - }); - let body = egui::ScrollArea::vertical().id_salt("xiaoyi-settings-body").max_height(body_height).show(ui, |ui| { - for (role, label) in [(ModelRole::Chat,"对话模型"),(ModelRole::Copy,"文案模型"),(ModelRole::Image,"生图模型")] { - ui.label(RichText::new(label).size(12.0).color(t.text_dim)); - self.model_picker(ui, role, ui.available_width(), true); - if role == ModelRole::Chat { self.thinking_picker(ui); } - } - if !self.copy_catalog_error.is_empty() { - ui.horizontal_wrapped(|ui| { - ui.label("文案目录未加载").on_hover_text(&self.copy_catalog_error); - if super::stitch_ui::action_button(ui,"重试",super::stitch_ui::ButtonRole::Quiet,true).clicked(){self.send("restore",json!({}));} - }); - } - if !self.image_catalog_error.is_empty() { - ui.horizontal_wrapped(|ui| { - ui.label("生图目录未加载").on_hover_text(&self.image_catalog_error); - if super::stitch_ui::action_button(ui, "重试", super::stitch_ui::ButtonRole::Quiet, true).clicked() { - self.send("restore", json!({})); - } - }); - } - ui.add_space(4.0); - ui.horizontal(|ui| { - icon(ui, "lock", t.text_dim); - ui.label(RichText::new(if self.key_saved { "个人 Key 已连接" } else { "个人 Key 未连接" }).size(13.0).color(t.text)); - if self.busy.as_deref() == Some("configure") { - super::stitch_ui::ai_loader(ui, ui.scope_id().with("configure-loading"), true, self.reduce_motion); - ui.label("正在校验…"); - } else if super::stitch_ui::action_button(ui, if self.key_settings { - "收起" - } else if self.key_saved { - "更换" - } else { - "设置" - }, super::stitch_ui::ButtonRole::Quiet, self.busy.is_none() && !self.account.is_null()) - .clicked() - { - self.key_settings = !self.key_settings; - if !self.key_settings { - self.clear_settings_key_draft(); - } - } - }); - super::stitch_ui::morph_surface(ui, ui.scope_id().with("key-reveal"), self.key_settings, self.reduce_motion, |ui| { - if !self.onboarding.is_open() { - self.model_key_editor(ui, "settings", self.key_settings, false); - } - }); - super::stitch_ui::divider(ui); - self.knowledge_settings(ui); - super::stitch_ui::divider(ui); - - if let Some(id) = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc) { - let notifications = super::stitch_ui::action_button(ui, "通知与警告", super::stitch_ui::ButtonRole::Quiet, true); - let count=ui.data(|data|data.get_temp::(id)).map_or(0,|history|history.unread); - if count>0 { - // On the label's centre line, a badge's own half-width to the right of the control. - let rect=Rect::from_center_size(notifications.rect.right_center()+vec2(15.0,0.0),vec2(24.0,20.0)); - super::stitch_ui::paint_badge(ui,id.with("unread-count"),rect,super::stitch_ui::BadgeKind::Count,&count.to_string(),self.reduce_motion); - } - self.panel_geometry["notificationsButton"] = rect_value(notifications.rect); - if notifications.clicked() { - ui.ctx().data_mut(|data| data.get_temp_mut_or_default::(id).open = true); - self.close_model_settings(); - } - } - // 有"通知与警告"时补一条分隔线;没有时上面已经是分隔线。 - let after_notifications = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc).is_some(); - self.client_version_settings(ui, after_notifications); - let after_version = after_notifications || self.client_update.version["version"].is_string(); - self.storage_settings_section(ui, after_version); - }); - // egui reports the pre-auto-shrink inner rect. Match the - // actual vertical viewport used by ScrollArea::end, rather - // than incorrectly counting its unused space as content. - let mut body_rect = body.inner_rect; - body_rect.set_height(body_rect.height().min(body.content_size.y)); - self.panel_geometry["settingsBody"] = rect_value(body_rect); - self.panel_geometry["settingsContentHeight"] = json!(body.content_size.y); - ui.add_space(4.0); - })); - if glass { - #[cfg(not(target_arch = "wasm32"))] - show_settings_glass(ui, frame, t.card, visual.opacity, transform.scaling, contents); - #[cfg(target_arch = "wasm32")] - contents(ui); - } else { - super::stitch_ui::material_frame(ui, frame, contents); - } - }); - if open && !popup_visible && !nested_open { - self.close_model_settings(); - ui.ctx().request_repaint(); - } - } - - pub(super) fn multi_project_view_model( - &self, - app: &PhotocraftApp, - ctx: &egui::Context, - ) -> multi_project_ui::MultiProjectViewModel { - if let Some(injected) = multi_project_ui::snapshot(ctx) { - return injected; - } - let snap = self.multi_project_ui_snapshot(app); - let active_section = match snap.active_section { - super::multi_project_state::WorkspaceSectionKind::Projects => multi_project_ui::WorkspaceSection::Projects, - super::multi_project_state::WorkspaceSectionKind::Brief => multi_project_ui::WorkspaceSection::Brief, - super::multi_project_state::WorkspaceSectionKind::Canvas => multi_project_ui::WorkspaceSection::Canvas, - }; - let map_status = |status: &super::multi_project_state::ProjectRunVisualStatus| match status { - super::multi_project_state::ProjectRunVisualStatus::Running => multi_project_ui::MultiRunStatus::Running, - super::multi_project_state::ProjectRunVisualStatus::Queued => multi_project_ui::MultiRunStatus::Queued, - super::multi_project_state::ProjectRunVisualStatus::Paused => multi_project_ui::MultiRunStatus::Paused, - super::multi_project_state::ProjectRunVisualStatus::PartialDelivered => multi_project_ui::MultiRunStatus::PartialDelivered, - super::multi_project_state::ProjectRunVisualStatus::Completed => multi_project_ui::MultiRunStatus::Completed, - super::multi_project_state::ProjectRunVisualStatus::Failed => multi_project_ui::MultiRunStatus::Failed, - }; - let global_runs = snap - .global_runs - .into_iter() - .map(|run| { - let output_id = run.producing_output_id.unwrap_or_default(); - let output_label = if run.producing_output_label.is_empty() && !output_id.is_empty() { - multi_project_ui::output_display_label(&output_id).to_owned() - } else { - run.producing_output_label - }; - multi_project_ui::GlobalRunEntry { - project_id: run.project_id, - project_title: run.project_title, - status: map_status(&run.status), - producing_output_id: output_id, - producing_output_label: output_label, - progress_label: run.progress_label, - elapsed_secs: run.elapsed_secs, - active_slots: run.active_slots, - has_attention: run.has_attention, - } - }) - .collect(); - let active_project_title = (!snap.active_project_title.is_empty()).then_some(snap.active_project_title); - let viewing_output_label = snap.viewing_output_id.as_deref().map(|id| { - if snap.viewing_output_label.is_empty() { - multi_project_ui::output_display_label(id).to_owned() - } else { - snap.viewing_output_label.clone() - } - }); - let producing_output_label = snap.producing_output_id.as_deref().map(|id| { - if snap.producing_output_label.is_empty() { - multi_project_ui::output_display_label(id).to_owned() - } else { - snap.producing_output_label.clone() - } - }); - multi_project_ui::MultiProjectViewModel { - global_runs, - max_concurrent: snap.max_concurrent, - active_project_id: snap.active_project_id, - active_project_title, - active_section, - viewing_output_id: snap.viewing_output_id, - viewing_output_label, - producing_output_id: snap.producing_output_id, - producing_output_label, - viewing_differs_from_producing: snap.viewing_differs_from_producing, - } - } - - pub(super) fn handle_multi_project_action( - &mut self, - app: &mut PhotocraftApp, - ctx: &egui::Context, - action: multi_project_ui::MultiProjectAction, - ) { - match &action { - multi_project_ui::MultiProjectAction::SwitchToProject(project_id) => { - if self.open_project_index(app, project_id).is_some() { - self.focus_project_by_id(app, project_id); - } else if let Some(item) = self - .projects - .iter() - .find(|p| p["localId"].as_str() == Some(project_id.as_str()) || p["id"].as_str() == Some(project_id.as_str())) - .cloned() - { - if let Err(error) = self.request_project_open(app, item) { - self.error = error; - } - } - } - multi_project_ui::MultiProjectAction::PauseProject(project_id) => { - if self.open_project_index(app, project_id).is_some() { - self.pause_project_run(app, project_id); - } else { - super::production_controls::queue_action( - ctx, - "production-stop", - super::production_controls::stop_input(timeline::StopMode::Pause), - ); - } - } - multi_project_ui::MultiProjectAction::ResumeProject(project_id) => { - if self.open_project_index(app, project_id).is_some() { - self.resume_project_run(app, project_id); - } else { - self.resume_product_production(app); - } - } - multi_project_ui::MultiProjectAction::JumpToProducingOutput { project_id, .. } => { - if self.open_project_index(app, project_id).is_some() { - self.focus_project_by_id(app, project_id); - } - self.jump_to_producing_output(app); - } - } - multi_project_ui::push_action(ctx, action); - } - - fn storage_settings_section(&mut self, ui: &mut Ui, show_divider: bool) { - let reduced = self.reduce_motion; - let ctx = ui.ctx().clone(); - let (action, modal_opened) = storage_settings_ui::with_machine_state(&ctx, |state| { - let was_open = state.migrate_modal_open || state.cleanup_modal_open; - let action = storage_settings_ui::storage_settings_card(ui, state, reduced, show_divider); - let now_open = state.migrate_modal_open || state.cleanup_modal_open; - (action, !was_open && now_open) - }); - if modal_opened { - self.close_model_settings(); - ui.ctx().request_repaint(); - } - if let Some(action) = action { - let (method, payload) = action.to_request(); - let _ = self.tx.send(Request::Action(method.into(), payload)); - } - } - - pub(super) fn storage_modals_ui(&mut self, ctx: &egui::Context) { - let pass = ctx.cumulative_pass_nr(); - let pass_id = Id::unique("xiaoyi-storage-modals-pass"); - let already_rendered = ctx.data(|data| data.get_temp::(pass_id) == Some(pass)); - if already_rendered { - return; - } - ctx.data_mut(|data| data.insert_temp(pass_id, pass)); - let reduced = self.reduce_motion; - let action = storage_settings_ui::with_machine_state(ctx, |state| { - storage_settings_ui::show_storage_modals(ctx, state, reduced) - }); - if let Some(action) = action { - let (method, payload) = action.to_request(); - let _ = self.tx.send(Request::Action(method.into(), payload)); - } - } - - pub(super) fn receive_storage_event(&mut self, ctx: &egui::Context, method: &str, result: Result) { - let apply_migration_patch = |mig: &mut storage_settings_ui::MigrationStateView, patch: &Value| { - if let Some(phase) = patch["phase"].as_str() { - mig.phase = storage_settings_ui::MigrationPhase::parse(phase); - } - if let Some(target) = patch["targetRoot"].as_str().filter(|s| !s.is_empty()) { - mig.target_root = target.to_owned(); - } - if patch.get("targetFreeBytes").is_some() { - mig.target_free_bytes = patch["targetFreeBytes"].as_u64(); - } - if let Some(req) = patch["requiredBytes"].as_u64() { - mig.required_bytes = req; - } - if let Some(copied) = patch["copiedBytes"].as_u64() { - mig.copied_bytes = copied; - } - if let Some(total) = patch["totalBytes"].as_u64() { - mig.total_bytes = total; - } - if patch.get("validationError").is_some() { - mig.validation_error = patch["validationError"].as_str().filter(|s| !s.is_empty()).map(str::to_owned); - } - if let Some(warnings) = patch["validationWarnings"].as_array() { - mig.validation_warnings = warnings.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(); - } - if let Some(blocking) = patch["blockingProjects"].as_array() { - mig.blocking_projects = blocking.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(); - } else if !matches!(mig.phase, storage_settings_ui::MigrationPhase::ReadyToSwitch | storage_settings_ui::MigrationPhase::Idle) { - mig.blocking_projects.clear(); - } - if let Some(steps) = patch.get("switchSteps").or_else(|| patch.get("steps")).and_then(Value::as_array) { - mig.switch_steps = steps - .iter() - .map(|row| storage_settings_ui::SwitchStep { - id: row["id"].as_str().unwrap_or_default().to_owned(), - label: row["label"].as_str().unwrap_or_default().to_owned(), - state: storage_settings_ui::SwitchStepState::parse( - row["state"].as_str().or_else(|| row["status"].as_str()).unwrap_or("pending"), - ), - }) - .collect(); - } - if patch.get("error").is_some() { - mig.error = patch["error"].as_str().filter(|s| !s.is_empty()).map(str::to_owned); - } - if patch.get("rollbackNote").is_some() { - mig.rollback_note = patch["rollbackNote"].as_str().filter(|s| !s.is_empty()).map(str::to_owned); - } - }; - - match method { - "storage-status" => match result { - Ok(val) if val.get("mode").is_some() => { - let view = storage_settings_ui::StorageStatusView::from_json(&val); - storage_settings_ui::set_status(ctx, view); - if val["autoOpenReleaseModal"] == true { - storage_settings_ui::with_machine_state(ctx, |state| { - state.migrate_modal_open = true; - }); - } - } - Ok(_) => {} - Err(error) => { - storage_settings_ui::with_machine_state(ctx, |state| { - state.status.status_text = Some(error); - state.status.status_is_error = true; - }); - } - }, - "storage-status-refresh" => {} - "storage-scan" => match result { - Ok(val) => storage_settings_ui::set_scan(ctx, storage_settings_ui::StorageScanView::from_json(&val)), - Err(error) => { - storage_settings_ui::with_machine_state(ctx, |state| { - state.scan.scanning = false; - state.scan.error = Some(error); - }); - } - }, - "storage-cleanup" => match result { - Ok(val) => { - let mut scan = storage_settings_ui::StorageScanView::from_json(&val); - scan.scanning = false; - scan.cleanup_running = false; - storage_settings_ui::set_scan(ctx, scan); - } - Err(error) => { - storage_settings_ui::with_machine_state(ctx, |state| { - state.scan.cleanup_running = false; - state.scan.cleanup_result = Some(storage_settings_ui::CleanupResultView { - freed_bytes: 0, - message: String::new(), - error: Some(error), - }); - }); - } - }, - "storage-migrate" => match result { - Ok(val) => { - if val["requiresExit"] == true { - self.storage_switch_pending = true; - self.storage_restart_requested = true; - storage_settings_ui::with_machine_state(ctx, |state| { - apply_migration_patch(&mut state.status.migration, &val); - state.status.migration.phase = storage_settings_ui::MigrationPhase::Switching; - state.migrate_modal_open = true; - }); - } else if let Some(picked) = val["pickedRoot"].as_str() { - storage_settings_ui::with_machine_state(ctx, |state| { - state.target_input = picked.to_owned(); - if val["migration"].is_object() { - apply_migration_patch(&mut state.status.migration, &val["migration"]); - } - }); - } else if val["migration"].is_object() { - storage_settings_ui::with_machine_state(ctx, |state| { - apply_migration_patch(&mut state.status.migration, &val["migration"]); - }); - } else if val["deferred"] == true { - storage_settings_ui::with_machine_state(ctx, |state| { - state.migrate_modal_open = false; - }); - } else if val["cancelled"] == true { - storage_settings_ui::with_machine_state(ctx, |state| { - if state.status.migration.phase.is_non_closable() { - state.status.migration.phase = storage_settings_ui::MigrationPhase::ReadyToSwitch; - } - }); - } else if val["phase"].is_string() { - storage_settings_ui::with_machine_state(ctx, |state| { - apply_migration_patch(&mut state.status.migration, &val); - }); - } - } - Err(error) => { - storage_settings_ui::with_machine_state(ctx, |state| { - if matches!( - state.status.migration.phase, - storage_settings_ui::MigrationPhase::Idle | storage_settings_ui::MigrationPhase::Validating - ) { - state.status.migration.phase = storage_settings_ui::MigrationPhase::Idle; - state.status.migration.validation_error = Some(error); - } else { - state.status.migration.phase = storage_settings_ui::MigrationPhase::Failed; - state.status.migration.error = Some(error); - } - }); - } - }, - "storage-migrate-progress" => match result { - Ok(val) => { - storage_settings_ui::with_machine_state(ctx, |state| { - apply_migration_patch(&mut state.status.migration, &val); - if state.target_input.is_empty() && !state.status.migration.target_root.is_empty() { - state.target_input = state.status.migration.target_root.clone(); - } - if state.status.migration.phase.is_non_closable() { - state.migrate_modal_open = true; - } - }); - } - Err(error) => { - storage_settings_ui::with_machine_state(ctx, |state| { - state.status.migration.phase = storage_settings_ui::MigrationPhase::Failed; - state.status.migration.error = Some(error); - }); - } - }, - _ => {} - } - ctx.request_repaint(); - } -} - -/// Experimental, local-acceptance-only opt-in. Until device-loss, resource -/// failure, performance and real-window verification are complete, a normal -/// launch uses the existing opaque popup and unchanged native renderer path. -fn knowledge_connection_status(ui: &mut Ui, saved: bool, check: Option<&Result<(), String>>, checking: bool) { - use super::stitch_ui::{StatusTone, status_label}; - let stored = if saved { "已保存到本机" } else { "本机未保存" }; - let (status, tone) = match (checking, check) { - (true, _) => ("正在校验", StatusTone::Neutral), - (false, Some(Ok(()))) => ("上次校验通过", StatusTone::Neutral), - (false, Some(Err(_))) => ("上次校验失败", StatusTone::Error), - (false, None) if saved => ("本次尚未校验", StatusTone::Neutral), - (false, None) => ("等待配置", StatusTone::Neutral), - }; - status_label(ui, &format!("{stored} · {status}"), tone); - if let Some(Err(error)) = check.filter(|_| !checking) { - status_label(ui, error, StatusTone::Error); - } -} - -#[cfg(not(target_arch = "wasm32"))] -fn settings_glass_supported(ctx: &egui::Context) -> bool { - let initialized = Id::unique("jiansun-settings-glass-opt-in-initialized"); - let should_initialize = ctx.data_mut(|data| { - if data.get_temp::(initialized).unwrap_or(false) { - false - } else { - data.insert_temp(initialized, true); - true - } - }); - if should_initialize && std::env::var_os("PHOTOCRAFT_EXPERIMENTAL_STITCH_GLASS").as_deref() == Some(std::ffi::OsStr::new("1")) { - eframe::egui_wgpu::stitch_backdrop_set_experiment_enabled(ctx, true); - } - eframe::egui_wgpu::stitch_backdrop_supported(ctx) -} - -#[cfg(target_arch = "wasm32")] -fn settings_glass_supported(_ctx: &egui::Context) -> bool { - false -} - -/// The paired callbacks bracket an opaque emergency underlay. The validated -/// split renderer omits it; the normal renderer keeps it if a capability or -/// planner check fails, including the current frame. This does not guarantee -/// presentation after GPU device loss and is intentionally opt-in only. -#[cfg(not(target_arch = "wasm32"))] -fn show_settings_glass(ui: &mut Ui, mut frame: egui::Frame, base: Color32, opacity: f32, scale: f32, contents: impl FnOnce(&mut Ui) -> R) { - use eframe::egui_wgpu::BackdropMarker; - - let begin = ui.painter().add(egui::Shape::Noop); - let fallback = ui.painter().add(egui::Shape::Noop); - let end = ui.painter().add(egui::Shape::Noop); - frame.fill = frame.fill.gamma_multiply(0.58); - let shown = super::stitch_ui::material_frame(ui, frame, contents); - let rect = shown.response.rect - egui::epaint::MarginF32::from(frame.outer_margin); - let radius = f32::from(frame.corner_radius.nw) * scale; - let start_marker = BackdropMarker { blur_radius_points: 5.0 * scale, corner_radius_points: radius, opacity }; - let end_marker = BackdropMarker { blur_radius_points: 0.0, corner_radius_points: radius, opacity }; - ui.painter().set(begin, egui::Shape::Callback(start_marker.new_paint_callback(rect))); - // Ignore Area's measurement fade, but retain the explicit panel transition - // when a shrinking backdrop falls back to ordinary painting. - let mut opaque_painter = ui.painter().clone(); - opaque_painter.set_opacity(opacity.clamp(0.0, 1.0)); - opaque_painter.set(fallback, egui::Shape::rect_filled(rect, frame.corner_radius, Color32::from_rgb(base.r(), base.g(), base.b()))); - ui.painter().set(end, egui::Shape::Callback(end_marker.new_paint_callback(rect))); } #[cfg(test)] -mod tests { - use crate::jiansun::test_support::SettleUi; - use crate::jiansun::Event; - use std::sync::mpsc; - use super::*; - use egui::pos2; - - #[test] - fn production_delivery_card_opens_the_actual_saved_directory() { - use egui_kittest::{Harness, kittest::Queryable}; - - let root = tempfile::tempdir().unwrap(); - let folder = root.path().join("成品"); - std::fs::create_dir(&folder).unwrap(); - let path = folder.to_str().unwrap(); - for (done, full, label) in [(3, true, "打开交付文件夹"), (1, false, "打开导出文件夹")] { - std::fs::write(folder.join("交付清单.json"), json!({"allOutputsCompleted":full,"completedOutputs":done,"totalOutputs":3}).to_string()).unwrap(); - let (mut app, requests) = dock_fixture(); - let (opened, paths) = mpsc::channel(); - app.services.open_folder = Some(Box::new(move |path| { - opened.send(path.to_owned()).unwrap(); - Ok(()) - })); - let workspace = app.jiansun.as_mut().unwrap(); - workspace.product_checkpoint = json!({"deliveryDir": root.path().join("预设目录")}); - workspace.messages.push(json!({ - "role":"assistant", - "productionSummary":{"exported":0,"total":3,"slotCoverage":{"empty":3,"total":3}}, - "productionDelivery":{"state":"bundle_saved","path":path,"allOutputsCompleted":!full} - })); - let mut harness = Harness::builder().with_size(vec2(760.0, 380.0)) - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .build_ui_state(|ui, app: &mut PhotocraftApp| { - let mut workspace = app.jiansun.take().unwrap(); - workspace.production_outcome_ui(ui, false, app); - app.jiansun = Some(workspace); - }, app); - harness.run_steps(3); - harness.get_by_label(path); - harness.get_by_label(label).click(); - harness.run_steps(2); - assert_eq!(paths.try_recv().unwrap(), folder); - assert!(paths.try_recv().is_err()); - assert!(requests.try_recv().is_err()); - } - } - - #[test] - fn paused_production_can_open_the_saved_partial_delivery_from_its_checkpoint() { - use egui_kittest::{Harness, kittest::Queryable}; - - let folder = tempfile::tempdir().unwrap(); - std::fs::write(folder.path().join("交付清单.json"), br#"{"allOutputsCompleted":false}"#).unwrap(); - let (mut app, _) = dock_fixture(); - let (opened, paths) = mpsc::channel(); - app.services.open_folder = Some(Box::new(move |path| { - opened.send(path.to_owned()).unwrap(); - Ok(()) - })); - app.jiansun.as_mut().unwrap().product_checkpoint = json!({ - "phase":"paused", - "partialDelivered":true, - "deliveryDir":folder.path(), - "productionDelivery":{"state":"bundle_saved","allOutputsCompleted":false} - }); - let mut harness = Harness::builder().with_size(vec2(760.0, 380.0)) - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .build_ui_state(|ui, app: &mut PhotocraftApp| { - let mut workspace = app.jiansun.take().unwrap(); - workspace.production_outcome_ui(ui, false, app); - app.jiansun = Some(workspace); - }, app); - harness.run_steps(3); - harness.get_by_label(folder.path().to_str().unwrap()); - harness.get_by_label("打开导出文件夹").click(); - harness.run_steps(2); - assert_eq!(paths.try_recv().unwrap(), folder.path()); - assert!(harness.query_by_label("打开交付文件夹").is_none()); - } - - #[test] - fn production_counts_alone_do_not_confirm_delivery() { - use egui_kittest::{Harness, kittest::Queryable}; - - let folder = tempfile::tempdir().unwrap(); - let (app, _) = dock_fixture(); - let mut harness = Harness::builder().with_size(vec2(760.0, 380.0)) - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .build_ui_state(|ui, app: &mut PhotocraftApp| { - let mut workspace = app.jiansun.take().unwrap(); - workspace.production_outcome_ui(ui, false, app); - app.jiansun = Some(workspace); - }, app); - for path in [Value::Null, json!(folder.path().join("已移走")), json!(folder.path())] { - let workspace = harness.state_mut().jiansun.as_mut().unwrap(); - workspace.messages = vec![json!({ - "role":"assistant", - "productionSummary":{"exported":3,"total":3}, - "productionDelivery":{"state":"bundle_saved","allOutputsCompleted":true,"path":path} - })]; - harness.run_steps(2); - harness.get_by_label("成品交付尚未确认"); - assert!(harness.query_by_label("整套制作已完成 · 已交付 3/3 份").is_none()); - assert!(harness.query_by_label("打开交付文件夹").is_none()); - } - } - - #[test] - fn delivery_review_uses_the_mounted_variant_and_reports_a_missing_layer() { - let (mut workspace, app, _, layer, _) = super::super::canvas_workspace::tests::native_fixture(); - let ctx = egui::Context::default(); - let id = workspace.delivery_hint_id(); - for (native_layer, found) in [(layer, true), (u64::MAX, false)] { - workspace.canvas_workspace.locate_request = None; - ctx.data_mut(|data| data.insert_temp(id, ("detail".to_owned(), json!({"variantId":"wood","nativeLayerId":native_layer})))); - let mut response = ctx.settle_ui(egui::RawInput::default(), |ui| workspace.finish_delivery_hint(&app, ui)); - response.textures_delta.clear(); - if found { - let locate = workspace.canvas_workspace.locate_request.as_ref().unwrap(); - assert_eq!(locate["productVariantId"], "wood"); - assert_eq!(locate["targets"][0]["nativeLayerId"], layer); - } else { - assert!(workspace.canvas_workspace.locate_request.is_none()); - assert_eq!(workspace.error, "当前成品中已找不到该核对位置"); - } - } - } - - #[test] - fn asset_dock_open_folder_requests_the_current_project() { - let (mut workspace, app, requests, _, _) = super::super::canvas_workspace::tests::native_fixture(); - let doc = app.session.active().unwrap().doc.id.0; - let mut harness = egui_kittest::Harness::builder() - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .build_ui(move |ui| workspace.production_assets_ui(ui, doc)); - use egui_kittest::kittest::Queryable; - harness.get_by_label("打开本地文件夹").click(); - harness.run(); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected folder action") }; - assert_eq!(method, "open-generated-folder"); - assert_eq!(input, json!({"doc":doc,"accountId":"owner","origin":"https://local.test"})); - } - - #[test] - fn notification_badges_count_only_new_entries_in_the_current_history() { - let mut history=AgentNotifications::default(); - history.add("导出字体提示");history.add("导出字体提示"); - assert_eq!(history.unread,1); - history.unread=0; - history.add("导出字体提示"); - assert_eq!(history.unread,0,"viewed duplicates do not become unread again"); - history.add("需要核查原请求"); - assert_eq!(history.unread,1); - assert_eq!(history.entries.len(),2); - assert_eq!(AgentNotifications::default().unread,0,"a different account starts with its own history"); - } - - #[test] - fn settings_footer_remains_visible_in_small_viewports_with_key_editor_open() { - for (width, height, scale) in [(960.0, 720.0, 1.0), (1100.0, 760.0, 1.25), (960.0, 720.0, 1.5)] { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - ctx.set_pixels_per_point(scale); - let (mut app, _) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.model_settings = true; - w.key_settings = true; - for time in [0.0, 0.2, 0.6, 1.0, 1.4] { - let mut frame = ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width, height))), - time: Some(time), ..Default::default() - }, |ui| crate::panels::right_dock(&mut app, ui)); - frame.textures_delta.clear(); - } - let w = app.jiansun.as_ref().unwrap(); - let body = geometry(w, "settingsBody"); - assert!(Rect::from_min_size(egui::Pos2::ZERO, vec2(width, height)).contains_rect(body)); - assert!(w.panel_geometry.get("reduceMotion").is_none()); - } - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn settings_glass_keeps_opaque_fallback_inside_paired_markers_on_popup_entry() { - use eframe::egui_wgpu::BackdropMarker; - let ctx = egui::Context::default(); - let mut open = true; - let mut result = None; - // Popup's first pass measures its position without painting. - for _ in 0..2 { - let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| { - let anchor = ui.button("settings"); - egui::Popup::from_response(&anchor).frame(egui::Frame::NONE).open_bool(&mut open).show(|ui| { - let frame = super::super::stitch_ui::surface_frame(ui.ctx(), super::super::stitch_ui::SurfaceRole::Dialog); - show_settings_glass(ui, frame, Color32::from_rgb(38, 39, 43), 1.0, 1.0, |ui| { ui.label("settings"); }); - }); - }); - output.textures_delta.clear(); - result = Some(ctx.tessellate(output.shapes, output.pixels_per_point)); - } - let jobs = result.unwrap(); - let markers: Vec<_> = jobs.iter().enumerate().filter_map(|(index, job)| { - let egui::epaint::Primitive::Callback(callback) = &job.primitive else { return None }; - callback.callback.downcast_ref::().map(|marker| (index, marker, callback.rect)) - }).collect(); - assert_eq!(markers.len(), 2); - assert!(markers[0].1.blur_radius_points > 0.0); - assert_eq!(markers[1].1.blur_radius_points, 0.0); - assert_eq!(markers[0].2, markers[1].2); - assert_eq!(markers[1].0, markers[0].0 + 2); - let egui::epaint::Primitive::Mesh(fallback) = &jobs[markers[0].0 + 1].primitive else { panic!("missing fallback mesh") }; - assert!(fallback.vertices.iter().any(|vertex| vertex.color.a() == 255)); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn settings_glass_fallback_fades_with_the_retiring_panel() { - use eframe::egui_wgpu::BackdropMarker; - for opacity in [1.0_f32, 0.5, 0.1, 0.0] { - let ctx = egui::Context::default(); - let output = ctx.settle_ui(egui::RawInput::default(), |ui| { - let frame = super::super::stitch_ui::overlay_frame(ui.ctx(), super::super::stitch_ui::SurfaceRole::Dialog, opacity); - show_settings_glass(ui, frame, Color32::from_rgb(38, 39, 43), opacity, 0.12 + opacity * 0.88, |ui| { ui.label("settings"); }); - }); - let jobs = ctx.tessellate(output.shapes, output.pixels_per_point); - let markers: Vec<_> = jobs.iter().enumerate().filter_map(|(index, job)| { - let egui::epaint::Primitive::Callback(callback) = &job.primitive else { return None }; - callback.callback.downcast_ref::().map(|_| index) - }).collect(); - assert_eq!(markers.len(), 2); - let alpha = jobs[markers[0] + 1..markers[1]].iter().filter_map(|job| { - let egui::epaint::Primitive::Mesh(mesh) = &job.primitive else { return None }; - mesh.vertices.iter().map(|vertex| vertex.color.a()).max() - }).max().unwrap_or(0); - assert!(alpha <= (opacity * 255.0).ceil() as u8, "fallback must follow panel opacity {opacity}"); - if opacity > 0.0 { assert!(alpha > 0); } - } - } - - fn enter_event(modifiers: egui::Modifiers, repeat: bool) -> egui::Event { - egui::Event::Key { key: egui::Key::Enter, physical_key: Some(egui::Key::Enter), pressed: true, repeat, modifiers } - } - - fn enter_release() -> egui::Event { - egui::Event::Key { key: egui::Key::Enter, physical_key: Some(egui::Key::Enter), pressed: false, repeat: false, modifiers: egui::Modifiers::NONE } - } - - fn input_frame(ctx: &egui::Context, text: &mut String, events: Vec) -> bool { - let mut submit = false; - let _ = ctx.settle_ui(egui::RawInput { events, ..Default::default() }, |ui| { - let id = Id::unique("keyboard-acceptance"); - ui.memory_mut(|memory| memory.request_focus(id)); - submit = composer_enter(ui, id); - ui.add(egui::TextEdit::multiline(text).id(id).return_key(egui::KeyboardShortcut::new(egui::Modifiers::SHIFT, egui::Key::Enter))); - }); - submit - } - - #[test] - fn enter_submits_once_and_shift_enter_keeps_a_real_newline() { - let ctx = egui::Context::default(); - let mut text = "调整灯光".to_owned(); - input_frame(&ctx, &mut text, vec![]); - assert!(input_frame(&ctx, &mut text, vec![enter_event(egui::Modifiers::NONE, false)])); - assert!(!text.contains('\n')); - assert!(!input_frame(&ctx, &mut text, vec![enter_event(egui::Modifiers::NONE, true)])); - input_frame(&ctx, &mut text, vec![enter_release()]); - assert!(!input_frame(&ctx, &mut text, vec![enter_event(egui::Modifiers::SHIFT, false)])); - assert!(text.contains('\n')); - } - - #[test] - fn ime_preedit_commit_and_delayed_confirmation_never_submit() { - let ctx = egui::Context::default(); - let mut text = String::new(); - input_frame(&ctx, &mut text, vec![]); - assert!(!input_frame( - &ctx, - &mut text, - vec![egui::Event::Ime(egui::ImeEvent::Preedit { text: "deng".into(), active_range_chars: None }), enter_event(egui::Modifiers::NONE, false)] - )); - assert!(!input_frame(&ctx, &mut text, vec![egui::Event::Ime(egui::ImeEvent::Commit("灯".into())), enter_event(egui::Modifiers::NONE, false)])); - assert!(!input_frame(&ctx, &mut text, vec![enter_event(egui::Modifiers::NONE, false)])); - input_frame(&ctx, &mut text, vec![enter_release()]); - input_frame(&ctx, &mut text, vec![]); - assert!(input_frame(&ctx, &mut text, vec![enter_event(egui::Modifiers::CTRL, false)])); - assert!(text.contains('灯')); - } - - #[test] - fn shared_project_turns_keep_the_original_target_after_later_selection() { - let messages = vec![ - json!({"role":"user","text":"改首屏","target":{"kind":"slot","slotId":"first"}}), - json!({"role":"assistant","kind":"reply","text":"好的","target":{"kind":"slot","slotId":"first"}}), - json!({"role":"user","text":"再看第二屏","target":{"kind":"slot","slotId":"second"}}), - ]; - let grouped = turns(&messages); - assert_eq!(grouped.len(), 2); - assert_eq!(grouped[0].target.unwrap()["slotId"], "first"); - assert_eq!(grouped[1].target.unwrap()["slotId"], "second"); - assert_eq!(subject_label(&json!({"kind":"selection","selectedLayerIds":[1,2,3]}), &Value::Null), "已选 3 个对象"); - } - - #[test] - fn grouped_image_results_keep_their_individual_slot_and_color_targets() { - let messages = vec![ - json!({"role":"user","text":"看看结果"}), - json!({"role":"assistant","kind":"image","taskId":"task-a","slotId":"slot-a","productVariantId":"teak","outputId":"detail"}), - json!({"role":"assistant","kind":"image","taskId":"task-b","slotId":"slot-b","productVariantId":"walnut","outputId":"detail"}), - ]; - let grouped = turns(&messages); - assert_eq!(grouped.len(), 1); - let images: Vec<_> = grouped[0].images().collect(); - assert_eq!(images.len(), 2); - let first = image_location(images[0], "task-a"); - let second = image_location(images[1], "task-b"); - assert_eq!((first["slotId"].as_str(), first["productVariantId"].as_str(), first["candidateId"].as_str()), (Some("slot-a"), Some("teak"), Some("task-a"))); - assert_eq!((second["slotId"].as_str(), second["productVariantId"].as_str(), second["candidateId"].as_str()), (Some("slot-b"), Some("walnut"), Some("task-b"))); - } - - #[test] - fn assistant_reply_is_unframed_and_wraps_while_user_keeps_a_bubble() { - fn scan(shape: &egui::Shape, user_surface: &mut bool, old_assistant_surface: &mut bool, reply_rows: &mut usize, text: &str) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| scan(shape, user_surface, old_assistant_surface, reply_rows, text)), - egui::Shape::Rect(rect) if rect.corner_radius.nw >= 12 && rect.rect.width() < 150.0 && rect.fill.a() == 255 => *user_surface = true, - egui::Shape::Rect(rect) if rect.fill == Color32::from_rgb(40, 42, 46) => *old_assistant_surface = true, - egui::Shape::Text(shape) if shape.galley.text() == text => *reply_rows = shape.galley.rows.len(), - _ => {} - } - } - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let reply = "保持产品结构和真实花色,让首屏的自然光更柔和,并继续保留文字和其他可编辑图层。"; - let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(240.0, 600.0))), ..Default::default() }, |ui| { - ui.set_width(200.0); - user_bubble(ui, "你好"); - assistant_reply(ui, Id::unique("assistant-reply-test"), reply); - }); - let (mut user_surface, mut old_assistant_surface, mut reply_rows) = (false, false, 0); - for shape in &output.shapes { scan(&shape.shape, &mut user_surface, &mut old_assistant_surface, &mut reply_rows, reply); } - assert!(user_surface, "the user message retains its bubble"); - assert!(!old_assistant_surface, "the assistant reply has no full-width solid card"); - assert!(reply_rows > 1, "a long Chinese reply wraps in the available width"); - } - - #[test] - fn sent_reference_paints_the_recorded_image_without_a_card() { - let (mut app, _) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let w = app.jiansun.as_mut().unwrap(); - w.composer.clear(); - let texture = ctx.load_texture("frozen-reference", egui::ColorImage::filled([8, 5], Color32::WHITE), egui::TextureOptions::LINEAR); - let id = texture.id(); - w.agent_images.insert("ref-frozen".into(), texture); - let message = json!({"role":"user","text":"图里有什么?", - "requestScope":{"references":[{"kind":"layer","label":"主图"}]}, - "referenceContent":[{"imageId":"ref-frozen"}]}); - let frame = || ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(260.0, 360.0))), - ..Default::default() - }, |ui| { w.sent_references(ui, &message); }); - frame().drop_without_applying_deltas(); - let mut output = frame(); - let has_frame = output.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(rect) - if rect.brush.is_none() && rect.rect.width() <= 150.0 - && (rect.fill != Color32::TRANSPARENT || rect.stroke != Stroke::NONE))); - let shown = ctx.tessellate(std::mem::take(&mut output.shapes), output.pixels_per_point).iter() - .any(|shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id)); - output.drop_without_applying_deltas(); - assert!(shown); - assert!(!has_frame); - } - - #[test] - fn sent_user_text_reveals_in_order_without_resizing_the_bubble() { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&ctx); - let mut bounds = Vec::new(); - for time in [0.0, 0.2, 0.5, 1.0] { - let _ = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { - ui.set_width(240.0); - bounds.push(user_bubble_with_reveal(ui, "保留产品结构,让光线更加柔和。", Some(0.0), false)); - }); - } - assert!(bounds.windows(2).all(|pair| pair[0] == pair[1])); - let arrivals=super::super::typing_text::staggered("保留产品结构,让光线更加柔和。",0.0); - assert!(arrivals[0]=0.220)); - } - - #[test] - fn user_bubble_fits_shaped_chinese_text_and_respects_available_width() { - for width in [200.0, 300.0, 420.0] { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&ctx); - let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width + 20.0, 600.0))), ..Default::default() }, |ui| { - ui.set_width(width); - let right = ui.available_rect_before_wrap().right(); - let short = user_bubble(ui, "你好"); - let long = user_bubble(ui, "请保持产品原有结构与材质,让这一屏的自然光更柔和,并保留桌面和支架的真实比例。"); - assert!(short.width() < width * 0.55, "short messages must not stretch across the panel: {short:?}"); - assert!(long.width() <= width - 21.0, "long messages wrap without overflowing: {long:?}"); - assert!(long.height() > short.height(), "long Chinese text wraps inside the bubble"); - assert!((short.right() - right).abs() < 1.0 && (long.right() - right).abs() < 1.0, "both messages align to the right edge"); - }); - } - } - - fn only_layers(app: &mut PhotocraftApp) { - app.ui.panels.color = false; - app.ui.panels.properties = false; - app.ui.panels.history = false; - app.ui.panels.navigator = false; - app.ui.panels.brushes = false; - app.ui.panels.layers = true; - app.ui.panels.rail = false; - } - - fn dock_fixture() -> (PhotocraftApp, mpsc::Receiver) { - dock_fixture_with_size(3600) - } - - fn dock_fixture_with_size(height: u32) -> (PhotocraftApp, mpsc::Receiver) { - let (tx, requests) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - while requests.try_recv().is_ok() {} - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width":1440,"height":height,"name":"小壹 · 本地界面验收"})).unwrap(); - let services = crate::Services { - import: Some(Box::new(|name, bytes, depth| { - photocraft_io::import_with_options(name, bytes, depth).map(|r| (r.document, r.warnings)).map_err(|error| error.to_string()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(session, services); - app.sync_views(); - only_layers(&mut app); - app.ui.panels.color = true; - app.ui.panels.properties = true; - app.ui.dock_tabs.color = 0; - w.busy = None; - w.account = json!({"id":"local-ui-fixture"}); - w.library = false; - w.key_saved = true; - w.model_ready = true; - w.image_ready = true; - w.model = "discussion".into(); - w.models = vec![json!({"key":"discussion","id":"对话模型"})]; - w.image_model = "image".into(); - w.image_models = vec![json!({"key":"image","id":"生图模型"})]; - w.loaded_draft = app.session.active().map(|state| state.doc.id.0); - w.composer = "保持木纹与结构,调整这张图的光线。".into(); - w.messages = vec![ - json!({"role":"user","text":"这一屏的光线柔和一点,保留产品原有结构。"}), - json!({"role":"assistant","kind":"reply","text":"可以。先保留当前版本,我会针对选中的图位提供候选;采纳后再替换画布中的图片。"}), - ]; - w.composer_reference_add(&app).unwrap(); - app.jiansun = Some(w); - (app, requests) - } - - #[test] - #[ignore="GPU production composer and image card; writes to PHOTOCRAFT_AGENT_QA_OUT"] - fn gpu_glow_pill_production_surfaces() { - let _guard=photocraft_testkit::gpu_lock(); - struct Preview {app:PhotocraftApp,elapsed:f64} - impl eframe::App for Preview { - fn ui(&mut self,ui:&mut Ui,_:&mut eframe::Frame) { - ui.set_width(500.0); - let mut w=self.app.jiansun.take().unwrap(); - w.panel_geometry["panel"]=json!([0,0,520,640]);w.panel_geometry["composerMorph"]=json!(1.0); - let now=ui.input(|input|input.time); - let identity=Id::unique(("jiansun-result-waiting",&w.origin,w.account["id"].as_str(),w.owner_doc,w.messages.iter().rposition(|message|message["role"]=="user"))); - ui.ctx().data_mut(|data|{ - data.insert_temp(Id::unique("composer-sent-glow"),now-self.elapsed); - data.insert_temp(Id::unique("glow-pill-image-clock"),(identity,now-(self.elapsed+0.36),self.elapsed+0.36)); - }); - w.processing_card_ui(&self.app,ui);ui.add_space(30.0);w.composer_ui(&mut self.app,ui); - self.app.jiansun=Some(w); - } - } - let (mut app,requests)=dock_fixture();app.jiansun.as_mut().unwrap().busy=Some("image".into()); - let mut h=egui_kittest::Harness::builder().with_size(vec2(530.0,420.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_eframe(move|cc|{ - PhotocraftApp::setup_context(&cc.egui_ctx,crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); - app.gpu_render_state=cc.wgpu_render_state.clone();Preview {app,elapsed:1.0} - }); - let directory=std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - h.run_steps(4); - for (name,elapsed) in [("rest",1.0),("rise",0.14),("peak",0.28),("settle",0.52)] { - h.state_mut().elapsed=elapsed; - h.run_steps(1);h.render().unwrap().save(directory.join(format!("surfaces-{name}.png"))).unwrap(); - } - let w=h.state().app.jiansun.as_ref().unwrap(); - assert_eq!(w.panel_geometry["processingIdentity"],"siri-orb"); - assert_eq!(w.composer,"保持木纹与结构,调整这张图的光线。"); - h.state_mut().app.jiansun.as_mut().unwrap().reduce_motion=true; - h.run_steps(4);h.render().unwrap().save(directory.join("surfaces-reduced.png")).unwrap(); - assert!(requests.try_recv().is_err(),"rendering dispatches no generation or canvas edit"); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - #[ignore="Production task and composer motion; writes to PHOTOCRAFT_AGENT_QA_OUT"] - fn gpu_glow_workspace_task_lifecycle() { - let _guard=photocraft_testkit::gpu_lock(); - struct Preview {app:PhotocraftApp} - impl eframe::App for Preview { - fn ui(&mut self,ui:&mut Ui,_:&mut eframe::Frame) { - ui.set_width(480.0); - let mut workspace=self.app.jiansun.take().unwrap(); - workspace.panel_geometry=json!({"panel":[0,0,500,700],"composerMorph":1.0}); - workspace.processing_card_ui(&self.app,ui); - ui.add_space(30.0); - workspace.composer_ui(&mut self.app,ui); - self.app.jiansun=Some(workspace); - } - } - let (mut app,requests)=dock_fixture(); - app.jiansun.as_mut().unwrap().busy=Some("image".into()); - let mut h=egui_kittest::Harness::builder().with_size(vec2(510.0,600.0)).with_step_dt(1.0/30.0).wgpu().build_eframe(move|cc| { - PhotocraftApp::setup_context(&cc.egui_ctx,crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); - app.gpu_render_state=cc.wgpu_render_state.clone(); - Preview {app} - }); - let directory=std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - for index in 0..72 { - if index==30 {h.state_mut().app.jiansun.as_mut().unwrap().agent_effects_paused=true;} - if index==50 {h.state_mut().app.jiansun.as_mut().unwrap().busy=None;} - h.run_steps(1); - h.render().unwrap().save(directory.join(format!("lifecycle-{index:03}.png"))).unwrap(); - let workspace=h.state().app.jiansun.as_ref().unwrap(); - if index==24 {assert_eq!(workspace.panel_geometry["processingLightMode"],"glow-pill");} - if index==44 {assert_eq!(workspace.panel_geometry["processingLightMode"],"paused");} - if index==71 {assert!(workspace.panel_geometry["processing"].is_null());} - assert_eq!(workspace.panel_geometry["composerLightMode"],"glow-pill"); - assert_eq!(workspace.composer,"保持木纹与结构,调整这张图的光线。"); - } - assert!(requests.try_recv().is_err()); - } - - fn geometry(w: &Workspace, name: &str) -> Rect { - let value = &w.panel_geometry[name]; - let a = value.as_array().or_else(|| value["rect"].as_array()) - .unwrap_or_else(|| panic!("missing panel geometry for {name}: {value}")); - Rect::from_min_size( - pos2(a[0].as_f64().unwrap() as f32, a[1].as_f64().unwrap() as f32), - vec2(a[2].as_f64().unwrap() as f32, a[3].as_f64().unwrap() as f32), - ) - } - - fn dock_frame(ctx: &egui::Context, app: &mut PhotocraftApp, events: Vec) { - let mut output = ctx - .run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), events, ..Default::default() }, |ui| { - crate::panels::right_dock(app, ui) - }); - output.textures_delta.clear(); - } - - #[test] - fn production_hides_suggestions_and_followups_fill_without_sending() { - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.composer = "保留我的草稿".into(); - w.busy = Some("slot-apply-save".into()); - w.product_start_queued = true; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - dock_frame(&ctx, &mut app, vec![]); - let w = app.jiansun.as_mut().unwrap(); - assert!(w.panel_geometry["quickPrompts"].is_null(), "suggestions yield while a whole set is produced"); - assert!(w.panel_geometry["followupPrompts"].is_null()); - assert!(w.panel_geometry["taskStop"].is_array()); - assert!(w.panel_geometry["stop"].is_null()); - - w.busy = None; - w.product_start_queued = false; - w.messages.push(json!({"role":"assistant","kind":"reply","text":"已导出 2/3 份。", - "productionSummary":{"exported":2,"total":3}})); - for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } - let geometry = &app.jiansun.as_ref().unwrap().panel_geometry["followupPrompts"][0]; - assert_eq!(geometry["label"], "查看未完成项"); - let rect = geometry["rect"].as_array().unwrap(); - let value = |index: usize| rect[index].as_f64().unwrap() as f32; - let pos = pos2(value(0) + value(2) / 2.0, value(1) + value(3) / 2.0); - for pressed in [true, false] { - dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(pos), egui::Event::PointerButton { - pos,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE - }]); - } - let w = app.jiansun.as_ref().unwrap(); - assert!(w.composer.starts_with("保留我的草稿\n请梳理这轮未完成的文案")); - assert!(w.busy.is_none()); - assert!(!requests.try_iter().any(|request| matches!(request, Request::Action(method, _) if method == "agent" || method == "image"))); - } - - fn production_quick_actions_fixture() -> (PhotocraftApp, mpsc::Receiver) { - let (mut app, requests) = dock_fixture(); - let document = app.session.active().unwrap().doc.id.0; - let workspace = app.jiansun.as_mut().unwrap(); - workspace.open_projects.insert(document, workspace.local_identity("production-quick-actions")); - workspace.reduce_motion = true; - workspace.composer = "保留现有草稿".into(); - workspace.template_workflow = json!({"canvasFirst":true,"outputId":"detail"}); - workspace.messages.push(json!({"role":"assistant","kind":"reply","text":"本轮已完成 2 份输出,还有 1 份待制作。", - "productionSummary":{"exported":2,"total":3}})); - (app, requests) - } - - #[test] - fn production_quick_action_requires_stages_and_checkpoints_before_resuming() { - use egui_kittest::{Harness, kittest::Queryable}; - for width in [250.0, 360.0, 420.0] { - let (app, requests) = production_quick_actions_fixture(); - let mut harness = Harness::builder() - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .with_size(vec2(width, 520.0)) - .build_ui_state(|ui, app| { - if super::super::stitch_ui::ui_fonts_ready(ui) { super::super::agent_dock(app, ui); } - }, app); - PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); - harness.run_steps(5); - let workspace = harness.state().jiansun.as_ref().unwrap(); - assert_eq!(workspace.panel_geometry["followupPrompts"][0]["label"], "查看未完成项"); - assert!(harness.query_by_label("还有输出待完成").is_some()); - assert!(harness.query_by_label(CONTINUE_PRODUCTION).is_none()); - harness.state_mut().jiansun.as_mut().unwrap().template_workflow["productionStages"] = - json!([{"outputId":"detail","variantId":"wood"}]); - harness.run_steps(2); - let workspace = harness.state().jiansun.as_ref().unwrap(); - let prompts = workspace.panel_geometry["followupPrompts"].as_array().unwrap(); - let labels = [CONTINUE_PRODUCTION, "查看未完成项", "核对已有结果"]; - let composer_top = workspace.panel_geometry["composer"][1].as_f64().unwrap() as f32; - let first = harness.get_by_label(CONTINUE_PRODUCTION).rect(); - let mut previous = None::; - for (index, label) in labels.into_iter().enumerate() { - assert_eq!(prompts[index]["label"], label); - let accessible_label = if index == 0 { label.to_owned() } else { format!("填入输入框:{label}") }; - let rect = harness.get_by_label(&accessible_label).rect(); - assert!(rect.left() >= 0.0 && rect.right() <= width && rect.bottom() < composer_top, "{label} at {width}pt: {rect:?}"); - assert!((rect.center().y - first.center().y).abs() <= 1.0, "{label} wrapped at {width}pt: {first:?}, {rect:?}; {prompts:?}"); - assert!(previous.is_none_or(|prev| prev.right() <= rect.left())); - previous = Some(rect); - } - requests.try_iter().for_each(drop); - - harness.get_by_label("填入输入框:核对已有结果").click(); - harness.run_steps(2); - let draft = harness.state().jiansun.as_ref().unwrap().composer.clone(); - assert!(draft.contains("请检查目前已保留的文案和配图")); - assert!(!requests.try_iter().any(|request| matches!(request, Request::Action(method, _) if method == "agent" || method == "image"))); - - harness.get_by_label(CONTINUE_PRODUCTION).click(); - harness.run_steps(2); - let workspace = harness.state().jiansun.as_ref().unwrap(); - assert_eq!(workspace.pending_slot_apply.as_ref().unwrap()["resumeProduct"], true); - let queued: Vec<_> = requests.try_iter().collect(); - assert!(queued.iter().any(|request| matches!(request, Request::Save(..)))); - assert!(!queued.iter().any(|request| matches!(request, Request::Action(method, _) if method == "agent"))); - assert_eq!(harness.state().jiansun.as_ref().unwrap().composer, draft); - } - } - - fn live_production_fixture() -> (PhotocraftApp, mpsc::Receiver) { - live_production_fixture_with_size(3600) - } - - fn live_production_fixture_with_size(height: u32) -> (PhotocraftApp, mpsc::Receiver) { - let (mut app, requests) = dock_fixture_with_size(height); - let w = app.jiansun.as_mut().unwrap(); - w.composer.clear(); - w.pi_run = Some("offline-production".into()); - w.busy = Some("pi-agent".into()); - w.pi_product_production = true; - w.template_workflow = json!({"canvasFirst":true,"outputId":"detail","slots":[ - {"id":"hero","outputId":"detail","label":"首屏产品场景","frame":{"width":1440,"height":1800}}, - {"id":"scene","outputId":"detail","label":"空间搭配","frame":{"width":1600,"height":1200}} - ]}); - w.workflow.set_production_progress(&json!({ - "heading":"正在制作详情页","outputId":"detail","rendered":1,"total":3, - "pictureCells":[{"slotId":"hero","label":"首屏产品场景"},{"slotId":"scene","label":"空间搭配"}, - {"slotId":"finish","label":"材质细节","state":"verified"}], - "copyCells":[{"state":"verified"},{"state":"filled"},{}], - "workers":[{"number":1,"slotId":"hero","label":"首屏产品场景","step":"正在生图","active":true}, - {"slotId":"scene","label":"空间搭配","step":"生成","active":true}], - })); - let tool = |call: &str, name: &str, status: &str| json!({"role":"assistant","kind":"activity","text":"工具活动", - "event":{"version":1,"type":"tool","run":"offline-production","toolCallId":call,"toolName":name,"status":status,"durationMs":320}}); - w.messages = vec![ - json!({"role":"user","text":"制作详情、主图和 SKU 图。"}), - json!({"role":"assistant","kind":"thinking","active":false}), - json!({"role":"assistant","kind":"thinking","active":false}), - tool("read","canvas_read","started"), - tool("read","canvas_read","completed"), - tool("edit","canvas_edit","started"), - json!({"role":"assistant","kind":"image-job","taskId":"hero-job","run":"offline-production","workerNumber":1, - "slotLabel":"首屏产品场景","width":1440,"height":1800,"target":{"slotId":"hero","outputId":"detail"}}), - ]; - (app, requests) - } - - #[test] - fn production_projection_shares_worker_identity_and_yields_to_the_current_receipt() { - let (mut app, requests) = live_production_fixture(); - let w = app.jiansun.as_mut().unwrap(); - let before = w.messages.clone(); - let jobs = w.projected_worker_jobs(); - assert_eq!(jobs.len(), 1); - assert_eq!(jobs[0]["workerNumber"], 2); - assert_eq!(frame_image_ratio(&jobs[0]), Some(4.0 / 3.0)); - assert_eq!(w.messages, before); - assert!(requests.try_recv().is_err()); - let turn = turns(&w.messages).pop().unwrap(); - assert_eq!(turn.items.iter().filter(|row| matches!(row, TurnItem::Thinking(..))).count(), 1); - assert!(turn.items.iter().any(|row| matches!(row, TurnItem::Tools(rows) if rows.len() == 2))); - - w.messages.push(json!({"role":"assistant","kind":"image-job","taskId":"scene-job","run":"offline-production", - "target":{"slotId":"scene","outputId":"detail"}})); - assert!(w.projected_worker_jobs().is_empty()); - let mut progress = w.workflow.production_progress().clone(); - progress["reviews"] = json!([{"number":27,"active":true,"label":"木纹细节","step":"正在验图"}]); - w.workflow.set_production_progress(&progress); - let shown = w.production_workers(); - assert_eq!(shown.iter().map(|w| (w.number, w.stage)).collect::>(), - [(1, WorkerStage::Generating), (2, WorkerStage::Generating), (27, WorkerStage::Reviewing)]); - } - - #[test] - fn appended_tool_completion_changes_only_its_own_cached_item() { - let tool = |call: &str, status: &str| json!({"role":"assistant","kind":"activity", - "event":{"version":1,"type":"tool","run":"test","toolCallId":call,"toolName":"canvas_read","status":status}}); - let mut messages = vec![ - tool("earlier", "started"), - json!({"role":"assistant","kind":"activity","text":"画布已读取"}), - tool("later", "completed"), - json!({"role":"assistant","kind":"thinking","active":true}), - json!({"role":"assistant","kind":"copywriting-fields","optionsId":"copy","items":[{"applied":false}]}), - ]; - let layouts: Vec<_> = turns(&messages)[0].items.iter().map(|item| - (item.message_index(), TurnItemContent::capture(item, &messages))).collect(); - - messages.push(tool("earlier", "completed")); - messages[3]["active"] = json!(false); - messages[4]["items"][0]["applied"] = json!(true); - let transcript = turns(&messages); - let items = &transcript[0].items; - assert_eq!(items.len(), layouts.len()); - let unchanged: Vec<_> = items.iter().zip(&layouts).map(|(item, (index, content))| { - assert_eq!(item.message_index(), *index); - content.matches(item, &messages) - }).collect(); - assert_eq!(unchanged, [false, true, true, false, false]); - } - - #[test] - #[ignore = "600-frame offline production benchmark"] - fn long_conversation_frame_budget() { - use std::time::Instant; - - let (mut app, _requests) = live_production_fixture_with_size(34_838); - for index in 0..267 { - app.session.execute("layer.new.layer", json!({"name":format!("详情图层 {index}")})).unwrap(); - } - let fields = (0..33).map(|index| { - app.session.execute("type.create", json!({"text":format!("原始标题 {}", index + 1), - "x":40,"y":40 + index * 30})).unwrap(); - app.session.active().unwrap().selected_layers()[0].0 - }).collect::>(); - let state = app.session.active_mut().unwrap(); - let doc = Arc::make_mut(&mut state.doc); - let pages = json!([{"documentId":"S01","outputId":"detail","mapping":{"fields":[ - {"kind":"image","slotId":"hero"},{"kind":"image","slotId":"scene"} - ]}}]); - let mapping = json!({"version":1,"canvasFirst":true,"workspaceId":"offline", - "templateId":"chair","templateVersion":"1","templateHash":"offline", - "variantId":"wood","component":"detail","outputs":pages}); - doc.metadata.text.push(("jiansun.slot-mapping.v1".into(), mapping.to_string())); - let w = app.jiansun.as_mut().unwrap(); - for key in ["workspaceId", "templateId", "templateVersion", "templateHash", "variantId"] { - w.template_workflow[key] = mapping[key].clone(); - } - w.template_workflow["outputs"] = pages; - for slot in w.template_workflow["slots"].as_array_mut().unwrap() { - slot["documentId"] = json!("S01"); - slot["variantId"] = json!("wood"); - } - w.owner_doc = Some(doc.id.0); - w.observed_doc = w.owner_doc; - w.pi_binding = json!({"accountId":w.account["id"],"origin":w.origin}); - let mut progress = w.workflow.production_progress().clone(); - progress["pictureCells"] = json!((0..16).map(|i| json!({"slotId":format!("pic-{i}"),"label":format!("图位 {i}"),"state":"verified"})).collect::>()); - progress["copyCells"] = json!(vec![json!({"state":"filled"}); 33]); - w.workflow.set_production_progress(&progress); - // Match the production transcript: one start, then many tool and result rows in - // the same active turn. All message bodies and textures are offline fixtures. - let active_turn = std::mem::take(&mut w.messages); - w.messages.push(json!({"role":"user","text":"开始制作这把椅子的整套详情页。"})); - for index in 0..87 { - if index < 47 { - w.messages.push(json!({"role":"assistant","kind":"thinking","active":false})); - } - for call in 0..(6 + usize::from(index < 63)) { - w.messages.push(json!({"role":"assistant","kind":"activity","event":{ - "version":1,"type":"tool","run":"offline-history","toolCallId":format!("tool-{index}-{call}"), - "toolName":"canvas_read","status":"completed","durationMs":320 - }})); - } - w.messages.push(json!({"role":"assistant","kind":"activity","text":format!("第 {} 组已核对画布,保留结构、木纹和现有文字布局。", index + 1)})); - if index < 41 { - for variant in 0..(3 + usize::from(index == 0)) { - w.messages.push(json!({"role":"assistant","kind":"image","taskId":format!("candidate-{}", 3 * index + variant + usize::from(index > 0)), - "width":1440,"height":1800})); - } - } - if index % 13 == 0 { - w.messages.push(json!({"role":"assistant","kind":"reply", - "text":"候选图已生成。保留当前画布,确认光线和细节后可以采纳这张图。".repeat(12)})); - } - } - w.messages.push(json!({"role":"assistant","kind":"copywriting-fields","optionsId":"copy-33", - "items":fields.into_iter().enumerate().map(|(index, layer)| json!({"layer":layer,"name":format!("文案 {}",index+1), - "field":{"fieldId":format!("S01-T{index:02}"),"label":"标题","maxChars":16,"maxLines":1}, - "original":format!("原始标题 {}",index+1),"text":"自然木纹餐椅","applied":false})).collect::>(),"target":{}})); - w.messages.extend(active_turn.into_iter().filter(|message| message["role"] != "user")); - assert_eq!(turns(&w.messages).len(), 1); - let screenshots = std::env::var_os("PHOTOCRAFT_LONG_CONVERSATION_QA_OUT").map(std::path::PathBuf::from); - let full_transcript = std::env::var_os("PHOTOCRAFT_BENCH_FULL_TRANSCRIPT").is_some(); - let append = std::env::var_os("PHOTOCRAFT_BENCH_APPEND").is_some(); - let reset_on_append = std::env::var_os("PHOTOCRAFT_BENCH_RESET_ON_APPEND").is_some(); - let _gpu = screenshots.as_ref().map(|_| photocraft_testkit::gpu_lock()); - let builder = egui_kittest::Harness::builder() - .with_size(vec2(1440.0, 900.0)).with_max_steps(4); - let builder = if screenshots.is_some() { builder.wgpu() } else { builder }; - let builder = if append { builder.with_step_dt(1.0 / 60.0) } else { builder }; - let mut harness = builder.build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); - cc.egui_ctx.data_mut(|data| { - data.insert_temp(Id::unique("benchmark-full-transcript"), full_transcript); - data.insert_temp(Id::unique("benchmark-reset-on-append"), reset_on_append); - }); - let workspace = app.jiansun.as_mut().unwrap(); - workspace.pi_touched = Instant::now(); - let images = &mut workspace.agent_images; - for index in 64..124 { - let id = format!("candidate-{index}"); - let image = egui::ColorImage::filled([96, 120], Color32::from_rgb((index - 64) * 3, 92, 52)); - images.insert(id.clone(), cc.egui_ctx.load_texture(id, image, egui::TextureOptions::LINEAR)); - } - app - }); - harness.run_steps(24); - let app = harness.state_mut(); - let panel = &app.jiansun.as_ref().unwrap().panel_geometry; - assert_eq!(panel["open"], true); - assert!(panel["productionProgress"].is_array(), "{panel}"); - let point = geometry(app.jiansun.as_ref().unwrap(), "conversationClip").center(); - app.slow_frames.set_threshold_ms(0.0); - let tool_message = |index| json!({"role":"assistant","kind":"activity","event":{ - "version":1,"type":"tool","run":"offline-production", - "toolCallId":format!("append-{index}"),"toolName":"canvas_read", - "status":"completed","durationMs":320 - }}); - if screenshots.is_some() && append { - let w = app.jiansun.as_mut().unwrap(); - w.messages.extend((0..19).map(tool_message)); - harness.run_steps(24); - } - let panel_offset = harness.state().jiansun.as_ref().unwrap().panel_geometry["conversationScrollOffset"].as_f64().unwrap(); - let scroll = |harness: &mut egui_kittest::Harness<'_, PhotocraftApp>, delta| { - harness.event(egui::Event::PointerMoved(point)); - harness.event(egui::Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, - phase: egui::TouchPhase::Move, - unit: egui::MouseWheelUnit::Point, - delta: vec2(0.0, delta), - modifiers: egui::Modifiers::NONE, - }); - harness.step(); - harness.event(egui::Event::PointerGone); - harness.step(); - harness.run_steps(24); - }; - if let Some(directory) = screenshots { - std::fs::create_dir_all(&directory).unwrap(); - for (name, delta) in [("bottom", 0.0), ("middle", (panel_offset / 2.0) as f32), ("top", panel_offset as f32)] { - if delta != 0.0 { - scroll(&mut harness, delta); - } - harness.render().unwrap().save(directory.join(format!("{name}.png"))).unwrap(); - } - return; - } - - if append { - scroll(&mut harness, (panel_offset / 2.0) as f32); - assert!(harness.state().jiansun.as_ref().unwrap().panel_geometry["conversationBottomGap"].as_f64().unwrap() > 480.0); - } - - #[cfg(target_os = "windows")] - let thread_cpu_ticks = || { - let (_, _, kernel, user) = winsafe::HTHREAD::GetCurrentThread().GetThreadTimes().unwrap(); - u64::from(kernel) + u64::from(user) - }; - #[cfg(target_os = "windows")] - let cpu_start = (Instant::now(), thread_cpu_ticks()); - - let mut samples = Vec::with_capacity(600); - let mut total = 0.0; - let mut regions = [0.0; 6]; - let session_start = Instant::now(); - let mut next_append = Duration::from_secs(3); - let mut appended = 0; - let mut append_frames = Vec::new(); - while if append { session_start.elapsed() < Duration::from_secs(60) } else { samples.len() < 600 } { - let w = harness.state_mut().jiansun.as_mut().unwrap(); - w.pi_touched = Instant::now(); - let added = append && next_append < Duration::from_secs(60) && session_start.elapsed() >= next_append; - if added { - w.messages.push(tool_message(appended)); - appended += 1; - next_append += Duration::from_secs(3); - } - let started = Instant::now(); - harness.step(); - let elapsed = started.elapsed().as_secs_f64() * 1000.0; - samples.push(elapsed); - if added { - append_frames.push(elapsed); - assert!(harness.state().jiansun.as_ref().unwrap().panel_geometry["conversationBottomGap"].as_f64().unwrap() > 480.0); - } - let frame = harness.state().slow_frames.frames().next_back().unwrap(); - let ui = &frame.ui_regions; - total += frame.frame_ms; - for (sum, time) in regions.iter_mut().zip([ - ui.conversation, ui.production_head, ui.composer, ui.dock_panels, ui.canvas_overlays, ui.menu_status, - ]) { - *sum += time; - } - if append { - std::thread::sleep(Duration::from_secs_f64(1.0 / 60.0).saturating_sub(started.elapsed())); - } - } - if append { - assert_eq!(appended, 19); - append_frames.sort_unstable_by(f64::total_cmp); - eprintln!("{appended} appends: first-frame median {:.2} ms, max {:.2} ms", - append_frames[appended / 2], append_frames[appended - 1]); - } - #[cfg(target_os = "windows")] - { - let cpu_ms = (thread_cpu_ticks() - cpu_start.1) as f64 / 10_000.0; - let cpu_share = cpu_ms / (cpu_start.0.elapsed().as_secs_f64() * 10.0); - eprintln!("UI thread CPU: {cpu_ms:.1} ms ({cpu_share:.1}% of one core)"); - } - samples.sort_unstable_by(f64::total_cmp); - let frames = samples.len(); - let percentile = |p| samples[(frames * p as usize).div_ceil(100) - 1]; - let (p50, p95, p99, max) = (percentile(50), percentile(95), percentile(99), samples[frames - 1]); - let shares = regions.map(|time| time * 100.0 / total); - eprintln!("{frames} frames: p50 {p50:.2}, p95 {p95:.2}, p99 {p99:.2}, max {max:.2} ms"); - eprintln!("Frames above 33 ms: {}", samples.iter().filter(|&&ms| ms > 33.0).count()); - eprintln!("Percent of frame build (conversation, head, composer, dock, overlays, menu/status): {shares:.1?}"); - assert!(p95 <= 150.0, "long conversation p95 {p95:.2} ms"); - } - - #[test] - #[ignore = "GPU screenshots from the production dock with offline fixtures"] - fn agent_panel_batch2_gpu_evidence() { - use egui_kittest::kittest::Queryable; - let _gpu = photocraft_testkit::gpu_lock(); - let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - std::fs::create_dir_all(&directory).unwrap(); - struct Preview(PhotocraftApp); - impl eframe::App for Preview { - fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { - super::super::agent_dock(&mut self.0, ui); - } - } - for (width, live, name) in [(360.0, true, "agent-panel-live-production-360.png"), - (420.0, false, "agent-panel-settled-420.png")] { - let (mut app, requests) = if live { live_production_fixture() } else { production_quick_actions_fixture() }; - let w = app.jiansun.as_mut().unwrap(); - w.composer.clear(); - if !live { - w.template_workflow["productionStages"] = json!([{"outputId":"sku_images","variantId":"wood"}]); - w.messages = vec![ - json!({"role":"user","text":"继续制作整套"}), - json!({"role":"assistant","kind":"image","taskId":"offline-hero","width":4,"height":5}), - json!({"role":"assistant","kind":"image","taskId":"offline-detail","width":4,"height":5}), - json!({"role":"assistant","kind":"reply","text":"本轮已交付详情页和主图,SKU 图还有一份待完成。", - "productionSummary":{"exported":2,"total":3}}), - ]; - } - let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 760.0)).wgpu().build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); - app.gpu_render_state = cc.wgpu_render_state.clone(); - if !live { - let w = app.jiansun.as_mut().unwrap(); - for (id, color) in [("offline-hero", Color32::from_rgb(120, 101, 84)), - ("offline-detail", Color32::from_rgb(96, 116, 104))] { - let image = egui::ColorImage::filled([48, 60], color); - w.agent_images.insert(id.into(), cc.egui_ctx.load_texture(id, image, Default::default())); - } - } - Preview(app) - }); - harness.run_steps(12); - let w = harness.state().0.jiansun.as_ref().unwrap(); - if live { - assert_eq!(w.production_workers().len(), 2); - assert_eq!(w.panel_geometry["productionImageCells"]["total"], 3); - assert_eq!(w.projected_worker_jobs().len(), 1); - } else { - assert_eq!(w.panel_geometry["followupPrompts"].as_array().unwrap().len(), 3); - assert!(harness.query_by_label("还有输出待完成,可继续制作整套").is_some()); - } - harness.render().unwrap().save(directory.join(name)).unwrap(); - if live { - harness.get_by_label("展开制作详情").click(); - harness.run_steps(24); - harness.get_by_label("首屏产品场景 · 生图中").click(); - harness.run_steps(2); - let w = harness.state().0.jiansun.as_ref().unwrap(); - assert_eq!(w.canvas_workspace.locate_request.as_ref().map(|target| &target["slotId"]), Some(&json!("hero"))); - } - assert!(requests.try_recv().is_err()); - } - } - - #[test] - #[ignore = "offscreen GPU visual evidence"] - fn composer_quick_actions_visual_evidence() { - let _gpu = photocraft_testkit::gpu_lock(); - let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory")); - std::fs::create_dir_all(&directory).unwrap(); - let (mut app, _) = production_quick_actions_fixture(); - app.jiansun.as_mut().unwrap().template_workflow["productionStages"] = - json!([{"outputId":"detail","variantId":"wood"}]); - let mut harness = egui_kittest::Harness::builder() - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .with_size(vec2(360.0, 480.0)).wgpu().build_ui_state(|ui, app| { - if super::super::stitch_ui::ui_fonts_ready(ui) { super::super::agent_dock(app, ui); } - }, app); - PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); - harness.run_steps(6); - harness.render().expect("GPU composer render").save(directory.join("composer-quick-actions.png")).unwrap(); - } - - #[test] - #[ignore = "offline GPU comparison of one image slot before and after its receipt"] - fn image_receipt_replaces_the_placeholder_in_place() { - use egui_kittest::kittest::Queryable; - - let _gpu = photocraft_testkit::gpu_lock(); - let out = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - let (app, requests) = live_production_fixture(); - let task = "hero-job"; - let mut harness = egui_kittest::Harness::builder().with_size(vec2(420.0, 395.0)).wgpu() - .build_ui_state(move |ui, app: &mut PhotocraftApp| { - if !super::super::stitch_ui::ui_fonts_ready(ui) { return; } - Frame::NONE.fill(Tokens::get(ui.ctx()).agent().dock).inner_margin(12).show(ui, |ui| { - let w = app.jiansun.as_ref().unwrap(); - let message = w.messages.iter().find(|message| message["taskId"] == task).unwrap(); - let width = ui.available_width(); - w.image_result(ui, message, width, None); - }); - }, app); - PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); - harness.run_steps(8); - let waiting = harness.get_by_label("首屏产品场景 · 正在生成图片…").rect(); - harness.render().unwrap().save(out.join("same-slot-waiting.png")).unwrap(); - - let original = egui::ColorImage::filled([48, 60], Color32::from_rgb(120, 101, 84)); - let texture = harness.ctx.load_texture(task, original, Default::default()); - let w = harness.state_mut().jiansun.as_mut().unwrap(); - let index = w.messages.iter().position(|message| message["taskId"] == task).unwrap(); - w.register_image(json!({"taskId":task,"slotId":"hero","outputId":"detail"})); - let message = &w.messages[index]; - assert_eq!(message["kind"], "image"); - assert_eq!(message["taskId"], task); - let target = image_location(message, task); - let (_, _, label) = image_result_labels(&target, &w.template_workflow, &w.creation_brief); - w.agent_images.insert(task.into(), texture); - let mut progress = w.workflow.production_progress().clone(); - progress["candidateReviews"][task]["status"] = json!("adopted"); - w.workflow.set_production_progress(&progress); - harness.run_steps(8); - let received = harness.get_by_label(format!("定位 {label}").as_str()).rect(); - assert_eq!(waiting, received); - harness.render().unwrap().save(out.join("same-slot-received.png")).unwrap(); - assert!(matches!(requests.try_recv(), Ok(Request::Action(method, _)) if method == "agent-image-preview")); - assert!(requests.try_recv().is_err()); - } - - #[test] - #[ignore = "offscreen GPU acceptance at Windows window widths, UI scales and dock widths"] - fn p1_workspace_visual_matrix() { - use egui_kittest::kittest::Queryable; - - let _gpu = photocraft_testkit::gpu_lock(); - let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - std::fs::create_dir_all(&directory).unwrap(); - struct Preview(PhotocraftApp); - impl eframe::App for Preview { - fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { - let app = &mut self.0; - crate::panels::title_bar(app, ui); - crate::panels::options_bar(app, ui); - crate::panels::status_bar(app, ui); - crate::panels::toolbar(app, ui); - crate::panels::right_dock(app, ui); - } - } - - for width in [960.0, 1280.0, 1400.0] { - for scale in [1.0, 1.25, 1.5] { - for dock in [250.0, 360.0, 420.0] { - let (mut app, requests) = live_production_fixture(); - app.ui.dock_tabs.color = 4; - let doc = app.session.active().unwrap().doc.id.0; - let w = app.jiansun.as_mut().unwrap(); - w.open_projects.insert(doc, w.local_identity("p1-visual")); - w.reduce_motion = true; - w.template_workflow["workspaceId"] = json!("p1-visual"); - w.template_workflow["templateId"] = json!("fixture"); - w.template_workflow["templateVersion"] = json!("1"); - w.template_workflow["templateHash"] = json!("fixture"); - w.template_workflow["variantId"] = json!("wood"); - w.template_workflow["outputs"] = json!([{"outputId":"detail","documentId":"first"}]); - let mapping = json!({"version":1,"canvasFirst":true,"component":"detail","variantId":"wood", - "workspaceId":"p1-visual","templateId":"fixture","templateVersion":"1","templateHash":"fixture", - "outputs":[{"documentId":"first","mapping":{"fields":[]}}]}); - std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc) - .metadata.text.push(("jiansun.slot-mapping.v1".into(), mapping.to_string())); - let mut progress = w.workflow.production_progress().clone(); - progress["workers"][1]["step"] = json!("正在等待原请求"); - progress["workers"].as_array_mut().unwrap().push( - json!({"number":3,"slotId":"wood","label":"木纹细节","step":"正在准备","active":true})); - progress["workers"].as_array_mut().unwrap().extend([ - json!({"number":5,"slotId":"angle","label":"侧面角度","step":"正在生图","active":true}), - json!({"number":6,"slotId":"joinery","label":"连接结构","step":"正在准备","active":true}), - ]); - progress["copyCells"] = json!((0..45).map(|index| json!({ - "state": if index < 8 { "verified" } else if index < 37 { "filled" } else { "empty" } - })).collect::>()); - progress["reviews"] = json!([{"number":4,"slotId":"finish","label":"材质细节","step":"正在验图","active":true}]); - w.workflow.set_production_progress(&progress); - let mut harness = egui_kittest::Harness::builder().with_size(vec2(width / scale, 900.0 / scale)) - .with_pixels_per_point(scale).with_max_steps(64).wgpu().build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); - crate::panels::request_dock_width(&cc.egui_ctx, dock); - app.gpu_render_state = cc.wgpu_render_state.clone(); - Preview(app) - }); - harness.run_steps(12); - let stem = format!("{width}px-{scale}x-{dock}pt"); - let save = |harness: &mut egui_kittest::Harness, state| { - let shot = harness.render().expect("GPU workspace render"); - assert_eq!(shot.dimensions(), (width as u32, 900)); - shot.save(directory.join(format!("{stem}-{state}.png"))).unwrap(); - }; - assert!(harness.query_by_label("正在推进目标").is_some()); - save(&mut harness, "running"); - if (width, scale) == (960.0, 1.5) || (width, scale) == (1400.0, 1.0) { - harness.get_by_label("展开制作详情").click(); - harness.run_steps(12); - let w = harness.state().0.jiansun.as_ref().unwrap(); - assert_eq!(w.panel_geometry["productionWorkers"].as_array().unwrap().len(), 6); - save(&mut harness, "expanded"); - let app = &mut harness.state_mut().0; - app.session.execute("select.deselectLayers", json!({})).unwrap(); - let mut w = app.jiansun.take().unwrap(); - w.pi_run = None; - w.busy = None; - w.composer.clear(); - w.composer_reference_clear(app); - w.messages.push(json!({"role":"assistant","kind":"reply", - "text":"详情和主图已交付,SKU 图还有一份待完成。","productionSummary":{"exported":2,"total":3}})); - app.jiansun = Some(w); - harness.run_steps(12); - assert!(harness.query_by_label("继续制作整套").is_some()); - save(&mut harness, "settled"); - } - assert!(requests.try_recv().is_err(), "visual fixture dispatched a request at {stem}"); - } - } - } - } - - #[test] - fn conversation_scroll_keeps_reference_height_when_clipped() { - let (mut app, _) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - let ctx = egui::Context::default(); - let texture = ctx.load_texture("portrait", egui::ColorImage::filled([4, 7], Color32::WHITE), Default::default()); - w.agent_images.insert("reference".into(), texture); - let message = json!({"requestScope":{"references":[{"label":"Title"}]}, "referenceContent":[{"imageId":"reference"}]}); - let mut heights = Vec::new(); - for clip_top in [0.0, 200.0] { - let output = ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 350.0))), - ..Default::default() - }, |ui| { - ui.set_clip_rect(Rect::from_min_max(pos2(0.0, clip_top), pos2(300.0, 350.0))); - heights.push(ui.scope(|ui| w.sent_references(ui, &message)).response.rect.height()); - }); - output.drop_without_applying_deltas(); - } - assert!(heights[0] >= 110.0); - assert_eq!(heights[0], heights[1], "clipping a reference must not change the scroll extent"); - } - - #[test] - fn production_head_stays_pinned_while_reading_history() { - let (mut app, _) = dock_fixture(); - app.ui.dock_tabs.color = 4; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.composer.clear(); - w.busy = Some("pi-agent".into()); - w.pi_product_production = true; - w.messages.clear(); - for index in 0..16 { - w.messages.push(json!({"role":"user","text":format!("此前的输入 {index}")})); - w.messages.push(json!({"role":"assistant","text":"这张图片已有一版候选。"})); - } - w.messages.push(json!({"role":"user","text":"制作详情页 · 1/3"})); - w.stream_reply = "正在验图\n已回填 2/21 个图位\n准备核对扶手的木纹。".into(); - for _ in 0..5 { dock_frame(&ctx, &mut app, vec![]); } - let point = geometry(app.jiansun.as_ref().unwrap(), "conversationClip").center(); - dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(point), egui::Event::MouseWheel { - source: egui::MouseWheelSource::Unknown,phase:egui::TouchPhase::Move,unit:egui::MouseWheelUnit::Point, - delta:vec2(0.0,500.0),modifiers:egui::Modifiers::NONE, - }]); - for _ in 0..12 { dock_frame(&ctx, &mut app, vec![]); } - let w = app.jiansun.as_ref().unwrap(); - assert!(w.panel_geometry["conversationBottomGap"].as_f64().unwrap() > 48.0); - let head = geometry(w, "productionProgress"); - assert!(head.height() >= 44.0); - assert!(head.bottom() <= geometry(w, "conversationClip").top() + 1.0, - "状态头固定在对话上方:conversation {:?}, head {head:?}", geometry(w, "conversationClip")); - assert!(head.contains_rect(geometry(w, "productionProgressRail"))); - assert!(w.panel_geometry["quickPrompts"].is_null(), "suggestions yield while a whole set is produced"); - assert!(w.panel_geometry["productionHistoryToggle"].is_null()); - assert!(w.panel_geometry["agentStatus"].is_null()); - } - - #[test] - fn production_head_rail_takes_the_amber_of_filled_cells_before_the_cells_exist() { - let (mut app, _) = dock_fixture(); - app.ui.dock_tabs.color = 4; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.composer.clear(); - w.busy = Some("pi-agent".into()); - w.pi_product_production = true; - w.messages.clear(); - w.stream_reply = "正在验图\n已回填 2/21 个图位\n准备核对扶手的木纹。".into(); - fn tinted(shape: &egui::Shape, fill: Color32, out: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| tinted(shape, fill, out)), - egui::Shape::Rect(rect) if rect.fill == fill => out.push(rect.rect), - _ => {} - } - } - let amber = super::super::agent_stream::cell_filled(&Tokens::get(&ctx).agent()); - let mut painted = Vec::new(); - for _ in 0..5 { - let output = ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), - ..Default::default() - }, |ui| crate::panels::right_dock(&mut app, ui)); - painted.clear(); - for shape in &output.shapes { tinted(&shape.shape, amber, &mut painted); } - output.drop_without_applying_deltas(); - } - let rail = geometry(app.jiansun.as_ref().unwrap(), "productionProgressRail"); - assert!(painted.iter().any(|rect| rail.contains_rect(*rect)), - "状态头的进度条用已填待验的琥珀色:{rail:?} 对 {painted:?}"); - } - - #[test] - fn production_head_and_open_list_agree_on_a_waiting_sub_agent() { - use super::super::agent_stream::{STAGE_WAITING, worker_stage}; - 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()), - _ => {} - } - } - fn running_dots(shape: &egui::Shape, color: Color32, out: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| running_dots(shape, color, out)), - egui::Shape::Circle(circle) if circle.radius == 2.25 && circle.fill == color => out.push(circle.center), - _ => {} - } - } - // Every step the workflow reports for a sub-agent still held by an - // earlier request, and three that are not. - for step in ["正在等待原请求", "正在等待原任务结果…", "正在核查原请求…", "正在核查原结果…", "正在核查原模型请求", "正在定位原请求…"] { - assert_eq!(worker_stage(step, false, false), STAGE_WAITING, "{step} 仍在等上一条请求的结果"); - } - for (step, stage) in [("正在生图", "生图"), ("正在准备提示词", "准备"), ("正在验图", "验图"), ("已排队", "排队")] { - assert_eq!(worker_stage(step, false, false), stage, "{step}"); - } - for dock in [250.0, 520.0] { - let (mut app, _) = dock_fixture(); - app.ui.dock_tabs.color = 4; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - crate::panels::request_dock_width(&ctx, dock); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.composer.clear(); - w.busy = Some("pi-agent".into()); - w.pi_run = Some("visual-qa".into()); - w.pi_product_production = true; - w.messages = vec![ - json!({"role":"user","text":"制作详情、主图和 SKU"}), - json!({"role":"assistant","kind":"reply","text":"先做首屏的产品场景图。"}), - json!({"role":"assistant","kind":"image-job","taskId":"qa-pending","run":"visual-qa", - "width":4,"height":5,"workerNumber":1,"slotLabel":"S01 - 首屏产品场景","step":"正在生图"}), - ]; - w.workflow.set_production_progress(&json!({"heading":"正在分派详情页图片","rendered":2,"total":21, - "workers":[{"number":1,"slotId":"hero","label":"首屏产品场景","step":"正在生图","active":true}, - {"number":2,"slotId":"space","label":"空间搭配图","step":"正在核查原请求…","active":true}, - {"number":3,"slotId":"detail","label":"同款细节图","step":"正在等待原请求","active":true}]})); - let mut seen = Vec::new(); - let mut dot_centers = Vec::new(); - let running_color = Tokens::get(&ctx).agent().accent_text; - let frame = |app: &mut PhotocraftApp, events: Vec, seen: &mut Vec, dots_out: &mut Vec| { - let output = ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), events, ..Default::default() - }, |ui| crate::panels::right_dock(app, ui)); - seen.clear(); - dots_out.clear(); - for shape in &output.shapes { - texts(&shape.shape, seen); - running_dots(&shape.shape, running_color, dots_out); - } - output.drop_without_applying_deltas(); - }; - let center = |rect: &Value| { - let (x, y, width, height) = (rect[0].as_f64().unwrap() as f32, rect[1].as_f64().unwrap() as f32, - rect[2].as_f64().unwrap() as f32, rect[3].as_f64().unwrap() as f32); - egui::pos2(x + width / 2.0, y + height / 2.0) - }; - let button = |pos: egui::Pos2, pressed: bool| vec![ - egui::Event::PointerMoved(pos), - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, - ]; - for _ in 0..6 { frame(&mut app, vec![], &mut seen, &mut dot_centers); } - // Collapsed: the summary row names both waiting sub-agents the one way. - let shown = seen.join(" / "); - assert_eq!(seen.iter().filter(|text| text.ends_with(STAGE_WAITING)).count(), 2, "面板宽 {dock}:{shown}"); - assert!(seen.iter().all(|text| !text.contains("待查") && !text.contains("等回执")), "面板宽 {dock}:{shown}"); - // Open the head the way a pointer does. - let toggle = center(&app.jiansun.as_ref().unwrap().panel_geometry["productionProgressTag"]); - frame(&mut app, button(toggle, true), &mut seen, &mut dot_centers); - frame(&mut app, button(toggle, false), &mut seen, &mut dot_centers); - for _ in 0..3 { frame(&mut app, vec![], &mut seen, &mut dot_centers); } - let shown = seen.join(" / "); - let count_line = format!("生图 1 · {STAGE_WAITING} 2"); - assert!(seen.iter().any(|text| text == &count_line), "展开后的统计行,面板宽 {dock}:{shown}"); - let list = app.jiansun.as_ref().unwrap().panel_geometry["productionWorkers"].as_array().cloned().unwrap_or_default(); - assert_eq!(list.len(), 3, "展开后的列表,面板宽 {dock}:{shown}"); - for (number, expected) in [(1_usize, 1_usize), (2, 0), (3, 0)] { - let row = &list[number - 1]; - assert_eq!(row["worker"].as_u64(), Some(number as u64)); - let rect = &row["indicator"]; - let indicator = Rect::from_min_size(egui::pos2(rect[0].as_f64().unwrap() as f32, rect[1].as_f64().unwrap() as f32), - egui::vec2(rect[2].as_f64().unwrap() as f32, rect[3].as_f64().unwrap() as f32)); - let painted = dot_centers.iter().filter(|dot| indicator.contains(**dot)).count(); - assert_eq!(painted, expected, "子代理 {number} 的运行状态点,面板宽 {dock}"); - } - } - } - - #[test] - fn interactive_timeline_rows_light_up_for_keyboard_focus() { - use super::super::agent_stream::{EventRow, EventTone, RowAction}; - fn fills(shape: &egui::Shape, fill: Color32, out: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| fills(shape, fill, out)), - egui::Shape::Rect(rect) if rect.fill == fill => out.push(rect.rect), - _ => {} - } - } - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&ctx); - let hover = Tokens::get(&ctx).agent().hover; - let row = std::cell::Cell::new(Rect::NOTHING); - let frame = |events: Vec, lit: &mut Vec| { - let mut output = ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(600.0, 200.0))), events, ..Default::default() - }, |ui| { super::super::stitch_ui::scope_with_motion(ui, true, |ui| { - row.set(super::super::agent_stream::event_row(ui, Id::unique("focus-row"), EventRow { - glyph: "settings", text: "工具调用 · 1/2 已完成", meta: None, tone: EventTone::Quiet, - hint: None, action: RowAction::Expand(false), - }, true).rect); - }); }); - lit.clear(); - for shape in &output.shapes { fills(&shape.shape, hover, lit); } - output.textures_delta.clear(); - }; - let mut lit = Vec::new(); - frame(vec![], &mut lit); - frame(vec![], &mut lit); - assert!(lit.is_empty(), "an untouched row is not lit: {lit:?}"); - frame(vec![egui::Event::Key { key: egui::Key::Tab, physical_key: Some(egui::Key::Tab), pressed: true, - repeat: false, modifiers: egui::Modifiers::NONE }], &mut lit); - frame(vec![], &mut lit); - assert!(lit.iter().any(|rect| *rect == row.get()), "keyboard focus lights the row like hover: {:?} 对 {lit:?}", row.get()); - } - - #[test] - fn queued_image_slots_take_one_line_and_only_the_running_slot_takes_its_card() { - let (mut app, _) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.pi_run = Some("running".into()); - let job = |run: &str| json!({"role":"assistant","kind":"image-job","taskId":format!("job-{run}"),"run":run, - "width":4,"height":5,"workerNumber":1,"slotLabel":"第10屏 · 打磨与触感场景图","step":"正在生图"}); - fn canvas_rects(shape: &egui::Shape, canvas: Color32, out: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| canvas_rects(shape, canvas, out)), - egui::Shape::Rect(rect) if rect.fill == canvas => out.push(rect.rect.height()), - _ => {} - } - } - let canvas = crate::theme::Tokens::get(&ctx).agent().canvas; - let output = ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 900.0))), - ..Default::default() - }, |ui| { - ui.set_width(620.0); - ui.horizontal(|ui| { - w.image_result(ui, &job("running"), 300.0, None); - w.image_result(ui, &job("later"), 300.0, None); - }); - }); - let mut heights = Vec::new(); - for shape in &output.shapes { canvas_rects(&shape.shape, canvas, &mut heights); } - heights.sort_by(f32::total_cmp); - output.drop_without_applying_deltas(); - // 300pt at 4:5 is a 272×340 card; a queued slot keeps the height of one line. - assert_eq!(heights, vec![32.0, 340.0]); - } - - #[test] - fn starter_suggestions_sit_above_the_composer_and_only_fill_the_draft() { - use super::super::agent_stream::SUGGESTION_ROW_HEIGHT; - let (mut app, requests) = dock_fixture(); - app.ui.dock_tabs.color = 4; - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.composer.clear(); - w.messages.clear(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } - let w = app.jiansun.as_ref().unwrap(); - let prompts = w.panel_geometry["quickPrompts"].as_array().expect("starter suggestions sit above the composer").clone(); - assert_eq!(prompts.len(), 2); - assert_eq!(prompts[0]["label"], "梳理资料"); - assert!(w.panel_geometry["followupPrompts"].is_null(), "the starter pair and the follow-ups never stack"); - let first = &prompts[0]["rect"]; - let composer = geometry(w, "composer"); - let bottom = first[1].as_f64().unwrap() as f32 + first[3].as_f64().unwrap() as f32; - assert!(bottom <= composer.top() + 1.0 && bottom >= composer.top() - SUGGESTION_ROW_HEIGHT - 2.0, - "the row hugs the composer: chip bottom {bottom}, composer {composer:?}"); - let value = |index: usize| first[index].as_f64().unwrap() as f32; - let pos = pos2(value(0) + value(2) / 2.0, value(1) + value(3) / 2.0); - for pressed in [true, false] { - dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(pos), egui::Event::PointerButton { - pos, button:egui::PointerButton::Primary, pressed, modifiers:egui::Modifiers::NONE, - }]); - } - dock_frame(&ctx, &mut app, vec![]); - let w = app.jiansun.as_ref().unwrap(); - assert!(w.composer.contains("请读取当前项目资料"), "choosing a suggestion fills the draft: {}", w.composer); - assert!(w.busy.is_none()); - assert!(!requests.try_iter().any(|request| matches!(request, Request::Action(method, _) if method == "agent" || method == "image"))); - } - - #[test] - fn empty_conversation_says_what_xiaoyi_does_and_leaves_once_something_is_said() { - 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 app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.composer.clear(); - w.messages.clear(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let mut seen = Vec::new(); - let frame = |app: &mut PhotocraftApp, seen: &mut Vec| { - let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), ..Default::default() }, |ui| { - crate::panels::right_dock(app, ui) - }); - seen.clear(); - for clipped in &output.shapes { texts(&clipped.shape, seen); } - output.textures_delta.clear(); - }; - for _ in 0..3 { frame(&mut app, &mut seen); } - for line in ["小壹可以帮你", "为图位生成候选图,采纳后放进画布", "写详情页文案,并核对卖点依据", "整套制作详情、主图和 SKU", - "在下面的输入框里写下需求,或点一条建议开始。"] { - assert!(seen.iter().any(|text| text == line), "an empty conversation shows「{line}」"); - } - assert!(!seen.iter().any(|text| text == "我的项目"), "a project is open, so the projects entry stays out of the way"); - app.jiansun.as_mut().unwrap().messages = vec![json!({"role":"user","text":"这一屏的光线柔和一点"})]; - for _ in 0..3 { frame(&mut app, &mut seen); } - assert!(!seen.iter().any(|text| text == "小壹可以帮你"), "the guidance leaves with the first message"); - assert!(requests.try_recv().is_err(), "guidance sends nothing"); - } - - #[test] - fn picture_progress_counts_rendered_first_previews_and_ignores_unplaced_candidates() { - use super::super::agent_stream::Cell; - use photocraft_doc::{Layer, LayerContent}; - use photocraft_geom::Rect as PixelRect; - let (mut app, _requests) = dock_fixture(); - let mut doc = app.session.active().unwrap().doc.as_ref().clone(); - let mut pixels = photocraft_raster::Surface::new(doc.pixel_format()); - pixels.fill_rect(PixelRect::from_xywh(0, 0, 12, 12), &[0.25, 0.25, 0.25, 1.0]); - let applied = Layer::new("accepted", LayerContent::Raster(pixels.clone())); - let mut preview = Layer::new("first preview", LayerContent::Raster(pixels.clone())); - preview.visible = false; - let mut empty = Layer::new("empty", LayerContent::Raster(pixels)); - empty.visible = false; - let (adopted, first, spare) = (applied.id, preview.id, empty.id); - doc.metadata.text.extend([ - ("jiansun.slot-mapping.v1".into(), json!({"component":"detail","variantId":"wood"}).to_string()), - ("jiansun.adopted.wood.applied".into(), "accepted".into()), - ]); - doc.layers.extend([applied, preview.clone(), empty]); - app.session.add_document(doc, None); - let doc_id = app.session.active().unwrap().doc.id.0; - let slots = [("applied", adopted), ("first", first), ("spare", spare)]; - app.jiansun.as_mut().unwrap().template_workflow = json!({"canvasFirst":true,"outputId":"detail","variantId":"wood", - "slots":slots.map(|(id, layer)| json!({"id":id,"nativeLayerId":layer.0,"outputId":"detail","variantId":"wood"}))}); - let progress = json!({"outputId":"detail","variantId":"wood","pictureCells":slots.map(|(id, _)| json!({"slotId":id}))}); - let statuses = |app: &PhotocraftApp| { - let mut cells = [Cell::Verified, Cell::Empty, Cell::Filled]; - production_image_cells(app, app.jiansun.as_ref().unwrap(), &progress, &mut cells); - cells - }; - assert_eq!(statuses(&app), [Cell::Verified, Cell::Empty, Cell::Empty]); - let tx = app.jiansun.as_ref().unwrap().tx.clone(); - let binding = json!({"doc":doc_id,"nativeLayerId":first.0,"candidateId":"first-image"}); - app.queue_slot_preview(&tx, first, binding.clone()); - assert_eq!(statuses(&app), [Cell::Verified, Cell::Empty, Cell::Empty]); - preview.visible = true; - app.receive_slot_preview(&binding, Some(Box::new(preview))); - assert_eq!(statuses(&app), [Cell::Verified, Cell::Preview, Cell::Empty]); - } - - #[test] - fn cell_rail_wraps_distinct_cells_and_keeps_its_counts() { - use super::super::agent_stream::{Cell, ROW, cell_rail}; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let cells: Vec = (0..45).map(|index| if index < 8 { - Cell::Verified - } else if index < 37 { - Cell::Filled - } else { - Cell::Empty - }).collect(); - let mut rails = Vec::new(); - for width in [520.0, 250.0] { - ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 400.0))), - ..Default::default() - }, |ui| { - ui.set_width(width); - let before = ui.cursor().top(); - let rail = cell_rail(ui, Id::unique(("rail", width as u64)), "文案", &cells, false, |index| format!("第 {} 项", index + 1)); - let spent = ui.cursor().top() - before; - rails.push((rail["total"].clone(), rail["filled"].clone(), rail["verified"].clone(), rail["rect"][2].clone(), rail["rect"][3].clone(), rail["bar"].clone(), spent)); - }).drop_without_applying_deltas(); - } - for (total, filled, verified, rail_width, rail_height, bar, spent) in rails { - assert_eq!((total, filled, verified), (json!(45), json!(37), json!(8))); - assert_eq!(bar, false); - let width = rail_width.as_f64().unwrap(); - let height = rail_height.as_f64().unwrap() as f32; - assert_eq!(height > ROW, width < 300.0); - assert!((spent - height).abs() < 8.0); - - } - } - - #[test] - fn production_reply_uses_readable_references_in_live_and_saved_text() { - let workflow = json!({"outputs":[{"documentId":"front","name":"展示页","fields":[ - {"fieldId":"front-copy","kind":"text","label":"标题"}, - {"fieldId":"S09-T02","kind":"image","label":"产品全貌"} - ]}]}); - let display = |text, streaming| production_reply_text(text, streaming, &workflow); - assert_eq!(display("front 的 front-copy 对应 S09-T02,原图 P03。", false), - "展示页 的 标题 对应 产品全貌,原图 P03。"); - assert_eq!(display("正在修订 S09-T0", true), "正在修订 S09-T0"); - assert_eq!(display("已制作用于 SKU", true), "已制作用于 SKU"); - assert_eq!(display("核对 sources、links 和分句索引", false), - "核对 资料来源、图文对应关系 和句子对应关系"); - assert_eq!(display("正在补图。[{\"name\":\"delegate_image_slots\"}]继续验图。", false), - "正在补图。继续验图。"); - assert_eq!(display("正在补图。[{\"name\":", true), "正在补图。"); - assert_eq!(display("正在补图。 48.0); - app.jiansun.as_mut().unwrap().stream_reply.push_str("\n\nA second paragraph updates the active reply."); - dock_frame(&ctx, &mut app, vec![]); - assert!(panel(&app)["conversationBottomGap"].as_f64().unwrap() > 48.0, "reading history pauses automatic following"); - let jump = geometry(app.jiansun.as_ref().unwrap(), "latestMessage").center(); - for pressed in [true, false] { - dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(jump), egui::Event::PointerButton { - pos: jump, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, - }]); - } - for _ in 0..8 { - dock_frame(&ctx, &mut app, vec![]); - } - let gap = panel(&app)["conversationBottomGap"].as_f64().unwrap(); - assert!(gap < 1.0, "jump must reach the actual bottom, gap={gap}"); - app.jiansun.as_mut().unwrap().stream_reply.push_str("\n\nA third paragraph arrives after returning to the bottom."); - for _ in 0..4 { - dock_frame(&ctx, &mut app, vec![]); - } - let w = app.jiansun.as_ref().unwrap(); - assert!(panel(&app)["conversationBottomGap"].as_f64().unwrap() < 1.0); - assert!(geometry(w, "conversationClip").expand(1.0).contains_rect(geometry(w, "agentStatus"))); - } - - #[test] - fn composer_with_an_inline_reference_keeps_its_accessible_input_name() { - use egui_kittest::kittest::Queryable; - let (mut app, _) = dock_fixture(); - let mut workspace = app.jiansun.take().unwrap(); - workspace.composer.clear(); - workspace.reduce_motion = true; - let mut h = egui_kittest::Harness::builder().with_context_setup(crate::cjk_fonts::install_system_provider_for_tests).with_size(vec2(520.0, 300.0)).build_ui_state( - |ui, state: &mut (Workspace, PhotocraftApp)| state.0.composer_ui(&mut state.1, ui), (workspace, app)); - h.run_steps(3); - assert!(geometry(&h.state().0, "subject").width() > 0.0, "fixture must actually show an inline reference"); - h.check_accessibility(); - h.get_by_role_and_label(egui::accesskit::Role::MultilineTextInput, "小壹消息输入"); - } - - #[test] - fn candidate_trace_requires_one_real_matching_turn_and_rechecks_its_scope() { - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - let target = json!({"candidateId":"candidate-a","taskId":"task-a","slotId":"slot-a","productVariantId":"v-a"}); - let image = json!({"role":"assistant","kind":"image","taskId":"task-a", - "target":{"candidateId":"candidate-a","taskId":"task-a","slotId":"slot-a","productVariantId":"v-a"}}); - assert!(candidate_matches_message(&target, &image)); - assert!(!candidate_matches_message(&json!({"taskId":"task-a","slotId":"other"}), &image)); - assert!(!candidate_matches_message(&json!({"candidateId":"candidate-a","run":"different"}), &image)); - assert!(!candidate_matches_message(&json!({"slotId":"slot-a"}), &image)); - w.messages = vec![json!({"role":"user","text":"第一轮"}),image.clone()]; - w.trace_canvas_candidate(&app,target.clone()); - assert_eq!(w.pending_candidate_trace.as_ref().unwrap()["turn"],0); - w.pending_candidate_trace = None; - w.messages.extend([json!({"role":"user","text":"第二轮"}),image]); - w.trace_canvas_candidate(&app,target); - assert!(w.pending_candidate_trace.is_none(),"ambiguous history cannot select an arbitrary turn"); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn candidate_trace_scrolls_real_history_to_the_turn_and_stays_there() { - for reduced in [false, true] { - let (mut app, requests) = dock_fixture(); - app.ui.dock_tabs.color = 4; - let mut w = app.jiansun.take().unwrap(); - w.reduce_motion = reduced; - w.composer.clear(); - let target = json!({"candidateId":"candidate-a","taskId":"task-a","slotId":"slot-a"}); - w.messages.clear(); - for index in 0..18 { - w.messages.push(json!({"role":"user","text":format!("第 {index} 轮请求")})); - if index == 3 { - w.messages.push(json!({"role":"assistant","kind":"image","taskId":"task-a","target":target})); - } else { - w.messages.push(json!({"role":"assistant","kind":"reply","text":"本轮回复:保留产品结构与真实材质。"})); - } - } - app.jiansun = Some(w); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let frame = |app:&mut PhotocraftApp,time:f64| { - let _ = ctx.settle_ui(egui::RawInput { time:Some(time), - screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(960.0,600.0))), ..Default::default() - }, |ui| crate::panels::right_dock(app,ui)); - }; - for time in [0.0,0.1,0.2] { frame(&mut app,time); } - let initial = app.jiansun.as_ref().unwrap().panel_geometry["conversationScrollOffset"].as_f64().unwrap(); - let mut w = app.jiansun.take().unwrap(); - w.trace_canvas_candidate(&app,target.clone()); - app.jiansun = Some(w); - for time in [0.3,0.4,0.5,0.65,0.8] { frame(&mut app,time); } - let w = app.jiansun.as_ref().unwrap(); - let offset = w.panel_geometry["conversationScrollOffset"].as_f64().unwrap(); - assert!(offset < initial, "the chosen earlier turn moves into view"); - let turn = geometry(w,"candidateTraceRect"); - let clip = geometry(w,"conversationClip"); - assert!((turn.center().y-clip.center().y).abs() < 80.0, "target={turn:?}, viewport={clip:?}"); - frame(&mut app,1.0); - let settled = app.jiansun.as_ref().unwrap().panel_geometry["conversationScrollOffset"].as_f64().unwrap(); - assert!((settled-offset).abs() < 2.0, "the scroll area must not jump back to the bottom"); - let mut w = app.jiansun.take().unwrap(); - w.trace_canvas_candidate(&app,json!({"candidateId":"unknown"})); - app.jiansun = Some(w); - frame(&mut app,1.2); - assert!((app.jiansun.as_ref().unwrap().panel_geometry["conversationScrollOffset"].as_f64().unwrap()-settled).abs() < 2.0); - assert!(requests.try_recv().is_err()); - } - } - - #[test] - #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] - fn candidate_trace_visual_acceptance() { - let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); - let (mut app, requests) = dock_fixture(); - app.ui.dock_tabs.color = 4; - let target = json!({"candidateId":"candidate-a","taskId":"task-a","slotId":"slot-a"}); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = false; - w.composer.clear(); - w.messages.clear(); - for index in 0..18 { - w.messages.push(json!({"role":"user","text":format!("第 {index} 轮请求")})); - if index == 3 { - w.messages.push(json!({"role":"assistant","kind":"image","taskId":"task-a","target":target})); - } else { - w.messages.push(json!({"role":"assistant","kind":"reply","text":"本轮回复:保留产品结构与真实材质。"})); - } - } - let mut h = egui_kittest::Harness::builder().with_size(vec2(1280.0,800.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_ui_state( - |ui, app:&mut PhotocraftApp| { - if !ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - crate::panels::title_bar(app,ui); - crate::panels::options_bar(app,ui); - crate::panels::status_bar(app,ui); - crate::panels::toolbar(app,ui); - crate::panels::right_dock(app,ui); - egui::CentralPanel::default().frame(Frame::NONE.fill(Tokens::get(ui.ctx()).canvas)) - .show(ui,|ui| crate::canvas::document_area(app,ui)); - },app); - PhotocraftApp::setup_context(&h.ctx,crate::theme::ThemeKind::ProMedium); - for time in [0.0,0.1,0.2] { h.input_mut().time=Some(time); h.step(); } - let old_offset = h.state().jiansun.as_ref().unwrap().panel_geometry["conversationScrollOffset"].as_f64().unwrap(); - let clip = geometry(h.state().jiansun.as_ref().unwrap(),"conversationClip"); - h.render().unwrap().save(std::path::Path::new(&directory).join("candidate-trace-before.png")).unwrap(); - { - let app = h.state_mut(); - let mut w = app.jiansun.take().unwrap(); - w.trace_canvas_candidate(app,target); - app.jiansun = Some(w); - } - let mut measurements = Vec::new(); - let mut lit_pixels = Vec::new(); - let mut settled_pixels = Vec::new(); - let mut image_width = 0usize; - for step in 0..=78 { - let time = 0.3 + f64::from(step) / 60.0; - h.input_mut().time=Some(time); h.step(); - let name = match step { 0 => "0ms", 9 => "150ms", 21 => "350ms", 22 => "366ms", 78 => "settled", _ => continue }; - let w = h.state().jiansun.as_ref().unwrap(); - let offset = w.panel_geometry["conversationScrollOffset"].as_f64().unwrap(); - measurements.push(json!({"frame":name,"time":time,"offset":offset, - "paintedTargetRect":w.panel_geometry["candidateTraceRect"],"clip":w.panel_geometry["conversationClip"]})); - let image = h.render().unwrap(); - if step == 22 { image_width = image.width() as usize; lit_pixels = image.as_raw().clone(); } - if step == 78 { settled_pixels = image.as_raw().clone(); } - image.save(std::path::Path::new(&directory).join(format!("candidate-trace-{name}.png"))).unwrap(); - } - let offset_150 = measurements[1]["offset"].as_f64().unwrap(); - let offset_350 = measurements[2]["offset"].as_f64().unwrap(); - let settled = measurements[4]["offset"].as_f64().unwrap(); - assert!(offset_150 < old_offset && offset_350 < offset_150,"the real scroll progresses toward the older turn"); - assert!((settled-offset_350).abs() < 2.0,"later frames do not pull the reader back to the bottom"); - let first = measurements[0]["paintedTargetRect"].as_array().unwrap(); - let first_rect = Rect::from_min_size(pos2(first[0].as_f64().unwrap() as f32,first[1].as_f64().unwrap() as f32), - vec2(first[2].as_f64().unwrap() as f32,first[3].as_f64().unwrap() as f32)); - assert!(!clip.intersects(first_rect),"the target begins outside the viewport"); - let centered = measurements[3]["paintedTargetRect"].as_array().unwrap(); - let target_rect = Rect::from_min_size(pos2(centered[0].as_f64().unwrap() as f32,centered[1].as_f64().unwrap() as f32), - vec2(centered[2].as_f64().unwrap() as f32,centered[3].as_f64().unwrap() as f32)); - assert!(clip.contains_rect(target_rect),"the target is visibly inside the viewport: {target_rect:?} in {clip:?}"); - assert!((target_rect.center().y-clip.center().y).abs() < 80.0,"the painted target is centered"); - let bounds = target_rect.intersect(clip); - let mut changed = 0usize; - for y in bounds.top().ceil() as usize..bounds.bottom().floor() as usize { - for x in bounds.left().ceil() as usize..bounds.right().floor() as usize { - let index = (y * image_width + x) * 4; - if lit_pixels.get(index..index+4) != settled_pixels.get(index..index+4) { changed += 1; } - } - } - assert!(changed > 20,"the visible target actually changes when its one-shot pulse exits"); - let evidence = json!({"initialOffset":old_offset,"initialTarget":rect_value(first_rect),"initialClip":rect_value(clip),"frames":measurements}); - std::fs::write(std::path::Path::new(&directory).join("candidate-trace.json"),serde_json::to_vec_pretty(&evidence).unwrap()).unwrap(); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn referencing_a_real_layer_opens_composer_and_accepts_keyboard_text() { - let (mut app, requests) = dock_fixture(); - app.session.execute("layer.new.layer", json!({"name":"引用目标"})).unwrap(); - let doc = app.session.active().unwrap().doc.id.0; - let layer = app.session.active().unwrap().selected_layers()[0].0; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - app.ui.dock_tabs.color = 0; - app.jiansun.as_mut().unwrap().composer.clear(); - assert!(super::super::action_in_ui(&mut app,&ctx,"composer-reference-add", - json!({"documentId":doc+1,"nativeLayerId":layer,"component":"layer"})).is_err()); - assert_eq!(app.ui.dock_tabs.color,0); - assert!(!ctx.memory(|memory| memory.has_focus(super::super::composer_input_id()))); - super::super::action_in_ui(&mut app,&ctx,"composer-reference-add", - json!({"documentId":doc,"nativeLayerId":layer,"component":"layer"})).unwrap(); - let frame = |app:&mut PhotocraftApp,time:f64,events| { - let _ = ctx.settle_ui(egui::RawInput { time:Some(time), events, - screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() - }, |ui| crate::panels::right_dock(app,ui)); - }; - for time in [0.0,0.2,0.4,0.6] { frame(&mut app,time,vec![]); } - assert_eq!(app.ui.dock_tabs.color,4); - assert_eq!(app.jiansun.as_ref().unwrap().panel_geometry["composerExpanded"],true); - assert!(ctx.memory(|memory| memory.has_focus(super::super::composer_input_id()))); - frame(&mut app,0.7,vec![egui::Event::Text("补充要求".into())]); - assert_eq!(app.jiansun.as_ref().unwrap().composer,"补充要求"); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn message_entry_keeps_following_content_fixed_at_zero_and_full_opacity() { - let render = |progress| { - let ctx = egui::Context::default(); - let mut result = None; - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(420.0,400.0))), ..Default::default() }, |ui| { - ui.set_width(320.0); - let message = agent_motion::message_visual(ui,progress,|ui| user_bubble(ui,"真实消息")); - let next = ui.label("下方消息"); - result = Some((message.response.rect,next.rect)); - }); - result.unwrap() - }; - let start = render(0.0); - let end = render(1.0); - assert_eq!(start.0,end.0,"entry owns its full layout from the first frame"); - assert_eq!(start.1,end.1,"following content cannot jump when the entrance ends"); - } - - #[test] - fn composer_send_pulse_belongs_to_the_accepted_action_and_never_to_history() { - for keyboard in [false, true] { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - w.reduce_motion = false; - let frame = |w: &mut Workspace, app: &mut PhotocraftApp, time: f64, events| { - let _ = ctx.settle_ui(egui::RawInput { time:Some(time), events, - screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), ..Default::default() }, |ui| { - w.composer_ui(app, ui); - }); - }; - frame(&mut w,&mut app,0.0,vec![]); - assert!(ctx.data(|data| data.get_temp::(Id::unique("composer-sent-glow"))).is_none()); - if keyboard { - ctx.memory_mut(|memory| memory.request_focus(Id::unique("jiansun-composer-input"))); - frame(&mut w,&mut app,0.3,vec![enter_event(egui::Modifiers::NONE,false)]); - } else { - let pos = geometry(&w,"send").center(); - for (time, pressed) in [(0.2,true),(0.3,false)] { - frame(&mut w,&mut app,time,vec![egui::Event::PointerMoved(pos),egui::Event::PointerButton { - pos,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); - } - } - assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,_) if method=="agent")); - let started = ctx.data(|data| data.get_temp::(Id::unique("composer-sent-glow"))).unwrap(); - assert_eq!(started,0.3); - let user_index=w.messages.iter().rposition(|message|message["role"]=="user").unwrap(); - assert_eq!(ctx.data(|data|data.get_temp::(w.user_reveal_id(Some(user_index)))),Some(started),"accepted submissions reveal even before the conversation baseline is drawn"); - frame(&mut w,&mut app,0.5,vec![]); - assert_eq!(ctx.data(|data| data.get_temp::(Id::unique("composer-sent-glow"))),Some(started), "repaint does not retrigger"); - w.reduce_motion = true; - frame(&mut w,&mut app,0.6,vec![]); - assert!(ctx.data(|data| data.get_temp::(Id::unique("composer-sent-glow"))).is_none()); - w.reduce_motion = false; - w.busy = None; - w.model_ready = false; - w.composer = "预检查失败仍保留".into(); - frame(&mut w,&mut app,1.0,vec![enter_release(),enter_event(egui::Modifiers::NONE,false)]); - assert_eq!(w.composer,"预检查失败仍保留"); - assert!(requests.try_recv().is_err()); - assert!(ctx.data(|data| data.get_temp::(Id::unique("composer-sent-glow"))).is_none()); - } - } - - #[test] - fn real_conversation_shapes_fit_narrow_and_wide_docks_without_clipping() { - fn collect(shape: &egui::Shape, ids: &[egui::TextureId], images: &mut Vec<(egui::TextureId, Rect)>, texts: &mut Vec<(String, Rect, usize)>) { - match shape { - egui::Shape::Vec(shapes) => { - for child in shapes { - collect(child, ids, images, texts); - } - } - egui::Shape::Rect(rect) if ids.contains(&rect.fill_texture_id()) => images.push((rect.fill_texture_id(), rect.rect)), - egui::Shape::Text(text) => texts.push((text.galley.text().to_owned(), Rect::from_min_size(text.pos, text.galley.size()), text.galley.rows.len())), - _ => {} - } - } - - let reply = "这是一段需要完整显示的长中文回复:请保留产品的真实外观、花色和结构,同时让自然光更柔和,让桌面细节清晰,确保所有内容按照当前侧栏宽度换行,不能被右边界裁掉。"; - for dock_width in [288.0, 320.0, 400.0] { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let mut ids = Vec::new(); - for index in 1..=3 { - let image = egui::ColorImage::filled([96, 128], Color32::from_rgb(65 * index as u8, 60, 40)); - let texture = ctx.load_texture(format!("layout-proof-{dock_width}-{index}"), image, egui::TextureOptions::LINEAR); - ids.push(texture.id()); - app.jiansun.as_mut().unwrap().agent_images.insert(format!("task-{index}"), texture); - } - { - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.creation_brief = json!({"variants":[{"id":"teak","name":"非常长的真实花色名称"}]}); - w.template_workflow = json!({"slots":[ - {"id":"slot-1","documentId":"P1","label":"首屏产品场景主图","candidates":[{"id":"task-1"},{"id":"task-2"}]}, - {"id":"slot-2","documentId":"P2","label":"木纹细节","candidates":[{"id":"task-3"}]} - ]}); - w.messages = vec![ - json!({"role":"user","text":"你好"}), - json!({"role":"assistant","kind":"reply","text":reply}), - json!({"role":"assistant","kind":"image","taskId":"task-1","slotId":"slot-1","productVariantId":"teak"}), - json!({"role":"assistant","kind":"image","taskId":"task-2","slotId":"slot-1","productVariantId":"teak"}), - json!({"role":"assistant","kind":"image","taskId":"task-3","slotId":"slot-2","productVariantId":"teak"}), - ]; - } - crate::panels::request_dock_width(&ctx, dock_width); - let mut output = None; - for _ in 0..4 { - let mut frame = ctx.settle_ui( - egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 1550.0))), ..Default::default() }, - |ui| crate::panels::right_dock(&mut app, ui), - ); - frame.textures_delta.clear(); - output = Some(frame); - } - let output = output.unwrap(); - let clip = geometry(app.jiansun.as_ref().unwrap(), "conversationClip"); - let mut images = Vec::new(); - let mut texts = Vec::new(); - for shape in &output.shapes { - collect(&shape.shape, &ids, &mut images, &mut texts); - } - let reply_shape = texts.iter().find(|(text, _, _)| text == reply).expect("the complete selectable reply must be painted"); - assert!(reply_shape.2 > 1, "long Chinese reply wraps at dock width {dock_width}"); - assert!(reply_shape.1.left() >= clip.left() && reply_shape.1.right() <= clip.right() + 1.0, "reply must fit its visible viewport at {dock_width}: {:?} in {clip:?}", reply_shape.1); - let mut image_rects = Vec::new(); - for (index, id) in ids.iter().enumerate() { - let image = images.iter().find(|(texture, _)| texture == id).expect("each result has one real image").1; - let (page, number) = if index == 2 { ("P2", "候选 1") } else if index == 1 { ("P1", "候选 2") } else { ("P1", "候选 1") }; - let caption = format!("{page} · {number}"); - assert!(texts.iter().any(|(text, rect, _)| text == &caption && image.contains_rect(*rect)), - "{caption} must be painted inside its own image at width {dock_width}"); - assert!(image.left() >= clip.left() && image.right() <= clip.right() + 1.0, "image exceeds the conversation at {dock_width}: {image:?}"); - image_rects.push(image); - } - if dock_width >= 400.0 { - assert!(image_rects[0].right() <= image_rects[1].left()); - assert!(image_rects[0].bottom() <= image_rects[2].top()); - } else if dock_width == 288.0 { - assert!(image_rects.windows(2).all(|pair| pair[0].bottom() <= pair[1].top())); - } - assert!(requests.try_recv().is_err(), "drawing result history must not issue a model request"); - } - } - - #[test] - fn image_light_surface_spans_the_conversation_column() { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - app.jiansun.as_mut().unwrap().busy = Some("slot-generate".into()); - for _ in 0..3 { - dock_frame(&ctx, &mut app, vec![]); - } - let workspace = app.jiansun.as_ref().unwrap(); - let processing = geometry(workspace, "processing"); - let panel = geometry(workspace, "panel"); - assert!(processing.width() >= panel.width() - 32.0, "the actual processing light must not collapse to a tiny status pill"); - assert!(geometry(workspace, "stop").right() <= panel.right(), "the real stop control stays usable"); - assert!(requests.try_recv().is_err(), "painting a running state never dispatches a model request"); - } - - #[test] - fn conversation_wait_uses_the_shared_unframed_loader_instead_of_the_image_task_surface() { - for busy in ["agent", "pi-agent", "slot-copy"] { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - app.jiansun.as_mut().unwrap().busy = Some(busy.into()); - for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } - let w = app.jiansun.as_ref().unwrap(); - assert!(w.panel_geometry["agentStatus"].is_array(), "{busy} keeps a stable AI Loader row"); - assert!(w.panel_geometry["processing"].is_null(), "{busy} must not use the image task frame"); - assert!(w.panel_geometry["processingPlaceholder"].is_null()); - assert!(w.panel_geometry["processingBlob"].is_null()); - assert_eq!(w.panel_geometry["processingLightMode"], "inactive"); - let status = geometry(w, "agentStatus"); - let stop = geometry(w, "taskStop"); - assert!(status.height() <= 30.0 && stop.height() <= 30.0, "{busy}: status={status:?}, stop={stop:?}"); - assert!(requests.try_recv().is_err(), "waiting UI never starts a real request"); - } - } - - #[test] - fn one_turn_keeps_reply_anchor_and_manual_disclosure_across_realistic_tool_gaps() { - fn collect(shape: &egui::Shape, out: &mut Vec<(String, Rect)>) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, out)), - egui::Shape::Text(text) => out.push((text.galley.text().to_owned(), Rect::from_min_size(text.pos, text.galley.size()))), - _ => {} - } - } - fn frame(ctx: &egui::Context, w: &Workspace, time: f64, events: Vec) -> Vec<(String, Rect)> { - let output = ctx.settle_ui(egui::RawInput { - screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,900.0))),time:Some(time),events,..Default::default() - }, |ui| { - ui.set_width(520.0); - let turn = turns(&w.messages).pop().unwrap(); - w.turn_ui(ui, turn, Id::unique("stable-conversation-trace"), w.messages.len(), true, false, None); - }); - let mut texts = Vec::new(); - for shape in &output.shapes { collect(&shape.shape, &mut texts); } - output.drop_without_applying_deltas(); - texts - } - fn click(ctx: &egui::Context, w: &Workspace, time: f64, pos: egui::Pos2) { - for (offset, pressed) in [(0.0, true),(0.1, false)] { - frame(ctx,w,time+offset,vec![egui::Event::PointerMoved(pos),egui::Event::PointerButton { - pos,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE - }]); - } - } - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.busy = Some("pi-agent".into()); - w.stream_reply = "标题已完成,继续补充细线。".into(); - w.messages = vec![json!({"role":"user","text":"请完成标题和细线"}), - json!({"role":"assistant","kind":"activity","text":"开始:组合画布操作","event":{ - "version":1,"type":"tool","run":"trace-run","toolCallId":"one","toolName":"codemode","status":"started"}})]; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let initial = frame(&ctx,w,0.0,vec![]); - let reply_top = initial.iter().find(|(text,_)|text==&w.stream_reply).unwrap_or_else(|| panic!("reply shape missing: {initial:?}")).1.top(); - let summary_top = initial.iter().find(|(text,_)|text == "正在组合画布操作…").unwrap().1.top(); - assert!(summary_top < reply_top, "the processing summary precedes the live reply"); - w.messages[1]["event"]["status"] = json!("completed"); - frame(&ctx,w,0.1,vec![]); - let gap = frame(&ctx,w,6.2,vec![]); - assert!(gap.iter().any(|(text,_)|text=="组合画布操作"), "completed tools stay expanded during a provider wait"); - assert!(gap.iter().find(|(text,_)|text == "已完成 · 组合画布操作").unwrap().1.top() < gap.iter().find(|(text,_)|text==&w.stream_reply).unwrap().1.top()); - let header = gap.iter().find(|(text,_)|text == "已完成 · 组合画布操作").unwrap().1.center(); - click(&ctx,w,6.3,header); - w.messages.push(json!({"role":"assistant","kind":"activity","text":"开始:执行原生操作","event":{ - "version":1,"type":"tool","run":"trace-run","toolCallId":"two","toolName":"native_call","status":"started"}})); - let closed = frame(&ctx,w,12.5,vec![]); - assert!(!closed.iter().any(|(text,_)|text=="组合画布操作" || text=="执行原生操作"), "new tools must respect the reader's collapsed state"); - assert!(closed.iter().find(|(text,_)|text == "已完成 1 项 · 正在执行原生操作…").unwrap().1.top() < closed.iter().find(|(text,_)|text==&w.stream_reply).unwrap().1.top()); - let header = closed.iter().find(|(text,_)|text == "已完成 1 项 · 正在执行原生操作…").unwrap().1.center(); - click(&ctx,w,12.6,header); - w.busy = None; - let held = frame(&ctx,w,20.0,vec![]); - assert!(held.iter().any(|(text,_)|text=="组合画布操作"), "manual expansion remains open after the whole turn ends"); - - let automatic = egui::Context::default(); - PhotocraftApp::setup_context(&automatic, crate::theme::ThemeKind::ProMedium); - w.busy = Some("pi-agent".into()); - frame(&automatic,w,30.0,vec![]); - w.busy = None; - frame(&automatic,w,31.0,vec![]); - assert!(frame(&automatic,w,31.4,vec![]).iter().any(|(text,_)|text=="组合画布操作")); - assert!(frame(&automatic,w,31.7,vec![]).iter().any(|(text,_)|text=="组合画布操作"), "the group stays visible during the completion hold"); - assert!(!frame(&automatic,w,32.9,vec![]).iter().any(|(text,_)|text=="组合画布操作")); - w.busy = Some("pi-agent".into()); - w.messages[2]["event"]["status"] = json!("completed"); - w.messages.push(json!({"role":"assistant","kind":"activity","text":"开始:读取画布","event":{ - "version":1,"type":"tool","run":"trace-run","toolCallId":"three","toolName":"canvas_read","status":"started"}})); - let next = frame(&automatic,w,33.0,vec![]); - assert!(next.iter().any(|(text,_)|text=="执行原生操作")); - assert!(next.iter().any(|(text,_)|text=="读取画布"), "new tool start and previous completion keep the disclosure open"); - assert!(requests.try_recv().is_err(), "the synthetic timing trace cannot issue a provider or native mutation"); - } - - #[test] - fn real_turn_layout_has_parallel_thinking_tools_and_response_with_one_loader() { - fn circles(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| circles(shape, out)), - egui::Shape::Circle(circle) if (circle.radius - 3.0).abs() < 0.01 => out.push(circle.center), - _ => {} - } - } - fn texts(shape: &egui::Shape, out: &mut Vec<(String, Rect)>) { - 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(), Rect::from_min_size(text.pos, text.galley.size()))), - _ => {} - } - } - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.busy = Some("pi-agent".into()); - w.stream_reply = "正式回复".into(); - w.messages = vec![json!({"role":"user","text":"用户请求"}), - json!({"role":"assistant","kind":"thinking","active":true,"text":"内部思考内容"}), - json!({"role":"assistant","kind":"activity","text":"工具一","event":{"version":1,"type":"tool","run":"r","toolCallId":"a","toolName":"codemode","status":"completed"}}), - json!({"role":"assistant","kind":"activity","text":"工具二","event":{"version":1,"type":"tool","run":"r","toolCallId":"b","toolName":"native_call","status":"started"}})]; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 900.0))), ..Default::default() }, |ui| { - ui.set_width(520.0); - let turn = turns(&w.messages).pop().unwrap(); - w.turn_ui(ui, turn, Id::unique("one-loader-test"), w.messages.len(), true, false, None); - w.agent_status_ui(ui, true); - }); - let mut labels = Vec::new(); - for shape in &output.shapes { texts(&shape.shape, &mut labels); } - let top = |label: &str| labels.iter().find(|(text, _)| text.starts_with(label)).unwrap_or_else(|| panic!("missing {label}: {labels:?}")).1.top(); - assert!(top("用户请求") < top("正在深度思考…") && top("正在深度思考…") < top("已完成 1 项 · 正在执行原生操作…")); - assert!(top("已完成 1 项 · 正在执行原生操作…") < top("正式回复")); - assert!(!labels.iter().any(|(text, _)| text == "内部思考内容")); - let mut dots = Vec::new(); - for shape in &output.shapes { circles(&shape.shape, &mut dots); } - assert_eq!(dots.len(), 3, "one three-dot loader for the entire turn"); - assert!((dots[0].y - dots[1].y).abs() < 0.01 && (dots[1].y - dots[2].y).abs() < 0.01); - assert!((dots[1].x - dots[0].x - 8.0).abs() < 0.01 && (dots[2].x - dots[1].x - 8.0).abs() < 0.01, - "the 6pt dots retain fixed, equally spaced positions"); - assert!(requests.try_recv().is_err()); - output.drop_without_applying_deltas(); - } - - #[test] - fn production_replies_are_inline_between_tools_and_thinking() { - fn texts(shape: &egui::Shape, out: &mut Vec<(String, Rect)>) { - 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(), Rect::from_min_size(text.pos, text.galley.size()))), - _ => {} - } - } - fn frame(ctx: &egui::Context, w: &Workspace, events: Vec) -> Vec<(String, Rect)> { - let mut out = Vec::new(); - let output = ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 900.0))), events, ..Default::default() - }, |ui| { - ui.set_width(520.0); - let turn = turns(&w.messages).pop().unwrap(); - w.turn_ui(ui, turn, Id::unique("narration-test"), w.messages.len(), true, false, None); - }); - for shape in &output.shapes { texts(&shape.shape, &mut out); } - output.drop_without_applying_deltas(); - out - } - let rows_of = |labels: &[(String, Rect)], prefix: &str| -> Vec { - labels.iter().filter(|(text, _)| text.starts_with(prefix)).map(|(_, rect)| rect.top()).collect() - }; - let shows = |labels: &[(String, Rect)], prefix: &str| labels.iter().any(|(text, _)| text.starts_with(prefix)); - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - { - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.busy = Some("pi-agent".into()); - w.stream_reply = "全部图位已完成。".into(); - w.messages = vec![json!({"role":"user","text":"制作详情、主图和 SKU"}), - json!({"role":"assistant","kind":"reply","text":"我先核对原图。"}), - json!({"role":"assistant","kind":"reply","text":"模板已就绪。"}), - json!({"role":"assistant","kind":"activity","text":"读取画布","event":{ - "version":1,"type":"tool","run":"fold","toolCallId":"read","toolName":"canvas_read","status":"completed"}}), - json!({"role":"assistant","kind":"reply","text":"正在安排图位。"}), - json!({"role":"assistant","kind":"thinking","active":false,"output":{}})]; - } - for _ in 0..2 { frame(&ctx, app.jiansun.as_ref().unwrap(), vec![]); } - let labels = frame(&ctx, app.jiansun.as_ref().unwrap(), vec![]); - assert!(!shows(&labels, "过程说明")); - let order = ["我先核对原图。", "模板已就绪。", "已完成 · 读取画布", "正在安排图位。", "已深度思考", "全部图位已完成。"]; - let positions: Vec<_> = order.iter().map(|prefix| rows_of(&labels, prefix)[0]).collect(); - assert!(positions.windows(2).all(|rows| rows[0] < rows[1]), "{labels:?}"); - assert!(requests.try_recv().is_err()); - - } - - type HandoffText = (String, Rect, u8, Vec); - type HandoffMesh = Vec<(egui::Pos2, u8)>; - - fn handoff_frame(ctx: &egui::Context, w: &Workspace, time: f64, conversation: Id) -> (Vec, Vec) { - fn collect(shape: &egui::Shape, texts: &mut Vec, meshes: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, texts, meshes)), - egui::Shape::Text(text) => { - let alpha = text.galley.rows.iter().flat_map(|row| &row.visuals.mesh.vertices).map(|vertex| vertex.color.a()).max().unwrap_or(0); - // The selectable label is intentionally transparent; inspect - // the real glyph layer and its per-section masks instead. - if alpha > 0 { texts.push((text.galley.text().to_owned(), Rect::from_min_size(text.pos, text.galley.size()), alpha, - text.galley.rows.iter().flat_map(|row| row.glyphs.iter().filter(|glyph| !glyph.uv_rect.is_nothing()) - .map(|glyph| row.visuals.mesh.vertices.get(glyph.first_vertex as usize).map_or(0, |vertex| vertex.color.a()))).collect())); } - } - egui::Shape::Mesh(mesh) => meshes.push(mesh.vertices.iter().map(|vertex| (vertex.pos, vertex.color.a())).collect()), - _ => {} - } - } - let output = ctx.settle_ui(egui::RawInput { - screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,900.0))),time:Some(time),..Default::default() - }, |ui| { - ui.set_width(520.0); - let turn = turns(&w.messages).pop().unwrap(); - w.turn_ui(ui,turn,conversation,w.messages.len(),true, false, None); - }); - let mut texts = Vec::new(); - let mut meshes = Vec::new(); - for shape in &output.shapes { collect(&shape.shape, &mut texts, &mut meshes); } - output.drop_without_applying_deltas(); - (texts, meshes) - } - - #[test] - fn thinking_is_a_status_during_and_after_a_turn_and_old_text_stays_hidden() { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.busy = Some("pi-agent".into()); - w.messages = vec![json!({"role":"user","text":"请分析"}), - json!({"role":"assistant","kind":"thinking","active":true,"text":"独立思考原文", - "output":{"tokens":128,"tokensPerSecond":43.5,"estimated":true}})]; - let id = Id::unique("thinking-alone"); - let (running, _) = handoff_frame(&ctx, w, 0.0, id); - assert!(running.iter().any(|(text,_,_,_)| text == "正在深度思考…")); - assert!(!running.iter().any(|(text,_,_,_)| text.contains("tokens") || text.contains("tok/s"))); - assert!(!running.iter().any(|(text,_,_,_)| text == "独立思考原文")); - assert!(!running.iter().any(|(text,_,_,_)| text.starts_with("工具调用"))); - w.busy = None; - let (interrupted, _) = handoff_frame(&ctx, w, 0.2, id); - assert!(interrupted.iter().any(|(text,_,_,_)| text == "思考已中断")); - w.messages[1]["active"] = json!(false); - w.messages[1]["output"] = json!({"tokens":145,"tokensPerSecond":45.0,"estimated":false}); - w.messages.push(json!({"role":"assistant","kind":"activity","event":{ - "version":1,"type":"tool","run":"thinking-test","toolCallId":"read","toolName":"canvas_read", - "status":"completed","durationMs":12}})); - w.messages.push(json!({"role":"assistant","kind":"reply","text":"分析结论"})); - let (finished, _) = handoff_frame(&ctx, w, 0.3, id); - assert!(!finished.iter().any(|(text,_,_,_)| text == "独立思考原文")); - assert!(!finished.iter().any(|(text,_,_,_)| text.contains("tokens") || text.contains("tok/s"))); - assert!(finished.iter().any(|(text,_,_,_)| text == "12ms")); - let header = finished.iter().find(|(text,_,_,_)| text == "已深度思考").unwrap().1.center(); - for pressed in [true, false] { - ctx.settle_ui(egui::RawInput { time:Some(0.5), events:vec![egui::Event::PointerMoved(header), - egui::Event::PointerButton { pos:header, button:egui::PointerButton::Primary, pressed, modifiers:egui::Modifiers::NONE }], - screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,900.0))), ..Default::default() }, |ui| { - ui.set_width(520.0); - w.turn_ui(ui, turns(&w.messages).pop().unwrap(), id, w.messages.len(), true, false, None); - }).drop_without_applying_deltas(); - } - let (reopened, _) = handoff_frame(&ctx, w, 0.7, id); - assert!(!reopened.iter().any(|(text,_,_,_)| text == "独立思考原文")); - assert!(!reopened.iter().any(|(text,_,_,_)| text.starts_with("工具调用"))); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn a_final_receipt_and_lingering_stream_keep_one_response_and_finish_its_glow() { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = false; - w.busy = Some("pi-agent".into()); - w.messages = vec![json!({"role":"user","text":"发送历史"})]; - w.stream_reply = "回复保持在原位置".into(); - let id = Id::unique("lingering-stream"); - handoff_frame(&ctx,w,0.0,id); - let (before,_) = handoff_frame(&ctx,w,0.3,id); - let top = before.iter().find(|(text,_,_,_)| text==&w.stream_reply).unwrap().1.top(); - w.messages.push(json!({"role":"assistant","kind":"reply","text":w.stream_reply})); - w.busy = None; - w.unknown = true; - let (after, meshes) = handoff_frame(&ctx,w,0.4,id); - let response:Vec<_> = after.iter().filter(|(text,_,_,_)| text==&w.stream_reply).collect(); - assert_eq!(response.len(),1); - assert_eq!(response[0].1.top(),top); - assert!(after.iter().any(|(text,_,_,_)| text=="输出未完成"), "handoff retains the real incomplete-output warning"); - assert!(!meshes.is_empty(), "the live reply carries its remaining glow across handoff"); - let (_, rested) = handoff_frame(&ctx, w, 3.2, id); - assert!(rested.is_empty(), "the lasting receipt never replays the finished glow"); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn live_receipt_overlap_keeps_one_body_and_one_anchor_while_the_turn_continues() { - for (live, receipt, expected) in [("答复前缀", "答复前缀", "答复前缀"), - ("答复前缀和新内容", "答复前缀", "答复前缀和新内容"), - ("答复前缀", "答复前缀和新内容", "答复前缀和新内容")] { - let ctx=egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let (mut app,requests)=dock_fixture(); - let w=app.jiansun.as_mut().unwrap(); - w.reduce_motion=true; - w.busy=Some("pi-agent".into()); - w.messages=vec![json!({"role":"user","text":"继续当前任务"})]; - w.stream_reply=live.into(); - let id=Id::unique("live-handoff-overlap"); - let (before,_)=handoff_frame(&ctx,w,0.0,id); - let top=before.iter().find(|(text,_,_,_)|text==live).unwrap().1.top(); - w.messages.push(json!({"role":"assistant","kind":"reply","text":receipt})); - let (after,_)=handoff_frame(&ctx,w,0.1,id); - let bodies:Vec<_>=after.iter().filter(|(text,_,_,_)|text.starts_with("答复前缀")).collect(); - assert_eq!(bodies.len(),1,"live={live}, receipt={receipt}"); - assert_eq!(bodies[0].0,expected); - assert_eq!(bodies[0].1.top(),top); - assert!(requests.try_recv().is_err()); - } - } - - #[test] - fn a_non_tool_activity_never_creates_a_processing_summary() { - let ctx=egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let (mut app,requests)=dock_fixture(); - let w=app.jiansun.as_mut().unwrap(); - w.reduce_motion=true; - w.messages=vec![json!({"role":"user","text":"确认记录"}), - json!({"role":"assistant","kind":"activity","text":"已采纳图片,可撤销"}), - json!({"role":"assistant","kind":"reply","text":"正文结论"})]; - let (texts,_)=handoff_frame(&ctx,w,0.0,Id::unique("activity-without-tools")); - assert!(!texts.iter().any(|(text,_,_,_)|text.starts_with("工具调用"))); - assert!(texts.iter().any(|(text,_,_,_)|text=="图片采纳记录")); - assert!(texts.iter().any(|(text,_,_,_)|text=="正文结论")); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn streamed_final_reply_keeps_its_anchor_and_only_fades_a_genuinely_new_suffix() { - for (stream, final_text, appending) in [ - ("已完成矩形", "已完成矩形", false), - ("准备处理。已完成矩形", "已完成矩形", false), - ("已完成矩形,并适配视图。", "已完成矩形", false), - ("已完成", "已完成矩形", true), - ] { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = false;w.busy = Some("pi-agent".into()); - w.messages = vec![json!({"role":"user","text":"完成当前操作"})]; - w.stream_reply = stream.into(); - let id = Id::unique("completed-stream-trace"); - handoff_frame(&ctx,w,0.0,id); - let (before, _) = handoff_frame(&ctx,w,0.70,id); - let top = before.iter().find(|(text,_,_,_)|text==stream).unwrap().1.top(); - w.messages.push(json!({"role":"assistant","kind":"reply","text":final_text})); - w.stream_reply.clear();w.busy = None; - let (first, _) = handoff_frame(&ctx,w,0.80,id); - let visible = if appending { "已完成矩" } else { final_text }; - let (_,rect,alpha,sections) = first.iter().find(|(text,_,_,_)|text==visible) - .expect("the already visible reply cannot disappear for its final message entrance"); - assert_eq!(rect.top(),top,"finishing the same turn cannot replay its five-point arrival offset"); - assert_eq!(*alpha,255,"the already displayed prefix stays fully opaque"); - if appending { - assert!(sections.first()==Some(&255) && sections.last()==Some(&0), "the old prefix remains opaque: {sections:?}"); - let (during, _) = handoff_frame(&ctx,w,0.90,id); - let (_,_,alpha,sections) = during.iter().find(|(text,_,_,_)| text==final_text).unwrap(); - assert_eq!(*alpha,255); - assert!(sections.first()==Some(&255) && sections.last().is_some_and(|alpha| *alpha > 0 && *alpha < 255)); - assert_eq!(during.iter().filter(|(text,_,_,_)| text==final_text).count(), 1); - let reveal = super::super::typing_text::ENTER + 2.0 * super::super::typing_text::STEP; - let (settled, _) = handoff_frame(&ctx,w,0.80 + reveal + 0.05,id); - let (_,_,alpha,sections) = settled.iter().find(|(text,_,_,_)| text==final_text).unwrap(); - assert_eq!(*alpha,255); - assert!(sections.iter().all(|alpha| *alpha == 255), "the final suffix settles after its glyphs arrive"); - } - assert!(requests.try_recv().is_err()); - } - } - - #[test] - fn legacy_stream_without_user_row_hands_off_to_the_same_visible_reply() { - fn collect(shape: &egui::Shape, out: &mut Vec<(Rect, u8)>) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, out)), - egui::Shape::Text(text) if text.galley.text() == "无用户行的流式回复" => { - let alpha = text.galley.rows.iter().flat_map(|row| &row.visuals.mesh.vertices) - .map(|vertex| vertex.color.a()).max().unwrap_or(0); - if alpha > 0 { out.push((Rect::from_min_size(text.pos, text.galley.size()), alpha)); } - } - _ => {} - } - } - let (mut app, requests) = dock_fixture(); - app.ui.dock_tabs.color = 4; - let w = app.jiansun.as_mut().unwrap(); - w.messages.clear(); - w.stream_reply = "无用户行的流式回复".into(); - w.busy = Some("pi-agent".into()); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let frame = |app: &mut PhotocraftApp, time| { - let output = ctx.settle_ui(egui::RawInput { - time:Some(time),screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() - }, |ui| crate::panels::right_dock(app, ui)); - let mut found = Vec::new(); - for shape in &output.shapes { collect(&shape.shape, &mut found); } - found - }; - frame(&mut app,0.0); - let before = frame(&mut app,0.65); - assert_eq!(before.len(), 1); - let w = app.jiansun.as_mut().unwrap(); - w.messages.push(json!({"role":"assistant","kind":"reply","text":"无用户行的流式回复"})); - w.stream_reply.clear(); - w.busy = None; - let after = frame(&mut app,0.75); - assert_eq!(after.len(), 1, "the final receipt must paint exactly once"); - assert_eq!(after[0].1, 255, "visible text must not restart its opacity entrance"); - assert_eq!(after[0].0.top(), before[0].0.top(), "the reply keeps its vertical anchor"); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn identical_final_reply_finishes_last_stream_batch_without_jumping() { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.busy = Some("pi-agent".into()); - w.messages = vec![json!({"role":"user","text":"请回答"})]; - w.stream_reply = "已完成".into(); - let id = Id::unique("early-final-trace"); - handoff_frame(&ctx,w,0.0,id); - handoff_frame(&ctx,w,0.3,id); - w.stream_reply = "已完成矩形".into(); - let (during, _) = handoff_frame(&ctx,w,0.4,id); - let top = during.iter().find(|(text,_,_,_)|text=="已完成矩").unwrap().1.top(); - w.messages.push(json!({"role":"assistant","kind":"reply","text":"已完成矩形"})); - w.stream_reply.clear(); - w.messages.push(json!({"role":"assistant","kind":"activity","event":{ - "version":1,"type":"tool","run":"trace","toolCallId":"call_trace|fc_trace","toolName":"canvas_read","status":"started"}})); - let (after, _) = handoff_frame(&ctx,w,0.5,id); - let (_,rect,alpha,sections) = after.iter().find(|(text,_,_,_)|text=="已完成矩形").unwrap(); - assert_eq!(rect.top(), top); - assert_eq!(*alpha, 255); - assert!(sections.last().is_some_and(|alpha| *alpha > 0 && *alpha < 255)); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn a_different_or_unstreamed_reply_still_has_its_normal_message_entrance() { - for previous in [None,Some("这是另一段已显示的文字")] { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = false;w.busy = Some("pi-agent".into()); - w.messages = vec![json!({"role":"user","text":"请直接回答"})]; - w.stream_reply = previous.unwrap_or("").into(); - let id = Id::unique("new-reply-trace"); - handoff_frame(&ctx,w,0.0,id);handoff_frame(&ctx,w,0.3,id); - w.messages.push(json!({"role":"assistant","kind":"reply","text":"这是一条真正的新回复"})); - w.stream_reply.clear();w.busy = None; - let (first, _) = handoff_frame(&ctx,w,0.4,id); - let first = first.iter().find(|(text,_,_,_)|text=="这是一条真正的新回复"); - assert!(first.is_none_or(|(_,_,alpha,_)|*alpha<255), "new content starts its own message entrance"); - let (settled, _) = handoff_frame(&ctx,w,1.0,id); - assert_eq!(settled.iter().find(|(text,_,_,_)|text=="这是一条真正的新回复").unwrap().2,255); - assert!(requests.try_recv().is_err()); - } - } - - #[test] - fn historical_adoption_note_does_not_claim_live_undo_after_native_undo() { - fn labels(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| labels(shape, out)), - egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), - _ => {} - } - } - let (mut app, requests) = dock_fixture(); - app.session.execute("layer.new.layer", json!({"name":"临时编辑"})).unwrap(); - app.session.execute("edit.undo", json!({})).unwrap(); - let messages = vec![ - json!({"role":"user","text":"采纳这张图片"}), - json!({"role":"assistant","kind":"activity","text":"已采纳图片,可撤销"}), - json!({"role":"user","text":"检查其他操作"}), - json!({"role":"assistant","kind":"activity","text":"已完成:保留其他图层"}), - ]; - { - let w = app.jiansun.as_mut().unwrap(); - w.messages = messages.clone(); - w.reduce_motion = true; - } - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let mut output = None; - for _ in 0..3 { - output = Some(ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 1000.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui))); - } - let mut text = Vec::new(); - for shape in &output.unwrap().shapes { labels(&shape.shape, &mut text); } - assert!(text.iter().any(|label| label.contains("图片采纳记录")), "the painted history uses a past-tense label"); - assert!(text.iter().all(|label| !label.contains("已采纳图片,可撤销")), "undo must not leave a false live undo promise"); - assert!(text.iter().any(|label| label.contains("已完成:保留其他图层")), "unrelated activity text is unchanged"); - assert_eq!(app.jiansun.as_ref().unwrap().messages, messages, "rendering never rewrites stored conversation history"); - assert_eq!(activity_history_label("其他可撤销操作"), "其他可撤销操作", "only the known historical note is normalized"); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn structured_tool_activity_uses_real_status_and_never_displays_raw_fields() { - let statuses = [ - ("pending", "等待"), ("started", "进行中"), ("completed", "已完成"), - ("failed", "失败"), ("stopped", "已停止"), ("unexpected", "状态未知"), - ]; - for (state, label) in statuses { - let event = json!({"version":1,"type":"tool","status":state,"toolName":"canvas_read", - "summary":"secret summary","arguments":"secret argument","output":"secret output"}); - let (visible, _) = tool_activity_label(&event).unwrap(); - assert_eq!(visible, format!("{label} · 读取画布")); - assert!(!visible.contains("secret")); - } - let foreign = json!({"version":1,"type":"tool","status":"started","toolName":"secret tool"}); - assert_eq!(tool_activity_label(&foreign).unwrap().0, "进行中 · 工具"); - let timed = json!({"version":1,"type":"tool","status":"completed","toolName":"canvas_read","durationMs":1250}); - assert_eq!(tool_activity_label(&timed).unwrap().0, "已完成 · 读取画布 · 1.3s"); - assert_eq!((duration_text(25), duration_text(9_999), duration_text(27_400), duration_text(61_200)), - ("25ms".to_owned(), "10.0s".to_owned(), "27s".to_owned(), "1m01s".to_owned())); - let running = json!({"version":1,"type":"tool","status":"started","toolName":"canvas_read","durationMs":1250}); - assert_eq!(tool_activity_label(&running).unwrap().0, "进行中 · 读取画布", "never invent an elapsed time from a nonterminal event"); - let invalid = json!({"version":1,"type":"tool","status":"completed","toolName":"canvas_read","durationMs":-1}); - assert_eq!(tool_activity_label(&invalid).unwrap().0, "已完成 · 读取画布"); - let messages = vec![ - json!({"role":"user","text":"检查画布"}), - json!({"role":"assistant","kind":"activity","text":"legacy record"}), - json!({"role":"assistant","kind":"activity","text":"sanitized", "event":foreign}), - ]; - let grouped = turns(&messages); - assert!(matches!(grouped[0].items.as_slice(), - [TurnItem::Notice("legacy record", _), TurnItem::Tools(tools)] if tools.len() == 1)); - } - - #[test] - fn active_tool_timer_needs_a_matching_running_event_and_real_timestamp() { - let message = json!({"event":{"version":1,"type":"tool","run":"run-a","status":"started","timestampMs":10_000}}); - assert_eq!(active_tool_elapsed(std::slice::from_ref(&message), Some("run-a"), 12_500), Some(2_500)); - assert_eq!(active_tool_elapsed(std::slice::from_ref(&message), Some("run-b"), 12_500), None); - assert_eq!(active_tool_elapsed(std::slice::from_ref(&message), None, 12_500), None); - assert_eq!(active_tool_elapsed(std::slice::from_ref(&message), Some("run-a"), 9_999), None); - let completed = json!({"event":{"version":1,"type":"tool","run":"run-a","status":"completed","timestampMs":10_000}}); - assert_eq!(active_tool_elapsed(&[completed], Some("run-a"), 12_500), None); - let invalid = json!({"event":{"version":1,"type":"tool","run":"run-a","status":"started","timestampMs":-1}}); - assert_eq!(active_tool_elapsed(&[invalid], Some("run-a"), 12_500), None); - } - - #[test] - fn model_names_read_as_names_and_unknown_ids_stay_verbatim() { - assert_eq!(model_display_name("gpt-image-2.5-flare-burst"), "GPT Image 2.5 Flare Burst"); - assert_eq!(model_display_name("nano-banana-pro-4k-vip"), "Nano Banana Pro 4K VIP"); - assert_eq!(model_display_name("Copy One"), "Copy One"); - assert_eq!(model_display_name("discussion"), "discussion"); - assert_eq!(model_display_name("team-special-v2"), "team-special-v2", "one unknown word keeps the whole id"); - } - - #[test] - fn tool_activity_labels_real_reconcile_workflow_and_preview_without_accepting_unknown_names() { - for (name, expected) in [("native_reconcile","核查原生任务"),("workflow_execute","执行创作操作"), - ("canvas_preview","预览修改"),("unregistered_secret","工具")] { - let event=json!({"version":1,"type":"tool","status":"started","toolName":name}); - assert_eq!(tool_activity_label(&event).unwrap().0,format!("进行中 · {expected}")); - } - } - - #[test] - fn context_ring_real_click_opens_its_details() { - let ctx=egui::Context::default(); PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let screen=Rect::from_min_size(egui::Pos2::ZERO,vec2(600.0,400.0)); - let id=std::cell::Cell::new(Id::NULL); let rect=std::cell::Cell::new(Rect::NOTHING); - let frame=|events| { - let _=ctx.settle_ui(egui::RawInput { screen_rect:Some(screen),events,..Default::default() },|ui| { - let response=context_meter(ui,None,true,true); id.set(response.id); rect.set(response.rect); - }); - }; - frame(vec![]); let pos=rect.get().center(); - frame(vec![egui::Event::PointerMoved(pos)]); - for pressed in [true,false] { frame(vec![egui::Event::PointerButton {pos,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE}]); } - assert!(egui::Popup::is_id_open(&ctx,id.get().with("popup")),"a real click opens context details"); - } - - #[test] - fn hovering_context_ring_paints_only_one_capacity_tooltip() { - fn count(shape:&egui::Shape, wanted:&str) -> usize { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().map(|shape| count(shape,wanted)).sum(), - egui::Shape::Text(text) => usize::from(text.galley.text()==wanted), - _ => 0, - } - } - let ctx=egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - ctx.all_styles_mut(|style| style.interaction.tooltip_delay=0.0); - let rect=std::cell::Cell::new(Rect::NOTHING); - let frame=|time,events| ctx.settle_ui(egui::RawInput { time:Some(time),screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(600.0,300.0))),events,..Default::default() },|ui| { - rect.set(context_meter(ui,None,true,true).rect); - }); - frame(0.0,vec![]); - frame(1.0,vec![egui::Event::PointerMoved(rect.get().center())]); - let mut actual=0; - for index in 1..=8 { - let output=frame(1.0+f64::from(index)*0.1,vec![]); - actual=output.shapes.iter().map(|shape|count(&shape.shape,CONTEXT_PENDING)).sum(); - } - assert_eq!(actual,1,"the shared ring owns the sole tooltip"); - } - - #[test] - #[ignore = "offscreen GPU visual acceptance for the single shared context tooltip"] - fn context_tooltip_visual_acceptance() { - let directory=std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); - let rect=std::cell::Cell::new(Rect::NOTHING); - let mut h=egui_kittest::Harness::builder().with_size(vec2(400.0,180.0)).with_pixels_per_point(1.5).with_step_dt(0.1).wgpu().build_ui(|ui| { - let t=Tokens::get(ui.ctx()).agent(); - ui.painter().rect_filled(ui.max_rect(),0.0,t.dock); - rect.set(context_meter(ui,None,true,true).rect); - }); - PhotocraftApp::setup_context(&h.ctx,crate::theme::ThemeKind::ProMedium); - h.ctx.all_styles_mut(|style|style.interaction.tooltip_delay=0.0); - h.run_steps(4); h.hover_at(rect.get().center()); h.run_steps(12); - h.render().unwrap().save(std::path::Path::new(&directory).join("context-single-tooltip.png")).unwrap(); - } - - - #[test] - fn context_meter_uses_selected_pi_capacity_with_the_existing_receipt() { - let models=vec![json!({"key":"grok","id":"grok-4.7","contextWindow":500000,"contextWindowSource":"pi-model-catalog:xai/grok-4.7"}),json!({"key":"other","id":"other","contextWindow":1000000,"contextWindowSource":"pi"})]; - let usage=json!({"version":1,"model":"grok-4.7","modelKey":"grok","contextTokens":17572,"contextSource":"pi-last-response","contextWindow":null}); - let selected=context_for_model(&usage,&models,"grok").unwrap();assert_eq!(context_label(Some(&selected)),"18K/500K"); - let other=context_for_model(&usage,&models,"other").unwrap();assert_eq!(context_fraction(Some(&other)),None);assert_eq!(other["contextWindow"],1000000); - assert!(!context_label(Some(&selected)).contains("tokens"));assert!(!context_label(Some(&other)).contains("未知")); - } - #[test] - fn model_visibility_hides_history_and_unready_chat_without_an_allowlist() { - for id in [ - "gpt-5.6-sol", "gpt-5.6-terra", "gpt-6-astra", "gpt-6-sol", "gpt-6.1-sol", - "gpt-6.1-terra", "gpt-6.2-astra", "glm-5.3", "glm-5.3-flashx", "glm-5.3-prime", - "claude-fable-5-1", "claude-opus-4-5-20251101", "claude-opus-4-6", "claude-opus-5-5", - "claude-haiku-4-5-20251001", "claude-sonnet-4-6", "gemini-3-flash", "gemini-3.1-pro", - "gemini-3.8-pro", "gemini-4-argon", "gemini-4-carbon", "grok-4.5", "grok-4.6", - "world-generation", "deepseek-ocr", - ] { - let model = json!({"id":id, "productionReady":true}); - assert!(is_hidden_model(ModelRole::Chat, &model), "{id}"); - assert!(is_hidden_model(ModelRole::Copy, &model), "{id}"); - } - for id in [ - "gpt-6.2-sol", "claude-sonnet-5-5", "claude-sonnet-5", "claude-haiku-5-5", - "gemini-4-hydrogen", "gemini-4-neon", "grok-4.7", "deepseek-v4.1-flash-1017", - "qwen4-max", "98k-future-visual", - ] { - assert!(!is_hidden_model(ModelRole::Chat, &json!({"id":id, "productionReady":true})), "{id}"); - } - let text_only = json!({"id":"text-only", "productionReady":false}); - assert!(is_hidden_model(ModelRole::Chat, &text_only)); - assert!(!is_hidden_model(ModelRole::Copy, &text_only)); - assert!(!is_hidden_model(ModelRole::Chat, &json!({"id":"98k-future"}))); - } - - #[test] - fn model_picker_preserves_saved_history_and_toggles_other_hidden_options() { - use egui_kittest::{Harness, kittest::Queryable}; - - for width in [960.0, 360.0] { - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - w.reduce_motion = true; - w.available_models = None; - w.model = "saved-alias".into(); - w.models = vec![ - json!({"key":"saved-alias","id":"claude-opus-4-6","productionReady":true,"productionVerified":true}), - json!({"key":"history","id":"grok-4.6","productionReady":true,"productionVerified":true}), - json!({"key":"text","id":"text-only","productionReady":false,"imageInputStatus":"disabled"}), - json!({"key":"new","id":"gpt-6.2-sol","productionReady":true,"productionVerified":true}), - json!({"key":"future","id":"98k-future-visual"}), - ]; - let snapshots = std::env::var_os("PHOTOCRAFT_MODEL_PICKER_SNAPSHOTS"); - let builder = Harness::builder().with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .with_size(vec2(width, 600.0)); - let builder = if snapshots.is_some() { builder.wgpu() } else { builder }; - let mut h = builder.build_ui_state(|ui, w: &mut Workspace| { - w.model_picker(ui, ModelRole::Chat, 180.0, true); - }, w); - let mut click = |label: &str| { - let point = h.get_by_label(label).rect().center(); - h.hover_at(point); - h.run_steps(2); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: point, button: egui::PointerButton::Primary, - pressed, modifiers: egui::Modifiers::NONE }); - h.run_steps(1); - } - h.run_steps(4); - }; - click("claude-opus-4-6"); - let toggle = "显示历史/全部模型"; - let legacy = "grok-4.6 · 可制作"; - let text_only = "text-only · 仅文本"; - for show_all in [false, true, false] { - assert_eq!(h.state().show_all_models, show_all); - assert!(h.query_by_label("claude-opus-4-6 · 可制作").is_some()); - assert!(h.query_by_label("gpt-6.2-sol · 可制作").is_some()); - assert!(h.query_by_label("98k-future-visual").is_some()); - assert_eq!(h.query_by_label(legacy).is_some(), show_all); - assert_eq!(h.query_by_label(text_only).is_some(), show_all); - if let Some(path) = &snapshots { - h.render().unwrap().save(std::path::Path::new(path).join(format!("models-{width}-{show_all}.png"))).unwrap(); - } - h.get_by_label(toggle).click(); - h.run_steps(4); - } - assert_eq!(h.state().model, "saved-alias"); - assert!(requests.try_recv().is_err()); - } - } - - #[test] - fn switching_a_model_saves_only_that_preference_with_the_connected_key() { - use egui_kittest::{Harness, kittest::Queryable}; - - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - w.reduce_motion = true; - w.copy_model = "one".into(); - w.copy_models = vec![json!({"key":"one","id":"Copy One"}), json!({"key":"two","id":"Copy Two"})]; - w.available_models = Some(vec!["Copy One".into(), "Copy Two".into()]); - w.copy_ready = true; - let mut h = Harness::builder().with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .with_size(vec2(600., 500.)).build_ui_state(|ui, w: &mut Workspace| { - w.model_picker(ui, ModelRole::Copy, 300., true); - }, w); - h.run_steps(5); - for label in ["Copy One", "Copy Two"] { - let point = h.get_by_label(label).rect().center(); - h.hover_at(point); - h.run_steps(2); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { - pos:point,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE, - }); - h.run_steps(1); - } - h.run_steps(4); - } - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected a local preference action") }; - assert_eq!(method, "select-model"); - assert_eq!(input["field"], "copyModel"); - assert_eq!(input["selection"], "two"); - assert!(input.get("key").is_none()); - assert!(h.state().model_ready && h.state().copy_ready && h.state().image_ready); - let w = h.state_mut(); - w.receive_model_preference(&input); - assert_eq!(w.copy_model, "two"); - assert_eq!(w.model, "discussion"); - assert_eq!(w.image_model, "image"); - assert!(w.model_ready && w.copy_ready && w.image_ready); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn model_menu_exit_stays_above_the_settings_panel() { - fn text_order(shape:&egui::Shape,labels:&mut Vec){match shape{egui::Shape::Vec(shapes)=>for shape in shapes{text_order(shape,labels)},egui::Shape::Text(text)=>labels.push(text.galley.text().into()),_=>{}}} - let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let (mut app,requests)=dock_fixture();let w=app.jiansun.as_mut().unwrap();w.model_settings=true;w.reduce_motion=false; - w.copy_models=vec![json!({"key":"a","id":"文案当前模型"}),json!({"key":"b","id":"文案备选模型"})];w.copy_model="a".into();w.available_models=None; - let frame=|w:&mut Workspace,time:f64,events|ctx.settle_ui(egui::RawInput{time:Some(time),events,screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(800.0,700.0))),..Default::default()},|ui|{let anchor=ui.button("设置");w.settings_popup(ui,&anchor);}); - for i in 0..20 {let _=frame(w,f64::from(i)*0.05,vec![]);} - let id=ctx.data(|data|data.get_temp::(Id::unique(("agent-model-last-popup",ModelRole::Copy,true)))).unwrap();egui::Popup::open_id(&ctx,id); - for i in 20..30 {let _=frame(w,f64::from(i)*0.05,vec![]);} - egui::Popup::close_id(&ctx,id); - for time in [1.501,1.55] { - let output=frame(w,time,vec![]);let mut labels=Vec::new();for clipped in &output.shapes{text_order(&clipped.shape,&mut labels);} - let panel=labels.iter().position(|label|label=="小壹设置").unwrap();let menu=labels.iter().position(|label|label=="文案备选模型").expect("the closing menu stays mounted");assert!(menu>panel,"the retained menu paints above its parent throughout exit"); - } - assert!(requests.try_recv().is_err());assert_eq!(w.copy_model,"a"); - } - #[test] - fn context_meter_keeps_chat_usage_when_copy_model_reports_usage() { - let (mut app,_requests)=dock_fixture();let w=app.jiansun.as_mut().unwrap(); - w.model="chat".into();w.models=vec![json!({"key":"chat","id":"chat-model"})]; - let chat=json!({"version":1,"model":"chat-model","modelKey":"chat","contextTokens":58000,"contextSource":"pi-last-response","contextWindow":1000000,"capacitySource":"pi-models"}); - w.receive_chat_context_usage(&chat);w.receive_chat_context_usage(&json!({"version":1,"model":"copy-model","modelKey":"copy","contextTokens":20000})); - assert_eq!(w.pi_context_usage,chat);assert_eq!(context_label(Some(&w.pi_context_usage)),"58K/1M"); - } - - #[test] - fn context_meter_never_treats_missing_or_invalid_measurement_as_zero() { - assert_eq!(context_fraction(None), None); - let mut usage=json!({"contextSource":"pi-session","contextTokens":25,"contextWindow":100,"capacitySource":"catalog", - "piContextUsage":{"tokens":25,"contextWindow":100,"percent":37.0}}); - assert_eq!(context_fraction(Some(&usage)), Some(0.37), "use Pi's percentage, not a local ratio"); - usage["piContextUsage"]["percent"]=Value::Null; assert_eq!(context_fraction(Some(&usage)), None); - usage["piContextUsage"]["percent"]=json!(101); assert_eq!(context_fraction(Some(&usage)), None); - usage["piContextUsage"]["percent"]=json!(25); usage["piContextUsage"]["contextWindow"]=json!(200); assert_eq!(context_fraction(Some(&usage)), None); - } - - #[test] - fn context_meter_shows_real_usage_without_inventing_capacity_or_crossing_models() { - let models = vec![json!({"key":"chat-a","id":"model-a"}), json!({"key":"chat-b","id":"model-b"})]; - let mut usage = json!({"version":1,"model":"model-a","modelKey":"chat-a","receipt":{"inputTokens":140,"cachedTokens":100}}); - assert_eq!(context_label(context_for_model(&usage, &models, "chat-a").as_ref()), CONTEXT_UNAVAILABLE); - assert_eq!(context_label(context_for_model(&usage, &models, "chat-b").as_ref()), CONTEXT_UNAVAILABLE); - usage["estimatedTokens"] = json!(200); - assert_eq!(context_label(Some(&usage)), CONTEXT_UNAVAILABLE, "discard the previous custom byte estimate"); - usage["contextTokens"] = json!(150); - usage["contextSource"] = json!("pi-last-response"); - assert_eq!(context_label(Some(&usage)), CONTEXT_UNAVAILABLE); - usage["contextTokens"] = json!(200); - usage["contextSource"] = json!("pi-session"); - usage["contextWindow"] = json!(1000); - assert_eq!(context_label(Some(&usage)), CONTEXT_UNAVAILABLE); - usage["capacitySource"] = json!("explicit-catalogue"); - usage["piContextUsage"] = json!({"tokens":200,"contextWindow":1000,"percent":20}); - assert_eq!(context_label(Some(&usage)), "200/1K"); - usage["contextTokens"] = json!(-1); - assert_eq!(context_label(Some(&usage)), "—/1K"); - } - - #[test] - fn readable_error_history_and_candidate_view_do_not_repeat_a_request_or_change_the_draft() { - let (mut app,requests)=dock_fixture(); - let mut w=app.jiansun.take().unwrap(); - w.origin="https://example.test".into(); - w.project_context=json!({"localId":"same-project"}); - w.owner_doc=app.session.active().map(|state|state.doc.id.0); - w.reduce_motion=true; - w.error="can't read smart source within the preview budget: pcraft: limit exceeded: canvas 1440x35827 exceeds 8192 pixels per side".into(); - w.template_workflow=json!({"slots":[{"candidates":[{"id":"retained-image","status":"complete"}]}]}); - let draft=w.composer.clone();let messages=w.messages.clone(); - let revision=app.session.active().unwrap().revision; - let ctx=egui::Context::default(); - crate::PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let id=notification_id(&w.origin,&w.account,&w.project_context,w.owner_doc).unwrap(); - let mut history=AgentNotifications {open:true,..Default::default()}; - history.add("本地SDK操作失败;请检查原请求状态,勿重发"); - ctx.data_mut(|data|data.insert_temp(id,history)); - let out={ - let mut last=None; - for n in 0..5 { - last=Some(ctx.settle_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(500.,700.))),time:Some(n as f64*0.1),..Default::default()},|ui| {w.notifications_ui(ui);})); - } - last.unwrap() - }; - let text=out.shapes.iter().filter_map(|shape|match &shape.shape {egui::Shape::Text(text)=>Some(text.galley.text()),_=>None}).collect::>().join("\n"); - assert!(text.contains("当前问题")); - assert!(text.contains("图片暂时无法读取") && !text.contains("can't read smart source"),"technical details start collapsed"); - let rect:[f32;4]=serde_json::from_value(w.panel_geometry["notificationCandidates"].clone()).unwrap(); - let at=egui::pos2(rect[0]+rect[2]/2.,rect[1]+rect[3]/2.); - let mut clicked=false; - for (time,pressed) in [(0.6,true),(0.7,false)] { - let _=ctx.settle_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(500.,700.))),time:Some(time),events:vec![egui::Event::PointerMoved(at),egui::Event::PointerButton {pos:at,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE}],..Default::default()},|ui| {clicked|=w.notifications_ui(ui);}); - } - assert!(clicked); - assert!(requests.try_recv().is_err(),"viewing retained candidates must not call a model or send an operation"); - assert_eq!(w.composer,draft);assert_eq!(w.messages,messages); - assert_eq!(app.session.active().unwrap().revision,revision); - w.error.clear(); - ctx.data_mut(|data|data.get_temp_mut_or_default::(id).open=true); - let out=ctx.settle_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(500.,700.))),time:Some(1.),..Default::default()},|ui| {w.notifications_ui(ui);}); - let text=out.shapes.iter().filter_map(|shape|match &shape.shape {egui::Shape::Text(text)=>Some(text.galley.text()),_=>None}).collect::>().join("\n"); - assert!(text.contains("历史通知") && !text.contains("当前问题")); - assert_eq!(ctx.data(|data|data.get_temp::(id).unwrap().entries.len()),2,"historical records remain available after the active issue ends"); - } - - #[test] - fn notification_history_uses_real_errors_and_persisted_export_receipts() { - let mut history = AgentNotifications::default(); - let receipts = vec![ - json!({"text":"普通回复不会变成通知"}), - json!({"text":"保存副本时有导出提示:\n保留工程"}), - ]; - history.observe("", true, None, &[]); - history.observe("连接暂不可用", true, Some("提示库离线,本机内容已保留"), &receipts); - assert_eq!(history.entries.len(), 4); - history.observe("连接暂不可用", true, Some("提示库离线,本机内容已保留"), &receipts); - assert_eq!(history.entries.len(), 4, "a repaint cannot replay a notification"); - assert!(!history.entries.iter().any(|entry| entry.contains("普通回复"))); - history.observe("", false, None, &[]); - assert_eq!(history.entries.len(), 4, "resolved issues remain reviewable in the current session"); - for i in 0..45 { history.add(&format!("真实错误 {i}")); } - assert_eq!(history.entries.len(), 40, "session history stays bounded"); - } - - #[test] - fn notifications_fit_a_small_window_and_escape_preserves_history() { - let (tx, requests) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - while requests.try_recv().is_ok() {} - w.origin = "https://example.test".into(); - w.account = json!({"id":"owner"}); - w.project_context = json!({"localId":"qa"}); - w.owner_doc = Some(42); - w.reduce_motion = true; - let id = notification_id(&w.origin, &w.account, &w.project_context, w.owner_doc).unwrap(); - let ctx = egui::Context::default(); - let mut history = AgentNotifications { open:true, ..Default::default() }; - history.add(&"导出提示:请保留分层工程与原素材。".repeat(12)); - ctx.data_mut(|data| data.insert_temp(id, history)); - let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 300.0)); - for frame in 0..4 { - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(screen), time:Some(frame as f64 * 0.1), ..Default::default() }, |ui| {w.notifications_ui(ui);}); - } - let rect: [f32; 4] = serde_json::from_value(w.panel_geometry["notifications"].clone()).unwrap(); - assert!(screen.contains_rect(Rect::from_min_size(egui::pos2(rect[0],rect[1]),vec2(rect[2],rect[3]))), "long notifications must scroll inside the viewport: {rect:?}"); - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(screen), time:Some(0.5), events:vec![egui::Event::Key { - key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed:true, repeat:false, modifiers:egui::Modifiers::NONE, - }], ..Default::default() }, |ui| { - w.notifications_ui(ui); - assert!(!ui.input(|input| input.key_pressed(egui::Key::Escape)), "a handled close cannot leak to the underlying editor"); - }); - let history = ctx.data(|data| data.get_temp::(id)).unwrap(); - assert!(!history.open); - assert_eq!(history.entries.len(), 1, "closing a view never deletes its real warning"); - assert_eq!(w.panel_geometry["notificationsOpen"], false); - assert!(requests.try_recv().is_err(), "reviewing and closing notifications sends no backend request"); - } - - #[test] - fn notification_escape_has_priority_in_the_actual_composer_path() { - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - w.owner_doc = Some(app.session.active().unwrap().doc.id.0); - w.project_context = json!({"localId":"keyboard-review"}); - w.model_settings = true; - w.reduce_motion = true; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let id = notification_id(&w.origin, &w.account, &w.project_context, w.owner_doc).unwrap(); - ctx.data_mut(|data| data.insert_temp(id, AgentNotifications { open:true, ..Default::default() })); - let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0,600.0)); - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(screen), ..Default::default() }, |ui| w.composer_ui(&mut app, ui)); - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(screen), - events:vec![egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed:true, repeat:false, - modifiers:egui::Modifiers::NONE }], ..Default::default() }, |ui| w.composer_ui(&mut app, ui)); - assert!(!ctx.data(|data| data.get_temp::(id).unwrap().open)); - assert!(w.model_settings, "the underlying settings must not consume a close intended for the notification"); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn toast_and_morph_are_scoped_and_have_real_lifetimes() { - let toast = AgentToast { shown_at: 10.0 }; - assert!(toast_active(&toast, 10.0)); - assert!(toast_active(&toast, 12.39)); - assert!(!toast_active(&toast, 12.4)); - assert!(!toast_active(&toast, 9.9)); - assert!(!toast_active(&toast, f64::NAN)); - let account = json!({"id":"a"}); - let project = json!({"localId":"project"}); - let id = toast_id("https://one", &account, &project, Some(4)).unwrap(); - assert_ne!(Some(id), toast_id("https://other", &account, &project, Some(4))); - assert_ne!(Some(id), toast_id("https://one", &json!({"id":"b"}), &project, Some(4))); - assert_ne!(Some(id), toast_id("https://one", &account, &project, Some(5))); - assert_eq!(toast_id("https://one", &Value::Null, &project, Some(4)), None); - let conversation = Id::unique("project-a"); - assert_eq!(activity_morph_id(conversation, &[2, 5]), activity_morph_id(conversation, &[2, 5, 8])); - assert_ne!(activity_morph_id(conversation, &[2]), activity_morph_id(Id::unique("project-b"), &[2])); - assert_ne!(activity_morph_id(conversation, &[2]), activity_morph_id(conversation, &[3])); - } - - #[test] - fn copy_reply_emits_only_the_exact_visible_reply_on_user_click() { - let ctx = egui::Context::default(); - let mut rect = Rect::NOTHING; - let render = |time, events, rect: &mut Rect| ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 100.0))), time: Some(time), events, ..Default::default() - }, |ui| { *rect = copy_reply(ui, "真实中文回复").rect; }); - let idle = render(0.0, vec![], &mut rect); - assert!(idle.platform_output.commands.is_empty()); - let pos = rect.center(); - let pointer = |pressed| vec![egui::Event::PointerMoved(pos), egui::Event::PointerButton { - pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, - }]; - let _ = render(0.1, pointer(true), &mut rect); - let released = render(0.2, pointer(false), &mut rect); - assert_eq!(released.platform_output.commands, [egui::OutputCommand::CopyText("真实中文回复".into())]); - } - - #[test] - fn suggestions_preserve_draft_and_only_compare_real_candidates_in_the_selected_scope() { - let mut draft = "保留已有要求".to_owned(); - insert_suggestion(&mut draft, "先讨论画面"); - assert_eq!(draft, "保留已有要求\n先讨论画面"); - let mut empty = " ".to_owned(); - insert_suggestion(&mut empty, "梳理资料"); - assert_eq!(empty, "梳理资料"); - - let target = json!({"slotId":"one","productVariantId":"teak"}); - let mut workflow = json!({"slots":[{"id":"one","variantId":"teak","candidates":[ - {"id":"a","status":"complete"}, {"id":"b","status":"running"}, {"id":"c","status":"complete","variant":"walnut"} - ]}]}); - assert!(!has_comparable_candidates(&workflow, &target), "running or another variant is not a comparable result"); - workflow["slots"][0]["candidates"][1]["status"] = json!("complete"); - assert!(has_comparable_candidates(&workflow, &target)); - workflow["slots"][0]["candidates"][1]["id"] = json!("a"); - assert!(!has_comparable_candidates(&workflow, &target), "duplicate candidate IDs count only once"); - assert!(!has_comparable_candidates(&workflow, &json!({"slotId":"one"})), "unknown variant must not be guessed"); - } - - fn dock_click(ctx: &egui::Context, app: &mut PhotocraftApp, key: &str) { - let pos = geometry(app.jiansun.as_ref().unwrap(), key).center(); - for pressed in [true, false] { - dock_frame( - ctx, - app, - vec![ - egui::Event::PointerMoved(pos), - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, - ], - ); - } - dock_frame(ctx, app, vec![]); - } - - #[test] - fn conversation_places_choices_below_the_image_in_the_same_turn() { - fn label_top(shape: &egui::Shape, wanted: &str) -> Option { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().find_map(|shape| label_top(shape, wanted)), - egui::Shape::Text(text) if text.galley.text() == wanted => Some(text.pos.y), - _ => None, - } - } - let (mut app, _) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.messages = vec![ - json!({"role":"user","text":"生成首图"}), - json!({"role":"assistant","kind":"image","taskId":"layout-image"}), - json!({"role":"assistant","kind":"pi-ui-request","request":{"id":"choose","title":"首屏主图怎么处理"}}), - ]; - let mut output = ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(500.0, 800.0))), - ..Default::default() - }, |ui| { - let turn = turns(&w.messages).into_iter().next().unwrap(); - w.turn_ui(ui, turn, Id::unique("layout"), 1, true, false, None); - }); - output.textures_delta.clear(); - let top = |wanted| output.shapes.iter().find_map(|shape| label_top(&shape.shape, wanted)).unwrap(); - assert!(top("生成图片") < top("首屏主图怎么处理")); - } - - #[test] - fn conversation_preview_eviction_retains_measured_layout() { - let (mut app, _) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let frame = |app: &PhotocraftApp| { - let mut bounds = Rect::NOTHING; - let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| { - let start = ui.cursor().min; - app.jiansun.as_ref().unwrap().image_result(ui, &json!({"taskId":"layout-image"}), 112.0, None); - bounds = Rect::from_min_max(start, ui.cursor().min); - }); - output.textures_delta.clear(); - bounds - }; - for size in [[100, 20], [20, 100]] { - let texture = ctx.load_texture("layout-image", egui::ColorImage::filled(size, Color32::WHITE), egui::TextureOptions::LINEAR); - app.jiansun.as_mut().unwrap().agent_images.insert("layout-image".into(), texture); - let hot = frame(&app); - app.jiansun.as_mut().unwrap().agent_images.remove("layout-image"); - assert_eq!(hot, frame(&app), "eviction must retain the measured image layout"); - } - } - - #[test] - fn conversation_result_preserves_image_ratio_and_overlays_the_caption() { - let (mut app, _) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for dimensions in [[200, 100], [100, 200]] { - let texture = ctx.load_texture("result", egui::ColorImage::filled(dimensions, Color32::WHITE), egui::TextureOptions::LINEAR); - let texture_id = texture.id(); - let w = app.jiansun.as_mut().unwrap(); - w.agent_images.insert("result".into(), texture); - let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| { - w.image_result(ui, &json!({"taskId":"result"}), 200.0, None); - }); - output.textures_delta.clear(); - let image = output.shapes.iter().find_map(|shape| match &shape.shape { - egui::Shape::Rect(rect) if rect.fill_texture_id() == texture_id => Some(rect.rect), - _ => None, - }).expect("preview texture"); - let caption = output.shapes.iter().find_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text() == "候选图片" => Some(Rect::from_min_size(text.pos, text.galley.size())), - _ => None, - }).expect("image caption"); - assert!((image.width() / image.height() - dimensions[0] as f32 / dimensions[1] as f32).abs() < 0.01); - assert!(image.contains_rect(caption)); - } - } - - #[test] - fn offscreen_conversation_preview_does_not_refresh_texture_recency() { - let (mut app, _) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for id in ["hidden", "recent"] { - let texture = ctx.load_texture(id, egui::ColorImage::filled([8, 8], Color32::WHITE), egui::TextureOptions::LINEAR); - app.jiansun.as_mut().unwrap().agent_images.insert(id.into(), texture); - } - ctx.settle_ui(egui::RawInput::default(), |ui| { - ui.set_clip_rect(Rect::from_min_size(pos2(5000.0, 5000.0), vec2(20.0, 20.0))); - app.jiansun.as_ref().unwrap().image_result(ui, &json!({"taskId":"hidden"}), 112.0, None); - }).textures_delta.clear(); - let cache = &app.jiansun.as_ref().unwrap().agent_images; - assert_eq!(cache.iter().next().map(|(key, _)| key.as_str()), Some("hidden")); - ctx.settle_ui(egui::RawInput::default(), |ui| { - app.jiansun.as_ref().unwrap().image_result(ui, &json!({"taskId":"hidden"}), 112.0, None); - }).textures_delta.clear(); - assert_eq!(cache.iter().next_back().map(|(key, _)| key.as_str()), Some("hidden")); - } - - #[test] - fn conversation_image_context_menu_uses_stitch_popup_and_keeps_its_own_target() { - fn scan(shape: &egui::Shape, texture: egui::TextureId, fill: Color32, image: &mut Option, frame: &mut Option, label: &mut Option) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| scan(shape, texture, fill, image, frame, label)), - egui::Shape::Rect(rect) if rect.fill_texture_id() == texture => *image = Some(rect.rect), - egui::Shape::Rect(rect) if rect.fill == fill && rect.corner_radius == egui::CornerRadius::same(8) => *frame = Some(rect.rect), - egui::Shape::Text(text) if text.galley.text() == "查看大图" => *label = Some(Rect::from_min_size(text.pos, text.galley.size())), - _ => {} - } - } - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let texture = ctx.load_texture("history-candidate", egui::ColorImage::filled([80, 80], Color32::WHITE), egui::TextureOptions::LINEAR); - let texture_id = texture.id(); - app.jiansun.as_mut().unwrap().agent_images.insert("image-a".into(), texture); - let value = json!({"taskId":"image-a", "slotId":"slot-a", "productVariantId":"color-a"}); - // Context popups have a real fade-in and an initial sizing pass. Advance - // time between frames before inspecting their final frame colors. - let time = std::cell::Cell::new(0.0); - let run = |ctx: &egui::Context, app: &PhotocraftApp, events| { - let current = time.get(); - time.set(current + 0.25); - let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), time: Some(current), events, ..Default::default() }, |ui| { - app.jiansun.as_ref().unwrap().image_result(ui, &value, 112.0, None); - }); - output.textures_delta.clear(); - output - }; - let first = run(&ctx, &app, vec![]); - let mut image = None; - let mut frame = None; - let mut label = None; - let fill = super::super::stitch_ui::menu_base(); - for shape in &first.shapes { scan(&shape.shape, texture_id, fill, &mut image, &mut frame, &mut label); } - let pos = image.expect("history result contains the actual preview texture").center(); - for pressed in [true, false] { - run(&ctx, &app, vec![egui::Event::PointerMoved(pos), egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }]); - } - let opened = run(&ctx, &app, vec![]); - image = None; frame = None; label = None; - for shape in &opened.shapes { scan(&shape.shape, texture_id, fill, &mut image, &mut frame, &mut label); } - let pos = label.expect("the context popup exposes original-image preview").center(); - let frame = frame.expect("the opened context popup uses the scoped Stitch frame after its fade-in"); - assert!((176.0..=208.0).contains(&frame.width()), "the menu stays compact instead of filling the canvas: {}", frame.width()); - for pressed in [true, false] { - run(&ctx, &app, vec![egui::Event::PointerMoved(pos), egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }]); - } - assert_eq!(ctx.data(|data| data.get_temp::(Id::unique("jiansun-image-expanded"))), Some("image-a".into())); - assert!(requests.try_recv().is_err(), "opening a preview never sends a model request"); - } - - #[test] - fn image_card_reference_menu_attaches_placeholder_and_loaded_images() { - use egui_kittest::kittest::Queryable; - for (width, theme, original) in [(520.0, crate::theme::ThemeKind::ProMedium, false), - (260.0, crate::theme::ThemeKind::ProLight, true)] { - let (mut app, requests) = dock_fixture(); - let doc = app.session.active().unwrap().doc.id.0; - let workspace = app.jiansun.as_mut().unwrap(); - workspace.reduce_motion = true; - workspace.composer.clear(); - workspace.messages.truncate(1); - let kind = if original { "template-image" } else { "image" }; - workspace.messages.push(json!({"role":"assistant","kind":kind,"taskId":"reference-card", - "documentId":doc,"fieldId":"hero","label":"首屏"})); - let directory = std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").map(std::path::PathBuf::from); - let mut builder = egui_kittest::Harness::builder().with_size(vec2(width, 680.0)) - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests).with_max_steps(64); - let _gpu = directory.as_ref().map(|_| photocraft_testkit::gpu_lock()); - if directory.is_some() { builder = builder.wgpu(); } - let mut harness = builder.build_ui_state(|ui, app| { - if super::super::stitch_ui::ui_fonts_ready(ui) { super::super::agent_dock(app, ui); } - }, app); - PhotocraftApp::setup_context(&harness.ctx, theme); - if !original { - let texture = harness.ctx.load_texture("reference-card", - egui::ColorImage::filled([80, 60], Color32::from_rgb(158, 113, 73)), Default::default()); - harness.state_mut().jiansun.as_mut().unwrap().agent_images.insert("reference-card".into(), texture); - } - harness.run_steps(8); - let card_label = if original { "模板原图加载中" } else { "定位 首屏" }; - let pos = harness.get_by_label(card_label).rect().center(); - for pressed in [true, false] { - harness.event(egui::Event::PointerMoved(pos)); - harness.event(egui::Event::PointerButton { pos, button:egui::PointerButton::Secondary, - pressed, modifiers:egui::Modifiers::NONE }); - harness.run_steps(2); - } - let item = harness.get_by_label("引用到小壹"); - assert!(item.rect().left() >= 0.0 && item.rect().right() <= width); - if let Some(directory) = &directory { - std::fs::create_dir_all(directory).unwrap(); - harness.render().unwrap().save(directory.join(format!("xiaoyi-image-reference-menu-{width}.png"))).unwrap(); - } - harness.get_by_label("引用到小壹").click(); - harness.run_steps(4); - let app = harness.state(); - let workspace = app.jiansun.as_ref().unwrap(); - let refs = workspace.composer_reference_snapshot(app).unwrap(); - let reference = refs.iter().find(|item| item["taskId"] == "reference-card").unwrap(); - assert_eq!(reference["kind"], kind); - assert_eq!(reference["fieldId"], "hero"); - assert!(harness.ctx.memory(|memory| memory.has_focus(super::super::composer_input_id()))); - assert!(requests.try_iter().all(|request| !matches!(request, Request::Action(method, _) if method == "agent"))); - } - } - - #[test] - fn model_menu_uses_stitch_rows_and_only_selects_available_models() { - fn labels(shape: &egui::Shape, out: &mut Vec<(String, Rect, usize)>) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| labels(shape, out)), - egui::Shape::Text(text) => out.push((text.galley.text().to_owned(), Rect::from_min_size(text.pos, text.galley.size()), text.galley.rows.len())), - _ => {} - } - } - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - { - let w = app.jiansun.as_mut().unwrap(); - w.key_saved = false; - w.models.push(json!({"key":"new-model","id":"测试模型甲"})); - w.models.push(json!({"key":"long-model","id":"测试超长名称模型用于验证菜单不会在窄窗口隐藏完整模型名称测试超长名称模型"})); - w.models.push(json!({"key":"blocked-model","id":"未开放模型乙"})); - w.available_models = Some(vec!["对话模型".into(), "测试模型甲".into(), "测试超长名称模型用于验证菜单不会在窄窗口隐藏完整模型名称测试超长名称模型".into()]); - } - for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } - dock_click(&ctx, &mut app, "settings"); - for _ in 0..18 { dock_frame(&ctx, &mut app, vec![]); } - dock_click(&ctx, &mut app, "chatModel"); - for _ in 0..18 { dock_frame(&ctx, &mut app, vec![]); } - let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)); - let mut text = Vec::new(); - for shape in &output.shapes { labels(&shape.shape, &mut text); } - let unselected = text.iter().find(|(name, _, _)| name == "未选择").expect("the menu renders an unselected option").1; - assert!(text.iter().any(|(name, _, _)| name == "未开放模型乙 · Key未开放")); - let available = text.iter().find(|(name, _, _)| name == "测试模型甲").expect("the open menu renders an available model").1; - assert!((unselected.left() - available.left()).abs() < 2.0, "option text shares a left edge instead of being centered"); - let long = text.iter().find(|(name, _, _)| name == "测试超长名称模型用于验证菜单不会在窄窗口隐藏完整模型名称测试超长名称模型").expect("long model name is present"); - assert!(long.1.width() <= 560.0, "the full name fits or wraps within the responsive popup"); - assert!((unselected.left() - long.1.left()).abs() < 2.0, "wrapped option starts on the same left edge"); - let target = available.center(); - for pressed in [true, false] { - dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(target), egui::Event::PointerButton { pos: target, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }]); - } - assert_eq!(app.jiansun.as_ref().unwrap().model, "new-model"); - assert!(app.jiansun.as_ref().unwrap().key_settings, "choosing a model without a saved key opens connection setup"); - assert!(requests.try_recv().is_err(), "opening and selecting locally must not send a model request"); - } - - #[test] - fn model_menu_closes_on_scope_change_and_when_controls_are_disabled() { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let w = app.jiansun.as_mut().unwrap(); - let frame = |w: &mut Workspace| { - let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), ..Default::default() }, - |ui| { w.model_picker(ui, ModelRole::Chat, 160.0, true); }); - }; - let last = Id::unique(("agent-model-last-popup", ModelRole::Chat, true)); - frame(w); - let first = ctx.data(|d| d.get_temp::(last)).unwrap(); - egui::Popup::open_id(&ctx, first); - assert!(egui::Popup::is_id_open(&ctx, first)); - w.project_context["localId"] = json!("another-project"); - frame(w); - let second = ctx.data(|d| d.get_temp::(last)).unwrap(); - assert_ne!(first, second); - assert!(!egui::Popup::is_id_open(&ctx, first)); - egui::Popup::open_id(&ctx, second); - w.busy = Some("pi-agent".into()); - frame(w); - assert!(!egui::Popup::is_id_open(&ctx, second)); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn thinking_picker_labels_the_automatic_setting_and_keeps_its_empty_value() { - use egui_kittest::kittest::Queryable; - for width in [250.0, 520.0] { - let (mut app, requests) = dock_fixture(); - let mut workspace = app.jiansun.take().unwrap(); - workspace.reduce_motion = true; - workspace.models[0]["reasoning"] = json!(true); - workspace.models[0]["reasoningEfforts"] = json!(["high"]); - workspace.thinking_by_model[workspace.model.as_str()] = json!("high"); - - let mut harness = egui_kittest::Harness::builder() - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .with_size(vec2(width, 240.0)) - .build_ui_state(|ui, workspace: &mut Workspace| workspace.thinking_picker(ui), workspace); - harness.run_steps(4); - harness.get_by_label("高").click(); - harness.run_steps(4); - harness.get_by_label("自动").click(); - harness.run_steps(4); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected a local preference action") }; - assert_eq!(method, "select-model"); - assert_eq!(input["field"], "thinkingLevel"); - assert_eq!(input["selection"], ""); - } - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] - fn thinking_picker_visual_acceptance() { - use egui_kittest::kittest::Queryable; - let _gpu = photocraft_testkit::gpu_lock(); - let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - struct Preview(PhotocraftApp); - impl eframe::App for Preview { - fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { - super::super::agent_dock(&mut self.0, ui); - } - } - for width in [250.0, 520.0] { - let (mut app, requests) = dock_fixture(); - let workspace = app.jiansun.as_mut().unwrap(); - workspace.reduce_motion = true; - workspace.model_settings = true; - workspace.models[0]["reasoning"] = json!(true); - workspace.models[0]["reasoningEfforts"] = json!(["low","medium","high"]); - let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 760.0)).wgpu().build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); - app.gpu_render_state = cc.wgpu_render_state.clone(); - Preview(app) - }); - harness.run_steps(6); - let trigger = geometry(harness.state().0.jiansun.as_ref().unwrap(), "thinkingLevel"); - assert!(trigger.left() >= 0.0 && trigger.right() <= width); - harness.get_by_label("自动").click(); - harness.run_steps(4); - harness.render().unwrap().save(directory.join(format!("thinking-picker-{width}.png"))).unwrap(); - harness.get_by_label("高").click(); - harness.run_steps(4); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected a local preference action") }; - assert_eq!(method, "select-model"); - assert_eq!(input["field"], "thinkingLevel"); - assert_eq!(input["selection"], "high"); - } - } - - #[test] - fn focused_model_picker_uses_the_list_without_a_duplicate_tooltip() { - fn labels(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| labels(shape, out)), - egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), - _ => {} - } - } - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let w = app.jiansun.as_mut().unwrap(); - let name = "很长的对话模型名称在狭窄侧栏中仍需可以通过键盘完整查看"; - w.models = vec![json!({"key":"long", "id":name})]; - w.model = "long".into(); - w.reduce_motion = true; - let frame = |w: &mut Workspace, events: Vec| { - let mut response_id = None; - let output = ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(360.0, 600.0))), - events, ..Default::default() - }, |ui| { response_id = Some(w.model_picker(ui, ModelRole::Chat, 80.0, true).id); }); - (output, response_id.unwrap()) - }; - let (_, id) = frame(w, vec![]); - ctx.memory_mut(|memory| memory.request_focus(id)); - let mut text = Vec::new(); - for _ in 0..4 { - let (focused, _) = frame(w, vec![]); - for shape in &focused.shapes { labels(&shape.shape, &mut text); } - } - assert!(ctx.memory(|memory| memory.has_focus(id)), "the model picker receives keyboard focus"); - assert!(!text.iter().any(|text| text == &format!("对话模型:{name}")), "focus does not add a duplicate native tooltip"); - frame(w, vec![enter_event(egui::Modifiers::NONE, false)]); - frame(w, vec![enter_release()]); - assert!(egui::Popup::is_id_open(&ctx, id.with("popup")), "Enter opens the focused model picker"); - text.clear(); - let (opened, _) = frame(w, vec![]); - for shape in &opened.shapes { labels(&shape.shape, &mut text); } - assert!(text.iter().any(|text| text.contains(name)), "the opened list exposes the full model name"); - frame(w, vec![egui::Event::Key { key: egui::Key::Escape, physical_key: Some(egui::Key::Escape), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]); - assert!(!egui::Popup::is_id_open(&ctx, id.with("popup")), "Escape closes the model picker"); - assert_eq!(w.model, "long"); - assert!(requests.try_recv().is_err(), "reading and dismissing the list cannot reconfigure or call a model"); - } - - #[test] - fn connection_popup_uses_generic_local_key_copy_and_does_not_send() { - fn labels(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| labels(shape, out)), - egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), - _ => {} - } - } - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - { - let w = app.jiansun.as_mut().unwrap(); - w.key_saved = false; - w.key_settings = true; - w.model_settings = true; - w.reduce_motion = true; - } - let mut output = None; - for _ in 0..3 { - let mut frame = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)); - frame.textures_delta.clear(); - output = Some(frame); - } - let mut text = Vec::new(); - for shape in &output.unwrap().shapes { labels(&shape.shape, &mut text); } - assert!(text.iter().any(|text| text == "小壹设置")); - assert!(!text.iter().any(|text| text == "连接信息保存在本机,可随时更换。")); - assert!(text.iter().any(|text| text == "输入个人 Key")); - assert!(!text.iter().any(|text| text == CONTEXT_UNAVAILABLE), "missing usage does not add a permanent warning to settings"); - assert!(text.iter().all(|text| !text.to_lowercase().contains("98k"))); - assert!(requests.try_recv().is_err(), "opening connection settings must not send a model request"); - } - - #[test] - fn connection_popup_exit_keeps_visual_and_clears_key() { - fn has_label(shape: &egui::Shape, label: &str) -> bool { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().any(|shape| has_label(shape, label)), - egui::Shape::Text(text) => text.galley.text() == label, - _ => false, - } - } - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - { - let w = app.jiansun.as_mut().unwrap(); - w.model_settings = true; - w.key_settings = true; - w.api_key = "temporary-secret".into(); - w.xiaoyi_key = "synthetic-xiaoyi-draft".into(); - w.reduce_motion = false; - } - let frame = |time: f64, app: &mut PhotocraftApp| { - ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), - time: Some(time), - ..Default::default() - }, |ui| crate::panels::right_dock(app, ui)) - }; - for time in [0.0, 0.1, 0.3, 0.4] { let _ = frame(time, &mut app); } - { - let w = app.jiansun.as_mut().unwrap(); - w.model_settings = false; - w.key_settings = false; - } - let exiting = frame(0.41, &mut app); - assert!(app.jiansun.as_ref().unwrap().api_key.is_empty(), "closing must clear the secret before visual exit"); - assert!(app.jiansun.as_ref().unwrap().xiaoyi_key.is_empty()); - assert!(exiting.shapes.iter().any(|shape| has_label(&shape.shape, "小壹设置")), "the closing surface remains visible during exit"); - let _ = frame(0.7, &mut app); - let closed = frame(1.2, &mut app); - assert!(!closed.shapes.iter().any(|shape| has_label(&shape.shape, "小壹设置")), "the surface is removed after exit"); - assert!(requests.try_recv().is_err(), "display and exit must not dispatch a model request"); - } - - #[test] - fn image_preview_zoom_preserves_pointer_position_and_physical_pixel_scale() { - let viewport = vec2(400.0, 300.0); - let image = vec2(1600.0, 1200.0); - let mut view = ArtifactPreviewView::default(); - let at = vec2(35.0, 25.0); - let before = view.center + at / (image * view.scale(viewport, image, 1.5)); - view.zoom_at(1.0, at, viewport, image, 1.5); - let after = view.center + at / (image * view.scale(viewport, image, 1.5)); - assert!((before - after).length() < 0.0001); - assert!((view.scale(viewport, image, 1.5) * 1.5 - 1.0).abs() < 0.0001, "100% maps a texture pixel to a physical screen pixel"); - } - - #[test] - fn image_preview_zoom_and_drag_are_local_and_new_images_start_fitted() { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let id = Id::unique("jiansun-image-expanded"); - let snapshot_id = id.with("exit-snapshot"); - let texture = ctx.load_texture("preview-navigation", egui::ColorImage::filled([1200, 900], Color32::WHITE), egui::TextureOptions::LINEAR); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.agent_images.insert("first".into(), texture.clone()); - w.agent_images.insert("second".into(), texture); - w.template_workflow = json!({"slots":[ - {"candidates":[{"taskId":"first","status":"complete"},{"taskId":"failed","status":"failed"},{"taskId":"second","status":"complete"}]}, - {"candidates":[{"taskId":"other-slot","status":"complete"}]} - ]}); - ctx.data_mut(|d| d.insert_temp(id, "first".to_owned())); - let frame = |time:f64, events| { - let mut output = ctx.settle_ui(egui::RawInput { - screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(800.0,600.0))), time:Some(time), events, ..Default::default() - }, |ui| w.artifact_window(ui)); - output.textures_delta.clear(); - }; - for time in [0.0, 0.1, 0.2] { let _ = frame(time,vec![]); } - let pos = pos2(400.0,350.0); - let _ = frame(0.3,vec![egui::Event::PointerMoved(pos), egui::Event::MouseWheel { - source:egui::MouseWheelSource::Unknown, phase:egui::TouchPhase::Move, - unit:egui::MouseWheelUnit::Point, delta:vec2(0.0,300.0), modifiers:egui::Modifiers::NONE }]); - let zoomed = ctx.data(|d| d.get_temp::(snapshot_id)).unwrap(); - assert!(zoomed.view.zoom.is_some_and(|zoom| zoom > 0.5), "wheel over preview zooms the actual image"); - let _ = frame(0.5,vec![egui::Event::PointerButton { pos, button:egui::PointerButton::Primary,pressed:true,modifiers:egui::Modifiers::NONE }]); - let _ = frame(0.6,vec![egui::Event::PointerMoved(pos + vec2(70.0,35.0))]); - let dragged = ctx.data(|d| d.get_temp::(snapshot_id)).unwrap(); - assert!(dragged.view.center.x < zoomed.view.center.x, "drag moves the viewport over the image"); - let _ = frame(0.7,vec![egui::Event::PointerButton { pos:pos+vec2(70.0,35.0),button:egui::PointerButton::Primary,pressed:false,modifiers:egui::Modifiers::NONE }]); - let _ = frame(0.75,vec![ - egui::Event::PointerButton { pos, button:egui::PointerButton::Primary,pressed:true,modifiers:egui::Modifiers::NONE }, - egui::Event::PointerMoved(pos + vec2(-40.0,-20.0)), - egui::Event::PointerButton { pos:pos+vec2(-40.0,-20.0),button:egui::PointerButton::Primary,pressed:false,modifiers:egui::Modifiers::NONE }, - ]); - let quick = ctx.data(|d| d.get_temp::(snapshot_id)).unwrap(); - assert!(quick.view.center.x > dragged.view.center.x, "a complete drag between rendered frames still moves the preview"); - assert!(quick.view.drag_position.is_none()); - let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - let _ = frame(0.8,vec![key(egui::Key::ArrowRight)]); - let _ = frame(0.9,vec![]); - let second = ctx.data(|d| d.get_temp::(snapshot_id)).unwrap(); - assert_eq!(second.key, "second"); - assert!(second.view.zoom.is_none()); - let _ = frame(1.0,vec![key(egui::Key::ArrowRight)]); - assert_eq!(ctx.data(|d| d.get_temp::(id)).as_deref(), Some("second")); - assert_eq!(second.view.center, Vec2::splat(0.5)); - assert!(requests.try_recv().is_err(), "preview navigation does not dispatch generation or adoption"); - } - - #[test] - fn image_preview_retains_texture_only_until_exit_or_scope_change() { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let id = Id::unique("jiansun-image-expanded"); - let texture = ctx.load_texture("preview-retained", egui::ColorImage::filled([8, 8], Color32::WHITE), egui::TextureOptions::LINEAR); - let w = app.jiansun.as_mut().unwrap(); - w.agent_images.insert("preview".into(), texture); - ctx.data_mut(|d| d.insert_temp(id, "preview".to_owned())); - let frame = |time: f64, w: &Workspace| { - let mut output = ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), - time: Some(time), ..Default::default() - }, |ui| w.artifact_window(ui)); - output.textures_delta.clear(); - }; - for time in [0.0, 0.1, 0.3] { let _ = frame(time, w); } - assert!(ctx.data(|d| d.get_temp::(id.with("exit-snapshot"))).is_some()); - ctx.data_mut(|d| d.remove::(id)); - w.agent_images.remove("preview"); - let _ = frame(0.31, w); - assert!(ctx.data(|d| d.get_temp::(id.with("exit-snapshot"))).is_some(), "closed preview retains its actual texture during exit"); - let _ = frame(0.6, w); - assert!(ctx.data(|d| d.get_temp::(id.with("exit-snapshot"))).is_none()); - let texture = ctx.load_texture("preview-other", egui::ColorImage::filled([8, 8], Color32::WHITE), egui::TextureOptions::LINEAR); - w.agent_images.insert("preview".into(), texture); - ctx.data_mut(|d| d.insert_temp(id, "preview".to_owned())); - let _ = frame(0.7, w); - w.account = json!({"id":"different-account"}); - let _ = frame(0.8, w); - assert!(ctx.data(|d| d.get_temp::(id)).is_none()); - assert!(ctx.data(|d| d.get_temp::(id.with("exit-snapshot"))).is_none(), "preview cannot survive an account change"); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn image_preview_scrim_closes_and_retains_the_real_texture_for_exit() { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let id = Id::unique("jiansun-image-expanded"); - let texture = ctx.load_texture("preview-scrim", egui::ColorImage::filled([8, 8], Color32::WHITE), egui::TextureOptions::LINEAR); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = false; - w.agent_images.insert("preview".into(), texture); - ctx.data_mut(|d| d.insert_temp(id, "preview".to_owned())); - let frame = |time:f64, events| { - let mut output = ctx.settle_ui(egui::RawInput { - screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,480.0))), time:Some(time), events, ..Default::default() - }, |ui| w.artifact_window(ui)); - output.textures_delta.clear(); - }; - let _ = frame(0.0,vec![]); - let _ = frame(0.3,vec![]); - let pos = pos2(12.0,12.0); - for (time,pressed) in [(0.31,true),(0.32,false)] { - let _ = frame(time,vec![egui::Event::PointerMoved(pos),egui::Event::PointerButton { - pos,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); - } - assert!(ctx.data(|d| d.get_temp::(id)).is_none(), "scrim click closes the preview"); - let _ = frame(0.33,vec![]); - assert!(ctx.data(|d| d.get_temp::(id.with("exit-snapshot"))).is_some(), "the real texture survives the exit"); - let _ = frame(0.51,vec![]); - assert!(ctx.data(|d| d.get_temp::(id.with("exit-snapshot"))).is_none()); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn native_agent_tab_keeps_draft_and_context_without_splitting_or_stealing_selection() { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for _ in 0..3 { - dock_frame(&ctx, &mut app, vec![]); - } - assert_eq!(app.ui.dock_tabs.color, 4, "Agent opens by default on startup"); - assert!(geometry(app.jiansun.as_ref().unwrap(), "agentTab").left() < geometry(app.jiansun.as_ref().unwrap(), "colorTab").left()); - let original = app.jiansun.as_ref().unwrap().composer.clone(); - assert!(geometry(app.jiansun.as_ref().unwrap(), "panel").height() > 640.0, "Agent uses the whole sidebar"); - let panel = geometry(app.jiansun.as_ref().unwrap(), "panel"); - let group = crate::dock::last_rects(&ctx)[0].1; - assert!((panel.left() - group.left()).abs() <= 0.5, "no inherited nested-panel margin"); - assert!((panel.right() - group.right()).abs() <= 0.5); - assert!((panel.top() - geometry(app.jiansun.as_ref().unwrap(), "agentTab").bottom()).abs() <= 1.0); - assert_eq!(crate::dock::last_rects(&ctx).len(), 1); - dock_click(&ctx, &mut app, "colorTab"); - assert_eq!(crate::dock::last_rects(&ctx).len(), 3, "native Color, Properties and Layers return together"); - dock_click(&ctx, &mut app, "layersTab"); - assert_eq!(app.ui.dock_tabs.layers, 0); - assert!(app.jiansun.as_ref().unwrap().panel_geometry.get("input").is_none()); - let w = app.jiansun.as_mut().unwrap(); - w.canvas_workspace.context = Some(json!({"kind":"layer","nativeLayerId":42,"label":"另一图层"})); - w.messages.push(json!({"role":"assistant","kind":"reply","text":"候选已保留"})); - dock_frame(&ctx, &mut app, vec![]); - assert_eq!(app.ui.dock_tabs.layers, 0, "selection and completion never activate the Agent tab"); - dock_click(&ctx, &mut app, "channelsTab"); - assert_eq!(app.ui.dock_tabs.layers, 1); - dock_click(&ctx, &mut app, "pathsTab"); - assert_eq!(app.ui.dock_tabs.layers, 2); - dock_click(&ctx, &mut app, "agentTab"); - assert_eq!(app.ui.dock_tabs.color, 4); - let w = app.jiansun.as_ref().unwrap(); - assert_eq!(w.composer, original); - assert_eq!(w.messages.len(), 3); - assert_eq!(w.canvas_workspace.context.as_ref().unwrap()["nativeLayerId"], 42); - assert!( - w.panel_geometry.get("nativeDock").is_none() && w.panel_geometry.get("agentHeader").is_none(), - "one original tab group, no additional dock or header" - ); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn paused_production_card_shows_a_static_heading_and_elapsed_time() { - use egui_kittest::kittest::Queryable; - - let directory = std::env::var_os("PHOTOCRAFT_PAUSED_CARD_QA_OUT").map(std::path::PathBuf::from); - let _gpu = directory.as_ref().map(|_| photocraft_testkit::gpu_lock()); - for width in [520.0, 250.0] { - let (mut app, _) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - let doc = app.session.active().unwrap().doc.id.0; - w.open_projects.insert(doc, w.local_identity("project")); - w.template_workflow = json!({"canvasFirst":true,"workspaceId":"ws"}); - w.product_checkpoint = json!({"active":true,"phase":"paused","project":"project","workspaceId":"ws", - "startedAt":1_000,"clockSavedAt":1_300}); - w.restore_production_checkpoint(&app); - w.agent_effects_paused = true; - w.workflow.set_production_progress(&json!({"heading":"正在制作详情页"})); - let run = w.product_production.as_ref().unwrap(); - assert!(run.waiting_to_resume()); - assert!(!run.showing_agent_progress()); - assert_eq!(run.elapsed(), Duration::from_secs(300)); - app.jiansun = Some(w); - let builder = egui_kittest::Harness::builder().with_size(vec2(width, 680.0)) - .with_context_setup(|ctx| { - PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(ctx); - }); - let builder = if directory.is_some() { builder.wgpu() } else { builder }; - let mut harness = builder.build_ui_state(|ui, app| super::super::agent_dock(app, ui), app); - harness.run_steps(8); - assert!(harness.query_all_by_label("等待恢复 · 已暂停").next().is_some()); - assert!(harness.query_all_by_label("正在准备详情页").next().is_none()); - assert!(harness.query_all_by_label("正在推进目标").next().is_none()); - assert!(harness.query_all_by_label("继续制作").next().is_some()); - let w = harness.state_mut().jiansun.as_mut().unwrap(); - assert_eq!(w.product_production.as_ref().unwrap().elapsed(), Duration::from_secs(300)); - if let Some(directory) = &directory { - harness.render().unwrap().save(directory.join(format!("paused-{width}.png"))).unwrap(); - } - let w = harness.state_mut().jiansun.as_mut().unwrap(); - w.receive_library_status(&json!({"libraryStatus":"sign_in_required","libraryHttpStatus":401})); - w.product_production = None; - harness.run_steps(8); - assert!(harness.query_all_by_label("重新连接").next().is_some()); - if let Some(directory) = &directory { - harness.render().unwrap().save(directory.join(format!("reconnect-{width}.png"))).unwrap(); - } - } - } - - #[test] - fn reconnect_opens_account_authorization_without_erasing_drafts_or_replaying_a_request() { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let w = app.jiansun.as_mut().unwrap(); - w.library_status = "sign_in_required".into(); - w.library_http_status = Some(401); - let draft = w.composer.clone(); - let messages = w.messages.clone(); - for _ in 0..3 { - dock_frame(&ctx, &mut app, vec![]); - } - assert!(!app.jiansun.as_ref().unwrap().can_send(&app)); - app.jiansun.as_mut().unwrap().unknown = true; - // Re-observe the reserved status row before clicking its new layout. - for _ in 0..2 { - dock_frame(&ctx, &mut app, vec![]); - } - assert!(app.jiansun.as_ref().unwrap().panel_geometry["reconnect"].is_array()); - dock_click(&ctx, &mut app, "reconnect"); - let w = app.jiansun.as_ref().unwrap(); - assert!(w.config); - assert_eq!(w.login_origin.as_deref(), Some(w.origin.as_str())); - assert_eq!(w.account["id"], "local-ui-fixture"); - assert_eq!(w.composer, draft); - assert_eq!(w.messages, messages); - assert!(w.unknown); - assert!(requests.try_recv().is_err(), "opening authorization neither dispatches nor repeats a model request"); - } - - #[test] - fn candidate_recovery_targets_the_original_image_instead_of_legacy_chat() { - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - w.unknown = true; - w.template_workflow = json!({"canvasFirst":true,"pending":true,"recoveryCandidateId":"original-image"}); - w.recover(&app); - assert!(matches!(requests.try_recv().unwrap(), Request::Action(method, value) - if method == "slot-recover" && value["candidateId"] == "original-image")); - assert!(requests.try_recv().is_err()); - assert!(!w.allow_apply); - } - - #[test] - fn library_action_failure_stays_in_the_shared_modal_and_preserves_the_draft() { - let (mut app, _) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - let draft = w.composer.clone(); - w.unknown = true; - w.receive_json_error("pi-rules", "请先在素材库登录".into()); - assert!(!w.config, "opening a local project must not force an account dialog"); - assert!(w.error.is_empty()); - w.receive_json_error("slot-recover", "请先在素材库登录".into()); - assert!(w.config); - assert_eq!(w.library_message, "请先在素材库登录"); - assert!(w.error.is_empty()); - assert!(w.unknown); - assert_eq!(w.composer, draft); - } - - #[test] - fn refreshed_authorization_clears_stale_errors_without_dropping_existing_connection_or_drafts() { - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - let draft = w.composer.clone(); - let account = w.account.clone(); - w.account_error = "该素材库尚未开放客户端授权".into(); - w.receive_library_status(&json!({"libraryStatus":"connected","libraryHttpStatus":200,"libraryAuthorizationEnabled":false})); - assert_eq!(w.library_authorization_enabled, Some(false)); - assert!(w.can_send(&app), "a paused new-grant endpoint does not revoke a valid existing session"); - assert!(!w.account_error.is_empty()); - w.receive_library_status(&json!({"libraryStatus":"connected","libraryHttpStatus":200,"libraryAuthorizationEnabled":true})); - assert!(w.account_error.is_empty(), "a verified restored endpoint must retire its stale authorization error"); - assert_eq!(w.account, account); - assert_eq!(w.composer, draft); - assert!(requests.try_recv().is_err(), "a status receipt cannot dispatch anything"); - w.receive_library_status(&json!({"libraryStatus":"sign_in_required","libraryHttpStatus":401})); - assert_eq!(w.library_authorization_enabled, None); - assert!(!w.can_send(&app)); - } - - #[test] - fn a_disabled_library_preserves_the_account_and_suspends_cloud_polling_and_new_dispatch() { - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - assert!(w.can_send(&app)); - w.connection_received(&json!({"libraryStatus":"disabled","libraryHttpStatus":403,"libraryMessage":"服务开关未开放"})); - w.model_ready = true; - w.image_ready = true; - w.project_refresh = Instant::now() - std::time::Duration::from_secs(60); - w.dispatch_project_refresh(); - assert!(!w.can_send_with(&app, false)); - assert!(!w.can_send_with(&app, true)); - assert!(!w.needs_library_login(), "a service switch must not be labelled an expired login"); - assert_eq!(w.account["id"], "local-ui-fixture"); - assert!(!w.composer.is_empty()); - assert!(!w.messages.is_empty()); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn custom_native_workspace_migrates_old_agent_to_the_top_color_group() { - use craft_ui::docking::{Layout, Node}; - let (mut app, _) = dock_fixture(); - app.ui.docking = Some(craft_ui::docking::Workspace::new(Layout { - root: Some(Node::Split { - axis: craft_ui::layout::SplitAxis::Vertical, - size: craft_ui::layout::SplitSize::FixedFirst(190.0), - first: Box::new(Node::Tabs { panels: vec!["color".into(), "swatches".into()], active: 0 }), - second: Box::new(Node::Tabs { panels: vec!["xiaoyi".into(), "layers".into(), "channels".into()], active: 0 }), - }), - ..Default::default() - })); - super::super::begin_native_dock(&mut app); - let layout = app.ui.docking.as_ref().unwrap(); - assert!(layout.validate().is_ok()); - assert!( - matches!(layout.layout.root.as_ref(),Some(Node::Split{first,second,..}) if matches!(first.as_ref(), Node::Tabs{panels,active:0} if panels==&["canvas"]) && matches!(second.as_ref(), Node::Split{first,second,..} if matches!(first.as_ref(), Node::Tabs{panels,active:0} if panels==&["xiaoyi","color","swatches"]) && matches!(second.as_ref(), Node::Tabs{panels,..} if panels==&["layers","channels"]))) - ); - crate::panel_docking::leave_agent(&mut app).unwrap(); - app.run("window.panel.activate", json!({"panel":"layers"})).unwrap(); - super::super::begin_native_dock(&mut app); - assert!(!super::super::agent_selected(&app), "native mode is not stolen back"); - assert_eq!(app.ui.docking.as_ref().unwrap().layout.panels().len(), 6); - } - - #[test] - fn plain_photocraft_keeps_its_original_tabs_and_runtime_capability_is_not_saved() { - let mut dock = crate::dock::DockLayout::default(); - let native = dock.visible_tabs(crate::dock::Group::Color, true); - assert_eq!(native, vec![(0, "Color"), (1, "Swatches"), (2, "Gradients"), (3, "Patterns")]); - dock.agent_available = true; - assert_eq!(dock.visible_tabs(crate::dock::Group::Color, true).first(), Some(&(4, "小壹"))); - assert_eq!(dock.visible_tabs(crate::dock::Group::Layers, true), vec![(0, "Layers"), (1, "Channels"), (2, "Paths")]); - let restored: crate::dock::DockLayout = serde_json::from_value(serde_json::to_value(&dock).unwrap()).unwrap(); - assert!(!restored.agent_available); - assert_eq!(restored.visible_tabs(crate::dock::Group::Color, true), native); - } - - #[test] - fn agent_remains_the_top_sidebar_mode_across_native_themes() { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for theme in [crate::theme::ThemeKind::ProMedium, crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::ProLight] { - app.set_theme(&ctx, theme); - for _ in 0..3 { - dock_frame(&ctx, &mut app, vec![]); - } - assert!(super::super::agent_selected(&app)); - assert!(geometry(app.jiansun.as_ref().unwrap(), "agentTab").left() < geometry(app.jiansun.as_ref().unwrap(), "colorTab").left()); - assert_eq!(crate::dock::last_rects(&ctx).len(), 1); - } - assert!(requests.try_recv().is_err()); - } - - #[test] - fn stop_preserves_request_and_replay_barrier_but_settles_local_motion() { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let w = app.jiansun.as_mut().unwrap(); - w.busy = Some("slot-generate".into()); - w.unknown = true; - for _ in 0..3 { - dock_frame(&ctx, &mut app, vec![]); - } - dock_click(&ctx, &mut app, "stop"); - let w = app.jiansun.as_mut().unwrap(); - assert!(w.agent_effects_paused && w.unknown); - assert_eq!(w.busy.as_deref(), Some("slot-generate")); - assert!(requests.try_recv().is_err()); - w.busy = None; - dock_frame(&ctx, &mut app, vec![]); - let w = app.jiansun.as_ref().unwrap(); - assert!(!w.agent_effects_paused); - assert!(w.result_needs_check()); - assert!(!w.can_send_with(&app, true)); - } - - #[test] - fn processing_card_only_uses_the_submitted_scope_and_never_dispatches() { - let (mut app, requests) = dock_fixture(); - let doc = app.session.active().unwrap().doc.id.0; - let w = app.jiansun.as_mut().unwrap(); - w.busy = Some("agent".into()); - w.owner_doc = Some(doc); - w.pi_request_scope = json!({"account":{"id":w.account["id"],"origin":w.origin},"project":{"documentId":doc}, - "subject":{"kind":"slot","slotId":"submitted-slot","label":"首屏"}}); - w.canvas_workspace.context = Some(json!({"kind":"slot","slotId":"later-selection","label":"另一屏"})); - assert_eq!(app.jiansun.as_ref().unwrap().processing_target(&app).unwrap()["slotId"], "submitted-slot"); - app.jiansun.as_mut().unwrap().account["id"] = json!("other-account"); - assert!(app.jiansun.as_ref().unwrap().processing_target(&app).is_none()); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn image_processing_has_one_neutral_placeholder_and_an_accessible_stop() { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - app.jiansun.as_mut().unwrap().busy = Some("slot-generate".into()); - for _ in 0..3 { - dock_frame(&ctx, &mut app, vec![]); - } - let w = app.jiansun.as_ref().unwrap(); - assert!(w.panel_geometry["processing"].is_array()); - assert!(w.panel_geometry["processingPlaceholder"].is_array()); - assert!(w.panel_geometry["processingBlob"].is_array(), "the task uses the same Siri Orb identity as the composer"); - assert_eq!(w.panel_geometry["processingBlobMoving"], true); - let placeholder: [f32; 4] = serde_json::from_value(w.panel_geometry["processingPlaceholder"].clone()).unwrap(); - let blob: [f32; 4] = serde_json::from_value(w.panel_geometry["processingBlob"].clone()).unwrap(); - assert_eq!(w.panel_geometry["processingPlaceholder"], w.panel_geometry["processing"], "image waiting uses the task surface without an inset panel"); - assert!(blob[2] <= 36.0 && blob[3] <= 36.0 && blob[0] >= placeholder[0] && blob[1] >= placeholder[1]); - assert!(w.panel_geometry["stop"].is_array()); - assert!(requests.try_recv().is_err(), "rendering progress must not send a model request"); - } - - #[test] - fn task_stop_and_completion_use_shared_material_and_fade_without_dispatch() { - for reduced in [false, true] { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let mut sample = |time: f64, pending: bool, paused: bool| { - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = reduced; - w.busy = pending.then(|| "slot-generate".into()); - w.agent_effects_paused = paused; - ctx.memory_mut(|memory| memory.request_focus(Id::unique("jiansun-composer-input"))); - let _ = ctx.settle_ui(egui::RawInput { time: Some(time), screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), ..Default::default() }, |ui| { - crate::panels::right_dock(&mut app, ui); - }); - app.jiansun.as_ref().unwrap().panel_geometry.clone() - }; - let running = sample(0.0, true, false); - assert_eq!(running["processingLightMode"], "glow-pill"); - assert_eq!(running["composerLightMode"], if reduced {"static"} else {"glow-pill"}); - let stopped = sample(1.0, true, true); - assert_eq!(stopped["processingLightMode"], "paused"); - assert_eq!(stopped["composerLightMode"], if reduced {"static"} else {"glow-pill"}); - assert_eq!(stopped["processingOpacity"], 1.0, "stopping retains the original pending request card"); - sample(1.2, true, true); - sample(2.0, false, false); - let leaving = sample(2.08, false, false); - if reduced { - assert!(leaving["processing"].is_null()); - } else { - let opacity = leaving["processingOpacity"].as_f64().unwrap(); - assert!(opacity > 0.0 && opacity < 1.0, "completed card fades as a whole, even after a local stop"); - } - assert!(sample(2.3, false, false)["processing"].is_null()); - assert!(ctx.data(|data|data.get_temp::(Id::unique("composer-sent-glow"))).is_none(),"task status never starts a composer send surge"); - assert!(requests.try_recv().is_err(), "state rendering cannot dispatch or repeat a request"); - } - } - - #[test] - fn image_processing_paints_neutral_status_without_the_upstream_name() { - fn collect_text(shape: &egui::Shape, texts: &mut Vec<(String, f32)>) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect_text(shape, texts)), - egui::Shape::Text(text) => texts.push((text.galley.text().to_owned(), text.pos.x)), - _ => {} - } - } - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let w = app.jiansun.as_mut().unwrap(); - w.busy = Some("slot-generate".into()); - w.image_progress = "98k 正在生成图片…".into(); - w.reduce_motion = true; - let mut output = None; - for _ in 0..3 { - let mut frame = ctx.settle_ui( - egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), ..Default::default() }, - |ui| crate::panels::right_dock(&mut app, ui), - ); - frame.textures_delta.clear(); - output = Some(frame); - } - let mut texts = Vec::new(); - for shape in &output.unwrap().shapes { - collect_text(&shape.shape, &mut texts); - } - let status_x = texts.iter().find(|(text, _)| text == "正在生成图片…") - .unwrap_or_else(|| panic!("real status should be painted as a neutral label: {texts:?}")).1; - let blob = &app.jiansun.as_ref().unwrap().panel_geometry["processingBlob"]; - let orb_right = (blob[0].as_f64().unwrap() + blob[2].as_f64().unwrap()) as f32; - assert!((0.0..=20.0).contains(&(status_x - orb_right)), "the status should sit beside the orb"); - assert!(!texts.iter().any(|(text, _)| text.contains("98k")), "status must not expose the upstream name"); - assert!(requests.try_recv().is_err(), "painting status must not dispatch a request"); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] - fn production_dock_visual_acceptance() { - use egui_kittest::kittest::Queryable; - let _gpu = photocraft_testkit::gpu_lock(); - let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - struct Preview(PhotocraftApp); - impl eframe::App for Preview { - fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { - super::super::agent_dock(&mut self.0, ui); - } - } - for width in [250.0, 520.0] { - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.composer.clear(); - w.reduce_motion = true; - w.pi_run = Some("visual-qa".into()); - w.busy = Some("pi-agent".into()); - w.pi_product_production = true; - let cells = |count, filled, verified| (0..count).map(|i| json!({ - "label":format!("第 {} 项", i + 1), - "state":if i < verified { "verified" } else if i < filled { "filled" } else { "empty" }, - })).collect::>(); - w.workflow.set_production_progress(&json!({"heading":"正在分派详情页图片","rendered":2,"total":21, - "pictureCells":cells(21, 6, 2),"copyCells":cells(45, 37, 8), - "copyPending":8,"workers":[ - {"number":1,"slotId":"hero","label":"首屏产品场景","step":"正在生图","active":true}, - {"number":2,"slotId":"scene","label":"空间搭配图","step":"正在准备","active":true}, - {"number":3,"slotId":"detail","label":"同款细节图","step":"正在等待原请求","active":true}], - "reviews":[{"number":4,"slotId":"finish","label":"材质图","step":"正在验图","active":true}]})); - w.messages = vec![ - json!({"role":"user","text":"制作详情、主图和 SKU"}), - json!({"role":"assistant","kind":"reply","text":"先做首屏的产品场景图,完成后核对产品结构。"}), - json!({"role":"assistant","kind":"image-job","taskId":"qa-pending","run":"visual-qa", - "width":4,"height":5,"workerNumber":1,"slotLabel":"S01 - 首屏产品场景","step":"正在生图"}), - ]; - let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 1040.0)).wgpu().build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); - app.gpu_render_state = cc.wgpu_render_state.clone(); - Preview(app) - }); - { - let w = harness.state_mut().0.jiansun.as_mut().unwrap(); - w.busy = None; - w.pi_run = None; - w.messages.push(json!({"role":"assistant","kind":"image","taskId":"previous-result"})); - } - harness.run_steps(4); - assert!(harness.state().0.jiansun.as_ref().unwrap().panel_geometry["productionProgressTag"].is_null()); - assert!(harness.state().0.jiansun.as_ref().unwrap().panel_geometry["productionShelf"].is_null()); - harness.render().unwrap().save(directory.join(format!("dock-{width}-idle.png"))).unwrap(); - { - let w = harness.state_mut().0.jiansun.as_mut().unwrap(); - w.messages.pop(); - w.messages.push(json!({"role":"assistant","kind":"image","taskId":"returned-result"})); - // A slot queued behind the running one keeps the height of one line. - w.messages.push(json!({"role":"assistant","kind":"image-job","taskId":"qa-queued","run":"later", - "width":4,"height":5,"workerNumber":2,"slotLabel":"S02 - 细节特写","step":"正在生图"})); - w.busy = Some("pi-agent".into()); - w.pi_run = Some("visual-qa".into()); - } - harness.run_steps(12); - let w = harness.state().0.jiansun.as_ref().unwrap(); - assert_eq!(w.panel_geometry["productionImageCells"]["total"], 21); - assert_eq!(w.panel_geometry["productionImageCells"]["filled"], 6); - assert_eq!(w.panel_geometry["productionImageCells"]["verified"], 2); - let copy = &w.panel_geometry["productionCopyCells"]; - assert_eq!(copy["total"], 45); - assert_eq!(copy["filled"], 37); - assert_eq!(copy["verified"], 8); - assert_eq!(copy["bar"], false); - assert_eq!(w.panel_geometry["productionImageCells"]["bar"], false); - // The head is pinned above the timeline and stays compact. - let head = geometry(w, "productionShelf"); - let clip = geometry(w, "conversationClip"); - assert!(head.bottom() <= clip.top() + 1.0, "状态头固定在对话上方:面板宽 {width}, 状态头 {head:?}, 对话 {clip:?}"); - assert!(head.bottom() < geometry(w, "composer").top(), "进度格换行后仍保留输入区:面板宽 {width}, {head:?}"); - let pictures = geometry(w, "productionImageCells"); - assert!(geometry(w, "productionProgressTag").bottom() <= pictures.top() && geometry(w, "taskStop").bottom() <= pictures.top(), - "停止键与展开钮在标题行,进度格在其下"); - assert!(geometry(w, "productionCopyCells").bottom() <= head.bottom() && pictures.top() > head.top(), - "图片格与文案默认可见:面板宽 {width}"); - let name = geometry(w, "productionTitle"); - assert!(head.contains_rect(name) && name.right() <= geometry(w, "productionProgressTag").left(), - "标题与展开钮互不遮挡:面板宽 {width}, {name:?}"); - harness.render().unwrap().save(directory.join(format!("dock-{width}-progress.png"))).unwrap(); - let click = |harness: &mut egui_kittest::Harness, key: &str| { - let point = geometry(harness.state().0.jiansun.as_ref().unwrap(), key).center(); - harness.hover_at(point); - for pressed in [true, false] { - harness.event(egui::Event::PointerButton { pos:point, button:egui::PointerButton::Primary, - pressed, modifiers:egui::Modifiers::NONE }); - harness.run_steps(1); - } - harness.run_steps(12); - }; - // The head opens in place for the per-slot detail of every sub-agent. - click(&mut harness, "productionProgressTag"); - let w = harness.state().0.jiansun.as_ref().unwrap(); - assert!(w.panel_geometry["productionWorkers"].is_array()); - assert!(geometry(w, "productionShelf").bottom() <= geometry(w, "conversationClip").top() + 1.0); - assert_eq!(harness.query_all_by_label("D").count(), 0, "复核使用图位名称:面板宽 {width}"); - let rows = w.panel_geometry["productionWorkers"].as_array().unwrap(); - assert_eq!(rows.len(), 4, "面板宽 {width}"); - assert_eq!(rows[rows.len() - 1]["review"], true); - let footprint = |row: &Value| { - let a = row["indicator"].as_array().unwrap(); - Rect::from_min_size(pos2(a[0].as_f64().unwrap() as f32, a[1].as_f64().unwrap() as f32), - vec2(a[2].as_f64().unwrap() as f32, a[3].as_f64().unwrap() as f32)) - }; - let columns = if width == 250.0 { 1 } else { 2 }; - for (index, row) in rows.iter().enumerate() { - let (mine, lead) = (footprint(row), footprint(&rows[index % columns])); - assert!((mine.width() - lead.width()).abs() < 0.01 && (mine.left() - lead.left()).abs() < 0.01, - "子代理状态点对齐:面板宽 {width}, {mine:?} 对 {lead:?}"); - } - harness.render().unwrap().save(directory.join(format!("dock-{width}-workers.png"))).unwrap(); - click(&mut harness, "productionProgressTag"); - assert!(requests.try_recv().is_err()); - } - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] - fn empty_dock_visual_acceptance() { - let _gpu = photocraft_testkit::gpu_lock(); - let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - struct Preview(PhotocraftApp); - impl eframe::App for Preview { - fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { - super::super::agent_dock(&mut self.0, ui); - } - } - for width in [250.0, 520.0] { - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.composer.clear(); - w.messages.clear(); - w.reduce_motion = true; - let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 760.0)).wgpu().build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); - app.gpu_render_state = cc.wgpu_render_state.clone(); - Preview(app) - }); - harness.run_steps(6); - assert!(harness.state().0.jiansun.as_ref().unwrap().panel_geometry["quickPrompts"].is_array(), - "starter suggestions sit under the guidance: 面板宽 {width}"); - harness.render().unwrap().save(directory.join(format!("dock-{width}-empty.png"))).unwrap(); - assert!(requests.try_recv().is_err()); - } - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] - fn project_page_dock_visual_acceptance() { - let _gpu = photocraft_testkit::gpu_lock(); - let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - struct Preview(PhotocraftApp); - impl eframe::App for Preview { - fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { - super::super::agent_dock(&mut self.0, ui); - } - } - let projects = |count: usize| (0..count).map(|index| json!({"id":format!("project-{index}"),"source":"native", - "name":if index % 3 == 1 { format!("客厅沙发 · 带贵妃位的加长版本 · 第 {index} 稿") } else { format!("客厅沙发 · 第 {index} 稿") }, - "updatedAt":format!("2026-11-{:02}T09:00:00Z", 28 - index)})).collect::>(); - // (state, whether a canvas is open behind the page, how many projects) - for width in [250.0, 520.0] { - for (name, canvas_open, count) in [("projects", true, 8), ("projects-home", false, 3), ("projects-none", false, 0)] { - let (mut app, requests) = dock_fixture(); - { - let w = app.jiansun.as_mut().unwrap(); - w.composer.clear(); - w.messages.clear(); - w.reduce_motion = true; - w.projects = projects(count); - } - if canvas_open { - app.jiansun.as_mut().unwrap().show_center(CenterView::Projects, true); - } else if let Some(closed) = app.session.close(0) { - let w = app.jiansun.as_mut().unwrap(); - w.open_projects.remove(&closed.doc.id.0); - w.loaded_draft = None; - w.owner_doc = None; - app.sync_views(); - } - let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 760.0)).wgpu().build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); - app.gpu_render_state = cc.wgpu_render_state.clone(); - Preview(app) - }); - harness.run_steps(6); - { - let app = &harness.state().0; - let w = app.jiansun.as_ref().unwrap(); - assert_eq!(w.agent_page(app), "projects", "{name} · 面板宽 {width}"); - assert!(w.panel_geometry["workspaceSearch"].is_null(), "{name} · 面板宽 {width}: the dock repeats no search"); - assert_eq!(w.panel_geometry["workspaceReturn"].is_array(), canvas_open, "{name} · 面板宽 {width}: the way back exists exactly when a canvas is open"); - } - harness.render().unwrap().save(directory.join(format!("dock-{width}-{name}.png"))).unwrap(); - assert!(requests.try_recv().is_err(), "{name} · 面板宽 {width}: rendering sends nothing"); - } - } - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] - fn review_surfaces_visual_acceptance() { - struct Preview(PhotocraftApp); - impl eframe::App for Preview { - fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { - super::super::agent_dock(&mut self.0, ui); - } - } - fn text_layers(app: &mut PhotocraftApp, texts: &[&str]) -> Vec { - texts.iter().map(|text| { - app.session.execute("type.create", json!({"text":text,"x":40,"y":40})).unwrap(); - app.session.active().unwrap().selected_layers()[0].0 - }).collect() - } - let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - type Setup = Box; - // One fresh dock per state. `notices` opens the notification window - // with that history. - let render = |width: f32, name: &str, setup: Setup, notices: Option>| { - let (mut app, requests) = dock_fixture(); - let mut workspace = app.jiansun.take().unwrap(); - setup(&mut workspace, &mut app); - app.jiansun = Some(workspace); - let notices = notices.map(|entries| { - let w = app.jiansun.as_ref().unwrap(); - (notification_id(&w.origin, &w.account, &w.project_context, w.owner_doc).expect("a scoped notification history"), entries) - }); - let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 760.0)).wgpu().build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); - if let Some((id, entries)) = notices { - cc.egui_ctx.data_mut(|data| data.insert_temp(id, AgentNotifications { - entries, unread: 0, last_error: String::new(), last_unknown: false, open: true, - })); - } - app.gpu_render_state = cc.wgpu_render_state.clone(); - Preview(app) - }); - harness.run_steps(8); - harness.render().unwrap().save(directory.join(format!("dock-{width}-{name}.png"))).unwrap(); - assert!(requests.try_recv().is_err(), "{name} · 面板宽 {width}: rendering sends nothing"); - }; - for width in [250.0, 520.0] { - render(width, "copy-options", Box::new(|w, _| { - w.composer.clear(); - w.origin = "https://fixture.invalid".into(); - w.owner_doc = w.loaded_draft; - w.observed_doc = w.loaded_draft; - w.messages = vec![ - json!({"role":"user","text":"帮我提炼这款电脑桌的卖点"}), - json!({"role":"assistant","kind":"reply","text":"整理了 5 条候选卖点,选好以后点「使用所选」。"}), - json!({"role":"assistant","kind":"copywriting-options","optionsId":"selling-visual","selected":[0,2], - "items":["实木桌板,承重稳定","桌面带走线孔,线材不外露","可调节脚垫,地面不平也放得稳","三种尺寸,适配不同房间","免工具安装,十分钟装好"], - "missing":["承重的具体数值待确认","有没有环保检测报告"],"target":{}}), - ]; - }), None); - render(width, "copy-fields", Box::new(|w, app| { - w.composer.clear(); - let doc = app.session.active().unwrap().doc.id.0; - let layers = text_layers(app, &["原始主标题", "原始副标题", "原始卖点"]); - app.session.execute("select.deselectLayers", json!({})).unwrap(); - w.owner_doc = Some(doc); - w.observed_doc = Some(doc); - let field = |id: &str, label: &str, max: u64| json!({"fieldId":id,"label":label,"maxChars":max,"maxLines":1}); - w.messages = vec![ - json!({"role":"user","text":"给首屏这三处文字各写一版候选"}), - json!({"role":"assistant","kind":"reply","text":"每格都给了候选。原文保留,预览满意后再采纳。"}), - json!({"role":"assistant","kind":"copywriting-fields","optionsId":"copy-visual","items":[ - {"layer":layers[0],"name":"主标题","field":field("S01-T01","主标题",12),"original":"原始主标题","text":"实木电脑桌","applied":false}, - {"layer":layers[1],"name":"副标题","field":field("S01-T02","副标题",24),"original":"原始副标题","text":"桌面带走线孔,线材不外露,居家办公更整洁","applied":false}, - {"layer":layers[2],"name":"卖点","field":field("S01-T03","卖点",16),"original":"原始卖点","text":"原始卖点","applied":false}, - ],"target":{}}), - ]; - }), None); - render(width, "notifications", Box::new(|w, _| { - w.origin = "https://fixture.invalid".into(); - w.owner_doc = w.loaded_draft; - }), Some(vec![ - "can't read smart source within the preview budget: pcraft: limit exceeded: canvas 1440x35827 exceeds 8192 pixels per side".into(), - "素材库请求失败(HTTP 503)".into(), - "模型服务暂时限流".into(), - ])); - render(width, "references", Box::new(|w, app| { - w.composer.clear(); - let doc = app.session.active().unwrap().doc.id.0; - for layer in text_layers(app, &["主标题图层", "副标题图层", "价格标签图层"]) { - w.composer_reference_add_target(app, &json!({"documentId":doc,"nativeLayerId":layer,"component":"layer"})).unwrap(); - } - app.session.execute("select.deselectLayers", json!({})).unwrap(); - }), None); - } - } - - #[test] - #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] - fn tool_timeline_visual_acceptance() { - use egui_kittest::kittest::Queryable; - - let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); - for width in [250.0, 520.0] { - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.messages = vec![ - json!({"role":"user","text":"制作详情、主图和 SKU"}), - json!({"role":"assistant","kind":"activity","text":"已接收制作任务。正在保存当前资料,接下来会按模板准备画布。"}), - json!({"role":"assistant","kind":"thinking","active":false,"output":{ - "tokens":518,"tokensPerSecond":147.0,"estimated":false}}), - json!({"role":"assistant","kind":"reply","text":"我先核对商品原图和模板,再安排制作。"}), - json!({"role":"assistant","kind":"activity","text":"读取画布","event":{ - "version":1,"type":"tool","run":"timeline","toolCallId":"read","toolName":"canvas_read","status":"completed","durationMs":120}}), - json!({"role":"assistant","kind":"activity","text":"读取制作规则","event":{ - "version":1,"type":"tool","run":"timeline","toolCallId":"rules","toolName":"workflow_read","status":"completed","durationMs":240}}), - json!({"role":"assistant","kind":"thinking","active":false,"output":{ - "tokens":293,"tokensPerSecond":92.0,"estimated":false}}), - ]; - w.stream_reply = "已找到模板中的 21 个图位。我会先规划文案,再按各屏卖点制作配图。".into(); - let mut h = egui_kittest::Harness::builder().with_size(vec2(width, 520.0)).wgpu() - .build_ui_state(|ui, app: &mut PhotocraftApp| { - if !ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - Frame::NONE.fill(Tokens::get(ui.ctx()).dock).inner_margin(12).show(ui, |ui| { - let w = app.jiansun.as_ref().unwrap(); - let turn = turns(&w.messages).pop().unwrap(); - w.turn_ui(ui, turn, Id::unique("tool-timeline-visual"), w.messages.len(), true, false, None); - }); - }, app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); - h.run_steps(8); - let save = |h: &mut egui_kittest::Harness, state: &str| { - let path = std::path::Path::new(&directory).join(format!("timeline-{width}-{state}.png")); - h.render().unwrap().save(path).unwrap(); - }; - save(&mut h, "collapsed"); - let button = h.get_by_label("已完成 2 项操作").rect().center(); - h.hover_at(button); - h.run_steps(2); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { - pos: button, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, - }); - h.run_steps(1); - } - h.run_steps(8); - save(&mut h, "expanded"); - assert!(h.query_by_label("我先核对商品原图和模板,再安排制作。").is_some()); - assert!(h.query_by_label("过程说明").is_none()); - assert!(requests.try_recv().is_err()); - } - } - - #[test] - #[ignore = "offscreen GPU timeline with a real-format tool receipt and a new inline reply"] - fn live_timeline_motion_visual_evidence() { - let _gpu = photocraft_testkit::gpu_lock(); - let out = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.busy = Some("pi-agent".into()); - w.messages = vec![ - json!({"role":"user","text":"核对当前画布后继续制作。"}), - json!({"role":"assistant","kind":"reply","text":"先看首屏卖点和原片是否一致。"}), - json!({"role":"assistant","kind":"thinking","active":false,"output":{"tokens":293}}), - json!({"role":"assistant","kind":"activity","event":{"version":1,"type":"tool","run":"visual", - "toolCallId":"call_4fca7b5|fc_0c72ae9","toolName":"canvas_read","status":"started"}}), - json!({"role":"assistant","kind":"activity","text":"模板已就绪。"}), - ]; - let mut h = egui_kittest::Harness::builder() - .with_size(vec2(360.0, 520.0)).with_step_dt(1.0 / 120.0).wgpu() - .build_ui_state(|ui, app: &mut PhotocraftApp| { - if !super::super::stitch_ui::ui_fonts_ready(ui) { return; } - Frame::NONE.fill(Tokens::get(ui.ctx()).agent().dock).inner_margin(12).show(ui, |ui| { - let w = app.jiansun.as_ref().unwrap(); - w.turn_ui(ui, turns(&w.messages).pop().unwrap(), Id::unique("live-tool-visual"), w.messages.len(), true, false, None); - }); - }, app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); - h.ctx.all_styles_mut(|style| style.animation_time = egui::Style::default().animation_time); - let save = |h: &mut egui_kittest::Harness, name| { - h.render().unwrap().save(out.join(format!("v2-{name}.png"))).unwrap(); - }; - h.run_steps(48); - save(&mut h, "tool-running"); - let w = h.state_mut().jiansun.as_mut().unwrap(); - w.messages[3]["event"]["status"] = json!("completed"); - w.messages[3]["event"]["durationMs"] = json!(320); - w.messages.push(json!({"role":"assistant","kind":"reply","text":"首屏原片与文案一致,接下来核对主图的构图和规格。"})); - h.run_steps(19); - save(&mut h, "inline-reveal"); - h.state_mut().jiansun.as_mut().unwrap().busy = None; - h.run_steps(204); - save(&mut h, "tool-completion-hold"); - h.run_steps(20); - save(&mut h, "tool-collapsing"); - h.run_steps(160); - save(&mut h, "tool-folded"); - assert!(requests.try_recv().is_err()); - } - - #[test] - #[ignore = "offscreen GPU visual evidence for the reply reveal frontier"] - fn typing_frontier_visual_evidence() { - let _gpu = photocraft_testkit::gpu_lock(); - let out = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - let reply = "已核对主图构图和原片,结果一致。继续检查每屏卖点和商品规格。\n```text\n主图:保留商品结构\n详情:核对材质和尺寸\n收尾:复查文字与图位\n```\n检查完成后即可保存。"; - for width in [270.0, 520.0] { - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = false; - w.busy = Some("pi-agent".into()); - w.messages = vec![ - json!({"role":"user","text":"核对主图和详情页。"}), - json!({"role":"assistant","kind":"thinking","active":true, - "output":{"tokens":84,"tokensPerSecond":17}}), - json!({"role":"assistant","kind":"activity","event":{ - "version":1,"type":"tool","run":"reveal-visual","toolCallId":"read", - "toolName":"canvas_read","status":"completed","durationMs":12}}), - ]; - let mut h = egui_kittest::Harness::builder() - .with_size(vec2(width, 360.0)).with_step_dt(1.0 / 120.0).wgpu() - .build_ui_state(|ui, app: &mut PhotocraftApp| { - if !super::super::stitch_ui::ui_fonts_ready(ui) { return; } - Frame::NONE.fill(Tokens::get(ui.ctx()).agent().dock).inner_margin(12).show(ui, |ui| { - let w = app.jiansun.as_ref().unwrap(); - w.turn_ui(ui, turns(&w.messages).pop().unwrap(), Id::unique("typing-frontier-visual"), w.messages.len(), true, false, None); - }); - }, app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); - let save = |h: &mut egui_kittest::Harness, frame| { - h.render().unwrap().save(out.join(format!("typing-{width}-{frame}.png"))).unwrap(); - }; - h.run_steps(40); - save(&mut h, "thinking"); - let w = h.state_mut().jiansun.as_mut().unwrap(); - w.messages[1]["active"] = json!(false); - w.stream_reply = reply.into(); - h.run_steps(28); - save(&mut h, "streaming"); - let w = h.state_mut().jiansun.as_mut().unwrap(); - w.messages.push(json!({"role":"assistant","kind":"reply","text":reply})); - w.stream_reply.clear(); - w.busy = None; - h.run_steps(67); - save(&mut h, "draining"); - h.run_steps(360); - save(&mut h, "settled"); - assert!(requests.try_recv().is_err()); - } - } - - #[test] - #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] - fn response_refinement_visual_acceptance() { - let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); - for (width, height, dock, scale) in [(1280.0,800.0,520.0,1.0),(1100.0,720.0,250.0,1.5)] { - let (mut app, requests) = dock_fixture(); - app.ui.dock_tabs.color = 4; - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = false; - w.focus_composer = true; - w.busy = Some("pi-agent".into()); - w.messages = vec![json!({"role":"user","text":"请保留木纹,检查当前图位。"}), - json!({"role":"assistant","kind":"thinking","text":"先核对产品原有结构与画布内容,再确认本次处理范围。"}), - json!({"role":"assistant","kind":"activity","text":"读取画布","event":{ - "version":1,"type":"tool","run":"visual-fixture","toolCallId":"one","toolName":"canvas_read","status":"completed","durationMs":27}}), - json!({"role":"assistant","kind":"activity","text":"检查范围","event":{ - "version":1,"type":"tool","run":"visual-fixture","toolCallId":"two","toolName":"workflow_read","status":"started"}})]; - w.stream_reply = "已核对当前画布,保留**产品结构**、木纹与花色。\n\n这里只调整光线,不生成图片。".into(); - let mut h = egui_kittest::Harness::builder().with_size(vec2(width,height)).with_pixels_per_point(scale) - .with_step_dt(1.0/120.0).with_max_steps(64).wgpu().build_ui_state( - |ui, app:&mut PhotocraftApp| { - if !ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } - crate::panels::title_bar(app,ui); - crate::panels::options_bar(app,ui); - crate::panels::status_bar(app,ui); - crate::panels::toolbar(app,ui); - crate::panels::right_dock(app,ui); - egui::CentralPanel::default().frame(Frame::NONE.fill(Tokens::get(ui.ctx()).canvas)) - .show(ui,|ui| crate::canvas::document_area(app,ui)); - },app); - PhotocraftApp::setup_context(&h.ctx,crate::theme::ThemeKind::ProMedium); - crate::panels::request_dock_width(&h.ctx,dock); - h.run_steps(4); - let save = |h:&mut egui_kittest::Harness,name:&str| { - h.render().unwrap().save(std::path::Path::new(&directory).join(format!("response-{dock}-{name}.png"))).unwrap(); - }; - save(&mut h,"streaming"); - h.state_mut().jiansun.as_mut().unwrap().stream_reply.push_str("新的句子平滑出现,标点保持原位。"); - h.run_steps(6); - save(&mut h,"new-batch"); - h.run_steps(20); - { - let w=h.state_mut().jiansun.as_mut().unwrap(); - w.messages.push(json!({"role":"assistant","kind":"reply","text":w.stream_reply})); - w.stream_reply.clear(); - w.busy=None; - } - h.run_steps(24); - save(&mut h,"completed"); - let now=h.ctx.input(|input|input.time); - h.ctx.data_mut(|data| data.insert_temp(Id::unique("composer-sent-glow"),now)); - h.run_steps(16); - save(&mut h,"send-glow"); - h.state_mut().jiansun.as_mut().unwrap().reduce_motion=true; - h.run_steps(4); - save(&mut h,"reduced"); - { - let w = h.state_mut().jiansun.as_mut().unwrap(); - w.messages = vec![json!({"role":"user","text":"制作详情、主图和 SKU"}), - json!({"role":"assistant","kind":"activity","text":"已接收制作任务。正在保存当前资料,接下来会按模板准备画布。"})]; - w.composer.clear(); - w.reduce_motion = false; - w.product_start_queued = true; - w.busy = Some("slot-apply-save".into()); - w.template_progress = json!({"phase":"save"}); - } - h.run_steps(4); - save(&mut h, "production-start"); - { - let w = h.state_mut().jiansun.as_mut().unwrap(); - w.product_start_queued = false; - w.busy = Some("pi-agent".into()); - w.pi_run = Some("goal-fixture".into()); - w.pi_product_production = true; - w.workflow.set_production_progress(&json!({"heading":"正在制作详情页","total":21,"rendered":2, - "workers":[{"number":1,"label":"首屏完整产品场景图","step":"正在生图","active":true}]})); - w.messages.push(json!({"role":"assistant","kind":"reply","text":"我先核对商品原图和模板,再安排制作。"})); - w.messages.push(json!({"role":"assistant","kind":"activity","text":"完成:读取画布","event":{ - "version":1,"type":"tool","run":"goal-fixture","toolCallId":"goal-read","toolName":"canvas_read","status":"completed"}})); - w.messages.push(json!({"role":"assistant","kind":"activity","text":"开始:分派生图","event":{ - "version":1,"type":"tool","run":"goal-fixture","toolCallId":"goal-stage","toolName":"delegate_image_slots","status":"started"}})); - w.stream_reply = "正在制作详情页。".into(); - } - h.run_steps(32); - save(&mut h, "production-streaming"); - h.state_mut().jiansun.as_mut().unwrap().stream_reply.push_str("首屏的配图已经开始生成。"); - h.run_steps(1); - save(&mut h, "production-new-batch"); - h.run_steps(32); - save(&mut h, "production-settled"); - { - let w = h.state_mut().jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.stream_reply.push_str("我会继续复核其余图位。"); - } - h.run_steps(2); - save(&mut h, "production-reduced"); - h.state_mut().jiansun.as_mut().unwrap().reduce_motion = false; - { - let w = h.state_mut().jiansun.as_mut().unwrap(); - w.messages.push(json!({"role":"assistant","kind":"reply","text":std::mem::take(&mut w.stream_reply)})); - w.pi_run = None; - w.busy = None; - w.messages.push(json!({"role":"assistant","kind":"reply","text":"已导出 2/3 份,待处理输出保留在项目中。", - "productionSummary":{"exported":2,"total":3}})); - } - h.run_steps(4); - save(&mut h, "production-followups"); - assert!(requests.try_recv().is_err(),"visual fixtures never dispatch a model or native operation"); - } - } - - #[test] - #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] - fn native_agent_visual_acceptance() { - let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); - let (mut app, requests) = dock_fixture(); - if let Ok(path) = std::env::var("PHOTOCRAFT_AGENT_QA_DOCUMENT") { - app.open_path(&path).expect("read-only local QA document"); - app.sync_views(); - } - let mut h = egui_kittest::Harness::builder().with_size(vec2(1280.0, 800.0)).with_pixels_per_point(1.5).with_max_steps(64).wgpu().build_ui_state( - |ui, app: &mut PhotocraftApp| { - if !ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - crate::panels::title_bar(app, ui); - crate::panels::options_bar(app, ui); - crate::panels::status_bar(app, ui); - crate::panels::toolbar(app, ui); - crate::panels::right_dock(app, ui); - egui::CentralPanel::default().frame(Frame::NONE.fill(Tokens::get(ui.ctx()).canvas)).show(ui, |ui| crate::canvas::document_area(app, ui)); - if let Some(workspace) = app.jiansun.as_mut() { workspace.account_dialog(ui); } - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); - h.run_steps(4); - h.state_mut().run("view.fitOnScreen", Value::Null).unwrap(); - for (name, pending, paused, tab) in [ - ("idle", false, false, 4), - ("processing", true, false, 4), - ("takeover", true, true, 4), - ("native-only", false, false, 0), - ("swatches", false, false, 1), - ] { - let app = h.state_mut(); - app.ui.dock_tabs.color = tab; - let w = app.jiansun.as_mut().unwrap(); - w.busy = pending.then(|| "slot-generate".into()); - w.agent_effects_paused = paused; - h.run_steps(4); - h.render().expect("native offscreen render").save(std::path::Path::new(&directory).join(format!("{name}.png"))).unwrap(); - } - h.state_mut().ui.dock_tabs.color = 4; - h.state_mut().jiansun.as_mut().unwrap().busy = Some("slot-generate".into()); - h.run_steps(4); - let first = h.render().unwrap(); - h.run_steps(30); - let second = h.render().unwrap(); - assert_ne!(first.as_raw(), second.as_raw(), "real pending state animates"); - second.save(std::path::Path::new(&directory).join("processing-later.png")).unwrap(); - h.state_mut().jiansun.as_mut().unwrap().reduce_motion = true; - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join("reduced-motion.png")).unwrap(); - let w = h.state_mut().jiansun.as_mut().unwrap(); - w.busy = None; - w.unknown = true; - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join("unknown-retained.png")).unwrap(); - { - let w = h.state_mut().jiansun.as_mut().unwrap(); - w.unknown = false; - w.model_settings = true; - w.library_status = "connected".into(); - w.image_models = ["gpt-image-2", "gpt-image-2-vip", "gpt-image-2.5", "gpt-image-2.5-flare", "gpt-image-2.5-flare-burst", "nano-banana-2", "nano-banana-2-cl"] - .into_iter().map(|name| json!({"key":name,"id":name})).collect(); - w.image_model = "nano-banana-2".into(); - } - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join("settings-with-usage.png")).unwrap(); - let settings_body = geometry(h.state().jiansun.as_ref().unwrap(), "settingsBody"); - h.event(egui::Event::PointerMoved(settings_body.center())); - h.event(egui::Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, phase: egui::TouchPhase::Move, - unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, -400.0), modifiers: egui::Modifiers::NONE, - }); - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join("settings-enterprise-knowledge.png")).unwrap(); - h.event(egui::Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, phase: egui::TouchPhase::Move, - unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, 400.0), modifiers: egui::Modifiers::NONE, - }); - h.run_steps(4); - let model_popup = h.ctx.data(|data| data.get_temp::(Id::unique(("agent-model-last-popup", ModelRole::Image, true)))).unwrap(); - egui::Popup::open_id(&h.ctx, model_popup); - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join("model-menu-alignment.png")).unwrap(); - egui::Popup::close_id(&h.ctx, model_popup); - { - let w = h.state_mut().jiansun.as_mut().unwrap(); - w.model_settings = false; - w.config = true; - } - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join("account-shared-dialog.png")).unwrap(); - { - let app = h.state_mut(); - app.ui.dock_tabs.color = 4; - let doc = app.session.active().unwrap().doc.id.0; - let w = app.jiansun.as_mut().unwrap(); - w.config = false; - w.reduce_motion = true; - w.busy = None; - w.unknown = false; - w.origin = "https://fixture.invalid".into(); - w.open_projects.insert(doc,w.local_identity("visual-test")); - w.composer = "用于检查拖放热区的本地草稿".into(); - w.focus_composer = true; - } - crate::panels::request_dock_width(&h.ctx,250.0); - h.run_steps(8); - let more = geometry(h.state().jiansun.as_ref().unwrap(),"composerMore"); - let composer = geometry(h.state().jiansun.as_ref().unwrap(),"composer"); - let send = geometry(h.state().jiansun.as_ref().unwrap(),"send"); - assert!(composer.contains_rect(send)); - h.render().unwrap().save(std::path::Path::new(&directory).join("composer-narrow-150.png")).unwrap(); - let at = more.center(); - for pressed in [true,false] { - h.input_mut().events = vec![egui::Event::PointerMoved(at),egui::Event::PointerButton { - pos:at,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]; - h.step(); - } - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join("composer-overflow-150.png")).unwrap(); - egui::Popup::close_all(&h.ctx); - h.run_steps(4); - let point = composer.center(); - h.state_mut().services.cursor_pos = Some(Box::new(move |_| Some(point))); - let before = h.render().unwrap(); - h.input_mut().hovered_files = vec![egui::HoveredFile { path:Some(std::env::temp_dir().join("fixture.png")), ..Default::default() }]; - h.step(); - let hovered = h.render().unwrap(); - assert_ne!(before.as_raw(),hovered.as_raw(),"a real hovered-file event paints feedback on the active composer"); - hovered.save(std::path::Path::new(&directory).join("composer-file-hover-150.png")).unwrap(); - h.input_mut().hovered_files.clear(); - h.set_pixels_per_point(1.25); - crate::panels::request_dock_width(&h.ctx,250.0); - h.run_steps(8); - let w = h.state().jiansun.as_ref().unwrap(); - assert!(geometry(w,"composer").contains_rect(geometry(w,"send"))); - let at = geometry(w,"composerMore").center(); - h.render().unwrap().save(std::path::Path::new(&directory).join("composer-narrow-125.png")).unwrap(); - for pressed in [true,false] { - h.input_mut().events = vec![egui::Event::PointerMoved(at),egui::Event::PointerButton { - pos:at,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]; - h.step(); - } - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join("composer-overflow-125.png")).unwrap(); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn replay_protection_during_an_active_request_is_not_a_terminal_unknown_status() { - let (tx, _) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - w.unknown = true; - for method in ["agent", "pi-agent", "recover", "image", "image-recover", "slot-generate", "slot-append", "slot-recover", "slot-copy"] { - w.busy = Some(method.into()); - assert!(w.pending()); - assert!(!w.result_needs_check()); - assert!(w.unknown, "display state must not clear the replay barrier"); - } - w.busy = None; - assert!(w.result_needs_check()); - w.unknown = false; - assert!(!w.result_needs_check()); - } - - #[test] - fn handing_over_a_candidate_keeps_original_request_and_prevents_late_adoption() { - let (tx, requests) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - let _ = requests.try_recv(); - w.busy = Some("slot-append".into()); - w.unknown = true; - w.canvas_workspace.pending_adoption = Some(json!({"candidateId":"original"})); - w.handover(); - assert!(w.canvas_workspace.handed_over); - assert!(w.canvas_workspace.pending_adoption.is_none()); - assert_eq!(w.busy.as_deref(), Some("slot-append")); - assert!(w.unknown); - assert!(requests.try_recv().is_err(), "handover neither retries nor cancels the upstream request"); - let count = w.messages.len(); - w.handover(); - assert_eq!(w.messages.len(), count); - } - - #[test] - fn adjacent_tool_groups_keep_their_place_between_replies() { - fn tool(id: &str, name: &str, status: &str) -> Value { - json!({"role":"assistant","kind":"activity","text":name,"event":{ - "version":1,"type":"tool","run":"timeline-run","toolCallId":id,"toolName":name,"status":status}}) - } - fn collect(shape: &egui::Shape, labels: &mut Vec<(String, f32)>) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, labels)), - egui::Shape::Text(text) => labels.push((text.galley.text().into(), text.pos.y)), - _ => {} - } - } - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.messages = vec![ - json!({"role":"user","text":"制作整套"}), - json!({"role":"assistant","kind":"reply","text":"先核对商品原片"}), - tool("one","canvas_read","started"), - tool("two","context_read","completed"), - json!({"role":"assistant","kind":"reply","text":"原片核对完成,接着制作"}), - tool("one","canvas_read","completed"), - tool("three","produce_current_output","completed"), - json!({"role":"assistant","kind":"reply","text":"成品已导出"}), - ]; - let turn = turns(&w.messages).pop().unwrap(); - assert!(matches!(&turn.items[..], - [TurnItem::Reply(_,1), TurnItem::Tools(first), TurnItem::Reply(_,4), - TurnItem::Tools(second), TurnItem::Reply(_,7)] - if first.len()==2 && first[0].1==2 && first[0].0["status"]=="completed" && second.len()==1)); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for width in [250.0, 520.0] { - let output = ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(650.0, 900.0))), - ..Default::default() - }, |ui| { - ui.set_width(width); - w.turn_ui(ui, turns(&w.messages).pop().unwrap(), Id::unique(("timeline-order", width as u64)), w.messages.len(), true, false, None); - }); - let mut labels = Vec::new(); - for shape in &output.shapes { collect(&shape.shape, &mut labels); } - let heads: Vec<_> = labels.iter().filter(|(s, _)| s=="已完成 2 项操作" || s.starts_with("已完成 · ")).map(|(_, y)| *y).collect(); - let y = |name: &str| labels.iter().find(|(s, _)| s==name).unwrap().1; - assert_eq!(heads.len(), 2, "visible timeline labels at {width}: {labels:?}"); - assert!(y("先核对商品原片") < heads[0] && heads[0] < y("原片核对完成,接着制作")); - assert!(y("原片核对完成,接着制作") < heads[1] && heads[1] < y("成品已导出")); - output.drop_without_applying_deltas(); - } - assert!(requests.try_recv().is_err()); - } - - #[test] - fn operations_are_grouped_under_the_actual_user_turn_without_losing_history() { - let messages = vec![ - json!({"role":"user","text":"精修产品"}), - json!({"role":"assistant","text":"图片已生成"}), - json!({"role":"assistant","kind":"activity","text":"已替换当前屏图片"}), - json!({"role":"assistant","kind":"reply","text":"已保留原有字体。"}), - json!({"role":"user","text":"修改标题"}), - ]; - let turns = turns(&messages); - assert_eq!(turns.len(), 2); - assert!(matches!(turns[0].items.as_slice(), - [TurnItem::Notice(..), TurnItem::Notice(..), TurnItem::Reply("已保留原有字体。", _)])); - assert_eq!(turns[1].user, Some("修改标题")); - } - - #[test] - fn repeated_status_keeps_only_its_latest_line() { - let saved = "详情页编辑稿已保存。小壹会自动核查 4 条原请求,确认结果后继续处理对应图位。"; - let again = "详情页编辑稿已保存。小壹会自动核查 1 条原请求,确认结果后继续处理对应图位。"; - let received = "已接收制作任务。正在保存当前资料,接下来会按模板准备画布。"; - let messages = vec![ - json!({"role":"user","text":"继续整套制作"}), - json!({"role":"assistant","kind":"activity","text":saved}), - json!({"role":"assistant","kind":"activity","text":received}), - json!({"role":"assistant","kind":"activity","text":again}), - json!({"role":"assistant","kind":"activity","text":received}), - ]; - let notices: Vec<_> = turns(&messages).into_iter().flat_map(|turn| turn.items).filter_map(|item| match item { - TurnItem::Notice(text, _) => Some(text), - _ => None, - }).collect(); - assert_eq!(notices, vec![saved, again, received]); - } - #[test] - fn failed_image_preflight_keeps_composer_and_never_dispatches_a_request() { - let (tx, requests) = mpsc::channel(); - let (_events, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - let _ = requests.try_recv(); - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); - let app = PhotocraftApp::new(session, crate::Services::default()); - w.loaded_draft = app.session.active().map(|state| state.doc.id.0); - w.busy = None; - w.image_ready = true; - w.image_mode = "regenerate".into(); - w.composer = "保留产品,调整背景".into(); - w.send_composer(&app); - assert_eq!(w.composer, "保留产品,调整背景"); - assert!(requests.try_recv().is_err()); - assert!(!w.error.is_empty()); - } - #[test] - fn composer_steers_an_active_chat_and_keeps_image_generation_disabled() { - let (mut app,requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - let doc = app.session.active().unwrap().doc.id.0; - let draft = w.composer.clone(); - let messages = w.messages.clone(); - w.pi_run = Some("12345678-1234-1234-1234-123456789012".into()); - w.busy = Some("agent".into()); - w.owner_doc = Some(doc); - w.pi_request_scope = json!({"project":{"documentId":doc},"subject":{"kind":"project"}}); - w.stream_reply = "未结束的回复".into(); - let scope = w.pi_request_scope.clone(); - assert!(w.can_send_with(&app,false)); - assert!(!w.can_send_with(&app,true)); - w.send_composer(&app); - let Request::Action(method,input) = requests.try_recv().unwrap() else { panic!("expected an action") }; - assert_eq!(method, "agent-steer"); - assert_eq!(input["text"], draft); - assert_eq!(input["behavior"], "steer"); - assert_eq!(input["doc"], doc); - assert!(w.composer.is_empty()); - assert_eq!(w.messages,messages); - assert_eq!(w.pi_request_scope,scope); - assert_eq!(w.busy.as_deref(),Some("agent")); - assert!(w.pi_run.is_some()); - assert_eq!(w.stream_reply,"未结束的回复"); - assert!(requests.try_recv().is_err()); - - w.pi_product_production = true; - w.canvas_workspace.output = "sku".into(); - w.composer = "补充详情页的安排".into(); - assert!(w.can_steer(&app)); - w.send_composer(&app); - assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent-steer" && input["doc"] == doc)); - assert_eq!(w.canvas_workspace.output, "sku"); - } - - #[test] - fn live_composer_renders_stop_beside_send_and_accepts_enter() { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let doc = app.session.active().unwrap().doc.id.0; - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.owner_doc = Some(doc); - w.busy = Some("agent".into()); - w.pi_run = Some("12345678-1234-1234-1234-123456789012".into()); - w.pi_queued_steering = vec!["保留高光".into()]; - w.pi_queued_followup = vec!["说明用色".into()]; - for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } - let w = app.jiansun.as_ref().unwrap(); - let send = geometry(w, "send"); - let stop = geometry(w, "stop"); - assert!(!send.intersects(stop)); - assert!(geometry(w, "composer").contains_rect(send.union(stop))); - ctx.memory_mut(|memory| memory.request_focus(super::super::composer_input_id())); - dock_frame(&ctx, &mut app, vec![egui::Event::Key { - key:egui::Key::Enter,physical_key:None,pressed:true,repeat:false,modifiers:egui::Modifiers::NONE, - }]); - assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent-steer" && input["doc"] == doc)); - app.jiansun.as_mut().unwrap().composer = "保留草稿".into(); - let center = stop.center(); - for pressed in [true, false] { - dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(center), egui::Event::PointerButton { - pos:center,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE, - }]); - } - assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent-abort" && input["doc"] == doc)); - assert!(app.jiansun.as_ref().unwrap().pi_queued_steering.is_empty()); - } - - #[test] - fn pending_steering_and_followup_render_above_the_composer_and_can_be_cleared() { - use egui_kittest::kittest::Queryable; - let (mut app, requests) = dock_fixture(); - let doc = app.session.active().unwrap().doc.id.0; - let mut w = app.jiansun.take().unwrap(); - w.owner_doc = Some(doc); - w.pi_run = Some("12345678-1234-1234-1234-123456789012".into()); - w.pi_queued_steering = vec!["保留高光".into()]; - w.pi_queued_followup = vec!["说明用色".into()]; - let mut harness = egui_kittest::Harness::builder() - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .with_size(vec2(520.0, 300.0)) - .build_ui_state(|ui, (w, app): &mut (Workspace, PhotocraftApp)| w.composer_ui(app, ui), (w, app)); - harness.run_steps(3); - assert_eq!(harness.query_all_by_label("待插话 · 当前步骤后注入 保留高光").count(), 1); - assert_eq!(harness.query_all_by_label("已排队 · 本轮结束后发送 说明用色").count(), 1); - let clear = harness.get_by_role_and_label(egui::accesskit::Role::Button, "清空待发送消息"); - assert!(clear.rect().bottom() <= geometry(&harness.state().0, "composer").top()); - clear.click(); - harness.run_steps(2); - assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent-clear-queue" && input["doc"] == doc)); - } - - #[test] - #[ignore = "Offscreen composer evidence; writes to PHOTOCRAFT_AGENT_QA_OUT"] - fn gpu_steering_composer_at_desktop_and_narrow_widths() { - use egui_kittest::kittest::Queryable; - let _guard = photocraft_testkit::gpu_lock(); - let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); - for width in [520.0, 260.0] { - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - w.reduce_motion = true; - w.busy = Some("agent".into()); - w.pi_run = Some("12345678-1234-1234-1234-123456789012".into()); - w.owner_doc = w.loaded_draft; - w.pi_queued_steering = vec!["保留高光与木纹细节".into()]; - w.pi_queued_followup = vec!["说明本轮用色".into()]; - let mut harness = egui_kittest::Harness::builder() - .with_context_setup(|ctx| { - PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(ctx); - }) - .with_size(vec2(width, 300.0)) - .wgpu() - .build_ui_state(|ui, (w, app): &mut (Workspace, PhotocraftApp)| w.composer_ui(app, ui), (w, app)); - harness.run_steps(3); - let w = &harness.state().0; - let composer = geometry(w, "composer"); - let stop = geometry(w, "stop"); - let send = geometry(w, "send"); - assert!(composer.contains_rect(stop.union(send))); - assert!(!stop.intersects(send)); - let clear = harness.get_by_role_and_label(egui::accesskit::Role::Button, "清空待发送消息"); - assert!(clear.rect().bottom() <= composer.top()); - assert!(requests.try_recv().is_err()); - harness.render().unwrap().save(directory.join(format!("steering-composer-{width}.png"))).unwrap(); - } - } - - #[test] - fn rejected_steering_resubmits_when_idle_and_preserves_an_unsent_draft_on_error() { - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - let doc = app.session.active().unwrap().doc.id.0; - let ctx = egui::Context::default(); - w.composer.clear(); - let mut receipt = json!({"accountId":w.account["id"],"origin":w.origin,"doc":doc, - "accepted":false,"reason":"not_streaming","text":"补充一下排版"}); - w.receive_json_event(&mut app, &ctx, "agent-steer".into(), Ok(receipt.clone())); - assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent" && input["text"] == receipt["text"])); - receipt["reason"] = json!("starting"); - receipt["error"] = json!("本轮正在连接"); - w.receive_json_event(&mut app, &ctx, "agent-steer".into(), Ok(receipt)); - assert_eq!(w.composer, "补充一下排版"); - assert_eq!(w.error, "本轮正在连接"); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn only_delivered_steering_has_the_timeline_tag() { - use egui_kittest::kittest::Queryable; - let (mut app, _) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - w.reduce_motion = true; - w.messages = vec![ - json!({"role":"user","text":"普通消息"}), - json!({"role":"user","kind":"steer","delivered":true,"text":"保留高光"}), - ]; - let h = egui_kittest::Harness::builder().with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .with_size(vec2(300.0, 260.0)).build_ui_state( - |ui, w: &mut Workspace| { - for turn in turns(&w.messages) { - w.turn_ui(ui, turn, Id::NULL, w.messages.len(), false, false, None); - } - }, w); - assert_eq!(h.query_all_by_label("已插话").count(), 1); - } - - #[test] - fn project_discussion_needs_a_model_but_no_brand_rules_or_canvas_write_grant() { - let (tx, requests) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - let _ = requests.try_recv(); - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); - let app = PhotocraftApp::new(session, crate::Services::default()); - w.loaded_draft = app.session.active().map(|state| state.doc.id.0); - w.busy = None; - w.model_ready = true; - w.image_mode = "chat".into(); - w.composer = "先讨论排版,不修改画布".into(); - assert!(w.agent_rule.is_null()); - assert!(w.can_send(&app)); - w.send_composer(&app); - assert!(matches!(requests.try_recv().unwrap(),Request::Action(method,_) if method=="agent")); - assert!(!w.allow_apply); - assert!(!w.pi_write_blocked); - w.busy = None; - w.unknown = true; - w.composer = "不能借聊天重发原请求".into(); - assert!(!w.can_send(&app)); - w.send_composer(&app); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn ordinary_send_uses_pi_even_after_a_previous_explicit_image_action() { - let (tx, requests) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - let _ = requests.try_recv(); - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); - let app = PhotocraftApp::new(session, crate::Services::default()); - w.loaded_draft = app.session.active().map(|state| state.doc.id.0); - w.busy = None; - w.model_ready = true; - w.image_ready = false; - w.image_mode = "generate".into(); - w.composer = "先讨论这一屏,不生成图片".into(); - w.send_discussion(&app); - assert_eq!(w.image_mode, "chat"); - assert!(matches!(requests.try_recv().unwrap(),Request::Action(method,_) if method=="agent")); - assert!(requests.try_recv().is_err(), "ordinary Send creates exactly one chat action, never an image action"); - } - - #[test] - fn explicit_image_action_keeps_unknown_request_and_draft_untouched() { - let (tx, requests) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - let _ = requests.try_recv(); - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); - let app = PhotocraftApp::new(session, crate::Services::default()); - w.busy = None; - w.unknown = true; - w.image_ready = true; - w.image_mode = "regenerate".into(); - w.composer = "保留这段未发送的要求".into(); - w.send_image_once(&app); - assert!(w.unknown); - assert_eq!(w.composer, "保留这段未发送的要求"); - assert!(requests.try_recv().is_err(), "a new-looking UI action cannot replay an unknown request"); - } - - #[test] - fn canvas_first_image_action_requires_the_current_slot_variant_and_dispatch_capability() { - let (tx, requests) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - let _ = requests.try_recv(); - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); - let app = PhotocraftApp::new(session, crate::Services::default()); - w.loaded_draft = app.session.active().map(|state| state.doc.id.0); - w.busy = None; - w.model_ready = true; - w.image_ready = true; - w.composer = "保留原图,追加暖光候选".into(); - w.canvas_workspace.variant = "brown".into(); - w.template_workflow = json!({"canvasFirst":true,"slots":[{"id":"current-slot"}],"capabilities":{"imageDispatchAllowed":true}}); - assert!(!w.can_send_with(&app, true), "project-level discussion does not guess an image target"); - assert!(w.can_send_with(&app, false)); - w.canvas_workspace.context = Some(json!({"slotId":"other-slot","productVariantId":"brown"})); - assert!(!w.can_send_with(&app, true)); - w.canvas_workspace.context = Some(json!({"slotId":"current-slot","productVariantId":"other-color"})); - assert!(!w.can_send_with(&app, true)); - w.canvas_workspace.context = Some(json!({"slotId":"current-slot","productVariantId":"brown"})); - assert!(w.can_send_with(&app, true)); - w.template_workflow["capabilities"]["imageDispatchAllowed"] = json!(false); - assert!(!w.can_send_with(&app, true)); - w.send_image_once(&app); - assert_eq!(w.composer, "保留原图,追加暖光候选"); - assert!(requests.try_recv().is_err()); - w.template_workflow["capabilities"]["imageDispatchAllowed"] = json!(true); - w.unknown = true; - assert!(!w.can_send_with(&app, true)); - w.send_image_once(&app); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn candidate_context_shows_its_page_variant_and_actual_candidate_ordinal() { - let workflow = json!({"slots":[{"id":"slot-1","candidates":[{"id":"first"},{"id":"second"},{"id":"third"}]}]}); - let subject = json!({"kind":"candidate","pageId":"S02","slotId":"slot-1","label":"木纹细节","variantLabel":"柚木色","candidateId":"third"}); - assert_eq!(subject_label(&subject, &workflow), "S02 · 木纹细节 · 柚木色 · 候选 3"); - assert_eq!(subject_label(&json!({"kind":"project","label":"当前项目"}), &workflow), "当前项目"); - assert_eq!(notice_kind("读取当前图位"), NoticeKind::Info, "a read is not falsely marked as a completed edit"); - assert_eq!(notice_kind("原请求待核查"), NoticeKind::NeedsCheck); - } - - #[test] - fn image_result_short_labels_follow_the_real_slot_order_and_keep_full_context() { - let workflow = json!({"slots":[ - {"id":"hero", "documentId":"S01", "label":"首屏产品场景主图", "candidates":[{"id":"a"},{"id":"b"},{"id":"c"}]}, - {"id":"detail", "documentId":"S02", "label":"木纹细节", "candidates":[{"id":"d"}]} - ]}); - let brief = json!({"variants":[{"id":"teak","name":"柚木色"}]}); - let target = image_location(&json!({"slotId":"hero","productVariantId":"teak","candidateId":"c"}), "task-2"); - let (page, short, full) = image_result_labels(&target, &workflow, &brief); - assert_eq!(page, "S01"); - assert_eq!(short, "候选 3", "the task/message order is irrelevant"); - assert_eq!(full, "S01 · 首屏产品场景主图 · 柚木色 · 候选 3"); - let other = image_location(&json!({"slotId":"detail","productVariantId":"teak","candidateId":"d"}), "task-1"); - assert_eq!(image_result_labels(&other, &workflow, &brief).0, "S02"); - assert_eq!(image_result_labels(&other, &workflow, &brief).1, "候选 1"); - let unknown = image_location(&json!({"slotId":"hero","productVariantId":"teak","candidateId":"missing"}), "task-3"); - assert_eq!(image_result_labels(&unknown, &workflow, &brief).1, "候选图片"); - assert_eq!(candidate_ordinal(&json!({"slotId":"hero"}), &workflow), None); - assert_eq!(candidate_ordinal(&json!({"candidateId":"a"}), &workflow), None); - let ambiguous = json!({"slots":[{"id":"hero","candidates":[{"id":"a"},{"id":"a"}]}]}); - assert_eq!(candidate_ordinal(&json!({"slotId":"hero","candidateId":"a"}), &ambiguous), None); - } - - #[test] - fn context_capsule_only_requests_native_location_and_never_sends_a_model_action() { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - w.composer.clear(); - let subject = json!({"kind":"candidate","label":"主视觉","pageId":"S01","slotId":"slot","outputId":"detail","productVariantId":"brown","candidateId":"candidate-3"}); - w.template_workflow = json!({"templateId":"pack","canvasFirst":true,"slots":[{"id":"slot","outputId":"detail","label":"主视觉","variantId":"brown","candidates":[{"id":"candidate-3"}]}]}); - w.canvas_workspace.context = Some(subject.clone()); - w.composer_reference_clear(&app); - w.composer_reference_add(&app).expect("attach the selected candidate to the draft"); - w.library = false; - w.focus_composer = true; - w.reduce_motion = true; - only_layers(&mut app); - app.ui.dock_tabs.color = 4; - app.jiansun = Some(w); - let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0)); - for _ in 0..2 { - let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { - let mut workspace = app.jiansun.take().unwrap(); - workspace.right(&mut app, ui); - app.jiansun = Some(workspace); - }); - output.textures_delta.clear(); - } - let expected_reference = app.jiansun.as_ref().unwrap().composer_reference_list(&app).into_iter() - .find(|reference| reference["candidateId"] == subject["candidateId"]).expect("the attached candidate remains available"); - assert_eq!(expected_reference["candidateId"], subject["candidateId"]); - let rect = app.jiansun.as_ref().unwrap().panel_geometry["subject"].as_array().unwrap(); - let at = - pos2((rect[0].as_f64().unwrap() + 12.0) as f32, (rect[1].as_f64().unwrap() + rect[3].as_f64().unwrap() / 2.0) as f32); - let mut hovered = ctx.settle_ui( - egui::RawInput { screen_rect: Some(screen), events: vec![egui::Event::PointerMoved(at)], ..Default::default() }, - |ui| { - let mut workspace = app.jiansun.take().unwrap(); - workspace.right(&mut app, ui); - app.jiansun = Some(workspace); - }, - ); - hovered.textures_delta.clear(); - for pressed in [true, false] { - let mut output = ctx.settle_ui( - egui::RawInput { - screen_rect: Some(screen), - events: vec![ - egui::Event::PointerMoved(at), - egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, - ], - ..Default::default() - }, - |ui| { - let mut workspace = app.jiansun.take().unwrap(); - workspace.right(&mut app, ui); - app.jiansun = Some(workspace); - }, - ); - output.textures_delta.clear(); - } - let w = app.jiansun.as_ref().unwrap(); - let located = w.canvas_workspace.locate_request.as_ref().unwrap_or_else(|| panic!("reference click did not locate: {}", w.panel_geometry)); - assert_eq!(located["candidateId"], expected_reference["candidateId"]); - assert_eq!(located["slotId"], expected_reference["slotId"]); - assert_eq!(located["productVariantId"], expected_reference["productVariantId"]); - assert_eq!(w.composer_reference_list(&app), vec![expected_reference]); - assert!(requests.try_recv().is_err()); - assert!(w.composer.is_empty()); - } - #[test] - fn streamed_text_is_scoped_and_cannot_apply_incomplete_edits() { - let ctx = egui::Context::default(); - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); - let mut app = PhotocraftApp::new(session, crate::Services::default()); - app.sync_views(); - let id = app.session.active().unwrap().doc.id.0; - let revision = app.session.active().unwrap().revision; - let (tx, _requests) = mpsc::channel(); - let (events, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - w.account = json!({"id":"a"}); - w.observed_doc = Some(id); - w.busy = Some("agent".into()); - for (account, doc, text) in [("b", id, "其他账户"), ("a", id + 1, "其他文档"), ("a", id, "正在调整中文")] { - events.send(Event::Json("agent-stream".into(), Ok(json!({"doc":doc,"accountId":account,"origin":w.origin,"text":text})))).unwrap(); - } - let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); - output.textures_delta.clear(); - assert_eq!(w.stream_reply, "正在调整中文"); - assert!(w.queue.is_empty()); - assert_eq!(app.session.active().unwrap().revision, revision); - w.unknown = true; - w.model_ready = true; - w.composer = "不要重发".into(); - w.busy = None; - assert!(!w.can_send(&app)); - } - #[test] - fn native_dock_keeps_input_and_actions_inside_supported_window_sizes() { - for (width, height) in [(1100.0, 720.0), (1280.0, 800.0), (1440.0, 900.0), (1920.0, 1080.0), (960.0, 600.0)] { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let (tx, _requests) = mpsc::channel(); - let (_events, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - let mut app_session = photocraft_engine::Session::new(); - app_session.execute("file.new",json!({"width":1440,"height":1800})).unwrap(); - let mut app = PhotocraftApp::new(app_session, crate::Services::default()); - app.sync_views(); - w.busy = None; - w.library = false; - w.account = json!({"id":"a"}); - w.key_saved = true; - w.composer = "很长的产品要求也只在输入区域内部滚动。\n".repeat(40); - w.messages = vec![json!({"role":"user","text":"用户要求"}), json!({"role":"assistant","kind":"reply","text":"这是答复"})]; - only_layers(&mut app); - app.ui.dock_tabs.color = 4; - app.jiansun = Some(w); - for _ in 0..2 { - let mut output = ctx - .run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width, height))), ..Default::default() }, |ui| { - crate::panels::right_dock(&mut app, ui) - }); - output.textures_delta.clear(); - } - let w = app.jiansun.as_ref().unwrap(); - let value = |name: &str| { - let a = w.panel_geometry[name].as_array().unwrap(); - Rect::from_min_size( - pos2(a[0].as_f64().unwrap() as f32, a[1].as_f64().unwrap() as f32), - vec2(a[2].as_f64().unwrap() as f32, a[3].as_f64().unwrap() as f32), - ) - }; - let panel = value("panel"); - let composer = value("composer"); - assert!(panel.contains_rect(composer), "{width}x{height}: panel={panel:?}, composer={composer:?}, geometry={}", w.panel_geometry); - let controls = vec!["input", "send", "settings", "composerOrb", "imageGenerate", "composerMore"]; - for key in controls { - assert!(composer.contains_rect(value(key)), "{key} at {width}x{height}"); - } - assert!(composer.height() <= height*0.5+1.0, "long drafts remain bounded at {width}x{height}: {}", composer.height()); - assert!(w.panel_geometry.get("chatModel").is_none() && w.panel_geometry.get("imageModel").is_none(), "model controls belong to settings only"); - assert!(w.panel_geometry.get("contextMeter").is_none(), "unavailable usage must not add noise to the composer"); - assert!(w.panel_geometry.get("rules").is_none(), "project rules do not become a second composer selector"); - assert!(w.panel_geometry.get("chatMode").is_none() && w.panel_geometry.get("imageMode").is_none(), "there is no persistent task-mode picker"); - } - } - - #[test] - fn composer_notices_keep_mini_input_inside_dock() { - for width in [250.0, 520.0] { - for notice in ["none", "error", "review", "unknown", "login", "key", "combined"] { - let (mut app, _) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.composer.clear(); w.focus_composer = false; w.reduce_motion = true; - if matches!(notice, "error" | "combined") { w.error = "原项目已关闭或移除,结果未写入其他项目".into(); } - w.pi_review = matches!(notice, "review" | "combined"); - w.unknown = notice == "unknown"; - if matches!(notice, "login" | "combined") { w.library_status = "disabled".into(); } - w.key_saved = notice != "key"; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - crate::panels::request_dock_width(&ctx, width); - for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } - let w = app.jiansun.as_ref().unwrap(); - let composer = geometry(w, "composer"); - let panel = geometry(w, "panel"); - assert!((composer.height() - 56.0 - reference_shelf_height(1, width - 28.0)).abs() < 1.0); - assert!(composer.bottom() <= panel.bottom() - 9.5, "{notice} at {width}: {composer:?} exceeds {panel:?}"); - assert!(composer.contains_rect(geometry(w, "input"))); - } - } - } - - #[test] - fn empty_unfocused_composer_keeps_references_above_the_native_input() { - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.composer.clear(); - w.focus_composer = false; - w.composer_attachments = Default::default(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for _ in 0..3 { - let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)).drop_without_applying_deltas(); - } - let w = app.jiansun.as_ref().unwrap(); - assert!(!w.panel_geometry["composerExpanded"].as_bool().unwrap()); - let subject = geometry(w, "subject"); - assert!(subject.height() <= 24.0, "reference chip: {subject:?}"); - assert!(subject.bottom() <= geometry(w, "input").top()); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn empty_caret_and_repeated_clicks_stay_in_the_native_input_below_references() { - let (mut app, requests) = dock_fixture(); - let w = app.jiansun.as_mut().unwrap(); - w.composer.clear(); - w.focus_composer = false; - w.reduce_motion = true; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0)); - let frame = |app: &mut PhotocraftApp, events| { - let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, - |ui| crate::panels::right_dock(app, ui)).drop_without_applying_deltas(); - }; - for _ in 0..3 { frame(&mut app, vec![]); } - let input = geometry(app.jiansun.as_ref().unwrap(), "input"); - let click = |app: &mut PhotocraftApp, at| { - for pressed in [true, false] { - frame(app, vec![egui::Event::PointerMoved(at), egui::Event::PointerButton { - pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, - }]); - } - for _ in 0..3 { frame(app, vec![]); } - }; - click(&mut app, input.left_top() + vec2(140.0, 10.0)); - for fraction in [0.35, 0.85, 0.55, 0.05] { - let w = app.jiansun.as_ref().unwrap(); - let input = geometry(w, "input"); - click(&mut app, pos2(input.right() - 20.0, input.top() + input.height() * fraction)); - let w = app.jiansun.as_ref().unwrap(); - assert!(w.panel_geometry["composerExpanded"].as_bool().unwrap()); - assert!(w.panel_geometry["composerFocused"].as_bool().unwrap()); - assert!(geometry(w, "input").contains(geometry(w, "inputCaret").left_top())); - assert!(geometry(w, "inputCaret").top() >= geometry(w, "subject").bottom()); - } - frame(&mut app, vec![egui::Event::Text("窗边光线".into())]); - frame(&mut app, vec![egui::Event::Key { key: egui::Key::Home, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]); - frame(&mut app, vec![]); - let w = app.jiansun.as_ref().unwrap(); - assert_eq!(w.composer, "窗边光线"); - assert!(geometry(w, "inputCaret").top() >= geometry(w, "subject").bottom()); - assert!(requests.try_recv().is_err(), "focus interactions never dispatch requests"); - } - - #[test] - fn pinned_production_stop_pauses_without_discarding_the_task() { - let (mut app, requests) = dock_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let w = app.jiansun.as_mut().unwrap(); - w.busy = Some("pi-agent".into()); - w.pi_product_production = true; - w.messages.push(json!({"role":"user","text":"一键制作整套详情页"})); - w.composer.clear(); - w.focus_composer = false; - w.reduce_motion = true; - for _ in 0..4 { dock_frame(&ctx, &mut app, vec![]); } - let w = app.jiansun.as_ref().unwrap(); - assert_eq!(w.panel_geometry["composerExpanded"], false); - let stop = geometry(w, "taskStop"); - assert!(geometry(w, "productionShelf").contains_rect(stop)); - assert!(!geometry(w, "composer").intersects(stop)); - assert!(w.panel_geometry["stop"].is_null()); - for pressed in [true,false] { - dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(stop.center()),egui::Event::PointerButton { - pos:stop.center(),button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE, - }]); - } - let w = app.jiansun.as_ref().unwrap(); - assert!(w.agent_effects_paused); - assert_eq!(w.busy.as_deref(), Some("pi-agent")); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn composer_actions_share_one_bottom_row_in_a_narrow_dock() { - for dock_width in [250.0, 288.0, 360.0, 520.0] { - let (mut app, _requests) = dock_fixture(); - app.ui.dock_tabs.color = 4; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - crate::panels::request_dock_width(&ctx, dock_width); - for _ in 0..2 { - let mut output = ctx.settle_ui(egui::RawInput { - screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(960.0, 600.0))), - ..Default::default() - }, |ui| crate::panels::right_dock(&mut app, ui)); - output.textures_delta.clear(); - } - let w = app.jiansun.as_ref().unwrap(); - let composer = geometry(w, "composer"); - let controls = vec!["subject", "input", "send", "composerOrb", "imageGenerate", "settings", "composerMore"]; - for key in controls { - assert!(composer.contains_rect(geometry(w, key)), "{key} must remain accessible in the compact composer"); - } - let row_y = geometry(w, "composerOrb").center().y; - let mut previous = geometry(w, "composerOrb"); - let row = vec!["composerMore", "imageGenerate", "settings", "send"]; - for key in row { - let control = geometry(w, key); - assert!((control.center().y - row_y).abs() < 1.0, "{key} must share the same bottom row"); - assert!(control.left() >= previous.right(), "{key} must not overlap its neighbour"); - previous = control; - } - assert!(composer.height() <= 252.0, "an empty attachment picker must not add another row: {}", composer.height()); - } - } - - - #[test] - fn composer_auto_height_grows_with_real_wrapped_draft_and_stays_inside_window() { - for size in [vec2(1518.0,1032.0),vec2(1100.0,720.0)] { - let (mut app,_requests)=dock_fixture();app.ui.dock_tabs.color=4;{let w=app.jiansun.as_mut().unwrap();w.reduce_motion=true;w.focus_composer=true;w.composer="短句".into();} - let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let frame=|app:&mut PhotocraftApp|{let _=ctx.settle_ui(egui::RawInput{screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,size)),..Default::default()},|ui|crate::panels::right_dock(app,ui));}; - for _ in 0..4{frame(&mut app);}let short=geometry(app.jiansun.as_ref().unwrap(),"composer").height(); - let text="请保留原来的产品结构、字体和字号,分别为本次引用的文字格生成候选文案。\n".repeat(8);app.jiansun.as_mut().unwrap().composer=text.clone(); - for _ in 0..4{frame(&mut app);}let w=app.jiansun.as_ref().unwrap();let surface=geometry(w,"composer");assert!(surface.height()>short+48.0);assert!(surface.height()<=size.y*0.5+1.0);assert!(surface.bottom()<=size.y);assert_eq!(w.composer,text); - } - } - #[test] - fn composer_paste_and_resize_keep_the_focused_caret_visible() { - let (mut app,_requests)=dock_fixture();app.ui.dock_tabs.color=4;{let w=app.jiansun.as_mut().unwrap();w.reduce_motion=true;w.focus_composer=true;w.composer.clear();} - let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let frame=|app:&mut PhotocraftApp,size,events|{let _=ctx.settle_ui(egui::RawInput{screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,size)),events,..Default::default()},|ui|crate::panels::right_dock(app,ui));}; - for _ in 0..4 {frame(&mut app,vec2(1518.0,1032.0),vec![]);} - frame(&mut app,vec2(1518.0,1032.0),vec![egui::Event::Text("请分别修改引用的文字格,保留字体字号和排版。".repeat(36))]); - for size in [vec2(1518.0,1032.0),vec2(1100.0,720.0)] {for _ in 0..4 {frame(&mut app,size,vec![]);}let w=app.jiansun.as_ref().unwrap();let caret=geometry(w,"inputCaret");let input=geometry(w,"input");assert!(input.expand(1.0).contains_rect(caret),"input={input:?}, caret={caret:?}");} - } - #[test] - fn composer_scrolling_input_keeps_the_shared_glass_background() { - let (mut app,_requests)=dock_fixture();app.ui.dock_tabs.color=4;{let w=app.jiansun.as_mut().unwrap();w.reduce_motion=true;w.focus_composer=true;w.composer="请保留文字格的原有排版。".repeat(40);} - let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let mut output=None;for _ in 0..4 {output=Some(ctx.settle_ui(egui::RawInput{screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1100.0,720.0))),..Default::default()},|ui|crate::panels::right_dock(&mut app,ui)));} - let input=geometry(app.jiansun.as_ref().unwrap(),"input");assert!(app.jiansun.as_ref().unwrap().panel_geometry["inputContentHeight"].as_f64().unwrap()>input.height() as f64); - fn masks(shape:&egui::Shape,input:Rect)->bool {match shape {egui::Shape::Mesh(mesh)=>{let bounds=mesh.calc_bounds();bounds.width()>input.width()*0.8&&bounds.height()<=24.0&&(bounds.bottom()-input.bottom()).abs()<1.0},egui::Shape::Vec(shapes)=>shapes.iter().any(|shape|masks(shape,input)),_=>false}} - assert!(!output.unwrap().shapes.iter().any(|shape|masks(&shape.shape,input)),"scrolling text must not add an opaque edge over the shared glass"); - } - #[test] - fn composer_reference_shelf_leaves_the_caret_in_the_first_text_row() { - let (mut app,_requests)=dock_fixture();app.ui.dock_tabs.color=4;let w=app.jiansun.as_mut().unwrap();w.reduce_motion=true;w.focus_composer=true;w.composer.clear(); - let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - for _ in 0..4{dock_frame(&ctx,&mut app,vec![]);}let w=app.jiansun.as_ref().unwrap();let row=geometry(w,"inputFirstRow");let chip=geometry(w,"subject");let caret=geometry(w,"inputCaret"); - assert!(row.top()>=chip.bottom(),"row={row:?}, chip={chip:?}");assert!(row.expand(1.0).contains(caret.left_top()));assert!(geometry(w,"input").expand(0.5).contains_rect(caret));assert!(w.panel_geometry["composerFocused"].as_bool().unwrap()); - dock_frame(&ctx, &mut app, vec![egui::Event::Text("Test color".into())]); - dock_frame(&ctx, &mut app, vec![]); - let w = app.jiansun.as_ref().unwrap(); - assert_eq!(w.composer, "Test color"); - assert!(geometry(w, "inputFirstRow").top() >= geometry(w, "subject").bottom()); - assert!(geometry(w, "inputCaret").left() > geometry(w, "input").left()); - } - #[test] - fn references_do_not_cover_loading_or_ready_input() { - for ready in [false, true] { - let (mut app, _) = dock_fixture(); - app.ui.dock_tabs.color=4; - let w=app.jiansun.as_mut().unwrap(); - w.reduce_motion=true; w.composer.clear(); - if !ready { w.loaded_draft=None; } - let ctx=egui::Context::default(); PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - for _ in 0..4 { dock_frame(&ctx,&mut app,vec![]); } - let w=app.jiansun.as_ref().unwrap(); - let chip=geometry(w,"subject"); let input=geometry(w,"input"); - assert!(input.top() >= chip.bottom(), "ready={ready}, chip={chip:?}, input={input:?}"); - } - } - - #[test] - fn composer_rejects_text_while_draft_load_is_pending() { - let (mut app, _) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - w.composer.clear(); w.loaded_draft = None; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let id = super::super::composer_input_id(); - ctx.memory_mut(|m| m.request_focus(id)); - let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), events, ..Default::default() }, |ui| w.composer_ui(app,ui)); - }; - frame(&mut w,&mut app,vec![]); - frame(&mut w,&mut app,vec![egui::Event::Text("不得丢失".into())]); - assert!(w.composer.is_empty(), "loading editor must not accept input it cannot preserve"); - let doc=app.session.active().unwrap().doc.id.0; - w.loaded_draft=Some(doc); - w.receive_composer_draft(&ctx,doc,&json!({"localId":"a","composer":"已存草稿","composerDraftToken":"token","composerDraftGeneration":0})); - assert_eq!(w.composer,"已存草稿"); - w.focus_composer=true; frame(&mut w,&mut app,vec![]); - frame(&mut w,&mut app,vec![egui::Event::Text("续写".into())]); - assert!(w.composer.contains("续写")); - } - - #[test] - fn composer_escape_collapses_selection_then_consumes_without_losing_text_or_focus() { - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - w.composer = "保留这段文字".into(); - w.reduce_motion = true; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let id = super::super::composer_input_id(); - ctx.memory_mut(|memory| memory.request_focus(id)); - let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { - let mut leaked = false; - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), events, ..Default::default() }, |ui| { - w.composer_ui(app,ui); - leaked = ui.input(|input| input.key_pressed(egui::Key::Escape)); - }); - leaked - }; - frame(&mut w,&mut app,vec![]); - let mut state = egui::text_edit::TextEditState::load(&ctx,id).unwrap(); - state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0),egui::text::CCursor::new(3)))); - state.store(&ctx,id); - let escape = || egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed:true, repeat:false, modifiers:egui::Modifiers::NONE }; - assert!(!frame(&mut w,&mut app,vec![escape()])); - let range = egui::text_edit::TextEditState::load(&ctx,id).unwrap().cursor.char_range().unwrap(); - assert_eq!(range.primary,range.secondary); - assert_eq!(w.composer,"保留这段文字"); - assert!(ctx.memory(|memory| memory.has_focus(id))); - assert!(!frame(&mut w,&mut app,vec![escape()])); - assert!(ctx.memory(|memory| memory.has_focus(id))); - assert_eq!(w.composer,"保留这段文字"); - w.composer.clear(); - w.focus_composer = true; - assert!(!frame(&mut w,&mut app,vec![escape()])); - assert!(!ctx.memory(|memory| memory.has_focus(id))); - assert!(!w.focus_composer); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn composer_escape_yields_to_top_modal_and_active_ime() { - let (mut app, requests) = dock_fixture(); - let mut w = app.jiansun.take().unwrap(); - w.composer = "保留输入内容".into(); - w.reduce_motion = true; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let id = super::super::composer_input_id(); - let modal = Id::unique("escape-priority-modal"); - let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events, show_modal:bool| { - let mut closed = false; - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), events, ..Default::default() }, |ui| { - w.composer_ui(app,ui); - if show_modal { closed = egui::Modal::new(modal).show(ui.ctx(),|ui| { ui.label("模态内容"); }).should_close(); } - }); - closed - }; - ctx.memory_mut(|memory| memory.request_focus(id)); - frame(&mut w,&mut app,vec![],true); - frame(&mut w,&mut app,vec![],true); - ctx.memory_mut(|memory| memory.request_focus(id)); - let escape = || egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed:true, repeat:false, modifiers:egui::Modifiers::NONE }; - assert!(frame(&mut w,&mut app,vec![escape()],true),"the top modal owns Escape"); - assert_eq!(w.composer,"保留输入内容"); - frame(&mut w,&mut app,vec![],false); - frame(&mut w,&mut app,vec![],false); - ctx.memory_mut(|memory| memory.request_focus(id)); - frame(&mut w,&mut app,vec![egui::Event::Ime(egui::ImeEvent::Preedit { text:"ni".into(), active_range_chars:None }),escape()],false); - assert_eq!(w.composer,"保留输入内容", "IME Escape cannot delete the draft"); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn composer_keeps_send_and_add_within_narrow_widths_and_scales() { - for width in [125.0,150.0,250.0] { - for scale in [1.0,1.25,1.5] { - let (mut app, _) = dock_fixture(); let mut w=app.jiansun.take().unwrap(); - w.reduce_motion=true; w.focus_composer=true; - let ctx=egui::Context::default(); PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); ctx.set_pixels_per_point(scale); - for _ in 0..4 { - let _=ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(width,500.0))), ..Default::default() }, |ui| { - ui.set_width(width); w.composer_ui(&mut app,ui); - }); - } - let composer=geometry(&w,"composer"); - assert!(composer.contains_rect(geometry(&w,"send")),"send must fit {width}pt at {scale}"); - assert!(composer.contains_rect(geometry(&w,"composerMore")),"add must fit {width}pt at {scale}"); - } - } - } - - #[test] - fn empty_composer_stays_open_during_internal_controls_at_high_dpi() { - for scale in [1.0,1.25,1.5] { - let (mut app, _) = dock_fixture(); app.ui.dock_tabs.color=4; - let w=app.jiansun.as_mut().unwrap(); w.composer.clear(); w.reduce_motion=true; w.focus_composer=true; - let ctx=egui::Context::default(); PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - ctx.set_pixels_per_point(scale); crate::panels::request_dock_width(&ctx,250.0); - for _ in 0..4 { dock_frame(&ctx,&mut app,vec![]); } - let original=geometry(app.jiansun.as_ref().unwrap(),"composer"); - for control in ["composerMore", "settings"] { - dock_click(&ctx,&mut app,control); - for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } - let w=app.jiansun.as_ref().unwrap(); - assert_eq!(w.panel_geometry["composerExpanded"],true,"{control}, scale={scale}"); - let now=geometry(w,"composer"); - assert!((now.height()-original.height()).abs()<1.0,"{control} must not move its composer, {original:?} -> {now:?}"); - dock_frame(&ctx,&mut app,vec![egui::Event::Key {key:egui::Key::Escape,physical_key:Some(egui::Key::Escape),pressed:true,repeat:false,modifiers:egui::Modifiers::NONE}]); - dock_frame(&ctx,&mut app,vec![egui::Event::Key {key:egui::Key::Escape,physical_key:Some(egui::Key::Escape),pressed:false,repeat:false,modifiers:egui::Modifiers::NONE}]); - for _ in 0..2 { dock_frame(&ctx,&mut app,vec![]); } - } - } - } - - #[test] - fn one_canvas_click_closes_an_open_add_menu_and_releases_the_empty_composer() { - let (mut app, _requests) = dock_fixture(); - app.ui.dock_tabs.color = 4; - let w = app.jiansun.as_mut().unwrap(); - w.composer.clear(); w.reduce_motion = true; w.focus_composer = true; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - crate::panels::request_dock_width(&ctx,250.0); - for _ in 0..4 { dock_frame(&ctx,&mut app,vec![]); } - dock_click(&ctx,&mut app,"composerMore"); - assert!(egui::Popup::is_id_open(&ctx,Id::unique("jiansun-composer-more-popup"))); - let outside = egui::pos2(100.0,100.0); - for pressed in [true,false] { dock_frame(&ctx,&mut app,vec![egui::Event::PointerMoved(outside),egui::Event::PointerButton { - pos:outside,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); } - for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } - assert!(!egui::Popup::is_id_open(&ctx,Id::unique("jiansun-composer-more-popup"))); - assert_eq!(app.jiansun.as_ref().unwrap().panel_geometry["composerExpanded"],false); - assert!(!ctx.memory(|memory| memory.has_focus(super::super::composer_input_id()))); - } - - #[test] - fn narrow_high_dpi_composer_overflow_exposes_real_secondary_actions() { - fn texts(shape:&egui::Shape, out:&mut Vec<(String,Rect)>) { - 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(),Rect::from_min_size(text.pos,text.galley.size()))), - _ => {} - } - } - for scale in [1.25,1.5] { - let (mut app, _requests) = dock_fixture(); - app.ui.dock_tabs.color = 4; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - ctx.set_pixels_per_point(scale); - crate::panels::request_dock_width(&ctx,250.0); - for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } - let w = app.jiansun.as_ref().unwrap(); - assert!(geometry(w,"composer").contains_rect(geometry(w,"send"))); - assert!(w.panel_geometry["composerMore"].is_array()); - dock_click(&ctx,&mut app,"composerMore"); - let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app,ui)); - let mut labels = Vec::new(); - for shape in &output.shapes { texts(&shape.shape,&mut labels); } - assert!(labels.iter().any(|(text,_)| text == "添加本地参考图")); - let prompt = labels.iter().find(|(text,_)|text == "常用提示词").unwrap().1.center(); - for pressed in [true,false] { dock_frame(&ctx,&mut app,vec![egui::Event::PointerMoved(prompt),egui::Event::PointerButton { - pos:prompt,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); } - assert!(app.jiansun.as_ref().unwrap().prompt_library.is_open(),"the menu invokes the existing prompt-library action"); - } - } - - #[test] - fn empty_composer_more_keeps_its_position_through_press_and_menu_then_collapses() { - fn collect(shape:&egui::Shape, out:&mut Vec<(String,Rect)>) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape,out)), - egui::Shape::Text(text) => out.push((text.galley.text().to_owned(),Rect::from_min_size(text.pos,text.galley.size()))), - _ => {} - } - } - let (mut app, _requests) = dock_fixture(); - app.ui.dock_tabs.color = 4; - let w = app.jiansun.as_mut().unwrap(); - w.reduce_motion = true; - w.composer.clear(); - w.focus_composer = true; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - crate::panels::request_dock_width(&ctx,250.0); - for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } - let more = geometry(app.jiansun.as_ref().unwrap(),"composerMore"); - let point = more.center(); - dock_frame(&ctx,&mut app,vec![egui::Event::PointerMoved(point),egui::Event::PointerButton { - pos:point,button:egui::PointerButton::Primary,pressed:true,modifiers:egui::Modifiers::NONE }]); - for _ in 0..4 { - dock_frame(&ctx,&mut app,vec![]); - let w=app.jiansun.as_ref().unwrap(); - assert_eq!(w.panel_geometry["composerExpanded"],true,"holding the press cannot collapse the composer"); - assert_eq!(geometry(w,"composerMore"),more,"the release target remains at the pressed position"); - } - dock_frame(&ctx,&mut app,vec![egui::Event::PointerButton { - pos:point,button:egui::PointerButton::Primary,pressed:false,modifiers:egui::Modifiers::NONE }]); - for _ in 0..2 { dock_frame(&ctx,&mut app,vec![]); } - let popup = Id::unique("jiansun-composer-more-popup"); - assert!(egui::Popup::is_id_open(&ctx,popup),"a real click opens the overflow menu with an empty draft"); - let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app,ui)); - let mut labels=Vec::new(); - for shape in &output.shapes { collect(&shape.shape,&mut labels); } - assert!(labels.iter().any(|(text,_)| text=="添加本地参考图")); - assert!(labels.iter().any(|(text,_)| text=="常用提示词")); - dock_frame(&ctx,&mut app,vec![egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed:true, repeat:false, modifiers:egui::Modifiers::NONE }]); - assert!(!egui::Popup::is_id_open(&ctx,popup), "Escape closes the real add menu"); - for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } - assert_eq!(app.jiansun.as_ref().unwrap().panel_geometry["composerExpanded"],true,"closing an internal menu keeps the composer expanded"); - let outside=egui::pos2(100.0,100.0); - for pressed in [true,false] { dock_frame(&ctx,&mut app,vec![egui::Event::PointerMoved(outside),egui::Event::PointerButton { pos:outside,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); } - for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } - assert_eq!(app.jiansun.as_ref().unwrap().panel_geometry["composerExpanded"],false,"an external click collapses an empty composer"); - assert!((geometry(app.jiansun.as_ref().unwrap(),"composer").height()-56.0-reference_shelf_height(1, 250.0-28.0)).abs()<1.0); - app.jiansun.as_mut().unwrap().focus_composer = true; - for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } - dock_click(&ctx,&mut app,"composerMore"); - let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app,ui)); - labels.clear(); - for shape in &output.shapes { collect(&shape.shape,&mut labels); } - let prompt = labels.iter().find(|(text,_)|text=="常用提示词").unwrap().1.center(); - for pressed in [true,false] { dock_frame(&ctx,&mut app,vec![egui::Event::PointerMoved(prompt),egui::Event::PointerButton { - pos:prompt,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); } - assert!(app.jiansun.as_ref().unwrap().prompt_library.is_open(),"the empty-draft menu invokes the real prompt library"); - } - - #[test] - fn workflow_card_distinguishes_a_screen_from_the_whole_output_and_current_canvas_export() { - let workflow = json!({"slots":[{"id":"detail-slot","documentId":"S01","fieldId":"S01-I01"},{"id":"sku-slot","documentId":"K02","fieldId":"K02-I02"}]}); - assert_eq!(workflow_scope(&json!({"intent":"fill_output","outputId":"detail","slotId":"detail-slot"}), &workflow), "详情 · S01"); - assert_eq!(workflow_scope(&json!({"intent":"fill_output","outputId":"main_images"}), &workflow), "主图 · 全组"); - assert_eq!(workflow_scope(&json!({"intent":"review_candidates","outputId":"sku_images","slotId":"sku-slot"}), &workflow), "SKU · K02"); - assert_eq!(workflow_scope(&json!({"intent":"export","outputId":"main_images"}), &workflow), "当前画布"); - assert_eq!(workflow_scope(&json!({"intent":"export_psd"}), &workflow), "当前画布"); - assert_eq!( - workflow_scope(&json!({"intent":"generate_candidate","outputId":"sku_images","slotId":"sku-slot","variant":"B"}), &workflow), - "SKU · K02-I02 · B" - ); - } - - #[test] - fn inline_reference_detaches_without_changing_canvas_or_draft_and_can_be_added_again() { - let (mut app, requests) = dock_fixture(); - app.ui.dock_tabs.color = 4; - app.jiansun.as_mut().unwrap().reduce_motion = true; - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } - let revision = app.session.active().unwrap().revision; - let selected = app.session.active().unwrap().selected_layers(); - let draft = app.jiansun.as_ref().unwrap().composer.clone(); - let click = |app: &mut PhotocraftApp, at| { - for pressed in [true, false] { - dock_frame(&ctx, app, vec![egui::Event::PointerMoved(at), egui::Event::PointerButton { - pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, - }]); - } - for _ in 0..3 { dock_frame(&ctx, app, vec![]); } - }; - let detach = geometry(app.jiansun.as_ref().unwrap(), "referenceRemove").center(); - click(&mut app, detach); - let w = app.jiansun.as_ref().unwrap(); - assert!(w.composer_reference_list(&app).is_empty()); - assert_eq!(w.composer, draft); - assert!(w.panel_geometry.get("subject").is_none()); - assert_eq!(app.session.active().unwrap().revision, revision); - assert_eq!(app.session.active().unwrap().selected_layers(), selected); - let add_menu = geometry(w, "composerMore").center(); - click(&mut app, add_menu); - let add = geometry(app.jiansun.as_ref().unwrap(), "referenceAdd").center(); - click(&mut app, add); - assert!(!app.jiansun.as_ref().unwrap().composer_reference_list(&app).is_empty()); - assert!(requests.try_recv().is_err(), "reference controls never dispatch a model"); - } - - #[test] - fn detached_reference_cannot_survive_as_a_hidden_request_target() { - let (mut app, requests) = dock_fixture(); - super::super::action(&mut app, "composer-reference-remove", json!({"index":0})).unwrap(); - let selected = app.session.active().unwrap().selected_layers(); - assert!(!selected.is_empty()); - super::super::action(&mut app, "agent", json!({"text":"只讨论整体设计"})).unwrap(); - let Request::Action(method, request) = requests.try_recv().unwrap() else { panic!("local request"); }; - assert_eq!(method, "agent"); - let scope = &request["context"]["requestScope"]; - assert_eq!(scope["subject"]["kind"], "project"); - assert_eq!(scope["references"], json!([])); - assert_eq!(scope["selected"], json!([])); - assert!(requests.try_recv().is_err()); - } +use agent_panel_test_exports::*; +#[cfg(test)] +mod agent_panel_test_exports { + pub(in super::super) use super::artifact_preview_ui::{ + ArtifactPreviewSnapshot, ArtifactPreviewView, image_location, + }; + pub(in super::super) use super::composer_ui::{ + composer_enter, copy_reply, has_comparable_candidates, + }; + pub(in super::super) use super::model_picker_ui::{context_meter, show_settings_glass}; + pub(in super::super) use super::models::{ + CONTEXT_PENDING, CONTEXT_UNAVAILABLE, context_for_model, context_fraction, context_label, + is_hidden_model, model_display_name, + }; + pub(in super::super) use super::notifications::{ + AgentNotifications, AgentToast, notification_id, toast_active, toast_id, + }; + pub(in super::super) use super::processing_card_ui::workflow_scope; + pub(in super::super) use super::production_reply_ui::production_image_cells; + pub(in super::super) use super::reference_shelf_ui::reference_shelf_height; + pub(in super::super) use super::turn_ui::{ + active_tool_elapsed, candidate_ordinal, frame_image_ratio, image_result_labels, + notice_kind, subject_label, user_bubble_with_reveal, + }; + pub(in super::super) use super::turns::{ + Turn, TurnItemLayouts, activity_history_label, duration_text, is_tool_event, + }; + pub(in super::super) use super::super::{Arc, Duration, Instant, Request}; + pub(in super::super) use super::super::stitch_state::{NoticeKind, WorkerStage}; } + +#[cfg(test)] +mod tests; diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/artifact_preview_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/artifact_preview_ui.rs new file mode 100644 index 00000000..175ae58b --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/artifact_preview_ui.rs @@ -0,0 +1,314 @@ +use super::super::RichText; +use egui::Stroke; +use super::super::{Tokens, Ui, Value, Workspace, json}; +use egui::{Color32, Id, Layout, Rect, Vec2, vec2}; +use egui::Sense; + +#[derive(Clone)] +pub(in crate::jiansun) struct ArtifactPreviewSnapshot { + pub(in crate::jiansun) scope: String, + pub(in crate::jiansun) key: String, + pub(in crate::jiansun) texture: egui::TextureHandle, + pub(in crate::jiansun) view: ArtifactPreviewView, +} + +#[derive(Clone)] +pub(in crate::jiansun) struct ArtifactPreviewView { + pub(in crate::jiansun) zoom: Option, + pub(in crate::jiansun) center: Vec2, + pub(in crate::jiansun) drag_position: Option, +} + +impl Default for ArtifactPreviewView { + fn default() -> Self { Self { zoom: None, center: Vec2::splat(0.5), drag_position: None } } +} + +impl ArtifactPreviewView { + pub(in crate::jiansun) fn scale(&self, viewport: Vec2, image: Vec2, pixels_per_point: f32) -> f32 { + self.zoom.map_or((viewport.x / image.x).min(viewport.y / image.y).min(1.0 / pixels_per_point), |zoom| zoom / pixels_per_point) + } + + pub(in crate::jiansun) fn zoom_at(&mut self, zoom: f32, at: Vec2, viewport: Vec2, image: Vec2, pixels_per_point: f32) { + let old = self.scale(viewport, image, pixels_per_point); + let fit = (viewport.x / image.x).min(viewport.y / image.y).min(1.0 / pixels_per_point); + self.zoom = Some(zoom.clamp(fit * pixels_per_point, 4.0)); + let new = self.scale(viewport, image, pixels_per_point); + self.center += at / image * (1.0 / old - 1.0 / new); + } +} + +pub(in crate::jiansun) fn image_preview_button(ui: &mut Ui, rect: Rect, key: &str) -> egui::Response { + let button = Rect::from_min_size(rect.right_top() + vec2(-34.0, 6.0), vec2(28.0, 28.0)); + let response = preview_icon_at(ui, button, key, "maximize-2", "放大预览"); + if response.clicked() { + ui.data_mut(|data| data.insert_temp(Id::unique("jiansun-image-expanded"), key.to_owned())); + } + response +} + +pub(in crate::jiansun) fn preview_icon_at(ui: &mut Ui, rect: Rect, key: &str, icon: &str, label: &str) -> egui::Response { + let mut controls = ui.new_child(egui::UiBuilder::new().id_salt(("preview-control", key)).max_rect(rect) + .layout(Layout::top_down(egui::Align::Min))); + controls.set_clip_rect(ui.clip_rect().intersect(rect)); + let mut frame = egui::Frame::NONE.corner_radius(8).begin(&mut controls); + let response = super::stitch_ui::icon_action_button(&mut frame.content_ui, icon, label, true, 28.0, true); + frame.frame.fill = Color32::from_black_alpha(if response.hovered() { 230 } else { 185 }); + frame.end(&mut controls); + response.on_hover_text(label) +} + +pub(in crate::jiansun) fn preview_neighbors<'a>(workflow: &'a Value, key: &str) -> (Option<&'a str>, Option<&'a str>) { + for slot in workflow["slots"].as_array().into_iter().flatten() { + let mut keys = slot["candidates"].as_array().into_iter().flatten() + .filter(|candidate| candidate["status"] == "complete") + .filter_map(|candidate| candidate.get("taskId").unwrap_or(&candidate["id"]).as_str()); + let mut previous = None; + while let Some(candidate) = keys.next() { + if candidate == key { return (previous, keys.next()); } + previous = Some(candidate); + } + } + (None, None) +} + +pub(in crate::jiansun) fn artifact_preview_contents(ui: &mut Ui, texture: &egui::TextureHandle, view: &mut ArtifactPreviewView, rect: Rect) { + let image = texture.size_vec2(); + let viewport = rect.size(); + let pixels_per_point = ui.ctx().pixels_per_point(); + let response = ui.interact(rect, ui.scope_id().with("preview-image"), Sense::click_and_drag()); + let response = response.on_hover_text("滚轮缩放 · 拖动查看 · 双击适应窗口"); + if response.double_clicked() { *view = ArtifactPreviewView::default(); } + if response.hovered() && ui.is_enabled() { + let (scroll, pinch) = ui.input_mut(|input| { + let values = (input.smooth_scroll_delta.y, input.zoom_delta()); + input.smooth_scroll_delta = Vec2::ZERO; + values + }); + let factor = if pinch != 1.0 { pinch } else { (scroll * 0.005).exp() }; + if factor != 1.0 { + let zoom = view.scale(viewport, image, pixels_per_point) * pixels_per_point * factor; + view.zoom_at(zoom, response.hover_pos().unwrap_or(rect.center()) - rect.center(), viewport, image, pixels_per_point); + ui.ctx().request_repaint(); + } + } + let scale = view.scale(viewport, image, pixels_per_point); + if ui.is_enabled() { + ui.input(|input| { + for event in &input.events { + match event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } if rect.contains(*pos) => view.drag_position = Some(*pos), + egui::Event::PointerMoved(pos) => { + if let Some(previous) = view.drag_position { + view.center -= (*pos - previous) / (image * scale); + view.drag_position = Some(*pos); + } + } + egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, .. } | egui::Event::PointerGone => view.drag_position = None, + _ => {} + } + } + }); + } else { view.drag_position = None; } + let half = (viewport / (image * scale) * 0.5).min(Vec2::splat(0.5)); + view.center = view.center.clamp(half, Vec2::splat(1.0) - half); + let can_pan = image.x * scale > viewport.x + 0.5 || image.y * scale > viewport.y + 0.5; + if can_pan { + let cursor = if view.drag_position.is_some() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab }; + response.on_hover_cursor(cursor); + } + let painter = ui.painter_at(rect.intersect(ui.clip_rect())); + painter.image(texture.id(), Rect::from_min_size(rect.center() - view.center * image * scale, image * scale), + Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE); +} + +pub(in crate::jiansun) fn artifact_preview_zoom_bar(ui: &mut Ui, texture: &egui::TextureHandle, view: &mut ArtifactPreviewView, viewport: Vec2, loading: bool, reduced: bool) { + let image = texture.size_vec2(); + let pixels_per_point = ui.ctx().pixels_per_point(); + let zoom = view.scale(viewport, image, pixels_per_point) * pixels_per_point; + let fit = ArtifactPreviewView::default().scale(viewport, image, pixels_per_point) * pixels_per_point; + let t = Tokens::get(ui.ctx()).agent(); + egui::Frame::NONE.fill(t.field).stroke(Stroke::new(1.0, t.field_border)).corner_radius(18) + .inner_margin(egui::Margin::symmetric(8, 0)).show(ui, |ui| { + ui.horizontal(|ui| { + use super::stitch_ui::{ButtonRole, action_button, icon_action_button}; + ui.spacing_mut().item_spacing.x = 3.0; + ui.spacing_mut().button_padding.x = 5.0; + if action_button(ui, "适应窗口", ButtonRole::Quiet, true).clicked() { + *view = ArtifactPreviewView::default(); + } + if action_button(ui, "原始大小", ButtonRole::Quiet, true).clicked() { + view.zoom_at(1.0, Vec2::ZERO, viewport, image, pixels_per_point); + } + if icon_action_button(ui, "minus", "缩小预览", true, 28.0, zoom > fit + 0.001).on_hover_text("缩小预览").clicked() { + view.zoom_at(zoom / 1.25, Vec2::ZERO, viewport, image, pixels_per_point); + } + if icon_action_button(ui, "plus", "放大预览", true, 28.0, zoom < 4.0).on_hover_text("放大预览").clicked() { + view.zoom_at(zoom * 1.25, Vec2::ZERO, viewport, image, pixels_per_point); + } + let percent = format!("{:.0}%", view.scale(viewport, image, pixels_per_point) * pixels_per_point * 100.0); + ui.add_sized(vec2(38.0, 28.0), egui::Label::new(RichText::new(percent).weak()).truncate()); + if loading { + super::stitch_ui::ai_loader(ui, ui.scope_id().with("artifact-preview-loading"), true, reduced); + } + }); + }); +} + + +pub(in crate::jiansun) fn image_location(value: &Value, id: &str) -> Value { + let mut target = json!({"kind":"candidate","taskId":id,"candidateId":id}); + for key in ["slotId", "productVariantId", "outputId", "documentId", "nativeLayerId"] { + if let Some(field) = value.get(key).filter(|field| !field.is_null()) + .or_else(|| value["target"].get(key).filter(|field| !field.is_null())) { + target[key] = field.clone(); + } + } + if value["variantId"].is_string() && !target["productVariantId"].is_string() { + target["productVariantId"] = value["variantId"].clone(); + } + if let Some(candidate) = value["candidateId"].as_str().or_else(|| value["target"]["candidateId"].as_str()) { + target["candidateId"] = json!(candidate); + } + target +} + +pub(in crate::jiansun) fn image_reference_target(value: &Value, id: &str, label: &str, original: bool) -> Value { + let mut target = json!({"taskId":id,"label":label}); + for key in ["documentId", "nativeLayerId", "slotId", "fieldId", "candidateId", "outputId", + "productVariantId", "pageId", "status", "source"] { + let field = value.get(key).filter(|field| !field.is_null()) + .or_else(|| if original { None } else { value["target"].get(key) }); + if let Some(field) = field { target[key] = field.clone(); } + } + if target["productVariantId"].is_null() { + target["productVariantId"] = value["variantId"].clone(); + } + target["kind"] = json!(if original { "template-image" } + else if target["slotId"].is_string() || target["candidateId"].is_string() { "candidate" } + else { "image" }); + if target["kind"] == "candidate" && target["candidateId"].is_null() { + target["candidateId"] = json!(id); + } + target +} + +pub(in crate::jiansun) fn activate_reference(ui: &mut Ui, reference: &Value, preview: Option<&str>) -> Option { + if reference["slotId"].is_string() || reference["nativeLayerId"].is_number() { + return Some(reference.clone()); + } + if let Some(id) = preview.or_else(|| reference["taskId"].as_str()) { + ui.data_mut(|data| data.insert_temp(Id::unique("jiansun-image-expanded"), id.to_owned())); + } + None +} + +/// Match explicit identities only: a reused slot or a similar label alone is +/// never enough to identify an earlier response. +pub(in crate::jiansun) fn candidate_matches_message(target: &Value, image: &Value) -> bool { + let saved = &image["target"]; + let mut identity = false; + for key in ["candidateId", "taskId", "run"] { + let requested = target[key].as_str().filter(|value| !value.is_empty()); + let recorded = image[key].as_str().or_else(|| saved[key].as_str()).filter(|value| !value.is_empty()); + if let Some(requested) = requested { + if let Some(recorded) = recorded { + if requested != recorded { return false; } + if key != "run" { identity = true; } + } else if key == "run" { return false; } + } + } + if !identity { return false; } + for key in ["slotId", "productVariantId", "outputId"] { + if let (Some(requested), Some(recorded)) = (target[key].as_str(), image[key].as_str().or_else(|| saved[key].as_str())) + && requested != recorded { return false; } + } + identity +} + + +impl Workspace { + pub(in crate::jiansun) fn artifact_window(&self, ui: &mut Ui) { + let id = Id::unique("jiansun-image-expanded"); + let snapshot_id = id.with("exit-snapshot"); + let transition_id = id.with("transition"); + let scope = json!([self.origin, self.account["id"], self.project_context["localId"], self.owner_doc]).to_string(); + let selected = ui.data(|d| d.get_temp::(id)); + let mut snapshot = ui.data(|d| d.get_temp::(snapshot_id)); + if snapshot.as_ref().is_some_and(|old| old.scope != scope) { + ui.data_mut(|d| { d.remove::(snapshot_id); d.remove::(id); }); + super::stitch_ui::overlay_transition(ui.ctx(), transition_id, false, true); + return; + } + if let Some(selected) = selected.as_ref() { + self.agent_images.mark_visible(selected); + if let Some(texture) = self.agent_images.get(selected) { + let view = snapshot.as_ref().filter(|old| old.key == *selected).map(|old| old.view.clone()).unwrap_or_default(); + let current = ArtifactPreviewSnapshot { scope, key: selected.clone(), texture: texture.clone(), view }; + ui.data_mut(|d| d.insert_temp(snapshot_id, current.clone())); + snapshot = Some(current); + } else if snapshot.is_none() { + if ui.input(|input| input.key_pressed(egui::Key::Escape)) { + ui.data_mut(|data| data.remove::(id)); + } + super::stitch_ui::overlay_transition(ui.ctx(), transition_id, false, true); + return; + } + } + let visual = super::stitch_ui::overlay_transition(ui.ctx(), transition_id, selected.is_some(), self.reduce_motion); + if !visual.render { + ui.data_mut(|d| d.remove::(snapshot_id)); + return; + } + if let Some(saved) = snapshot.as_mut() { + self.agent_images.mark_visible_existing(&saved.key); + let texture = &saved.texture; + let screen = ui.ctx().content_rect(); + let image = texture.size_vec2(); + let available = (screen.size() - vec2(104.0, 112.0)).max(Vec2::splat(1.0)); + let viewport = image * ArtifactPreviewView::default().scale(available, image, ui.ctx().pixels_per_point()); + let (previous, next) = preview_neighbors(&self.template_workflow, &saved.key); + let loading = selected.as_ref().is_some_and(|key| *key != saved.key); + let mut close = false; + let mut switch = None; + let modal = egui::Modal::new(id.with("lightbox")) + .frame(egui::Frame::NONE) + .backdrop_color(Color32::from_black_alpha((208.0 * visual.opacity) as u8)) + .show(ui.ctx(), |ui| { + let size = vec2((viewport.x + 80.0).max(260.0), viewport.y + 84.0); + let (body, _) = ui.allocate_exact_size(size, Sense::hover()); + super::stitch_ui::overlay_contents(ui, visual, |ui| { + let photo = Rect::from_center_size(egui::pos2(body.center().x, body.top() + 36.0 + viewport.y / 2.0), viewport); + artifact_preview_contents(ui, texture, &mut saved.view, photo); + let close_rect = Rect::from_min_size(body.right_top() - vec2(28.0, 0.0), Vec2::splat(28.0)); + close = preview_icon_at(ui, close_rect, "close", "x", "关闭预览").clicked(); + for (key, x, icon, label, shortcut) in [ + (previous, photo.left() - 24.0, "chevron-left", "上一张", egui::Key::ArrowLeft), + (next, photo.right() + 24.0, "chevron-right", "下一张", egui::Key::ArrowRight), + ] { + if let Some(key) = key { + let rect = Rect::from_center_size(egui::pos2(x, photo.center().y), Vec2::splat(28.0)); + if preview_icon_at(ui, rect, icon, icon, label).clicked() + || (ui.is_enabled() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, shortcut))) { + switch = Some(key); + } + } + } + let width = if loading { 274.0 } else { 252.0 }; + let bar = Rect::from_center_size(egui::pos2(photo.center().x, photo.bottom() + 29.0), vec2(width, 38.0)); + let mut controls = ui.new_child(egui::UiBuilder::new().id_salt("zoom-bar").max_rect(bar) + .layout(Layout::top_down(egui::Align::Min))); + artifact_preview_zoom_bar(&mut controls, texture, &mut saved.view, viewport, loading, self.reduce_motion); + }); + }); + ui.data_mut(|d| d.insert_temp(snapshot_id, saved.clone())); + if visual.interactive && (close || modal.should_close()) { + ui.data_mut(|d| d.remove::(id)); + ui.ctx().request_repaint(); + } else if let Some(key) = switch { + ui.data_mut(|d| d.insert_temp(id, key.to_owned())); + ui.ctx().request_repaint(); + } + } + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/composer_actions.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/composer_actions.rs new file mode 100644 index 00000000..2d80d479 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/composer_actions.rs @@ -0,0 +1,226 @@ +use super::super::Instant; +use super::turn_ui::frame_image_ratio; +use super::super::{PhotocraftApp, Request, Value, Workspace, json, stitch_state::WorkerStage}; +use super::turns::ProductionWorker; +use super::composer_ui::insert_suggestion; + +impl Workspace { + pub(in crate::jiansun) fn fill_prompt(&mut self, prompt: &str) { + insert_suggestion(&mut self.composer, prompt); + self.canvas_workspace.composer_edited(); + self.image_mode = "chat".into(); + self.focus_composer = true; + self.draft_changed = true; + self.touched = Instant::now(); + } + + pub(in crate::jiansun) fn pending(&self) -> bool { + matches!( + self.busy.as_deref(), + Some( + "agent" + | "agent-stopping" + | "pi-agent" + | "recover" + | "image" + | "image-recover" + | "image-use" + | "slot-generate" + | "slot-append" + | "slot-recover" + | "slot-copy" + ) + ) || self.pi_run.is_some() + || self.canvas_workspace.adoption_preparing() + || !self.queue.is_empty() + || self.pending_image.is_some() + || (self.workflow_waiting.is_some() && self.busy.is_some()) + } + + pub(in crate::jiansun) fn result_needs_check(&self) -> bool { + // A dispatched request is protected from replay while it is still + // running. That protection is not a terminal unknown-result message. + self.unknown && !self.pending() && self.product_production.is_none() && !self.product_start_queued + } + + pub(in crate::jiansun) fn batch_progress_visible(&self) -> bool { + !self.agent_effects_paused && (self.product_start_queued || self.product_production.is_some() + || self.pi_product_production && self.pending()) + } + + pub(in crate::jiansun) fn production_workers(&self) -> Vec> { + let progress = self.workflow.production_progress(); + let jobs = self.pi_run.as_deref().map_or_else(Vec::new, |run| self.workflow.worker_generations(run)); + let mut used = std::collections::HashSet::new(); + let rows = progress["workers"].as_array().into_iter().flatten().map(|row| (row, false)) + .chain(progress["reviews"].as_array().into_iter().flatten().map(|row| (row, true))); + let rows: Vec<_> = rows.filter(|(row, review)| row["active"] == true || (!review && row["step"] != "已交验图")).collect(); + let reserved: std::collections::HashSet<_> = rows.iter().filter_map(|(row, _)| row["number"].as_u64().filter(|n| *n > 0)).collect(); + let mut next = (1_u64..).filter(|n| !reserved.contains(n)); + rows.into_iter().map(|(row, review)| { + let number = row["number"].as_u64().filter(|n| *n > 0 && used.insert(*n)) + .unwrap_or_else(|| next.next().unwrap()); + let active = row["active"] == true; + let job = (!review && active && row["slotId"].is_string()).then(|| jobs.iter().rev().find(|job| + job["slotId"] == row["slotId"] && job["phase"] == "submitted" + && (row["number"].is_null() || job["workerNumber"] == row["number"]))).flatten(); + let image_step = job.and_then(|job| job["imageStep"].as_str()); + let step = image_step.or_else(|| row["step"].as_str()).unwrap_or(""); + let stage = WorkerStage::infer(step, review, image_step.is_some()); + ProductionWorker { + row, number, active, stage, step: step.to_owned(), review, + slot: row["label"].as_str().unwrap_or("").to_owned(), + frame: job.map(|job| job["imageFrame"].clone()).unwrap_or_default(), + } + }).collect() + } + + pub(in crate::jiansun) fn projected_worker_jobs(&self) -> Vec { + if self.product_start_queued || self.product_production.as_ref().is_some_and(|run| !run.showing_agent_progress()) { + return Vec::new(); + } + let progress = self.workflow.production_progress(); + let current = self.messages.iter().rposition(|row| row["role"] == "user").map_or(&self.messages[..], |i| &self.messages[i..]); + self.production_workers().into_iter().filter_map(|worker| { + if !worker.active || worker.stage != WorkerStage::Generating { return None; } + let slot_id = &worker.row["slotId"]; + if current.iter().any(|image| image["kind"] == "image-job" && image["finished"].is_null() + && self.pi_run.as_deref().is_some_and(|run| image["run"] == run) + && if slot_id.is_string() && image["target"]["slotId"].is_string() { + image["target"]["slotId"] == *slot_id + && (worker.row["number"].is_null() || image["workerNumber"].is_null() || image["workerNumber"] == worker.row["number"]) + && (image["target"]["outputId"].is_null() || progress["outputId"].is_null() || image["target"]["outputId"] == progress["outputId"]) + && (image["target"]["productVariantId"].is_null() || progress["variantId"].is_null() + || image["target"]["productVariantId"] == progress["variantId"]) + } else { + image["workerNumber"] == worker.number + }) { return None; } + let frame = [Some(&worker.frame), Some(worker.row), worker.row.get("imageFrame"), + self.template_workflow["slots"].as_array().into_iter().flatten().find(|slot| + slot["id"] == *slot_id && (progress["outputId"].is_null() || slot["outputId"] == progress["outputId"]) + && (progress["variantId"].is_null() || slot["variantId"].is_null() || slot["variantId"] == progress["variantId"])) + .map(|slot| &slot["frame"])] + .into_iter().flatten().find(|frame| frame_image_ratio(frame).is_some()); + Some(json!({ + "kind":"image-job", "taskId":format!("worker-preview-{}", worker.number), "projected":true, + "workerNumber":worker.number, "slotLabel":worker.slot, + "width":frame.map(|frame| &frame["width"]), "height":frame.map(|frame| &frame["height"]), + })) + }).collect() + } + + + pub(in crate::jiansun) fn production_assets(&self) -> impl Iterator { + let mut seen = std::collections::HashSet::new(); + self.messages.iter().filter(move |message| + matches!(message["kind"].as_str(), Some("image" | "template-image")) + && message["taskId"].as_str().is_some_and(|task| seen.insert(task))) + } + + pub(in crate::jiansun) fn open_generated_folder(&mut self, doc: u64) { + let action = json!({"doc":doc,"accountId":self.account["id"],"origin":self.origin}); + let result = self.tx.send(Request::Action("open-generated-folder".into(), action)); + self.canvas_workspace.generated_folder_status = Some((doc, if result.is_ok() { + "正在查找本地生成图…".into() + } else { + "本机服务暂不可用,请稍后再试。".into() + })); + } + + + pub(in crate::jiansun) fn can_send(&self, app: &PhotocraftApp) -> bool { + self.can_send_with(app, self.image_mode != "chat") + } + + pub(in crate::jiansun) fn can_send_with(&self, app: &PhotocraftApp, image: bool) -> bool { + if !image && self.can_steer(app) { return true; } + if !image && self.has_paused_production() && self.turn_idle() { + return self.can_resume_product() && self.composer_draft_ready(app) + && !self.library_blocked() && !self.composer.trim().is_empty(); + } + let target_ready = !image + || self.template_workflow["canvasFirst"] != true + || (self.template_workflow["capabilities"]["imageDispatchAllowed"] == true + && self.canvas_workspace.context.as_ref().is_some_and(|target| { + target["kind"] != "selection" + && target["productVariantId"] == self.canvas_workspace.variant + && target["slotId"] + .as_str() + .filter(|id| !id.is_empty()) + .is_some_and(|id| self.template_workflow["slots"].as_array().into_iter().flatten().any(|slot| slot["id"] == id)) + })); + !self.professional_child_active(app) && self.composer_draft_ready(app) + && !self.library_blocked() + && (image || self.composer_text_send_allowed_for(app)) + && target_ready + && self.can_start_turn() + && !self.pi_review + && (if image { self.image_ready } else { self.model_ready }) + && !self.composer.trim().is_empty() + } + + pub(in crate::jiansun) fn send_discussion(&mut self, app: &PhotocraftApp) { + if !self.can_steer(app) && !self.has_paused_production() && !self.composer_text_send_allowed_for(app) { + self.error = "当前对话模型暂不支持图片,请先移除附件或使用生图".into(); + return; + } + if self.can_send_with(app, false) { + self.image_mode = "chat".into(); + self.send_composer(app); + } + } + + pub(in crate::jiansun) fn send_image_once(&mut self, app: &PhotocraftApp) { + if self.can_send_with(app, true) { + if self.template_workflow["canvasFirst"] == true { + // The canvas-first workspace owns its immutable candidate + // append and ACK. Never route this to the legacy replacement. + if let Err(error) = self.canvas_generate_selected(app) { + self.error = error; + } + return; + } + // This is an explicit one-shot action. Ordinary Send/Ctrl+Enter + // always discuss through Pi; a previous image action is not a mode + // that can silently turn the next user message into a paid image. + if self.image_mode != "regenerate" { + self.image_mode = "generate".into(); + } + self.send_composer(app); + self.image_mode = "chat".into(); + } + } + + pub(in crate::jiansun) fn send_composer(&mut self, app: &PhotocraftApp) { + if !self.can_send(app) { + return; + } + let text = self.composer.clone(); + if self.image_mode == "chat" { + if self.can_steer(app) { + if self.steer(app, text, "steer") { + self.composer.clear(); + self.draft_changed = true; + } + return; + } + if self.has_paused_production() && self.turn_idle() { + self.resume_product_production_with(app, Some(text)); + if !self.has_paused_production() { + self.composer.clear(); + self.draft_changed = true; + } + return; + } + self.submit(app, text); + } else { + self.generate(app, text, &self.image_mode.clone()); + } + // Preflight errors keep the user's draft available to correct and resubmit deliberately. + if matches!(self.busy.as_deref(), Some("agent" | "pi-agent" | "image")) { + self.composer.clear(); + self.draft_changed = true; + } + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/composer_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/composer_ui.rs new file mode 100644 index 00000000..5f1b50a0 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/composer_ui.rs @@ -0,0 +1,677 @@ +use super::super::{Arc, CenterView, Instant, LayerContent, PhotocraftApp, RichText, Tokens, Ui, Value, Workspace, agent_motion, json, prompt_library_ui, stitch_timeline as timeline}; +use super::{CONTINUE_PRODUCTION, rect_value}; +use super::model_picker_ui::context_meter; +use super::models::{context_for_model, context_fraction}; +use super::notifications::{AgentNotifications, notification_id, toast_id}; +use super::notifications_ui::{draw_draft_toast, post_draft_toast}; +use super::reference_shelf_ui::reference_shelf_height; +use super::turn_ui::icon; +use super::turns::{conversation_settled, turns}; +use egui::{Align, Color32, FontId, Frame, Id, Layout, Rect, Response, Sense, Stroke, Vec2, vec2}; + +pub(in crate::jiansun) fn copy_visible_text(ui: &mut Ui, text: &str, label: &str) -> Response { + let response = super::stitch_ui::icon_button(ui, "copy", 24.0, false, label); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + if response.clicked() { ui.ctx().copy_text(text.to_owned()); } + response +} + +pub(in crate::jiansun) fn copy_reply(ui: &mut Ui, text: &str) -> Response { + copy_visible_text(ui, text, "复制这条回复") +} + +pub(in crate::jiansun) fn has_comparable_candidates(workflow: &Value, subject: &Value) -> bool { + let (Some(slot_id), Some(variant)) = (subject["slotId"].as_str().filter(|s| !s.is_empty()), subject["productVariantId"].as_str().filter(|s| !s.is_empty())) else { + return false; + }; + let mut ids = std::collections::HashSet::new(); + for slot in workflow["slots"].as_array().into_iter().flatten().filter(|slot| { + slot["id"] == slot_id && (slot["variantId"].is_null() || slot["variantId"] == variant) + }) { + for candidate in slot["candidates"].as_array().into_iter().flatten() { + let candidate_variant = candidate["variantId"].as_str().or_else(|| candidate["variant"].as_str()); + let same_variant = candidate_variant == Some(variant) || (candidate_variant.is_none() && slot["variantId"] == variant); + if same_variant && candidate["status"] == "complete" && let Some(id) = candidate["id"].as_str().filter(|id| !id.is_empty()) { + ids.insert(id); + } + } + } + ids.len() >= 2 +} + +pub(in crate::jiansun) fn insert_suggestion(draft: &mut String, prompt: &str) { + if draft.trim().is_empty() { + *draft = prompt.to_owned(); + } else { + if !draft.ends_with('\n') { draft.push('\n'); } + draft.push_str(prompt); + } +} + + +pub(in crate::jiansun) fn composer_galley(ui: &Ui, text: &str, width: f32) -> Arc { + let mut job = egui::text::LayoutJob::simple(text.to_owned(), FontId::proportional(14.0), Tokens::get(ui.ctx()).agent().text, width); + for section in &mut job.sections { section.format.line_height = Some(24.0); } + ui.fonts_mut(|fonts| fonts.layout_job(job)) +} + + +/// Read the submit key before TextEdit consumes it. IME confirmation belongs to +/// the editor, never to the model request; repeats are consumed without dispatch. +pub(in crate::jiansun) fn composer_enter(ui: &mut Ui, id: Id) -> bool { + let state_id = id.with("ime-submit-guard"); + if !ui.memory(|memory| memory.has_focus(id)) { + ui.data_mut(|data| data.remove::<(bool, u64)>(state_id)); + return false; + } + let frame = ui.ctx().cumulative_frame_nr(); + let (mut composing, mut confirmed) = ui.data(|data| data.get_temp::<(bool, u64)>(state_id)).unwrap_or((false, u64::MAX)); + let mut ime_event = false; + ui.input(|input| { + for event in &input.events { + match event { + egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) => { + composing = !text.is_empty(); + ime_event = true; + confirmed = frame; + } + egui::Event::Ime(egui::ImeEvent::Commit(_)) => { + composing = false; + ime_event = true; + confirmed = frame; + } + _ => {} + } + } + }); + ui.data_mut(|data| data.insert_temp(state_id, (composing, confirmed))); + let blocked = composing || ime_event || confirmed != u64::MAX && frame.saturating_sub(confirmed) <= 1; + let mut submit = false; + ui.input_mut(|input| { + input.events.retain(|event| { + if let egui::Event::Key { key: egui::Key::Enter, pressed: true, repeat, modifiers, .. } = event + && !modifiers.shift + && !modifiers.alt + { + submit |= !blocked && !repeat; + false + } else { + true + } + }); + }); + submit +} + + +impl Workspace { + /// What the canvas holds for the suggestion row: selected text, and a + /// selected object. + pub(in crate::jiansun) fn suggestion_scope(&self, app: &PhotocraftApp) -> (bool, bool) { + let has_text = app + .session + .active() + .is_some_and(|s| s.selected_layers().iter().any(|id| matches!(s.doc.layer(*id).map(|l| &l.content), Some(LayerContent::Text(_))))); + let selected = self.canvas_workspace.context.as_ref().is_some_and(|context| context["kind"] != "project"); + (has_text, selected) + } + + /// Suggestions follow what the canvas holds: selected text, a selected + /// object, or nothing. Choosing one only fills the composer. + pub(in crate::jiansun) fn suggestion_prompts(&self, has_text: bool, selected: bool) -> [(&'static str, &'static str); 2] { + let suggestions = if has_text { + [("精简文案", "请精简当前选中的文字,保留原有事实和语气。"), ("检查排版", "请检查当前文字的层级和间距,先讨论调整建议。")] + } else if selected { + let compare = self.canvas_workspace.context.as_ref().is_some_and(|subject| has_comparable_candidates(&self.template_workflow, subject)); + [ + ("讨论选中对象", "请结合当前选中的对象讨论可以改进的地方,先不要自动生成或替换。"), + if compare { + ("比较候选", "请比较当前图位的已有候选,说明各自特点,不自动采纳。") + } else { + ("讨论调整方向", "请结合选中对象和项目资料,先讨论可以调整的方向。") + }, + ] + } else { + [ + ("梳理资料", "请读取当前项目资料,梳理已有事实和需要补充的内容。"), + ("讨论页面", "请结合项目模板和产品资料,和我讨论页面的重点与安排。"), + ] + }; + suggestions + } + + pub(in crate::jiansun) fn suggestion_row(&mut self, app: &PhotocraftApp, ui: &mut Ui, key: &str, suggestions: [(&'static str, &'static str); 2], resume_production: Option, size: super::agent_stream::SuggestionSize, wrap: bool) { + use super::agent_stream::{SUGGESTION_CHIP_HEIGHT, SUGGESTION_GAP, suggestion_chip}; + let mut rects = Vec::new(); + let draft_ready = self.composer_draft_ready(app); + let layout = egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(wrap); + ui.allocate_ui_with_layout(vec2(ui.available_width(), SUGGESTION_CHIP_HEIGHT), layout, |ui| { + ui.spacing_mut().item_spacing = vec2(SUGGESTION_GAP, SUGGESTION_GAP); + if let Some(enabled) = resume_production { + let hint = "按图位完成剩余图片,保留已采纳结果和现有图层"; + let response = suggestion_chip(ui, "sparkles", CONTINUE_PRODUCTION, enabled, self.reduce_motion, size) + .on_hover_text(hint).on_disabled_hover_text(hint); + rects.push(json!({"label":CONTINUE_PRODUCTION,"rect":rect_value(response.rect)})); + if response.clicked() { + self.resume_product_production(app); + ui.ctx().request_repaint(); + } + } + let items = suggestions.map(|(label, _)| ("sparkles", label)); + let responses = timeline::suggestion_row(ui, &items, draft_ready, self.reduce_motion, size); + for ((label, prompt), response) in suggestions.into_iter().zip(responses) { + let response = response.on_hover_text(prompt); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, response.enabled(), format!("填入输入框:{label}"))); + rects.push(json!({"label":label,"rect":rect_value(response.rect)})); + if response.clicked() { + self.fill_prompt(prompt); + ui.ctx().request_repaint(); + } + } + }); + // Leave space between the shortcuts and the input surface. + ui.add_space(6.0); + self.panel_geometry[key] = json!(rects); + } + + /// Nothing has been said yet: a few lines say what 小壹 does here and + /// where to start. They name only what this client's tools can do. + pub(in crate::jiansun) fn empty_conversation_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + let t = Tokens::get(ui.ctx()).agent(); + let document_open = app.session.active().is_some(); + ui.add_space(24.0); + ui.add(egui::Label::new(RichText::new("小壹可以帮你").size(14.0).strong().color(t.text))); + ui.add_space(6.0); + for line in ["为图位生成候选图,采纳后放进画布", "写详情页文案,并核对卖点依据", "整套制作详情、主图和 SKU"] { + ui.horizontal_top(|ui| { + ui.add_space(1.0); + ui.add(egui::Label::new(RichText::new("·").size(12.0).color(t.text_faint))); + ui.add(egui::Label::new(RichText::new(line).size(12.0).color(t.text_dim)).wrap()); + }); + } + ui.add_space(8.0); + let start = if document_open { "在下面的输入框里写下需求,或点一条建议开始。" } else { "打开一个项目后,在下面的输入框里写下需求。" }; + ui.add(egui::Label::new(RichText::new(start).size(12.0).color(t.text_faint)).wrap()); + if !document_open && super::stitch_ui::action_button(ui, "我的项目", super::stitch_ui::ButtonRole::Secondary, true).clicked() { + self.show_center(CenterView::Projects, false); + } + } + + /// Follow-ups close a settled reply. They name the next step from the + /// reply's own receipt and never send anything by themselves. + pub(in crate::jiansun) fn followup_prompts(&self, production: bool) -> Option<[(&'static str, &'static str); 2]> { + if !conversation_settled(self, production) { return None; } + let index = self.messages.iter().rposition(|message| message["text"].as_str().is_some_and(|text| !text.is_empty()))?; + if turns(&self.messages).last().and_then(|turn| turn.last_reply.map(|(_, last)| last)) != Some(index) { return None; } + let summary = &self.messages[index]["productionSummary"]; + Some(if summary.is_object() { + if summary["exported"] == summary["total"] { + [("验收整套", "请检查本轮详情、主图和 SKU 的导出结果,逐项指出需要调整的地方。"), + ("核对卖点和配图", "请核对整页的卖点与配图是否对应,列出证据不足的地方。")] + } else { + [("查看未完成项", "请梳理这轮未完成的文案、图位和输出,说明每项卡在哪里。"), + ("核对已有结果", "请检查目前已保留的文案和配图,指出需要调整的地方。")] + } + } else { + [("展开下一步", "请把上一条建议展开为具体的下一步和验收标准。"), + ("核对依据", "请结合当前项目资料,核对上一条回复中的判断和依据。")] + }) + } + + + pub(in crate::jiansun) fn composer_surface_height(&self, app: &PhotocraftApp, ui: &Ui, width: f32, progress: f32) -> f32 { + let references = reference_shelf_height(self.composer_reference_list(app).len(), (width - 28.0).max(1.0)); + if progress == 0.0 { + return 56.0 + references; + } + let attachment = if self.composer_text_send_allowed_for(app) { 0.0 } else { self.composer_attachments_extra_height() }; + let wrap_width = (width - 32.0).max(1.0); + let layout_key = (wrap_width, ui.pixels_per_point(), Tokens::get(ui.ctx()).kind); + let height_id = ui.scope_id().with("composer-draft-height"); + type DraftHeight = ((f32, f32, crate::theme::ThemeKind), String, f32); + let cached = ui.data_mut(|data| data.remove_temp::>(height_id)).flatten(); + let (key, draft, text_height) = cached + .filter(|(key, draft, _)| *key == layout_key && draft == &self.composer) + .unwrap_or_else(|| (layout_key, self.composer.clone(), + composer_galley(ui, &self.composer, wrap_width).size().y.max(24.0))); + ui.data_mut(|data| data.insert_temp(height_id, Some((key, draft, text_height)))); + let expanded = (text_height + 74.0 + attachment).max(168.0) + .min((ui.ctx().content_rect().height() * 0.5 - references).max(168.0)); + 56.0 + references + (expanded - 56.0) * progress + } + + pub(in crate::jiansun) fn composer_notice_height(&self, ui: &Ui) -> f32 { + let gap = 6.0; + let row = ui.spacing().interact_size.y; + let button = 34.0_f32.max(row); + let mut height = 0.0; + if self.pi_review && self.busy.is_none() { height += button + 16.0 + gap; } + if self.result_needs_check() || (!self.pending() && self.ready_image.is_some()) { height += button + 16.0 + gap; } + if !self.error.is_empty() && self.error != self.library_message { height += super::operation_error::inline_height(ui,&self.error,(ui.available_width()-20.0).max(1.0)) + gap; } + if !self.needs_library_login() && !self.library_blocked() && !self.key_saved { height += button + gap; } + height + self.steering_queue_height() + } + + pub(in crate::jiansun) fn steering_queue_height(&self) -> f32 { + if self.pi_run.is_none() || self.agent_effects_paused || self.loaded_draft != self.owner_doc { return 0.0; } + let groups = usize::from(!self.pi_queued_steering.is_empty()) + usize::from(!self.pi_queued_followup.is_empty()); + if groups == 0 { 0.0 } else { (groups as f32 * 19.0).max(26.0) + 6.0 } + } + + pub(in crate::jiansun) fn steering_queue_ui(&mut self, ui: &mut Ui) { + let height = self.steering_queue_height(); + if height == 0.0 { return; } + let tint = Tokens::get(ui.ctx()).agent().text_dim; + ui.allocate_ui_with_layout(vec2(ui.available_width(), height - 6.0), Layout::right_to_left(Align::Center), |ui| { + let clear = super::stitch_ui::icon_button(ui, "x", 26.0, false, "清空待发送消息"); + if clear.clicked() { self.clear_steer_queue(); } + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 0.0; + for (title, messages) in [ + ("待插话 · 当前步骤后注入", &self.pi_queued_steering), + ("已排队 · 本轮结束后发送", &self.pi_queued_followup), + ] { + if messages.is_empty() { continue; } + let preview = messages.join(" / ").replace('\n', " "); + ui.add(egui::Label::new(RichText::new(format!("{title} {preview}")).size(12.0).color(tint)).truncate()) + .on_hover_text(format!("{title}\n{}", messages.join("\n"))); + } + }); + }); + } + + + pub(in crate::jiansun) fn composer_escape(&mut self, ui: &mut Ui) { + let input_id = super::composer_input_id(); + let ime_composing = ui.data(|data| data.get_temp::<(bool, u64)>(input_id.with("ime-submit-guard"))) + .is_some_and(|(composing, _)| composing) + || ui.input(|input| input.events.iter().any(|event| matches!(event, egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) if !text.is_empty()))); + let owns_focus = ui.memory(|memory| memory.has_focus(input_id) + || (memory.focused().is_none() && memory.had_focus_last_frame(input_id))); + if !self.model_settings && !self.prompt_library.is_open() + && !ime_composing && ui.memory(|memory| memory.top_modal_layer().is_none()) + && owns_focus + && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + let mut selection = egui::text_edit::TextEditState::load(ui.ctx(), input_id); + let range = selection.as_ref().and_then(|state| state.cursor.char_range()); + if let Some(range) = range.filter(|range| range.primary != range.secondary) { + if let Some(state) = selection.as_mut() { + state.cursor.set_char_range(Some(egui::text::CCursorRange::one(range.primary))); + } + if let Some(state) = selection { state.store(ui.ctx(), input_id); } + } else if self.composer.is_empty() { + self.focus_composer = false; + ui.memory_mut(|memory| memory.surrender_focus(input_id)); + } + if !self.composer.is_empty() { ui.memory_mut(|memory| memory.request_focus(input_id)); } + } + } + + pub(in crate::jiansun) fn composer_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + super::glow_pill::bind(ui, app.gpu_render_state.as_ref()); + let messages_before_send = self.messages.len(); + let mut prompt_anchor = None; + self.composer_reference_sync(app); + if self.notifications_ui(ui) { self.show_center(CenterView::Canvas, app.session.active().is_some()); } + self.composer_escape(ui); + let input_id = super::composer_input_id(); + let t = Tokens::get(ui.ctx()).agent(); + ui.spacing_mut().item_spacing = vec2(6.0, 6.0); + self.panel_geometry["productionProgress"] = Value::Null; + self.panel_geometry["productionProgressRail"] = Value::Null; + self.panel_geometry["productionWorkers"] = Value::Null; + self.panel_geometry["productionShelf"] = Value::Null; + self.panel_geometry["productionWorkersTag"] = Value::Null; + self.panel_geometry["productionProgressTag"] = Value::Null; + self.panel_geometry["productionImageCells"] = Value::Null; + self.panel_geometry["productionCopyCells"] = Value::Null; + self.panel_geometry["productionResume"] = Value::Null; + self.panel_geometry["productionStopPause"] = Value::Null; + self.panel_geometry["productionStopEnd"] = Value::Null; + self.panel_geometry["productionStopDeliver"] = Value::Null; + self.panel_geometry["productionStopStatus"] = Value::Null; + self.panel_geometry["productionBudget"] = Value::Null; + if self.pi_review && self.busy.is_none() { + self.status_row(ui, "info", "原建议未执行", t.warning, |this, ui| { + if super::stitch_ui::action_button(ui, "放弃原建议", super::stitch_ui::ButtonRole::Secondary, true).on_hover_text("保留原响应和已完成的修改;不重新运行模型或工具").clicked() { + this.send("pi-review", json!({"doc":app.session.active().map(|s|s.doc.id.0)})); + } + }); + } + self.panel_geometry["recoverResult"] = Value::Null; + if self.result_needs_check() { + let title = if self.original_image_recoveries().next().is_some() { + if self.original_image_recoveries().all(|(_, id)| { + self.image_recovery_schedules.get(id).is_some_and(|schedule| schedule.exhausted()) + }) { + "原图片暂未取回,已保留请求" + } else { + "图片结果待自动核查" + } + } + else if self.unknown_image { "有一张图片未确认结果" } + else { "有一项操作未确认结果" }; + self.status_row(ui, "info", title, t.warning, |this, ui| { + let action = super::stitch_ui::action_button(ui, "核查结果", super::stitch_ui::ButtonRole::Secondary, this.busy.is_none()) + .on_hover_text("只读取原请求结果,不重新生成"); + this.panel_geometry["recoverResult"] = rect_value(action.rect); + if action.clicked() { this.recover(app); } + }); + } else if !self.pending() && self.ready_image.is_some() { + self.status_row(ui, "image", "图片已就绪", t.text_dim, |this, ui| { + if super::stitch_ui::action_button(ui, "应用到画布", super::stitch_ui::ButtonRole::Primary, this.busy.is_none()).clicked() { + this.use_image(app); + } + }); + } + self.panel_geometry["reconnect"] = Value::Null; + self.error_notice_ui(ui); + self.steering_queue_ui(ui); + self.panel_geometry["send"] = Value::Null; + self.panel_geometry["stop"] = Value::Null; + let shortcut = composer_enter(ui, input_id); + let morph = self.panel_geometry["composerMorph"].as_f64().unwrap_or(1.0) as f32; + let can_stop = self.pending() && !self.batch_progress_visible() && !self.agent_effects_paused; + let compact_stop = can_stop && morph < 0.95; + let surface_height = self.composer_surface_height(app, ui, ui.available_width(), morph); + let (surface_rect, surface_response) = ui.allocate_exact_size(vec2(ui.available_width(), surface_height), Sense::hover()); + let radius = 28.0 - 4.0 * morph; + let material = super::stitch_ui::surface_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Composer); + ui.painter().rect_filled(surface_rect, radius, material.fill); + ui.painter().rect_stroke(surface_rect, radius, material.stroke, egui::StrokeKind::Inside); + let drop_active = self.panel_geometry["composerExpanded"].as_bool().unwrap_or(false); + self.composer_attachment_drop_surface(app, ui, surface_rect, radius, drop_active); + let light = agent_motion::reserve_background(ui); + let send_background = agent_motion::reserve_background(ui); + let mut content = ui.new_child(egui::UiBuilder::new().id_salt("composer-stable-surface") + .max_rect(surface_rect.shrink2(vec2(14.0, 12.0))).layout(Layout::top_down(Align::Min))); + content.set_clip_rect(surface_rect.shrink(2.0).intersect(ui.clip_rect())); + let parent_ui = ui; + let ui = &mut content; + let references = self.composer_reference_list(app); + self.panel_geometry["references"] = json!(references); + let reference_height = reference_shelf_height(references.len(), ui.max_rect().width()); + if reference_height > 0.0 { + let shelf = Rect::from_min_size(ui.max_rect().min, vec2(ui.max_rect().width(), reference_height - 6.0)); + let mut reference_ui = ui.new_child(egui::UiBuilder::new().id_salt("composer-references").max_rect(shelf)); + self.reference_shelf(app, &mut reference_ui, &references, shelf.height()); + } + let header_rect = ui.max_rect().translate(vec2(0.0, reference_height)); + let mut header = ui.new_child(egui::UiBuilder::new().id_salt("composer-header").max_rect(header_rect)); + header.set_opacity(morph * morph); + if morph < 0.95 { header.disable(); } + if morph > 0.001 { + self.composer_attachment_previews(app, &mut header); + } + let header_height = if header.min_rect().height() > 0.0 { header.min_rect().height() + 6.0 } else { 0.0 }; + let stop_space = if compact_stop { 36.0 } else { 0.0 }; + let mini_input = Rect::from_min_size( + egui::pos2(surface_rect.left() + 54.0, surface_rect.top() + reference_height + 17.0), + vec2((surface_rect.width() - 72.0 - stop_space).max(1.0), 24.0), + ); + let full_input = Rect::from_min_max( + egui::pos2(surface_rect.left() + 16.0, surface_rect.top() + 14.0 + reference_height + header_height), + egui::pos2(surface_rect.right() - 16.0, surface_rect.bottom() - 60.0)); + let input_rect = Rect::from_min_max(mini_input.min.lerp(full_input.min, morph), mini_input.max.lerp(full_input.max, morph)); + let typing_owner=Id::unique((&self.origin,self.account["id"].as_str(),self.observed_doc,self.loaded_draft)); + let reduced=self.reduce_motion; + let mut layouter = |ui: &Ui, text: &dyn egui::TextBuffer, wrap_width: f32| { + let mut galley=composer_galley(ui,text.as_str(),wrap_width); + super::typing_text::edit(ui,typing_owner,&mut galley,reduced); + galley + }; + let mut input_ui = ui.new_child(egui::UiBuilder::new().id_salt("composer-input-region").max_rect(input_rect)); + input_ui.set_clip_rect(input_rect.intersect(ui.clip_rect())); + input_ui.spacing_mut().scroll.fade.strength=0.0; + input_ui.visuals_mut().text_cursor.stroke=Stroke::new(1.5,t.text); + let draft_ready = self.composer_draft_ready(app); + if !draft_ready { input_ui.disable(); } + let text_start=ui.ctx().graphics(|graphics|graphics.get(ui.layer_id()).map_or(0,|list|list.next_idx().0)); + let resized=ui.data_mut(|data|{let id=input_id.with("viewport-size");let previous=data.get_temp::(id);data.insert_temp(id,input_rect.size());previous!=Some(input_rect.size())}); + let editor = egui::ScrollArea::vertical().id_salt("agent-input-scroll").animated(false) + .max_height(input_rect.height().max(24.0)).min_scrolled_height(input_rect.height().max(24.0)) + .content_margin(egui::Margin::ZERO).auto_shrink([false, false]) + .show(&mut input_ui, |ui| { + let hint = if !draft_ready { "正在加载项目草稿…" } + else if self.steering_available(app) { "继续补充要求,将在当前步骤后插话…" } + else { "告诉小壹,你想怎么改…" }; + let editor=super::stitch_ui::text_input(&mut self.composer, hint, true) + .layouter(&mut layouter).id(input_id).return_key(egui::KeyboardShortcut::new(egui::Modifiers::SHIFT, egui::Key::Enter)) + .font(FontId::proportional(14.0)).desired_rows(1).desired_width(f32::INFINITY) + .min_size(vec2(0.0, input_rect.height().max(24.0))).margin(egui::Margin::ZERO).frame(Frame::NONE).show(ui); + if resized&&editor.response.response.has_focus()&&let Some(range)=editor.cursor_range { + let caret=editor.galley.pos_from_cursor(range.primary).translate(editor.galley_pos.to_vec2()); + if !ui.clip_rect().contains_rect(caret){ui.scroll_to_rect_animation(caret,None,egui::style::ScrollAnimation::none());} + } + editor + }); + self.panel_geometry["inputScrollOffset"]=json!(editor.state.unclamped_offset().y); + let editor=editor.inner; + self.panel_geometry["inputContentHeight"]=json!(editor.galley.size().y); + if let Some(row)=editor.galley.rows.first(){self.panel_geometry["inputFirstRow"]=rect_value(Rect::from_min_size(editor.galley_pos+vec2(0.0,row.pos.y),vec2(input_rect.width(),row.size.y)));} + if let Some(range) = editor.cursor_range { + self.panel_geometry["inputCaret"] = rect_value(editor.galley.pos_from_cursor(range.primary).translate(editor.galley_pos.to_vec2())); + } + self.panel_geometry["inputHitRect"] = rect_value(editor.response.rect); + let response = editor.response.response.accessible_name("小壹消息输入"); + let text_end = ui.ctx().graphics(|graphics|graphics.get(ui.layer_id()).map_or(text_start, |list| list.next_idx().0)); + // 输入框的逐字柔光画在光涌玻璃上面、文字光标下面(见 `typing_text::paint_glow`)。 + super::typing_text::paint_glow(ui,typing_owner,editor.galley_pos); + let input_focused = response.has_focus(); + self.panel_geometry["input"] = rect_value(input_rect); + if self.focus_composer && draft_ready { response.request_focus(); self.focus_composer = false; } + if response.changed() { + self.canvas_workspace.composer_edited(); self.draft_changed = true; self.touched = Instant::now(); + } + let typing = input_focused && !self.composer.trim().is_empty() && !self.pending(); + let orb_id = Id::unique("composer-identity"); + let orb_progress = super::stitch_ui::morph_value(ui.ctx(), orb_id.with("size"), typing, self.reduce_motion); + let orb_center = egui::pos2(surface_rect.left() + 29.0, surface_rect.center().y + reference_height / 2.0) + .lerp(egui::pos2(surface_rect.left() + 35.0, surface_rect.bottom() - 33.0), morph); + let orb = Rect::from_center_size(orb_center, Vec2::splat(34.0 - 10.0 * morph + 16.0 * orb_progress)); + let typing_animation = typing && super::typing_text::is_animating(ui, typing_owner); + let background_canvas = self.product_view_detached() + || self.owner_doc.is_some_and(|owner| app.session.active().is_none_or(|state| state.doc.id.0 != owner)); + let working = !background_canvas && !self.agent_effects_paused && !self.pi_ui_waiting() + && (self.pending() || self.batch_progress_visible() && !self.has_paused_production()); + let motion = super::siri_orb::Motion::composer(self.reduce_motion, typing_animation, working); + let freeze = self.reduce_motion || background_canvas && !typing_animation; + let animation = super::siri_orb::paint(ui, orb_id, orb, motion, freeze); + self.panel_geometry["composerOrb"] = rect_value(orb); + self.panel_geometry["composerOrbTyping"] = json!(typing); + self.panel_geometry["composerOrbMotion"] = json!(if self.reduce_motion { "reduced" } else { motion.label() }); + self.panel_geometry["composerOrbPhase"] = animation.map_or(Value::Null, |a| json!(a.phase)); + self.panel_geometry["composerOrbSpeed"] = animation.map_or(Value::Null, |a| json!(a.speed)); + let toolbar_rect = Rect::from_min_max(egui::pos2(surface_rect.left() + 14.0, surface_rect.bottom() - 54.0), + egui::pos2(surface_rect.right() - 14.0, surface_rect.bottom() - 12.0)); + let mut toolbar = ui.new_child(egui::UiBuilder::new().id_salt("composer-toolbar").max_rect(toolbar_rect)); + toolbar.set_opacity(((morph - 0.3) / 0.7).clamp(0.0, 1.0)); + if morph < 0.95 { toolbar.disable(); } + let can = self.can_send_with(app, false); + let connect = (self.needs_library_login() || self.library_blocked()) + && draft_ready && self.busy.is_none() && !self.composer.trim().is_empty(); + let mut send_clicked = false; + if morph > 0.3 { + let ui = &mut toolbar; + // One responsive toolbar. Narrow docks retain every action with + // an accessible icon; only labels collapse, never controls. + ui.horizontal(|ui| { + let narrow = ui.available_width() < 260.0; + let ultra = ui.available_width() < if can_stop { 175.0 } else { 145.0 }; + let action_size = if narrow { 24.0 } else { 28.0 }; + ui.spacing_mut().item_spacing.x = if narrow { 1.0 } else { 3.0 }; + ui.spacing_mut().button_padding.x = 4.0; + let right_width = 30.0 + + if can_stop { 30.0 + ui.spacing().item_spacing.x } else { 0.0 } + + if ultra { 0.0 } else { action_size + ui.spacing().item_spacing.x }; + let left_width = (ui.available_width() - right_width - ui.spacing().item_spacing.x).max(1.0); + let mut compact_settings_anchor = None; + ui.allocate_ui_with_layout(vec2(left_width, 42.0), Layout::left_to_right(Align::Center), |ui| { + ui.allocate_exact_size(vec2(if ultra { 34.0 } else { 42.0 }, 42.0), Sense::hover()); + let add = super::stitch_ui::icon_button(ui, "plus", action_size, false, "添加"); + add.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "添加")); + self.panel_geometry["composerMore"] = rect_value(add.rect); + self.panel_geometry["referenceImage"] = Value::Null; + self.panel_geometry["promptLibrary"] = Value::Null; + prompt_anchor = Some(add.rect); + if ultra { compact_settings_anchor = Some(add.clone()); } + egui::Popup::menu(&add).id(Id::unique("jiansun-composer-more-popup")).style(super::stitch_ui::scoped_popup_style(ui)) + .frame(super::stitch_ui::command_menu_frame(ui.ctx())).show(|ui| { + ui.set_width(180.0); + let selected = self.canvas_subject(app)["kind"] != "project" && self.composer_draft_ready(app); + let reference = super::stitch_ui::command_menu_item(ui, "layers", "引用选中画布对象", selected); + self.panel_geometry["referenceAdd"] = rect_value(reference.rect); + if reference.clicked() { + match self.composer_reference_add(app) { Ok(()) => self.focus_composer = true, Err(error) => self.error = error } + ui.close(); + } + self.composer_attachment_menu_item(app, ui); + if super::stitch_ui::command_menu_item(ui, "folder-open", "常用提示词", true).clicked() { + self.close_model_settings(); + self.prompt_library.toggle(&self.account, &self.origin, &self.tx); ui.close(); + } + if ultra { + if super::stitch_ui::command_menu_item(ui, "sparkles", "生图", self.can_send_with(app, true)).clicked() { self.send_image_once(app); ui.close(); } + if super::stitch_ui::command_menu_item(ui, "sliders-horizontal", "连接设置、通知与警告", true).clicked() { + self.open_model_settings(); + ui.close(); + } + } + }); + if !ultra { + let image_action = super::stitch_ui::icon_action_button(ui, "sparkles", "生图", true, action_size, self.can_send_with(app, true)) + .on_hover_text("使用生图模型提交当前要求;普通发送仍是对话"); + self.panel_geometry["imageGenerate"] = rect_value(image_action.rect); + if image_action.clicked() { self.send_image_once(app); } + if left_width >= 120.0 { + let usage = context_for_model(&self.pi_context_usage, &self.models, &self.model); + if usage.as_ref().is_some_and(|value|value["contextWindow"].as_u64().is_some_and(|limit|limit>0)) { + let meter = context_meter(ui, usage.as_ref(), self.reduce_motion, true); + self.panel_geometry["contextIndicator"] = rect_value(meter.rect); + self.panel_geometry["contextPercent"] = context_fraction(usage.as_ref()).map_or(Value::Null,|fraction|json!(fraction*100.0)); + } + } + } + }); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let response = ui + .add_enabled_ui(can || connect, |ui| super::stitch_ui::send_action_button(ui, Id::unique("composer-send"), self.reduce_motion)) + .inner + .on_hover_text(if connect { "连接素材库后发送" } + else if self.can_steer(app) { "Enter 插话 · Shift+Enter 换行" } + else { "Enter 发送 · Shift+Enter 换行" }) + .on_disabled_hover_text(if self.unknown { "先核查原请求结果" } + else if !self.composer_text_send_allowed_for(app) { "当前对话模型暂不支持图片,请先移除附件或使用生图" } + else { "打开项目、连接模型并输入要求后发送" }); + self.panel_geometry["send"] = rect_value(response.rect); + send_clicked = response.clicked(); + if compact_stop { + ui.allocate_exact_size(vec2(30.0,30.0), Sense::hover()); + } else if can_stop { + let stop = super::stitch_ui::icon_button(ui, "square", 30.0, false, "停止小壹,保留原请求"); + self.panel_geometry["stop"] = rect_value(stop.rect); + if stop.clicked() { self.abort_chat_run(); } + } + if !ultra { + let response = super::stitch_ui::icon_button(ui, "sliders-horizontal", action_size, self.model_settings, "连接设置、通知与警告"); + let unread=notification_id(&self.origin,&self.account,&self.project_context,self.owner_doc) + .and_then(|id|ui.data(|data|data.get_temp::(id))).is_some_and(|history|history.unread>0); + if unread { + let dot=Rect::from_center_size(response.rect.right_top()+vec2(-3.0,3.0),vec2(8.0,8.0)); + super::stitch_ui::paint_badge(ui,response.id.with("unread"),dot,super::stitch_ui::BadgeKind::Unread,"",self.reduce_motion); + } + self.panel_geometry["settings"] = rect_value(response.rect); + if response.clicked() { + if self.model_settings { + self.close_model_settings(); + } else { + self.open_model_settings(); + } + } + self.model_settings_popup(ui, &response); + } + }); + if let Some(anchor) = compact_settings_anchor { self.model_settings_popup(ui, &anchor); } + }); + } + if send_clicked || (shortcut && (can || connect)) { + if connect { self.open_library_login(); } + else { self.send_discussion(app); } + } + // 设置浮层里点的"检查更新"在这里派发:浮层本身拿不到 app。 + self.flush_client_update_request(app); + let compact_stop_rect = Id::unique("jiansun-composer-compact-stop-rect"); + if compact_stop { + let compact_center = egui::pos2(surface_rect.right() - 27.0, mini_input.center().y); + let expanded_center = egui::pos2(toolbar_rect.right() - 48.0, toolbar_rect.center().y); + let rect = Rect::from_center_size(compact_center.lerp(expanded_center,morph),vec2(30.0,30.0)); + let mut control = ui.new_child(egui::UiBuilder::new().id_salt("composer-compact-stop").max_rect(rect)); + let stop = super::stitch_ui::icon_button(&mut control, "square", 30.0, false, "停止小壹,保留原请求"); + self.panel_geometry["stop"] = rect_value(stop.rect); + ui.data_mut(|data| data.insert_temp(compact_stop_rect, stop.rect)); + if stop.clicked() { self.abort_chat_run(); } + } else { + ui.data_mut(|data| data.remove::(compact_stop_rect)); + } + let ui = parent_ui; + let frame = egui::InnerResponse { inner: light, response: surface_response }; + self.panel_geometry["composer"] = rect_value(frame.response.rect); + ui.ctx().data_mut(|data| data.insert_temp(Id::unique("jiansun-composer-previous-rect"), frame.response.rect)); + self.panel_geometry["composerFocused"] = json!(input_focused); + // Only a submission accepted by the native path can launch the pulse. + // Loading history, repainting bubbles and failed preflight never do. + let sent = matches!(self.busy.as_deref(), Some("agent" | "pi-agent" | "image" | "slot-append" | "slot-generate")) + && self.messages.get(messages_before_send..).is_some_and(|messages| + messages.iter().any(|message| message["role"] == "user")); + if sent { + self.reveal_sent_user_text(ui,messages_before_send); + self.flush_document_draft(ui.ctx(), self.observed_doc, false); + } + super::stitch_ui::sent_glow(ui, Id::unique("composer-sent-glow"), super::stitch_ui::SendSurface {rect:frame.response.rect,radius,background:Some(send_background),text_range:Some(text_start..text_end),flanks:morph}, sent, self.reduce_motion); + + if self.prompt_library.show(ui, &self.account, &self.origin, &mut self.composer, &self.tx, + prompt_library_ui::PromptPanelPlacement { can_insert:draft_ready, reduced:self.reduce_motion, anchor:prompt_anchor, composer:frame.response.rect }) { + self.canvas_workspace.composer_edited(); + self.draft_changed = true; + self.touched = Instant::now(); + if let Some(id) = toast_id(&self.origin, &self.account, &self.project_context, self.owner_doc) { post_draft_toast(ui, id); } + } + if let Some(id) = toast_id(&self.origin, &self.account, &self.project_context, self.owner_doc) { + draw_draft_toast(ui, id, frame.response.rect, self.reduce_motion); + } + self.panel_geometry["composerLightMode"] = json!(super::stitch_ui::composer_glow_mode(ui,self.reduce_motion)); + if !self.needs_library_login() && !self.library_blocked() && !self.key_saved && super::stitch_ui::action_button(ui, "连接个人模型", super::stitch_ui::ButtonRole::Quiet, true).clicked() { + self.open_model_settings(); + self.key_settings = true; + ui.ctx().request_repaint(); + } + } + + pub(in crate::jiansun) fn error_notice_ui(&mut self,ui:&mut Ui) { + self.panel_geometry["errorNotice"]=Value::Null; + if self.error.is_empty() || self.error==self.library_message {return;} + if self.result_needs_check() && (self.error.contains("素材库请求失败(HTTP 503)") + || self.error.contains("结果未知;不会重发") || self.error.contains("原请求结果待核查")) { return; } + let error=self.error.clone(); + let details=super::operation_error::inline(ui,&error); + self.panel_geometry["errorNotice"]=json!({"title":super::operation_error::public_title(&error),"details":rect_value(details.rect)}); + if details.clicked() + && let Some(id)=notification_id(&self.origin,&self.account,&self.project_context,self.owner_doc) { + ui.ctx().data_mut(|data| { + let history=data.get_temp_mut_or_default::(id); + history.add(&error);history.open=true; + }); + } + } + + pub(in crate::jiansun) fn status_row(&mut self, ui: &mut Ui, name: &str, text: &str, tint: Color32, action: impl FnOnce(&mut Self, &mut Ui)) { + let frame=super::stitch_ui::surface_frame(ui.ctx(),super::stitch_ui::SurfaceRole::Task).stroke(Stroke::NONE).inner_margin(8); + super::stitch_ui::material_frame(ui,frame, |ui| { + ui.horizontal(|ui| { + icon(ui, name, tint); + ui.label(RichText::new(text).size(12.0).color(tint)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| action(self, ui)); + }); + }); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/image_registration.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/image_registration.rs new file mode 100644 index 00000000..a4ffaaa7 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/image_registration.rs @@ -0,0 +1,67 @@ +use super::super::{PhotocraftApp, Request, Value, Workspace, json}; +use super::artifact_preview_ui::{candidate_matches_message, image_location}; +use super::turns::turns; + +impl Workspace { + pub(in crate::jiansun) fn trace_canvas_candidate(&mut self, app: &PhotocraftApp, target: Value) { + self.pending_candidate_trace = None; + let Some((doc, revision)) = app.session.active().map(|state| (state.doc.id.0, state.revision)) else { return }; + let matching: Vec<_> = turns(&self.messages).into_iter().filter(|turn| + turn.images().any(|image| candidate_matches_message(&target, image))) + .map(|turn| turn.user_index).collect(); + if matching.len() != 1 { return; } + self.pending_candidate_trace = Some(json!({ + "scope":[self.origin,self.account["id"],self.project_context["localId"],doc,self.loaded_draft,revision], + "turn":matching.first().copied().flatten(),"target":target + })); + } + + pub(in crate::jiansun) fn track_worker_image(&mut self, value: &Value) { + let Some(op) = self.workflow.worker_image_progress(value) else { return; }; + let Some(task) = op["candidateId"].as_str().filter(|_| op["imageFrame"].is_object()) else { return; }; + if let Some(message) = self.messages.iter_mut().rev().find(|message| message["taskId"] == task + && matches!(message["kind"].as_str(), Some("image-job" | "image"))) + { + if message["kind"] == "image-job" { + message["step"] = op["imageStep"].clone(); + } + return; + } + self.messages.push(json!({ + "role":"assistant", "kind":"image-job", "taskId":task, "run":op["run"], "workerNumber":op["workerNumber"], + "width":op["imageFrame"]["width"], "height":op["imageFrame"]["height"], + "slotLabel":op["slotLabel"], "step":op["imageStep"], + "target":{"slotId":op["slotId"],"outputId":op["outputId"],"productVariantId":op["productVariantId"],"candidateId":task} + })); + self.draft_changed = true; + } + + pub(in crate::jiansun) fn register_image(&mut self, task: Value) { + let Some(id) = task["taskId"].as_str() else { + return; + }; + if !self.messages.iter().any(|m| m["kind"] == "image" && m["taskId"] == id) { + let mut message = json!({"role":"assistant","kind":"image","taskId":id,"target":image_location(&task, id)}); + for key in ["slotId", "outputId"] { + if task[key].is_string() { + message[key] = task[key].clone(); + } + } + if task["variantId"].is_string() { + message["productVariantId"] = task["variantId"].clone(); + } + if let Some(job) = self.messages.iter_mut().rev().find(|item| item["kind"] == "image-job" && item["taskId"] == id) { + for key in ["width", "height", "workerNumber", "slotLabel"] { + message[key] = job[key].clone(); + } + *job = message; + } else { + self.messages.push(message); + } + self.draft_changed = true; + } + if self.requested_previews.insert(id.to_owned()) { + let _ = self.tx.send(Request::Action("agent-image-preview".into(), json!({"doc":task["doc"],"taskId":id}))); + } + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/image_result_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/image_result_ui.rs new file mode 100644 index 00000000..c120a0dd --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/image_result_ui.rs @@ -0,0 +1,211 @@ +use super::super::stitch_timeline as timeline; +use super::artifact_preview_ui::image_location; +use super::turn_ui::paint_image_caption; +use egui::{FontId, Layout, Rect}; +use super::super::{Tokens, Ui, Value, Workspace, agent_motion}; +use super::artifact_preview_ui::{image_preview_button, image_reference_target}; +use super::turn_ui::{frame_image_ratio, image_card_size, image_result_labels}; +use egui::{Align2, Color32, Id, Response, Sense, Stroke, vec2}; + +impl Workspace { + pub(in crate::jiansun) fn timeline_images(&self, ui: &mut Ui, id: Id, images: &[&Value], flow: &mut super::agent_stream::Flow, doc: Option<&super::Document>) -> Option { + let heading = if images.iter().any(|image| image["kind"] == "template-image") { "图片来源" } else { "生成图片" }; + let count = images.len().to_string(); + ui.add_space(2.0); + let (row, results) = timeline::image_set(ui, id, timeline::ImageSet::conversation(heading, Some(&count), images.len()), + self.reduce_motion, |ui, index, width| self.image_result(ui, images[index], width, doc)); + flow.connect(ui, row.rect); + flow.break_run(); + results.into_iter().flatten().last() + } + + pub(in crate::jiansun) fn image_result(&self, ui: &mut Ui, value: &Value, cell_width: f32, doc: Option<&super::Document>) -> Option { + let t = Tokens::get(ui.ctx()).agent(); + let id = value["taskId"].as_str().or_else(|| value["id"].as_str()).filter(|id| !id.is_empty())?; + let now = ui.input(|input| input.time); + let enter = self.canvas_workspace.preview_arrival(id).map_or(1.0, |started| agent_motion::image_enter(now - started, 1.0, self.reduce_motion).0); + let mut locate = None; + let target = image_location(value, id); + let original = value["kind"] == "template-image" || value["original"] == true; + let (page_label, short_label, label) = if original { + let field = self.template_workflow["outputs"].as_array().into_iter().flatten() + .filter(|output| value["outputId"].is_null() || output["outputId"] == value["outputId"]) + .flat_map(|output| output["fields"].as_array().into_iter().flatten()) + .find(|field| field["kind"] == "image" && field["fieldId"] == value["fieldId"]) + .and_then(|field| field["label"].as_str()) + .or_else(|| value["fieldId"].as_str()).unwrap_or(""); + let label = if field.is_empty() { "模板原图".into() } else { format!("{field} · 模板原图") }; + (String::new(), "模板原图".into(), label) + } else if value["slotId"].is_null() && value["candidateId"].is_null() + && let Some(label) = value["label"].as_str().filter(|label| !label.is_empty()) + { + (String::new(), label.to_owned(), label.to_owned()) + } else { + image_result_labels(&target, &self.template_workflow, &self.creation_brief) + }; + let ratio_id = ui.scope_id().with(("result-image-ratio", id)); + let ratio = ui.data_mut(|data| { + if let Some(texture) = self.agent_images.peek(id) { + let size = texture.size_vec2(); + data.insert_temp(ratio_id, size.x / size.y.max(1.0)); + } + data.get_temp::(ratio_id).or_else(|| frame_image_ratio(value)).unwrap_or(1.0) + }); + let size = image_card_size(cell_width, ratio); + if value["kind"] == "image-job" { + let active = !self.agent_effects_paused && value["finished"].is_null() + && (value["projected"] == true || self.pi_run.as_deref().is_some_and(|run| value["run"] == run)); + let text = value["slotLabel"].as_str().unwrap_or("").to_owned(); + if !active { + // A queued slot keeps its cell and its place in order; it grows + // into the image card only once its own generation starts. + super::agent_stream::queued_job(ui, cell_width, &text, value["finished"].as_str().unwrap_or("等待结果")); + return None; + } + let step = value["step"].as_str().unwrap_or("正在生成图片…"); + let (rect, response) = ui.allocate_ui_with_layout( + vec2(cell_width, size.y), Layout::centered_and_justified(egui::Direction::TopDown), + |ui| ui.allocate_exact_size(size, Sense::empty()), + ).inner; + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{text} · {step}"))); + if ui.is_rect_visible(rect) { + let id = ui.scope_id().with(("timeline-image-job", id)); + let painter = ui.painter_at(rect); + painter.rect_filled(rect, t.radius_sm, t.canvas); + painter.rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); + let background = ui.painter().add(egui::Shape::Noop); + super::glow_pill::background(ui, id, rect, t.radius_sm, 0.56, background); + painter.text(rect.center(), Align2::CENTER_CENTER, step, FontId::proportional(super::agent_stream::TEXT_TITLE), t.text); + paint_image_caption(&painter, rect, &text); + } + return None; + } + let slot = self.template_workflow["slots"].as_array().into_iter().flatten().find(|slot| + target["slotId"].is_string() && slot["id"] == target["slotId"] && slot["outputId"] == target["outputId"] + && slot["variantId"] == target["productVariantId"]); + let candidate = slot.and_then(|slot| slot["candidates"].as_array()?.iter() + .find(|candidate| candidate["id"] == target["candidateId"])); + let live = doc.zip(target["slotId"].as_str().zip(target["productVariantId"].as_str())) + .filter(|(doc, _)| target["documentId"].as_u64().is_none_or(|id| doc.id.0 == id) + && self.canvas_workspace.output == target["outputId"] && self.canvas_workspace.variant == target["productVariantId"]); + let adopted = live.and_then(|(doc, (slot, variant))| super::canvas_workspace::adopted(doc, slot, variant)); + let manual = live.is_some_and(|(doc, (slot, variant))| super::canvas_workspace::manual_image(doc, slot, variant).is_some()); + let is_adopted = adopted.is_some() && adopted == target["candidateId"].as_str(); + let show_adopt = live.is_some() && !is_adopted && candidate.is_some_and(|candidate| candidate["status"] == "complete") + && self.can_start_turn() && self.saving.is_none(); + ui.push_id(id, |ui| ui.vertical(|ui| { + ui.set_width(cell_width); + ui.allocate_ui_with_layout(vec2(cell_width, size.y), Layout::centered_and_justified(egui::Direction::TopDown), |ui| { + if let Some(texture) = self.agent_images.peek(id) { + let (rect, response) = ui.allocate_exact_size(size, Sense::click()); + // Blur and fade in place: geometry, the rounded mask, the hit + // target and selection outline all remain at the final crop. + // The parent UI clip still bounds the image when scrolling. + if ui.is_rect_visible(rect) { + self.agent_images.mark_visible_existing(id); + let _ = self.agent_images.get(id); + if enter < 1.0 { + ui.painter().add(agent_motion::rounded_image_entry_blur(texture.id(), rect, enter, t.radius_sm)); + } else { + egui::Image::new(texture).fit_to_exact_size(rect.size()).corner_radius(t.radius_sm).paint_at(ui, rect); + } + } + agent_motion::message_repaint(ui, rect, enter); + let selected = !original && self.canvas_workspace.context.as_ref().is_some_and(|current| current["candidateId"] == target["candidateId"]); + if selected { + agent_motion::role_light(ui, agent_motion::Surface::new(response.id.with("selection-light"), rect.expand(1.0), t.radius_sm), self.reduce_motion, agent_motion::LightRole::CanvasTarget); + } else if response.hovered() { + ui.painter().rect_stroke(rect.expand(1.0), t.radius_sm, Stroke::new(1.0, t.text_dim), egui::StrokeKind::Outside); + } + let slot_label = slot.and_then(|slot| slot["label"].as_str()).or_else(|| value["slotLabel"].as_str()).unwrap_or(""); + let caption = [slot_label, page_label.as_str(), short_label.as_str()].into_iter() + .filter(|part| !part.is_empty()).collect::>().join(" · "); + paint_image_caption(&ui.painter_at(rect), rect, &caption); + let review = &self.workflow.production_progress()["candidateReviews"][id]; + let decision = candidate.and_then(|candidate| candidate["reviewDecision"].as_str()) + .or_else(|| value["reviewDecision"].as_str()).or_else(|| review["status"].as_str()); + let badge = if is_adopted { Some(("已采纳", t.agent_semantic().success)) } + else if manual { Some(("图位已手动编辑", t.text_faint)) } + else { match decision { + Some("passed" | "pass") => Some(("验图通过", t.agent_semantic().success)), + Some("not_selected") => Some(("未选用", t.text_faint)), + Some("rejected" | "revise" | "missing") => Some(("已退回", t.danger)), + Some("pending") => Some(("待核查", t.warning)), + _ if !original && target["slotId"].is_string() => Some(("待采纳", t.warning)), + _ => None, + }}; + if let Some((status, color)) = badge && rect.width() >= 112.0 && rect.height() >= 52.0 { + let painter = ui.painter_at(rect); + let font = crate::theme::agent_scale::Type::Meta.font_id(); + let text = painter.layout_no_wrap(status.to_owned(), font, Color32::WHITE); + let tag = Rect::from_min_size(rect.left_top() + vec2(8.0, 8.0), vec2(text.size().x + 21.0, 22.0)); + painter.rect_filled(tag, 6.0, Color32::from_black_alpha(188)); + painter.circle_filled(egui::pos2(tag.left() + 8.0, tag.center().y), 3.0, color); + painter.galley(egui::pos2(tag.left() + 15.0, tag.center().y - text.size().y * 0.5), text, Color32::WHITE); + } + let expand = (rect.width() >= 42.0 && rect.height() >= 42.0).then(|| image_preview_button(ui, rect, id)); + let response = response.on_hover_text(format!("{label} · 右键引用到小壹或查看大图")); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("定位 {label}"))); + if response.clicked() && !expand.is_some_and(|button| button.clicked()) { + if original { + ui.data_mut(|data| data.insert_temp(Id::unique("jiansun-image-expanded"), id.to_owned())); + } else { + locate = Some(image_location(value, id)); + } + } + self.image_reference_menu(ui, &response, value, id, &label, original, show_adopt); + } else { + let placeholder = if original { "模板原图加载中" } else { "定位图片" }; + let (rect, response) = ui.allocate_exact_size(size, Sense::click()); + let response = response.on_hover_cursor(egui::CursorIcon::PointingHand) + .on_hover_text(format!("{label} · 右键引用到小壹或查看大图")); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, placeholder)); + if ui.is_rect_visible(rect) { + ui.painter().rect_filled(rect, t.radius_sm, if response.hovered() { t.hover } else { t.field }); + let icon_size = rect.width().min(rect.height()).min(16.0); + crate::icons::paint(ui, Rect::from_center_size(rect.center(), vec2(icon_size, icon_size)), "image", icon_size, t.text_dim); + if response.has_focus() { + ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.text_dim), egui::StrokeKind::Inside); + } + } + if ui.is_rect_visible(response.rect) && matches!(value["status"].as_str(), None | Some("complete")) { + self.agent_images.mark_visible(id); + } + self.image_reference_menu(ui, &response, value, id, &label, original, show_adopt); + if response.clicked() && !original { + locate = Some(image_location(value, id)); + } + } + }); + })); + locate + } + + pub(in crate::jiansun) fn image_reference_menu(&self, ui: &mut Ui, response: &Response, value: &Value, id: &str, label: &str, original: bool, show_adopt: bool) { + egui::Popup::context_menu(response).frame(super::stitch_ui::menu_frame(ui.ctx())).show(|ui| { + super::stitch_ui::scope_with_motion(ui, self.reduce_motion, |ui| { + // menu_item fills its available width; constrain the + // popup rather than letting it inherit the whole canvas. + let width = 176.0_f32.min((ui.ctx().content_rect().width() - 32.0).max(1.0)); + ui.set_min_width(width); + ui.set_max_width(width); + ui.spacing_mut().item_spacing.y = 2.0; + if show_adopt && super::stitch_ui::menu_item(ui, "采纳", true).clicked() { + ui.data_mut(|data| data.insert_temp(Id::unique("xiaoyi-adopt-candidate"), image_location(value, id))); + ui.close(); + } + if super::stitch_ui::menu_item(ui, "引用到小壹", true).clicked() { + let target = image_reference_target(value, id, label, original); + ui.data_mut(|data| data.insert_temp(Id::unique("xiaoyi-image-reference"), target)); + ui.close(); + } + let preview = super::stitch_ui::menu_item(ui, "查看大图", true); + if preview.clicked() { + ui.data_mut(|d| d.insert_temp(Id::unique("jiansun-image-expanded"), id.to_owned())); + ui.close(); + } + }); + }); + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/model_picker_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/model_picker_ui.rs new file mode 100644 index 00000000..77ca6a73 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/model_picker_ui.rs @@ -0,0 +1,555 @@ +use super::super::{Request, RichText, Value}; +use super::models::{CONTEXT_PENDING, CONTEXT_UNAVAILABLE, context_fraction, context_label}; +use super::notifications::{AgentNotifications, notification_id}; +use super::super::agent_panel::storage_settings_ui; +use egui::{FontId, Frame, Rect, Sense, Vec2}; +use super::super::{PhotocraftApp, Tokens, Ui, Workspace, json}; +use super::rect_value; +use super::models::{ModelRole, is_hidden_model, model_display_name}; +use super::turn_ui::icon; +use egui::{Align, Color32, Id, Layout, Response, vec2}; + +pub(in crate::jiansun) fn context_meter(ui:&mut Ui,usage:Option<&Value>,reduced:bool,compact:bool)->Response{ + let t=Tokens::get(ui.ctx()).agent();let fraction=context_fraction(usage);let label=context_label(usage); + // The ring itself stays a dash; what it explains to a person is that the + // number is not known yet, which a bare dash cannot say. + let accessible=if label==CONTEXT_UNAVAILABLE {CONTEXT_PENDING.to_owned()}else{label.clone()}; + let response=ui.horizontal(|ui|{ + let response=super::stitch_ui::context_capacity(ui,fraction,&accessible).interact(Sense::click()); + if !compact {ui.label(RichText::new(&label).size(12.0).color(t.text));}response + }).inner; + response.widget_info(||egui::WidgetInfo::labeled(egui::Role::Button,true,accessible.as_str())); + super::stitch_ui::select_popup(ui,&response,260.0,reduced,|ui|{ + ui.label(RichText::new("当前上下文").strong().color(t.text)); + if let Some(fraction)=fraction { + super::stitch_ui::progress(ui,response.id.with("capacity"),&accessible,Some(fraction),reduced); + } else {ui.label(RichText::new(&accessible).size(12.0).color(t.text_dim));} + });response +} + + +impl Workspace { + pub(in crate::jiansun) fn model_picker(&mut self, ui: &mut Ui, role: ModelRole, width: f32, compact: bool) -> Response { + let t = Tokens::get(ui.ctx()).agent(); + let current = match role {ModelRole::Chat=>&self.model,ModelRole::Copy=>&self.copy_model,ModelRole::Image=>&self.image_model}; + let models = match role {ModelRole::Chat=>&self.models,ModelRole::Copy=>&self.copy_models,ModelRole::Image=>&self.image_models}; + let label = models.iter().find(|m| m["key"] == *current).and_then(|m| m["id"].as_str()).map(model_display_name).unwrap_or_else(|| "选择模型".to_owned()); + let display = label.clone(); + let mut selected = current.clone(); + let enabled = self.busy.is_none() && !self.account.is_null(); + let old_selection = selected.clone(); + let mut show_all_models = self.show_all_models; + let mut menu_rect = None; + // A native ComboBox owns its popup lifetime and keyboard semantics. + // Bind that popup to the current workspace identity and close the old + // one before switching scope or disabling selection. + let model_scope = json!([self.origin, self.account["id"], self.project_context["localId"], self.owner_doc]).to_string(); + let response = ui + .add_enabled_ui(enabled, |ui| { + super::stitch_ui::scope_with_motion(ui, self.reduce_motion, |ui| { + let response = ui.push_id(("agent-model", role, compact, &model_scope), |ui| { + super::stitch_ui::select_trigger(ui, &display, width, enabled) + }).inner; + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, enabled, &display)); + let popup_id = response.id.with("popup"); + let last_id = Id::unique(("agent-model-last-popup", role, compact)); + if let Some(previous) = ui.data(|d| d.get_temp::(last_id)) + && (previous != popup_id || !enabled) { + egui::Popup::close_id(ui.ctx(), previous); + } + if !enabled { egui::Popup::close_id(ui.ctx(), popup_id); } + ui.data_mut(|d| d.insert_temp(last_id, popup_id)); + let show_toggle = models.iter().any(|model| is_hidden_model(role, model)); + let showing_all = show_all_models; + let visible = models.iter().filter(|model| { + showing_all || model["key"] == old_selection || !is_hidden_model(role, model) + }); + let longest = visible.clone().filter_map(|model| model["id"].as_str()).map(|name| { + ui.painter().layout_no_wrap(model_display_name(name), FontId::proportional(13.0), t.text).size().x + 76.0 + }).fold(width, f32::max); + let limit = (ui.ctx().content_rect().width() * 0.52).clamp(240.0, 560.0).min((ui.ctx().content_rect().width() - 32.0).max(160.0)); + let popup_width = longest.min(limit).max(width.min(limit)); + let shown = super::stitch_ui::select_popup_with_behavior(ui, &response, popup_width, self.reduce_motion, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| { + ui.set_width((popup_width - 16.0).max(128.0)); + ui.set_max_width((popup_width - 16.0).max(128.0)); + ui.spacing_mut().item_spacing.y = 2.0; + ui.label(RichText::new(match role {ModelRole::Chat=>"对话模型",ModelRole::Copy=>"文案模型",ModelRole::Image=>"生图模型"}).size(12.0).strong().color(t.text_dim)); + ui.add_space(4.0); + egui::ScrollArea::vertical().id_salt(("agent-model-list", role, compact)).max_height(280.0).show(ui, |ui| { + let mut option = |ui: &mut Ui, key: &str, name: &str, allowed: bool| { + let is_selected = selected == key; + let label = if allowed { name.to_owned() } else { format!("{name} · Key未开放") }; + let item = super::stitch_ui::select_option(ui, &label, is_selected, allowed); + if item.clicked() { selected = key.to_owned(); ui.close(); } + }; + option(ui, "", "未选择", true); + for model in visible { + if let (Some(key), Some(id)) = (model["key"].as_str(), model["id"].as_str()) { + let name = model_display_name(id); + let label = match (role, model["productionReady"].as_bool(), model["imageInputStatus"].as_str()) { + (ModelRole::Chat, Some(true), _) if model["productionVerified"] != true => format!("{name} · 制作待实测"), + (ModelRole::Chat, Some(true), _) => format!("{name} · 可制作"), + (ModelRole::Chat, _, Some("disabled")) => format!("{name} · 仅文本"), + (ModelRole::Chat, Some(false), _) => format!("{name} · 制作待核验"), + _ => name, + }; + option(ui, key, &label, self.available(id)); + } + } + }); + if show_toggle { + super::stitch_ui::divider(ui); + super::stitch_ui::switch(ui, ui.scope_id().with("show-all-models"), &mut show_all_models, + "显示历史/全部模型", enabled, self.reduce_motion); + } + }); + if let Some(shown) = shown { + let rect = ui.ctx().layer_transform_to_global(shown.response.layer_id).map_or(shown.response.rect, |transform| transform * shown.response.rect); + menu_rect = Some(rect); + } + response + }) + .inner + }) + .inner; + self.show_all_models = show_all_models; + if let Some(rect) = menu_rect { + self.panel_geometry[role.menu()] = rect_value(rect); + } + if compact { + let rect = ui.ctx().layer_transform_to_global(response.layer_id).map_or(response.rect, |transform| transform * response.rect); + self.panel_geometry["model"] = rect_value(rect); + self.panel_geometry[role.geometry()] = rect_value(rect); + } + if selected != old_selection { + self.choose_model(role, selected); + } + response + } + + + pub(in crate::jiansun) fn onboarding_model_options(&mut self, ui: &mut Ui) { + use crate::theme::agent_scale::Type; + let roles = [(ModelRole::Chat, "对话模型", !self.models.is_empty()), + (ModelRole::Copy, "文案模型", !self.copy_models.is_empty()), + (ModelRole::Image, "生图模型", !self.image_models.is_empty())]; + let available = roles.into_iter().filter(|(_, _, available)| *available); + let count = available.clone().count(); + if count == 0 { + ui.horizontal_wrapped(|ui| { + super::stitch_ui::status_label(ui, "模型目录未加载", super::stitch_ui::StatusTone::Warning); + if super::stitch_ui::action_button(ui, "重试", super::stitch_ui::ButtonRole::Quiet, self.busy.is_none()).clicked() { + self.send("restore", json!({})); + } + }); + return; + } + ui.label(RichText::new("至少选择一个模型").font(Type::Meta.font_id()).color(Tokens::get(ui.ctx()).agent().text_dim)); + ui.horizontal_top(|ui| { + let width = (ui.available_width() - (count - 1) as f32 * ui.spacing().item_spacing.x) / count as f32; + for (role, label, _) in available { + ui.vertical(|ui| { + ui.set_width(width); + ui.label(label); + self.model_picker(ui, role, width, true); + }); + } + }); + } + + pub(in crate::jiansun) fn model_key_editor(&mut self, ui: &mut Ui, scope: &str, open: bool, focus: bool) { + let enabled = open && self.busy.is_none() && !self.account.is_null(); + ui.add_enabled_ui(enabled, |ui| { + let key_id = ui.make_persistent_id((scope, "personal-key", &self.origin, self.account["id"].as_str().unwrap_or_default())); + let input = super::stitch_ui::halo_field(ui, key_id.with("field"), None, self.reduce_motion, |ui| ui.add( + super::stitch_ui::text_input( + &mut self.api_key, + if self.key_saved { "输入新的个人 Key" } else { "输入个人 Key" }, + false, + ) + .id(key_id).password(true).desired_width(f32::INFINITY).frame(Frame::NONE), + ).accessible_name("模型 API Key")); + if focus && enabled { input.request_focus(); } + input.on_hover_text("只保存在本机系统凭据库"); + if super::stitch_ui::action_button(ui, "保存连接", super::stitch_ui::ButtonRole::Primary, + !self.api_key.trim().is_empty() && (!self.model.is_empty() || !self.copy_model.is_empty() || !self.image_model.is_empty())) + .clicked() + { + self.model_ready = false; + self.image_ready = false; + self.copy_ready = false; + self.send("configure", json!({"key":self.api_key,"model":self.model,"copyModel":self.copy_model,"imageModel":self.image_model})); + } + }); + } + + + pub(in crate::jiansun) fn thinking_picker(&mut self, ui: &mut Ui) { + let Some(model) = self.models.iter().find(|model| model["key"] == self.model && model["reasoning"] == true) else { + return; + }; + let label = |level: &str| match level { + "off" => "关闭", + "minimal" => "最少", + "low" => "低", + "medium" => "中", + "high" => "高", + "xhigh" => "很高", + "max" => "最高", + _ => "自动", + }; + let current = self.thinking_by_model.get(self.model.as_str()).and_then(Value::as_str).unwrap_or(""); + let mut selected = current; + let levels = model["reasoningEfforts"].as_array().into_iter().flatten().filter_map(Value::as_str); + let width = ui.available_width(); + let tokens = Tokens::get(ui.ctx()).agent(); + ui.push_id("xiaoyi-thinking-effort", |ui| { + ui.label(RichText::new("思考档位").size(12.0).color(tokens.text_dim)); + let trigger = super::stitch_ui::select_trigger(ui, label(current), width, self.model_ready && self.busy.is_none()); + self.panel_geometry["thinkingLevel"] = rect_value(trigger.rect); + super::stitch_ui::select_popup(ui, &trigger, width, self.reduce_motion, |ui| { + for level in ["", "off"].into_iter().chain(levels) { + if super::stitch_ui::select_option(ui, label(level), current == level, true).clicked() { + selected = level; + ui.close(); + } + } + }); + }); + if selected != current { + self.send("select-model", json!({"field":"thinkingLevel","selection":selected,"model":self.model, + "accountId":self.account["id"],"origin":self.origin})); + } + } + + pub(in crate::jiansun) fn xiaoyi_key_input(&mut self, ui: &mut Ui) { + use super::stitch_ui::{self, ButtonRole}; + let id = ui.make_persistent_id("xiaoyi-knowledge-key"); + let hint = if self.xiaoyi_key_saved { "输入新的制作 Key" } else { "输入制作 Key" }; + stitch_ui::halo_field(ui, id.with("field"), None, self.reduce_motion, |ui| ui.add( + stitch_ui::text_input(&mut self.xiaoyi_key, hint, false) + .id(id).password(true).desired_width(f32::INFINITY).frame(Frame::NONE), + )); + if stitch_ui::action_button(ui, "校验并保存", ButtonRole::Secondary, !self.xiaoyi_key.trim().is_empty()).clicked() { + let key = std::mem::take(&mut self.xiaoyi_key); + self.send("configure-xiaoyi-knowledge", json!({"key":key})); + } + } + + pub(in crate::jiansun) fn knowledge_settings(&mut self, ui: &mut Ui) { + use super::stitch_ui::{self, ButtonRole, StatusTone, status_label}; + use crate::theme::agent_scale::Type; + let t = Tokens::get(ui.ctx()).agent(); + ui.label(RichText::new("小壹知识库").size(Type::Title.size()).color(t.text)); + let checking = self.busy.as_deref() == Some("configure-xiaoyi-knowledge"); + if self.xiaoyi_knowledge_mode == "manual" { + knowledge_connection_status(ui, self.xiaoyi_key_saved, self.xiaoyi_key_check.as_ref(), checking); + } else { + let (status, tone) = match (checking, self.xiaoyi_key_check.as_ref(), self.xiaoyi_knowledge_mode.as_str()) { + (true, _, _) => ("正在连接", StatusTone::Neutral), + (false, Some(Err(_)), _) => ("连接失败", StatusTone::Error), + (false, _, "automatic") => ("素材库自动连接", StatusTone::Neutral), + _ if self.account.is_null() => ("登录后自动连接", StatusTone::Neutral), + _ => ("未连接", StatusTone::Neutral), + }; + status_label(ui, status, tone); + if let Some(Err(error)) = self.xiaoyi_key_check.as_ref().filter(|_| !checking) { + status_label(ui, error, StatusTone::Error); + } + } + ui.add_enabled_ui(self.busy.is_none(), |ui| { + if self.xiaoyi_knowledge_mode == "manual" && !self.xiaoyi_key_saved { + self.xiaoyi_key_input(ui); + } else { + if stitch_ui::action_button(ui, "检测连接", ButtonRole::Secondary, true).clicked() { + self.send("configure-xiaoyi-knowledge", json!({"key":""})); + } + if self.xiaoyi_knowledge_mode == "manual" { + let id = ui.make_persistent_id("replace-xiaoyi-knowledge-key"); + stitch_ui::disclosure(ui, id, "更换制作 Key", false, self.reduce_motion, |ui| { + self.xiaoyi_key_input(ui); + }); + } + } + }); + } + + + pub(in crate::jiansun) fn workspace_settings_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui, corner: egui::Pos2) { + // The brief's buttons disappear when the models are ready. Anchor the + // popup and its exit animation to the workspace instead. + let inset = crate::theme::agent_scale::space::MD; + let anchor = ui.interact( + Rect::from_min_size(corner + vec2(inset, -inset), Vec2::ZERO), + ui.make_persistent_id("workspace-settings-anchor"), + Sense::hover(), + ); + if self.notifications_ui(ui) { + self.show_center(super::CenterView::Canvas, app.session.active().is_some()); + } + self.model_settings_popup(ui, &anchor); + self.flush_client_update_request(app); + } + + pub(in crate::jiansun) fn model_settings_popup(&mut self, ui: &mut Ui, anchor: &Response) { + let retained = ui.ctx().read_response(egui::Popup::default_response_id(anchor)).is_some(); + if self.model_settings || self.key_settings || retained { + self.settings_popup(ui, anchor); + } + } + + pub(in crate::jiansun) fn settings_popup(&mut self, ui: &mut Ui, anchor: &Response) { + // The dock layout can change mid-pass. A mounted popup claims the pass + // so another host cannot draw a second copy during the handoff. + let host = Id::unique(("jiansun-settings-host", ui.ctx().viewport_id())); + let pass = ui.ctx().cumulative_pass_nr(); + if ui.data(|data| data.get_temp::(host)) == Some(pass) { + return; + } + let open = self.model_settings || self.key_settings; + let open_id = host.with("open"); + let was_open = ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(open_id), open)); + if was_open && !open { + self.clear_settings_key_draft(); + self.xiaoyi_key.clear(); + } + let t = Tokens::get(ui.ctx()).agent(); + let (visual, transform) = super::stitch_ui::floating_panel_motion(ui.ctx(), anchor.id.with("popup"), anchor, open, self.reduce_motion); + self.panel_geometry["settingsMotion"] = json!({"opacity":visual.opacity,"scale":transform.scaling,"interactive":visual.interactive}); + ui.ctx().data_mut(|data| data.insert_temp(Id::unique("jiansun-settings-retained"), visual.render)); + if !visual.render { + return; + } + ui.data_mut(|data| data.insert_temp(host, pass)); + let frame = super::stitch_ui::overlay_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Dialog, visual.opacity).inner_margin(18); + let global_anchor = ui.ctx().layer_transform_to_global(anchor.layer_id).map_or(anchor.rect, |transform| transform * anchor.rect); + let body_height = super::stitch_ui::floating_body_height(ui.ctx().content_rect(), global_anchor); + let glass = settings_glass_supported(ui.ctx()); + self.panel_geometry["settingsGlass"] = json!(glass); + // A model menu can extend beyond this surface. Its click or Escape + // belongs to that child menu, not to the settings dismissal handler. + let nested_open = [ModelRole::Chat,ModelRole::Copy,ModelRole::Image].into_iter().any(|role| { + ui.data(|data| data.get_temp::(Id::unique(("agent-model-last-popup", role, true)))) + .is_some_and(|id| egui::Popup::is_id_open(ui.ctx(), id)) + }); + let mut popup_visible = true; + egui::Popup::from_response(anchor) + .frame(egui::Frame::NONE) + .open_bool(&mut popup_visible) + .close_behavior(if visual.interactive && !nested_open { egui::PopupCloseBehavior::CloseOnClickOutside } else { egui::PopupCloseBehavior::IgnoreClicks }) + .show(|ui| { + let contents = |ui: &mut Ui| super::stitch_ui::overlay_contents(ui, visual, |ui| super::stitch_ui::scope_with_motion(ui, self.reduce_motion, |ui| { + ui.set_width(360.0_f32.min((ui.ctx().content_rect().width() - 32.0).max(180.0))); + ui.spacing_mut().item_spacing = vec2(8.0, 10.0); + ui.spacing_mut().scroll.floating = false; + ui.horizontal(|ui| { + ui.label(RichText::new("小壹设置").size(14.0).strong().color(t.text)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if super::stitch_ui::icon_button(ui, "x", 26.0, false, "关闭模型设置").clicked() { + self.close_model_settings(); + } + }); + }); + let body = egui::ScrollArea::vertical().id_salt("xiaoyi-settings-body").max_height(body_height).show(ui, |ui| { + for (role, label) in [(ModelRole::Chat,"对话模型"),(ModelRole::Copy,"文案模型"),(ModelRole::Image,"生图模型")] { + ui.label(RichText::new(label).size(12.0).color(t.text_dim)); + self.model_picker(ui, role, ui.available_width(), true); + if role == ModelRole::Chat { self.thinking_picker(ui); } + } + if !self.copy_catalog_error.is_empty() { + ui.horizontal_wrapped(|ui| { + ui.label("文案目录未加载").on_hover_text(&self.copy_catalog_error); + if super::stitch_ui::action_button(ui,"重试",super::stitch_ui::ButtonRole::Quiet,true).clicked(){self.send("restore",json!({}));} + }); + } + if !self.image_catalog_error.is_empty() { + ui.horizontal_wrapped(|ui| { + ui.label("生图目录未加载").on_hover_text(&self.image_catalog_error); + if super::stitch_ui::action_button(ui, "重试", super::stitch_ui::ButtonRole::Quiet, true).clicked() { + self.send("restore", json!({})); + } + }); + } + ui.add_space(4.0); + ui.horizontal(|ui| { + icon(ui, "lock", t.text_dim); + ui.label(RichText::new(if self.key_saved { "个人 Key 已连接" } else { "个人 Key 未连接" }).size(13.0).color(t.text)); + if self.busy.as_deref() == Some("configure") { + super::stitch_ui::ai_loader(ui, ui.scope_id().with("configure-loading"), true, self.reduce_motion); + ui.label("正在校验…"); + } else if super::stitch_ui::action_button(ui, if self.key_settings { + "收起" + } else if self.key_saved { + "更换" + } else { + "设置" + }, super::stitch_ui::ButtonRole::Quiet, self.busy.is_none() && !self.account.is_null()) + .clicked() + { + self.key_settings = !self.key_settings; + if !self.key_settings { + self.clear_settings_key_draft(); + } + } + }); + super::stitch_ui::morph_surface(ui, ui.scope_id().with("key-reveal"), self.key_settings, self.reduce_motion, |ui| { + if !self.onboarding.is_open() { + self.model_key_editor(ui, "settings", self.key_settings, false); + } + }); + super::stitch_ui::divider(ui); + self.knowledge_settings(ui); + super::stitch_ui::divider(ui); + + if let Some(id) = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc) { + let notifications = super::stitch_ui::action_button(ui, "通知与警告", super::stitch_ui::ButtonRole::Quiet, true); + let count=ui.data(|data|data.get_temp::(id)).map_or(0,|history|history.unread); + if count>0 { + // On the label's centre line, a badge's own half-width to the right of the control. + let rect=Rect::from_center_size(notifications.rect.right_center()+vec2(15.0,0.0),vec2(24.0,20.0)); + super::stitch_ui::paint_badge(ui,id.with("unread-count"),rect,super::stitch_ui::BadgeKind::Count,&count.to_string(),self.reduce_motion); + } + self.panel_geometry["notificationsButton"] = rect_value(notifications.rect); + if notifications.clicked() { + ui.ctx().data_mut(|data| data.get_temp_mut_or_default::(id).open = true); + self.close_model_settings(); + } + } + // 有"通知与警告"时补一条分隔线;没有时上面已经是分隔线。 + let after_notifications = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc).is_some(); + self.client_version_settings(ui, after_notifications); + let after_version = after_notifications || self.client_update.version["version"].is_string(); + self.storage_settings_section(ui, after_version); + }); + // egui reports the pre-auto-shrink inner rect. Match the + // actual vertical viewport used by ScrollArea::end, rather + // than incorrectly counting its unused space as content. + let mut body_rect = body.inner_rect; + body_rect.set_height(body_rect.height().min(body.content_size.y)); + self.panel_geometry["settingsBody"] = rect_value(body_rect); + self.panel_geometry["settingsContentHeight"] = json!(body.content_size.y); + ui.add_space(4.0); + })); + if glass { + #[cfg(not(target_arch = "wasm32"))] + show_settings_glass(ui, frame, t.card, visual.opacity, transform.scaling, contents); + #[cfg(target_arch = "wasm32")] + contents(ui); + } else { + super::stitch_ui::material_frame(ui, frame, contents); + } + }); + if open && !popup_visible && !nested_open { + self.close_model_settings(); + ui.ctx().request_repaint(); + } + } + + + pub(in crate::jiansun) fn storage_settings_section(&mut self, ui: &mut Ui, show_divider: bool) { + let reduced = self.reduce_motion; + let ctx = ui.ctx().clone(); + let (action, modal_opened) = storage_settings_ui::with_machine_state(&ctx, |state| { + let was_open = state.migrate_modal_open || state.cleanup_modal_open; + let action = storage_settings_ui::storage_settings_card(ui, state, reduced, show_divider); + let now_open = state.migrate_modal_open || state.cleanup_modal_open; + (action, !was_open && now_open) + }); + if modal_opened { + self.close_model_settings(); + ui.ctx().request_repaint(); + } + if let Some(action) = action { + let (method, payload) = action.to_request(); + let _ = self.tx.send(Request::Action(method.into(), payload)); + } + } + + pub(in crate::jiansun) fn storage_modals_ui(&mut self, ctx: &egui::Context) { + let pass = ctx.cumulative_pass_nr(); + let pass_id = Id::unique("xiaoyi-storage-modals-pass"); + let already_rendered = ctx.data(|data| data.get_temp::(pass_id) == Some(pass)); + if already_rendered { + return; + } + ctx.data_mut(|data| data.insert_temp(pass_id, pass)); + let reduced = self.reduce_motion; + let action = storage_settings_ui::with_machine_state(ctx, |state| { + storage_settings_ui::show_storage_modals(ctx, state, reduced) + }); + if let Some(action) = action { + let (method, payload) = action.to_request(); + let _ = self.tx.send(Request::Action(method.into(), payload)); + } + } + +} + + +/// Experimental, local-acceptance-only opt-in. Until device-loss, resource +/// failure, performance and real-window verification are complete, a normal +/// launch uses the existing opaque popup and unchanged native renderer path. +pub(in crate::jiansun) fn knowledge_connection_status(ui: &mut Ui, saved: bool, check: Option<&Result<(), String>>, checking: bool) { + use super::stitch_ui::{StatusTone, status_label}; + let stored = if saved { "已保存到本机" } else { "本机未保存" }; + let (status, tone) = match (checking, check) { + (true, _) => ("正在校验", StatusTone::Neutral), + (false, Some(Ok(()))) => ("上次校验通过", StatusTone::Neutral), + (false, Some(Err(_))) => ("上次校验失败", StatusTone::Error), + (false, None) if saved => ("本次尚未校验", StatusTone::Neutral), + (false, None) => ("等待配置", StatusTone::Neutral), + }; + status_label(ui, &format!("{stored} · {status}"), tone); + if let Some(Err(error)) = check.filter(|_| !checking) { + status_label(ui, error, StatusTone::Error); + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub(in crate::jiansun) fn settings_glass_supported(ctx: &egui::Context) -> bool { + let initialized = Id::unique("jiansun-settings-glass-opt-in-initialized"); + let should_initialize = ctx.data_mut(|data| { + if data.get_temp::(initialized).unwrap_or(false) { + false + } else { + data.insert_temp(initialized, true); + true + } + }); + if should_initialize && std::env::var_os("PHOTOCRAFT_EXPERIMENTAL_STITCH_GLASS").as_deref() == Some(std::ffi::OsStr::new("1")) { + eframe::egui_wgpu::stitch_backdrop_set_experiment_enabled(ctx, true); + } + eframe::egui_wgpu::stitch_backdrop_supported(ctx) +} + +#[cfg(target_arch = "wasm32")] +pub(in crate::jiansun) fn settings_glass_supported(_ctx: &egui::Context) -> bool { + false +} + +/// The paired callbacks bracket an opaque emergency underlay. The validated +/// split renderer omits it; the normal renderer keeps it if a capability or +/// planner check fails, including the current frame. This does not guarantee +/// presentation after GPU device loss and is intentionally opt-in only. +#[cfg(not(target_arch = "wasm32"))] +pub(in crate::jiansun) fn show_settings_glass(ui: &mut Ui, mut frame: egui::Frame, base: Color32, opacity: f32, scale: f32, contents: impl FnOnce(&mut Ui) -> R) { + use eframe::egui_wgpu::BackdropMarker; + + let begin = ui.painter().add(egui::Shape::Noop); + let fallback = ui.painter().add(egui::Shape::Noop); + let end = ui.painter().add(egui::Shape::Noop); + frame.fill = frame.fill.gamma_multiply(0.58); + let shown = super::stitch_ui::material_frame(ui, frame, contents); + let rect = shown.response.rect - egui::epaint::MarginF32::from(frame.outer_margin); + let radius = f32::from(frame.corner_radius.nw) * scale; + let start_marker = BackdropMarker { blur_radius_points: 5.0 * scale, corner_radius_points: radius, opacity }; + let end_marker = BackdropMarker { blur_radius_points: 0.0, corner_radius_points: radius, opacity }; + ui.painter().set(begin, egui::Shape::Callback(start_marker.new_paint_callback(rect))); + // Ignore Area's measurement fade, but retain the explicit panel transition + // when a shrinking backdrop falls back to ordinary painting. + let mut opaque_painter = ui.painter().clone(); + opaque_painter.set_opacity(opacity.clamp(0.0, 1.0)); + opaque_painter.set(fallback, egui::Shape::rect_filled(rect, frame.corner_radius, Color32::from_rgb(base.r(), base.g(), base.b()))); + ui.painter().set(end, egui::Shape::Callback(end_marker.new_paint_callback(rect))); +} + diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/model_settings.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/model_settings.rs new file mode 100644 index 00000000..eca70b50 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/model_settings.rs @@ -0,0 +1,75 @@ +use super::super::json; +use super::super::{Value, Workspace}; +use super::models::ModelRole; + +impl Workspace { + pub(in crate::jiansun) fn receive_chat_context_usage(&mut self,usage:&Value) { + if usage["version"]==1&&self.models.iter().any(|model|model["key"]==self.model&&model["id"]==usage["model"])&&usage["modelKey"].as_str().is_none_or(|key|key==self.model){self.pi_context_usage=usage.clone();} + } + + + pub(in crate::jiansun) fn choose_model(&mut self, role: ModelRole, selected: String) { + if self.key_saved && self.api_key.is_empty() { + self.send("select-model", json!({"field":role.setting(),"selection":selected, + "accountId":self.account["id"],"origin":self.origin})); + } else { + match role { + ModelRole::Chat => self.model = selected, + ModelRole::Copy => self.copy_model = selected, + ModelRole::Image => self.image_model = selected, + } + self.model_ready = false; + self.copy_ready = false; + self.image_ready = false; + if !self.onboarding.is_open() { + self.open_model_settings(); + self.key_settings = true; + } + } + } + + + pub(in crate::jiansun) fn receive_model_preference(&mut self, value: &Value) { + if value["field"] == "thinkingLevel" { + self.thinking_by_model = value["thinkingByModel"].clone(); + return; + } + let (selected, models, ready) = match value["field"].as_str() { + Some("model") => (&mut self.model, &self.models, &mut self.model_ready), + Some("copyModel") => (&mut self.copy_model, &self.copy_models, &mut self.copy_ready), + Some("imageModel") => (&mut self.image_model, &self.image_models, &mut self.image_ready), + _ => return, + }; + let Some(choice) = value["selection"].as_str() else { return; }; + *selected = choice.into(); + *ready = self.key_saved && self.available_models.as_ref().is_some_and(|available| { + models.iter().find(|model| model["key"] == choice).and_then(|model| model["id"].as_str()) + .is_some_and(|id| available.iter().any(|entry| entry == id)) + }); + } + + + pub(in crate::jiansun) fn open_model_settings(&mut self) { + if !self.model_settings { + self.model_settings = true; + self.prompt_library.close(); + self.maybe_check_update_on_settings_open(); + } + } + + pub(in crate::jiansun) fn clear_settings_key_draft(&mut self) { + if !self.onboarding.is_open() { + self.api_key.clear(); + } + } + + pub(in crate::jiansun) fn close_model_settings(&mut self) { + if self.model_settings || self.key_settings { + self.model_settings = false; + self.key_settings = false; + self.clear_settings_key_draft(); + self.xiaoyi_key.clear(); + } + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/models.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/models.rs new file mode 100644 index 00000000..5824a59c --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/models.rs @@ -0,0 +1,85 @@ +use super::super::json; +use super::super::Value; + +/// Model ids are catalog keys written for machines. Known words become a +/// readable name; one unknown word leaves the whole id untouched, rather +/// than a half-translated label that matches no receipt. +pub(in crate::jiansun) fn model_display_name(id: &str) -> String { + let word = |word: &str| -> Option { + match word { + "gpt" => Some("GPT".to_owned()), + "vip" | "cl" | "2k" | "4k" => Some(word.to_ascii_uppercase()), + "image" | "nano" | "banana" | "flare" | "burst" | "sunburst" | "lite" | "fast" | "pro" => { + Some(format!("{}{}", word[..1].to_ascii_uppercase(), &word[1..])) + } + _ if !word.is_empty() && word.bytes().all(|byte| byte.is_ascii_digit() || byte == b'.') => Some(word.to_owned()), + _ => None, + } + }; + let mut words = Vec::new(); + for part in id.split('-') { + let Some(part) = word(part) else { return id.to_owned() }; + words.push(part); + } + if words.len() > 1 { words.join(" ") } else { id.to_owned() } +} + +/// Only the timestamp emitted by the active tool can start a live timer. + + +#[derive(Clone,Copy,Debug,Hash,PartialEq,Eq)] +pub(in crate::jiansun) enum ModelRole {Chat,Copy,Image} +impl ModelRole { + pub(in crate::jiansun) fn setting(self) -> &'static str { + match self { Self::Chat => "model", Self::Copy => "copyModel", Self::Image => "imageModel" } + } + pub(in crate::jiansun) fn geometry(self)->&'static str {match self {Self::Chat=>"chatModel",Self::Copy=>"copyModel",Self::Image=>"imageModel"}} + pub(in crate::jiansun) fn menu(self)->&'static str {match self {Self::Chat=>"chatModelMenu",Self::Copy=>"copyModelMenu",Self::Image=>"imageModelMenu"}} +} + +pub(in crate::jiansun) fn is_hidden_model(role: ModelRole, model: &Value) -> bool { + if role == ModelRole::Chat && model["productionReady"] == false { + return true; + } + let Some(id) = model["id"].as_str() else { return false }; + let id = id.to_ascii_lowercase(); + matches!(id.as_str(), + "gpt-6.2-astra" | "claude-sonnet-4-6" | "gemini-4-argon" | "gemini-4-carbon" + | "grok-4.5" | "grok-4.6" | "world-generation" | "deepseek-ocr" + ) || [ + "gpt-5.6-", "gpt-6-", "gpt-6.1-", "glm-5.3", "claude-fable-", "claude-opus-", + "claude-haiku-4-5", "gemini-3-", "gemini-3.", + ].iter().any(|prefix| id.starts_with(prefix)) +} + +pub(in crate::jiansun) const CONTEXT_UNAVAILABLE:&str="—"; +pub(in crate::jiansun) const CONTEXT_PENDING:&str="开始对话后显示使用情况"; +pub(in crate::jiansun) fn usage_count(value:&Value)->Option{value.as_u64().filter(|n|*n<=9_007_199_254_740_991)} +pub(in crate::jiansun) fn context_for_model(usage:&Value,models:&[Value],selected:&str)->Option{ + let model=models.iter().find(|model|model["key"]==selected)?; + let same=usage["version"]==1&&usage["model"]==model["id"]&&usage["modelKey"].as_str().is_none_or(|key|key==selected); + let mut current=if same {usage.clone()} else {json!({"version":1,"model":model["id"],"modelKey":selected})}; + let has_capacity=current["contextWindow"].as_u64().is_some_and(|limit|limit>0)&¤t["capacitySource"].as_str().is_some_and(|source|!source.is_empty()); + if !has_capacity&&model["contextWindow"].as_u64().is_some_and(|limit|limit>0)&&model["contextWindowSource"].as_str().is_some_and(|source|!source.is_empty()) { + current["contextWindow"]=model["contextWindow"].clone();current["capacitySource"]=model["contextWindowSource"].clone(); + } + (same||current["contextWindow"].as_u64().is_some_and(|limit|limit>0)).then_some(current) +} +pub(in crate::jiansun) fn context_tokens(value:&Value)->Option{matches!(value["contextSource"].as_str(),Some("pi-session"|"pi-last-response")).then(||usage_count(&value["contextTokens"])).flatten()} +pub(in crate::jiansun) fn context_fraction(usage:Option<&Value>)->Option{ + let value=usage?; + let limit=usage_count(&value["contextWindow"])?; + if limit==0||value["capacitySource"].as_str().is_none_or(str::is_empty){return None;} + let used=context_tokens(value)?; + if value["contextSource"]=="pi-last-response" {return Some((used as f64/limit as f64).clamp(0.0,1.0) as f32);} + let native=&value["piContextUsage"];let percent=native["percent"].as_f64()?; + (value["contextSource"]=="pi-session"&&usage_count(&native["tokens"])==Some(used)&&usage_count(&native["contextWindow"])==Some(limit)&&percent.is_finite()&&(0.0..=100.0).contains(&percent)).then_some((percent/100.0) as f32) +} +pub(in crate::jiansun) fn context_number(tokens:u64)->String {if tokens>=1_000_000 {format!("{:.0}M",tokens as f64/1_000_000.0)} else if tokens>=1_000 {format!("{:.0}K",tokens as f64/1_000.0)} else {tokens.to_string()}} +pub(in crate::jiansun) fn context_label(usage:Option<&Value>)->String{ + let Some(value)=usage else {return CONTEXT_UNAVAILABLE.into()}; + let Some(limit)=usage_count(&value["contextWindow"]).filter(|limit|*limit>0) else {return CONTEXT_UNAVAILABLE.into()}; + if value["capacitySource"].as_str().is_none_or(str::is_empty){return CONTEXT_UNAVAILABLE.into();} + let used=context_tokens(value).map_or_else(||"—".into(),context_number); + format!("{used}/{}",context_number(limit)) +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/multi_project_view.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/multi_project_view.rs new file mode 100644 index 00000000..98182bca --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/multi_project_view.rs @@ -0,0 +1,129 @@ +use super::super::agent_panel::multi_project_ui; +use super::super::stitch_timeline as timeline; +use super::super::{PhotocraftApp, Workspace}; + +impl Workspace { + pub(in crate::jiansun) fn multi_project_view_model( + &self, + app: &PhotocraftApp, + ctx: &egui::Context, + ) -> multi_project_ui::MultiProjectViewModel { + if let Some(injected) = multi_project_ui::snapshot(ctx) { + return injected; + } + let snap = self.multi_project_ui_snapshot(app); + let active_section = match snap.active_section { + super::multi_project_state::WorkspaceSectionKind::Projects => multi_project_ui::WorkspaceSection::Projects, + super::multi_project_state::WorkspaceSectionKind::Brief => multi_project_ui::WorkspaceSection::Brief, + super::multi_project_state::WorkspaceSectionKind::Canvas => multi_project_ui::WorkspaceSection::Canvas, + }; + let map_status = |status: &super::multi_project_state::ProjectRunVisualStatus| match status { + super::multi_project_state::ProjectRunVisualStatus::Running => multi_project_ui::MultiRunStatus::Running, + super::multi_project_state::ProjectRunVisualStatus::Queued => multi_project_ui::MultiRunStatus::Queued, + super::multi_project_state::ProjectRunVisualStatus::Paused => multi_project_ui::MultiRunStatus::Paused, + super::multi_project_state::ProjectRunVisualStatus::PartialDelivered => multi_project_ui::MultiRunStatus::PartialDelivered, + super::multi_project_state::ProjectRunVisualStatus::Completed => multi_project_ui::MultiRunStatus::Completed, + super::multi_project_state::ProjectRunVisualStatus::Failed => multi_project_ui::MultiRunStatus::Failed, + }; + let global_runs = snap + .global_runs + .into_iter() + .map(|run| { + let output_id = run.producing_output_id.unwrap_or_default(); + let output_label = if run.producing_output_label.is_empty() && !output_id.is_empty() { + multi_project_ui::output_display_label(&output_id).to_owned() + } else { + run.producing_output_label + }; + multi_project_ui::GlobalRunEntry { + project_id: run.project_id, + project_title: run.project_title, + status: map_status(&run.status), + producing_output_id: output_id, + producing_output_label: output_label, + progress_label: run.progress_label, + elapsed_secs: run.elapsed_secs, + active_slots: run.active_slots, + has_attention: run.has_attention, + } + }) + .collect(); + let active_project_title = (!snap.active_project_title.is_empty()).then_some(snap.active_project_title); + let viewing_output_label = snap.viewing_output_id.as_deref().map(|id| { + if snap.viewing_output_label.is_empty() { + multi_project_ui::output_display_label(id).to_owned() + } else { + snap.viewing_output_label.clone() + } + }); + let producing_output_label = snap.producing_output_id.as_deref().map(|id| { + if snap.producing_output_label.is_empty() { + multi_project_ui::output_display_label(id).to_owned() + } else { + snap.producing_output_label.clone() + } + }); + multi_project_ui::MultiProjectViewModel { + global_runs, + max_concurrent: snap.max_concurrent, + active_project_id: snap.active_project_id, + active_project_title, + active_section, + viewing_output_id: snap.viewing_output_id, + viewing_output_label, + producing_output_id: snap.producing_output_id, + producing_output_label, + viewing_differs_from_producing: snap.viewing_differs_from_producing, + } + } + + pub(in crate::jiansun) fn handle_multi_project_action( + &mut self, + app: &mut PhotocraftApp, + ctx: &egui::Context, + action: multi_project_ui::MultiProjectAction, + ) { + match &action { + multi_project_ui::MultiProjectAction::SwitchToProject(project_id) => { + if self.open_project_index(app, project_id).is_some() { + self.focus_project_by_id(app, project_id); + } else if let Some(item) = self + .projects + .iter() + .find(|p| p["localId"].as_str() == Some(project_id.as_str()) || p["id"].as_str() == Some(project_id.as_str())) + .cloned() + { + if let Err(error) = self.request_project_open(app, item) { + self.error = error; + } + } + } + multi_project_ui::MultiProjectAction::PauseProject(project_id) => { + if self.open_project_index(app, project_id).is_some() { + self.pause_project_run(app, project_id); + } else { + super::production_controls::queue_action( + ctx, + "production-stop", + super::production_controls::stop_input(timeline::StopMode::Pause), + ); + } + } + multi_project_ui::MultiProjectAction::ResumeProject(project_id) => { + if self.open_project_index(app, project_id).is_some() { + self.resume_project_run(app, project_id); + } else { + self.resume_product_production(app); + } + } + multi_project_ui::MultiProjectAction::JumpToProducingOutput { project_id, .. } => { + if self.open_project_index(app, project_id).is_some() { + self.focus_project_by_id(app, project_id); + } + self.jump_to_producing_output(app); + } + } + multi_project_ui::push_action(ctx, action); + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/notifications.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/notifications.rs new file mode 100644 index 00000000..7e0b4ac2 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/notifications.rs @@ -0,0 +1,66 @@ +use super::super::{Value, Workspace}; +use egui::Id; + +#[derive(Clone)] +pub(in crate::jiansun) struct AgentToast { pub(in crate::jiansun) shown_at: f64 } + +pub(in crate::jiansun) fn toast_active(toast: &AgentToast, now: f64) -> bool { + now.is_finite() && toast.shown_at.is_finite() && now >= toast.shown_at && now - toast.shown_at < 2.4 +} + +pub(in crate::jiansun) fn toast_id(origin: &str, account: &Value, project: &Value, doc: Option) -> Option { + let account = account["id"].as_str().filter(|id| !id.is_empty())?; + if origin.is_empty() { return None; } + Some(Id::unique("jiansun-draft-toast").with((origin, account, project["localId"].as_str(), doc))) +} + +#[derive(Clone, Default)] +pub(in crate::jiansun) struct AgentNotifications { + pub(in crate::jiansun) entries: Vec, + pub(in crate::jiansun) unread: usize, + pub(in crate::jiansun) last_error: String, + pub(in crate::jiansun) last_unknown: bool, + pub(in crate::jiansun) open: bool, +} + +impl AgentNotifications { + pub(in crate::jiansun) fn add(&mut self, value: &str) { + if value.trim().is_empty() { return; } + let mut chars = value.chars(); + let mut visible = chars.by_ref().take(4000).collect::(); + if chars.next().is_some() { visible.push_str("…(内容已截断)"); } + if self.entries.iter().any(|item| item == &visible) { return; } + self.entries.push(visible); + if self.entries.len() > 40 { self.entries.remove(0); } + self.unread=(self.unread+1).min(self.entries.len()); + } + + pub(in crate::jiansun) fn observe(&mut self, error: &str, unknown: bool, warning: Option<&str>, receipts: &[Value]) { + if !error.is_empty() && error != self.last_error { self.add(error); } + self.last_error = error.to_owned(); + if unknown && !self.last_unknown && error.is_empty() { self.add("原请求结果待核查,未重复发送。"); } + self.last_unknown = unknown; + if let Some(warning) = warning { self.add(warning); } + for message in receipts { + if let Some(text) = message["text"].as_str().filter(|text| { + text.starts_with("保存副本时有导出提示:") || text.starts_with("PSD副本已导出,导出提示:") + }) { self.add(text); } + } + } +} + +pub(in crate::jiansun) fn notification_id(origin: &str, account: &Value, project: &Value, doc: Option) -> Option { + toast_id(origin, account, project, doc).map(|id| id.with("notifications")) +} + +impl Workspace { + pub(in crate::jiansun) fn recent_notification_entries(&self, ctx: &egui::Context) -> Vec { + let Some(id) = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc) else { + return Vec::new(); + }; + ctx.data(|data| data.get_temp::(id)) + .map(|history| history.entries.into_iter().rev().take(12).collect()) + .unwrap_or_default() + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/notifications_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/notifications_ui.rs new file mode 100644 index 00000000..e13004ba --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/notifications_ui.rs @@ -0,0 +1,112 @@ +use super::super::{RichText, Value}; +use super::super::{Tokens, Ui, Workspace, json}; +use super::rect_value; +use super::notifications::{AgentNotifications, AgentToast, notification_id, toast_active}; +use egui::{Id, Rect}; + +/// Only called after an actual library item was inserted into the draft. +pub(in crate::jiansun) fn post_draft_toast(ui: &Ui, id: Id) { + let now = ui.input(|input| input.time); + ui.ctx().data_mut(|data| data.insert_temp(id, AgentToast { shown_at: now })); + ui.ctx().request_repaint(); +} + +pub(in crate::jiansun) fn draw_draft_toast(ui: &Ui, id: Id, anchor: Rect, reduced: bool) { + let Some(toast) = ui.ctx().data(|data| data.get_temp::(id)) else { return }; + if !ui.is_rect_visible(anchor) { return; } + let now = ui.input(|input| input.time); + let active = toast_active(&toast, now); + let visual = super::stitch_ui::overlay_transition(ui.ctx(), id.with("transition"), active, reduced); + if visual.render { + let position = egui::pos2(anchor.left() + 8.0, (anchor.top() - 36.0).max(ui.clip_rect().top())); + egui::Area::new(id.with("surface")).order(egui::Order::Foreground).fixed_pos(position).interactable(false).show(ui.ctx(), |ui| { + super::stitch_ui::overlay_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Menu, visual.opacity).show(ui, |ui| { + super::stitch_ui::overlay_contents(ui, visual, |ui| { + let t = Tokens::get(ui.ctx()).agent(); + ui.label(RichText::new("已添加到草稿").size(12.0).color(t.text)); + }); + }); + }); + } + if active { + let remaining = (2.4 - (now - toast.shown_at)).max(0.01); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(remaining)); + } else if !visual.render { + ui.ctx().data_mut(|data| data.remove::(id)); + } +} + + +impl Workspace { + pub(in crate::jiansun) fn notifications_ui(&mut self, ui: &mut Ui)->bool { + self.panel_geometry["notificationCandidates"]=Value::Null; + let marker = Id::unique("jiansun-notification-last-scope"); + let current = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc); + let scope = current.unwrap_or_else(|| Id::unique("jiansun-notification-no-account")); + let previous = ui.ctx().data(|data| data.get_temp::(marker)); + let switched = previous.is_some_and(|old| old != scope); + if switched { + ui.ctx().data_mut(|data| { + if let Some(old) = previous { data.get_temp_mut_or_default::(old).open = false; } + if current.is_some() { data.get_temp_mut_or_default::(scope).open = false; } + }); + } + ui.ctx().data_mut(|data| data.insert_temp(marker, scope)); + let Some(id) = current else { return false }; + let mut history = ui.ctx().data(|data| data.get_temp::(id)).unwrap_or_default(); + let unknown = self.result_needs_check(); + if switched { + // Do not attribute an old in-memory error to the newly selected account. + history.last_error = self.error.clone(); history.last_unknown = unknown; + } + let identity_prefix = self.local_identity(""); + let project_id = self.owner_doc.filter(|doc| self.loaded_draft == Some(*doc)) + .and_then(|doc| self.open_projects.get(&doc)) + .and_then(|identity| identity.strip_prefix(&identity_prefix)) + .filter(|project| !project.is_empty()); + let receipts = if project_id.is_some() { self.messages.as_slice() } else { &[] }; + let diagnostics = super::operation_error::DiagnosticContext { + version: &self.client_update.version, + project_id, + messages: receipts, + }; + let warning = self.prompt_library.warning(); + history.observe(&self.error, unknown, warning.as_deref(), receipts); + let visual = super::stitch_ui::overlay_transition(ui.ctx(), id.with("transition"), history.open, self.reduce_motion); + if visual.interactive {history.unread=0;} + let mut view_candidates=false; + if visual.render { + let t = Tokens::get(ui.ctx()).agent(); + let screen = ui.ctx().content_rect(); + let width = (screen.width() - 64.0).clamp(1.0, 360.0); + let list_height = (screen.height() - 200.0).clamp(1.0, 260.0); + let mut bounds = Rect::NOTHING; + let closed = super::stitch_ui::dialog(ui, id.with("window"), "通知与警告", history.open, self.reduce_motion, width, |ui| { + ui.label(RichText::new("本次会话的通知;导出提示也保留在项目对话中。").size(12.0).color(t.text_dim)); + if history.entries.is_empty() { ui.label("暂无通知"); } + egui::ScrollArea::vertical().id_salt(id.with("entries")).max_height(list_height).show(ui, |ui| { + for (index,entry) in history.entries.iter().enumerate().rev() { + super::stitch_ui::divider(ui); + let active=!self.error.is_empty() && entry==&self.error; + ui.label(RichText::new(if active {"当前问题"} else {"历史通知"}).size(super::agent_stream::TEXT_META).color(t.text_dim)); + let has_candidates=self.template_workflow["slots"].as_array().into_iter().flatten() + .any(|slot|slot["candidates"].as_array().into_iter().flatten().any(|candidate|candidate["status"]=="complete")); + if active && super::operation_error::message(entry).image_read && has_candidates { + let button=super::stitch_ui::action_button(ui,"查看已有候选",super::stitch_ui::ButtonRole::Secondary,true); + self.panel_geometry["notificationCandidates"]=rect_value(button.rect); + if button.clicked() {view_candidates=true;} + } + super::operation_error::details(ui,id.with(("error-details",index)),entry,self.reduce_motion,Some(&diagnostics)); + } + }); + bounds = ui.min_rect(); + }); + if bounds.is_positive() { self.panel_geometry["notifications"] = rect_value(bounds); } + if closed || view_candidates { history.open = false; ui.ctx().request_repaint(); } + } + self.panel_geometry["notificationsOpen"] = json!(history.open); + ui.ctx().data_mut(|data| data.insert_temp(id, history)); + view_candidates + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/processing_card_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/processing_card_ui.rs new file mode 100644 index 00000000..141b8f26 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/processing_card_ui.rs @@ -0,0 +1,544 @@ +use super::super::{CenterView, Duration, Instant, Request, stitch_timeline as timeline, workflow_bridge}; +use super::production_reply_ui::{read_delivery_manifest, recover_delivery_manifest}; +use super::turn_ui::{active_tool_elapsed, frame_image_ratio, image_card_size}; +use egui::{Align, Layout}; +use super::super::{PhotocraftApp, RichText, Tokens, Ui, Value, Workspace, agent_motion, json}; +use super::rect_value; +use super::turn_ui::subject_label; +use egui::{Id, vec2}; + +pub(in crate::jiansun) fn workflow_scope(proposal: &Value, workflow: &Value) -> String { + if matches!(proposal["intent"].as_str(), Some("export" | "export_psd")) { + return "当前画布".into(); + } + if !matches!(proposal["intent"].as_str(), Some("fill_output" | "review_candidates" | "generate_candidate")) { + return String::new(); + } + let output = match proposal["outputId"].as_str() { + Some("main_images") => "主图", + Some("sku_images") => "SKU", + _ => "详情", + }; + let target = if let Some(slot_id) = proposal["slotId"].as_str() { + workflow["slots"] + .as_array() + .into_iter() + .flatten() + .find(|slot| slot["id"] == slot_id) + .and_then(|slot| if proposal["intent"] == "generate_candidate" { slot["fieldId"].as_str() } else { slot["documentId"].as_str() }) + .unwrap_or("图位已变化") + } else { + "全组" + }; + if proposal["intent"] == "generate_candidate" { + format!("{output} · {target} · {}", proposal["variant"].as_str().unwrap_or("候选已变化")) + } else { + format!("{output} · {target}") + } +} + + +impl Workspace { + /// Only render request-owned snapshots; the currently selected canvas + /// object is not a reliable target once an asynchronous request is sent. + pub(in crate::jiansun) fn processing_target(&self, app: &PhotocraftApp) -> Option { + let doc = app.session.active().map(|state| state.doc.id.0)?; + match self.busy.as_deref() { + Some("slot-append" | "slot-generate") => self.running_workflow_generation(doc) + .map(|op| { + let label = self.template_workflow["slots"].as_array().into_iter().flatten() + .find(|slot| slot["id"] == op["slotId"] && slot["outputId"] == op["outputId"]) + .map(|slot| &slot["label"]); + let kind = if op["candidateId"].is_string() { "candidate" } else { "slot" }; + json!({"kind":kind,"slotId":op["slotId"],"outputId":op["outputId"],"label":label, + "productVariantId":op["productVariantId"],"candidateId":op["candidateId"]}) + }) + .or_else(|| self.canvas_workspace.submitted_generation_target(&self.account["id"], &self.origin, Some(doc)).cloned()), + Some("agent" | "pi-agent") + if self.owner_doc == Some(doc) + && self.pi_request_scope["project"]["documentId"].as_u64() == Some(doc) + && self.pi_request_scope["account"]["id"] == self.account["id"] + && self.pi_request_scope["account"]["origin"] == self.origin + && self.pi_request_scope["project"]["localId"] + .as_str() + .is_none_or(|local| self.open_projects.get(&doc).is_some_and(|current| current == local)) => + { + self.pi_request_scope.get("subject").filter(|target| target.is_object()).cloned() + } + _ => None, + } + } + + pub(in crate::jiansun) fn processing_card_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui) { + super::glow_pill::bind(ui, app.gpu_render_state.as_ref()); + if self.batch_progress_visible() { return; } + let reduced = self.reduce_motion || agent_motion::hidden(ui, ui.available_rect_before_wrap().intersect(ui.clip_rect())) + || self.owner_doc.is_some_and(|owner| app.session.active().is_none_or(|state| state.doc.id.0 != owner)); + let pending = self.pending(); + let running = self.canvas_workspace.adoption_preparing() || (pending && !self.agent_effects_paused); + let processing_id = Id::unique("jiansun-processing-card"); + let image_task = matches!(self.busy.as_deref(), Some("image" | "slot-generate" | "slot-append" | "image-recover" | "slot-recover")) + || self.pending_image.is_some(); + // Conversation status uses AI Loader, never the image-generation + // surface. Reset a preceding image remnant before another task starts. + if pending && (!image_task || self.canvas_workspace.adoption_preparing()) { + let _ = agent_motion::task_visibility(ui, processing_id, false, true); + self.agent_status_ui(ui, running); + return; + } + let visibility = agent_motion::task_visibility(ui, processing_id, pending && image_task, reduced); + if visibility <= 0.0 { + ui.data_mut(|data|data.remove::<(Id,f64,f64)>(Id::unique("glow-pill-image-clock"))); + return; + } + let mut card_ui = ui.new_child(egui::UiBuilder::new().id_salt("task-card-content").max_rect(ui.available_rect_before_wrap())); + card_ui.set_opacity(visibility); + let parent_ui = ui; + let ui = &mut card_ui; + let t = Tokens::get(ui.ctx()).agent(); + let waiting_for_image = pending && matches!(self.busy.as_deref(), Some("image" | "slot-generate" | "slot-append")) + && self.pending_image.is_none() + && !self.agent_effects_paused; + // Keep the neutral placeholder only long enough to fade out. Its + // visual lifetime does not change the underlying task state or title. + // The submitted user message stays at the same index while tool and + // result records append. Selection, hover and viewport coordinates do + // not define the identity or restart the waiting mark. + let waiting_id = Id::unique(("jiansun-result-waiting", &self.origin, self.account["id"].as_str(), + self.owner_doc, self.messages.iter().rposition(|message| message["role"] == "user"))); + let waiting_visibility = ui.ctx().animate_bool_with_time( + waiting_id.with("visibility"), + waiting_for_image, + if reduced { 0.0 } else { 0.16 }, + ); + let active = running; + let title = if !pending { + "处理已结束" + } else if !active { + "已停止本地操作 · 原请求保留" + } else if waiting_for_image { + if self.image_progress.is_empty() { "正在生成图片…" } else { super::stitch_ui::processing_label(&self.image_progress) } + } else if matches!(self.busy.as_deref(), Some("recover" | "image-recover" | "slot-recover")) { + "正在核查原结果…" + } else if !self.queue.is_empty() || self.pending_image.is_some() { + "正在更新画布…" + } else if self.busy.as_deref() == Some("slot-copy") { + "正在生成图位文案…" + } else { + self.workflow_waiting.as_ref().and_then(|value| value["label"].as_str()).unwrap_or("正在回复…") + }; + let title = title.to_owned(); + let target = self.processing_target(app).filter(|target| target["kind"].as_str().is_some_and(|kind| !kind.is_empty() && kind != "project")); + // The conversation frame has its own margins. Size the task surface + // from the actual dock/clip rather than compounding those margins. + let dock_width = self.panel_geometry["panel"][2].as_f64().map(|width| width as f32).unwrap_or(ui.clip_rect().width()); + let desired_card_width = (dock_width - 32.0).max(0.0).min((ui.clip_rect().right() - ui.cursor().left()).max(0.0)); + let ratio = (waiting_visibility > 0.0).then(|| { + let slot = target.as_ref()?; + self.template_workflow["slots"].as_array()?.iter() + .find(|value| value["id"] == slot["slotId"] + && (slot["outputId"].is_null() || slot["outputId"] == value["outputId"]) + && (slot["productVariantId"].is_null() || value["variantId"].is_null() || slot["productVariantId"] == value["variantId"])) + .and_then(|value| frame_image_ratio(&value["frame"])) + }).flatten().unwrap_or(16.0 / 9.0); + let image_size = image_card_size(desired_card_width, ratio); + let elapsed_ms = if active { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok() + .and_then(|now| u64::try_from(now.as_millis()).ok()) + .and_then(|now| active_tool_elapsed(&self.messages, self.pi_run.as_deref(), now)) + } else { None }; + ui.add_space(10.0); + let card = super::stitch_ui::surface(ui, super::stitch_ui::SurfaceRole::Task, |ui| { + let waiting_background = agent_motion::reserve_background(ui); + let content_width = ((if waiting_visibility > 0.0 { image_size.x } else { desired_card_width }) - 26.0).max(0.0); + ui.set_width(content_width); + if waiting_visibility > 0.0 { + ui.set_min_height((image_size.y - 26.0).max(0.0)); + } + ui.horizontal(|ui| { + if waiting_visibility > 0.0 { + let (rect, _) = ui.allocate_exact_size(vec2(26.0, 26.0), egui::Sense::hover()); + let motion=if waiting_for_image {super::siri_orb::Motion::Thinking} else {super::siri_orb::Motion::Still}; + if let Some(orb) = super::siri_orb::paint(ui,waiting_id.with("identity"),rect,motion,reduced) { + self.panel_geometry["processingBlob"] = rect_value(rect); + self.panel_geometry["processingBlobPhase"] = json!(orb.phase); + self.panel_geometry["processingBlobMoving"] = json!(!reduced && waiting_for_image); + self.panel_geometry["processingIdentity"] = json!("siri-orb"); + } + } else { + super::stitch_ui::ai_loader(ui, processing_id.with("loader"), active, reduced); + } + let reserve = if active { 26.0 + ui.spacing().item_spacing.x } else { 0.0 }; + let label_width = (ui.available_width() - reserve).max(0.0); + let label = egui::Label::new(RichText::new(title).size(13.0).color(t.text)).truncate(); + if waiting_visibility > 0.0 { + ui.allocate_ui_with_layout(vec2(label_width, 26.0), Layout::left_to_right(Align::Center), |ui| { + ui.set_width(label_width); + ui.add(label); + }); + } else { + ui.add_sized(vec2(label_width, 26.0), label); + } + if active { + let stop = super::stitch_ui::icon_button(ui, "square", 26.0, false, "停止本地自动操作,保留原请求"); + self.panel_geometry["taskStop"] = rect_value(stop.rect); + if stop.clicked() { self.abort_chat_run(); } + } + }); + if let Some(ms) = elapsed_ms { + let seconds = ms / 1_000; + let response = ui.label(RichText::new(format!("工具已运行 {}:{:02}", seconds / 60, seconds % 60)).size(super::agent_stream::TEXT_META).color(t.text_dim)); + if !agent_motion::hidden(ui, response.rect) { ui.ctx().request_repaint_after(Duration::from_millis(1_000 - ms % 1_000)); } + } + if let Some(target) = &target { + ui.add_space(5.0); + let label = subject_label(target, &self.template_workflow); + ui.add(egui::Label::new(RichText::new(label).size(12.0).color(t.text_dim)).wrap()); + } + waiting_background + }); + self.panel_geometry["processing"] = rect_value(card.response.rect); + if waiting_visibility > 0.0 { + self.panel_geometry["processingPlaceholder"] = rect_value(card.response.rect); + } + let now=ui.input(|input|input.time); + let elapsed=ui.data_mut(|data|{ + let id=Id::unique("glow-pill-image-clock"); + let mut clock=data.get_temp::<(Id,f64,f64)>(id).filter(|clock|clock.0==waiting_id).unwrap_or((waiting_id,now,0.0)); + if active && !reduced {clock.2=(now-clock.1)*0.55;} + data.insert_temp(id,clock);clock.2 + }); + let activity=ui.ctx().animate_bool_with_time(processing_id.with("working"),active,if reduced || agent_motion::hidden(ui, card.response.rect) {0.0} else {0.16}); + let mut pulse=if reduced {super::glow_pill::Pulse::default()} else {super::glow_pill::waiting(elapsed)}; + pulse.surge*=activity; + pulse.warp*=activity; + super::glow_pill::paint(ui,super::glow_pill::Surface {id:processing_id,rect:card.response.rect,radius:t.radius, + time:if reduced {2.4} else {elapsed},pulse,opacity:visibility,background:Some(card.inner),text_range:None,flanks:0.0}); + if active && !reduced { agent_motion::schedule(ui, card.response.rect, agent_motion::Pace::Idle); } + self.panel_geometry["processingLightMode"] = json!(if active {"glow-pill"} else {"paused"}); + self.panel_geometry["processingOpacity"] = json!(visibility); + parent_ui.advance_cursor_after_rect(ui.min_rect()); + } + + pub(in crate::jiansun) fn agent_status_ui(&mut self, ui: &mut Ui, running: bool) { + let t = Tokens::get(ui.ctx()).agent(); + let id = Id::unique(("jiansun-agent-status", &self.origin, self.account["id"].as_str(), self.owner_doc, + self.messages.iter().rposition(|message| message["role"] == "user"))); + let preparing = self.canvas_workspace.adoption_preparing(); + let title = if preparing { "准备采纳…" } + else if self.pi_ui_waiting() { "等待你的回复…" } + else if !running { "已停止本地操作 · 原请求保留" } + else if self.busy.as_deref() == Some("recover") { "正在核查原结果…" } + else if !self.queue.is_empty() { "正在更新画布…" } + else { self.workflow_waiting.as_ref().and_then(|value| value["label"].as_str()).unwrap_or("正在处理…") }.to_owned(); + // A stable, unframed row remains throughout the turn, including the + // genuine network waits between tools. No glow, panel or target repeat. + let shown = ui.allocate_ui_with_layout(vec2(ui.available_width(), 26.0), Layout::right_to_left(Align::Center), |ui| { + ui.set_min_height(26.0); + // Reserve the stop target first. Generic shared field rows use a + // 32pt interaction height; this status has its own compact 26pt + // geometry and cannot inherit that minimum through horizontal(). + if running && !preparing { + let stop = super::stitch_ui::icon_button(ui, "square", 26.0, false, "停止本地自动操作,保留原请求"); + self.panel_geometry["taskStop"] = rect_value(stop.rect); + if stop.clicked() { self.abort_chat_run(); } + } + ui.allocate_ui_with_layout(vec2(ui.available_width(), 26.0), Layout::left_to_right(Align::Center), |ui| { + super::stitch_ui::ai_loader(ui, id.with("loader"), running, true); + ui.add(egui::Label::new(RichText::new(title).size(12.0).color(t.text_dim)).truncate()); + }); + }); + self.panel_geometry["agentStatus"] = rect_value(shown.response.rect); + self.panel_geometry["processingLightMode"] = json!("inactive"); + } + + pub(in crate::jiansun) fn production_outcome_ui(&mut self, ui: &mut Ui, production: bool, app: &PhotocraftApp) { + use timeline::RunOutcome; + self.finish_delivery_hint(app, ui); + if production { + return; + } + let receipt = self.messages.iter().rev().take_while(|row| row["role"] != "user") + .find(|row| row["productionSummary"].is_object()); + let checkpoint = &self.product_checkpoint; + let delivery = receipt.map_or(&checkpoint["productionDelivery"], |row| &row["productionDelivery"]); + let path = delivery["path"].as_str(); + let saved = path.and_then(|path| read_delivery_manifest(ui, path).map(|manifest| (path.to_owned(), manifest))) + .or_else(|| (path.is_none() && !delivery["error"].is_string()) + .then(|| recover_delivery_manifest(ui, checkpoint)).flatten()); + if let Some((path, manifest)) = saved { + if self.delivery_completion { + self.sync_confirm = false; + self.delivery_completion = false; + } + let label = if manifest["allOutputsCompleted"] == true { + "本地已落盘" + } else { + "部分成品已落盘" + }; + let count = manifest["completedOutputs"].as_u64().zip(manifest["totalOutputs"].as_u64()) + .map_or_else(|| label.to_owned(), |(done, total)| format!("{label} · {done}/{total} 份")); + let outcome = if manifest["allOutputsCompleted"] == true { + RunOutcome::Completed { summary: &count, path: &path } + } else { + RunOutcome::PartialDelivery { summary: &count, path: &path } + }; + let mut open = false; + timeline::run_outcome_card(ui, outcome, None, |_| open = true, |ui| { + self.delivery_receipts_ui(app, ui, &manifest); + }); + if open && app.services.open_folder.as_ref() + .is_none_or(|open| open(std::path::Path::new(&path)).is_err()) + { + self.error = "无法打开文件夹,请检查目录是否仍可访问".into(); + } + return; + } + + let producing = self.pi_product_production; + let outcome = if producing && self.agent_effects_paused { + Some(RunOutcome::Stopped { request_kept: self.pending() || self.unknown }) + } else if producing && self.result_needs_check() { + Some(RunOutcome::NeedsCheck) + } else if self.pending() { + None + } else if let Some(error) = delivery["error"].as_str() { + Some(RunOutcome::Failed { category: super::stitch_state::ErrorCategory::classify(error) }) + } else if path.is_some() || receipt.is_some() { + Some(RunOutcome::Waiting { reason: "成品交付尚未确认" }) + } else { + None + }; + if let Some(outcome) = outcome { + timeline::run_outcome_card(ui, outcome, None, |_| {}, |_| {}); + } + } + + pub(in crate::jiansun) fn delivery_receipts_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui, manifest: &Value) { + use super::stitch_ui::{self as kit, ButtonRole::Quiet, StatusTone::{Error, Neutral}}; + let doc = app.session.active().map(|doc| doc.doc.id.0); + let receipt = &self.project_context["materialDelivery"]; + let same_delivery = receipt["deliveryId"].as_str().map_or( + self.project_context["status"] == "completed", |id| manifest["deliveryId"] == id); + let material = receipt["materialId"].as_str().filter(|_| same_delivery); + let listing = &receipt["listingStatus"]; + let withdrawn = material.is_some() && receipt["state"] == "removed"; + let pending = self.busy.as_deref() == Some("project-sync") + || (same_delivery && matches!(receipt["state"].as_str(), Some("pending" | "uploading"))); + let upload_error = same_delivery.then(|| receipt["error"].as_str()).flatten() + .or_else(|| self.error.strip_prefix("素材库提交失败:")); + let (library_label, library_tone) = if withdrawn { + ("已撤回", Neutral) + } else if material.is_some() { + ("已建档", Neutral) + } else if upload_error.is_some() { + ("提交失败", Error) + } else if pending { + ("正在提交", Neutral) + } else if manifest["allOutputsCompleted"] == true { + ("待入库", Neutral) + } else { + ("待补齐成品", Neutral) + }; + let (listing_label, listing_tone) = match (material.is_some() && !withdrawn, listing["state"].as_str()) { + (false, _) => ("未触发", Neutral), + (true, Some("pending")) => ("等待上架", Neutral), + (true, Some("listing")) => ("上架中", Neutral), + (true, Some("listed")) => ("已上架", Neutral), + (true, Some("failed")) => ("上架失败", Error), + (true, _) => ("待查询", Neutral), + }; + let now = Instant::now(); + let mut refresh = material.is_some() && !withdrawn && doc.is_some_and(|doc| + self.listing_read_at.is_none_or(|(last_doc, next)| last_doc != doc || now >= next)); + let mut submit = false; + let mut open_listing = false; + let mut jump = None; + kit::status_label(ui, &format!("素材库 · {library_label}"), library_tone); + kit::status_label(ui, &format!("外部自动上架 · {listing_label}"), listing_tone); + if upload_error.is_some() || listing_tone == Error || self.listing_read_error.is_some() || self.finished_web_error.is_some() { + kit::disclosure(ui, ui.scope_id().with("delivery-details"), "查看提交与上架详情", false, self.reduce_motion, |ui| { + for error in [upload_error, self.listing_read_error.as_deref(), self.finished_web_error.as_deref(), + (listing_tone == Error).then(|| listing["message"].as_str()).flatten()].into_iter().flatten() { + super::operation_error::details(ui, ui.next_auto_id(), error, self.reduce_motion, None); + } + if self.listing_read_error.is_some() && kit::action_button(ui, "重新查询", Quiet, doc.is_some()).clicked() { + refresh = true; + } + if listing_tone == Error && kit::action_button(ui, "打开上架工作台", Quiet, !self.finished_web_pending).clicked() { + open_listing = true; + } + }); + } + if material.is_none() && manifest["allOutputsCompleted"] == true && !pending { + let ready = doc.is_some() && self.busy.is_none() && self.saving.is_none() + && !self.project_operation_pending() && !self.creation_dirty && !self.unknown; + let label = if upload_error.is_some() { "重试入库" } else { "提交素材库" }; + submit = kit::action_button(ui, label, Quiet, ready).clicked(); + } + + if let Some(hints) = manifest["reviewHints"].as_array().filter(|hints| !hints.is_empty()) { + kit::disclosure(ui, ui.scope_id().with("delivery-review"), &format!("人工核对({})", hints.len()), false, self.reduce_motion, |ui| { + for hint in hints { + let Some(message) = hint.as_str().or_else(|| hint["message"].as_str()) else { continue }; + ui.label(crate::client_brand::user_error(message, "有一项成品需要人工核对")); + let output = hint["outputId"].as_str().or_else(|| { + [("详情页:", "detail"), ("主图:", "main_images"), ("SKU 图:", "sku_images"), ("SKU:", "sku_images")] + .into_iter().find_map(|(prefix, output)| message.starts_with(prefix).then_some(output)) + }); + let Some(output) = output else { continue }; + let exact = hint["slotId"].is_string() || !hint["layerId"].is_null() || hint["nativeLayerId"].is_u64() + || !hint["screenId"].is_null() || !hint["pageId"].is_null() || hint["screenIndex"].is_u64(); + let label = if exact { "定位到画布" } else { "查看成品" }; + if kit::action_button(ui, label, Quiet, doc.is_some()).clicked() { + jump = Some((output.to_owned(), hint.clone())); + } + } + }); + } + + if refresh && let Some(doc) = doc { + self.listing_read_at = Some((doc, now + Duration::from_secs(15))); + if self.tx.send(Request::Action("delivery-status".into(), json!({"doc":doc}))).is_err() { + self.listing_read_error = Some("本机服务已停止,请重启后查看".into()); + } + } + if material.is_some() && !withdrawn { + ui.ctx().request_repaint_after(Duration::from_secs(15)); + } + if open_listing && let Some((doc, material)) = doc.zip(material) { + self.finished_web_error = None; + self.finished_web_pending = self.tx.send(Request::Action("finished-web-open".into(), + json!({"doc":doc,"materialId":material}))).is_ok(); + if !self.finished_web_pending { + self.finished_web_error = Some("本机服务已停止,请重启后重试".into()); + } + } + if submit { + self.sync_action(app, "project-sync", json!({"status":"completed","deliveryId":manifest["deliveryId"]})); + } + if let Some((output, hint)) = jump { + self.locate_delivery_hint(app, ui, &output, hint); + } + } + + pub(in crate::jiansun) fn locate_delivery_hint(&mut self, app: &PhotocraftApp, ui: &Ui, output: &str, hint: Value) { + let target = json!({"outputId":output,"variantId":hint["variantId"]}); + if let Err(error) = self.slot_action(app, "slot-skeleton", target) { + self.error = error; + return; + } + ui.data_mut(|data| data.insert_temp(self.delivery_hint_id(), (output.to_owned(), hint))); + self.show_center(CenterView::Canvas, app.session.active().is_some()); + self.creation_open = false; + ui.ctx().request_repaint(); + } + + pub(in crate::jiansun) fn delivery_hint_id(&self) -> Id { + Id::unique(("delivery-review-locate", &self.origin, self.account["id"].as_str(), self.owner_doc)) + } + + pub(in crate::jiansun) fn finish_delivery_hint(&mut self, app: &PhotocraftApp, ui: &Ui) { + if self.product_view_pending() || self.busy.as_deref() == Some("slot-skeleton") { + return; + } + let Some((output, hint)) = ui.data_mut(|data| data.remove_temp::<(String, Value)>(self.delivery_hint_id())) else { return }; + let workflow = &self.template_workflow; + if workflow["outputId"] != output || hint["variantId"].is_string() && hint["variantId"] != workflow["variantId"] { + self.error = "未能打开这条提示对应的成品".into(); + return; + } + let variant = workflow["variantId"].as_str(); + let native_id = hint["nativeLayerId"].as_u64().or(hint["layerId"].as_u64()) + .or_else(|| hint["layerId"].as_str().and_then(|id| id.strip_prefix('L').unwrap_or(id).parse().ok())) + .filter(|&id| app.session.active().is_some_and(|state| state.doc.layer(photocraft_doc::LayerId(id)).is_some())); + let pages = || workflow["outputs"].as_array().into_iter().flatten().filter(|page| page["outputId"] == output); + let page = hint["pageId"].as_str().or(hint["screenId"].as_str()) + .or_else(|| hint["screenIndex"].as_u64().and_then(|index| pages().nth(index as usize)?["documentId"].as_str())); + let slot = workflow["slots"].as_array().into_iter().flatten() + .filter(|slot| slot["outputId"] == output && (slot["variantId"].is_null() || slot["variantId"].as_str() == variant)) + .find(|slot| match hint["slotId"].as_str() { + Some(id) => slot["id"] == id, + None => page.is_some_and(|page| slot["documentId"] == page), + }) + .and_then(|slot| slot["id"].as_str()); + if native_id.is_some() || slot.is_some() { + self.canvas_locate(json!({"kind":"selection","outputId":output,"productVariantId":variant, + "targets":[{"nativeLayerId":native_id,"slotId":slot,"locateImageSlot":page.is_none() && native_id.is_none()}]})); + ui.ctx().request_repaint(); + } else if ["slotId", "layerId", "nativeLayerId", "pageId", "screenId", "screenIndex"] + .iter().any(|key| !hint[*key].is_null()) + { + self.error = "当前成品中已找不到该核对位置".into(); + } + } + + pub(in crate::jiansun) fn workflow_card_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + let receipt_id = Id::unique(("workflow-approved", &self.origin, self.account["id"].as_str(), self.project_context["localId"].as_str(), self.owner_doc)); + let receipt = ui.data(|data| data.get_temp::<(Value, usize)>(receipt_id)); + let proposal = match self.workflow.proposal().cloned() { Some(proposal) => proposal, None => match &receipt { Some((proposal, _)) => proposal.clone(), None => return } }; + let resolved = receipt.as_ref().filter(|(previous, _)| previous == &proposal).map(|(_, chosen)| *chosen); + let intent = proposal["intent"].as_str().unwrap_or(""); + let label = match intent { + "analyze" => "开始分析", + "selling_points" => "生成一批", + "plan" => "生成方案", + "review_plan" => "查看方案", + "install_template" => "载入模板", + "slot_copy" => "生成文案", + "apply_copy" => "回填文案", + "generate_candidate" => "生成此候选", + "review_candidates" => "查看候选", + "fill_output" => "回填画布", + "export" => "导出…", + "export_psd" => "导出 PSD…", + _ => return, + }; + let running = self.busy.is_some() || self.pi_run.is_some() || self.saving.is_some() || !self.queue.is_empty() || self.pending_image.is_some(); + let current = workflow_bridge::proposal_current(self, app); + let unknown = + self.unknown && matches!(intent, "analyze" | "selling_points" | "plan" | "install_template" | "slot_copy" | "apply_copy" | "generate_candidate"); + let ready = !running && current && !unknown; + self.panel_geometry["workflowReady"] = json!(ready); + let scope = workflow_scope(&proposal, &self.template_workflow); + ui.add_space(10.0); + let state = if let Some(choice) = resolved { timeline::ApprovalState::Decided(choice) } + else if unknown { timeline::ApprovalState::Blocked("结果待核查") } + else if !current { timeline::ApprovalState::Blocked("内容已更新") } + else { timeline::ApprovalState::Awaiting }; + let card = timeline::approval_card(ui, receipt_id.with(proposal.to_string()), timeline::ApprovalCard { + title: proposal["title"].as_str().unwrap_or(label), scope: (!scope.is_empty()).then_some(scope.as_str()), + instruction: proposal["instruction"].as_str().filter(|s| !s.trim().is_empty()), + action: label, opt_out: "暂不处理", state, + }, ready, self.reduce_motion); + if resolved.is_none() { + if ready && ui.clip_rect().contains_rect(card.action.rect) { + self.panel_geometry["workflowAccept"] = rect_value(card.action.rect); + } + if card.action.clicked() { + match self.accept_workflow(app) { + Ok(_) => { ui.data_mut(|data| data.insert_temp(receipt_id, (proposal.clone(), 0_usize))); } + Err(error) => self.error = error, + } + } + if let Some(response) = card.opt_out { + if ui.clip_rect().contains_rect(response.rect) { self.panel_geometry["workflowDismiss"] = rect_value(response.rect); } + if response.clicked() { + self.workflow_dismiss(); + ui.data_mut(|data| data.insert_temp(receipt_id, (proposal, 1_usize))); + } + } + } + if running { + ui.horizontal(|ui| { + super::stitch_ui::ai_loader(ui, ui.scope_id().with("workflow-saving"), true, self.reduce_motion); + if self.saving.is_some() { ui.label("正在保存…"); } + }); + } + self.panel_geometry["workflowCard"] = rect_value(card.rect); + if !running && self.workflow.take_card_reveal() { + ui.scroll_to_rect_animation(card.rect, Some(Align::BOTTOM), egui::style::ScrollAnimation::none()); + } + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/production_head_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/production_head_ui.rs new file mode 100644 index 00000000..fc875aed --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/production_head_ui.rs @@ -0,0 +1,192 @@ +use super::super::{Duration, PhotocraftApp, Ui, Value, Workspace, agent_motion, json, stitch_state::{RunState, WorkerStage}, stitch_timeline::{self as timeline, GoalProgressPanel}, template_preparation}; +use super::rect_value; +use super::models::usage_count; +use super::production_reply_ui::production_image_cells; +use egui::{Align, Id, Layout, Rect, Response, vec2}; + +impl Workspace { + pub(in crate::jiansun) fn production_head_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui) { + use super::agent_stream::Cell; + use timeline::{GoalBudget, GoalSlot, GoalStage, StagePhase, WorkerState}; + + let id = Id::unique(("jiansun-production-head", &self.origin, self.account["id"].as_str(), self.owner_doc)); + let run = self.product_production.as_ref(); + let preparing = self.product_start_queued.then(|| template_preparation::state(&self.template_progress)); + let waiting = run.is_some_and(|run| run.waiting_to_resume()) || self.template_progress["phase"] == "waiting" && preparing.is_some(); + let use_stream = preparing.is_none() && run.is_none_or(|run| run.showing_agent_progress()); + let progress = self.workflow.production_progress(); + let title = use_stream.then(|| progress["heading"].as_str().or_else(|| self.stream_reply.lines().next())).flatten() + .filter(|line| !line.is_empty()).map(str::to_owned) + .or_else(|| preparing.as_ref().map(|(label, _)| label.clone())) + .or_else(|| run.and_then(|run| run.progress_label())) + .unwrap_or_else(|| "正在准备详情页".into()); + let title = title.trim_start_matches("小壹").trim_start_matches([' ', '·']); + let show_work = use_stream || run.is_some_and(|run| run.waiting_for_originals()); + let source = |key: &str| progress[key].as_array().filter(|_| show_work).map(Vec::as_slice).unwrap_or_default(); + let image_source = source("pictureCells"); + let copy_source = source("copyCells"); + let cells_of = |rows: &[Value]| rows.iter().map(|cell| match cell["state"].as_str() { + Some("verified") => Cell::Verified, + Some("filled") => Cell::Filled, + Some("preview") => Cell::Preview, + _ => Cell::Empty, + }).collect::>(); + let mut image_cells = cells_of(image_source); + production_image_cells(app, self, progress, &mut image_cells); + let copy_cells = cells_of(copy_source); + let workers = if show_work { self.production_workers() } else { Vec::new() }; + let worker_states: Vec<_> = workers.iter().map(|worker| WorkerState { + number: worker.number, stage: worker.stage, slot: &worker.slot, active: worker.active, + }).collect(); + let filled = image_cells.iter().filter(|cell| cell.filled()).count(); + let current_counts = (if image_cells.is_empty() { progress["rendered"].as_u64().unwrap_or(0) as usize } else { filled }, + if image_cells.is_empty() { progress["total"].as_u64().unwrap_or(0) as usize } else { image_cells.len() }); + let fraction = preparing.as_ref().and_then(|(_, fraction)| *fraction).or_else(|| + (show_work && current_counts.1 > 0).then(|| current_counts.0 as f32 / current_counts.1 as f32)); + let working = run.and_then(|run| run.working_output()); + let current = working.as_ref().and_then(|row| row["outputId"].as_str()) + .or_else(|| show_work.then(|| progress["outputId"].as_str()).flatten()) + .or_else(|| (preparing.is_some() || self.pi_product_production && fraction.is_some()).then_some("detail")); + let requested = run.map(|run| run.requested_outputs()); + let pending = run.map(|run| run.pending_outputs()); + let contains = |value: &Option, output: &str| value.as_ref().and_then(Value::as_array) + .is_some_and(|rows| rows.iter().any(|row| row["outputId"] == output)); + let outputs = [("detail", "详情"), ("main_images", "主图"), ("sku_images", "SKU")]; + let pipeline: Vec<_> = outputs.iter().filter(|(output, _)| requested.is_none() || contains(&requested, output)) + .map(|(output, name)| (*name, if current == Some(*output) { StagePhase::Current(fraction.unwrap_or(0.0)) } + else if contains(&requested, output) && !contains(&pending, output) { StagePhase::Done } + else { StagePhase::Queued })).collect(); + let slots = || image_source.iter().zip(&image_cells).map(|(row, cell)| GoalSlot { + label: row["label"].as_str().unwrap_or("图位"), + state: match workers.iter().find(|worker| worker.active && worker.row["slotId"] == row["slotId"]).map(|worker| worker.stage) { + Some(WorkerStage::Generating) => timeline::SlotState::Generating, + Some(WorkerStage::Reviewing) => timeline::SlotState::Reviewing, + _ if row["state"] == "failed" => timeline::SlotState::Failed, + _ if cell.filled() => timeline::SlotState::Done, + _ => timeline::SlotState::Queued, + }, + }).collect(); + let stages: Vec<_> = outputs.iter().filter(|(_, name)| pipeline.iter().any(|(shown, _)| shown == name)) + .map(|(output, name)| { + let selected = current == Some(*output); + let (done, total, unit) = if selected && show_work { (current_counts.0, current_counts.1, "图位") } + else { (usize::from(pipeline.contains(&(*name, StagePhase::Done))), 1, "份") }; + GoalStage { name, done, total, unit, elapsed: None, tokens: None, + waiting_canvas: self.workflow.waiting_canvas(output), + slots: if selected && show_work { slots() } else { Vec::new() } } + }).collect(); + let head = super::production_controls::HeadControls::read(&self.production_control_state()); + let resume_ready = self.can_resume_product(); + let budget = if let Some(run) = run { + GoalBudget::Time { elapsed: run.elapsed(), limit: None } + } else if let Some(used) = usage_count(&progress["tokensUsed"]) { + GoalBudget::Tokens { used, limit: usage_count(&progress["tokenBudget"]) } + } else { + GoalBudget::Unreported + }; + let clock_paused = run.is_some_and(|run| run.clock_paused()); + let mut controls = head.view(resume_ready); + if clock_paused && matches!(controls.stop, timeline::StopPhase::Idle | timeline::StopPhase::Delivered) { + controls.stop = timeline::StopPhase::Paused; + } + let state = if clock_paused { RunState::WaitingResume } + else if self.pi_ui_waiting() { RunState::WaitingUser } + else if waiting { RunState::WaitingResume } else { RunState::Running }; + ui.add_space(10.0); + let full = ui.available_rect_before_wrap(); + let inner = Rect::from_min_max(full.left_top() + vec2(16.0, 0.0), full.right_bottom() - vec2(16.0, 0.0)); + let mut column = ui.new_child(egui::UiBuilder::new().id_salt(id).max_rect(inner).layout(Layout::top_down(Align::Min))); + column.spacing_mut().item_spacing.y = 4.0; + let result = timeline::goal_progress_panel(&mut column, id, GoalProgressPanel { + title, state, budget, pipeline: &pipeline, image_cells: &image_cells, copy_cells: ©_cells, + workers: &worker_states, roadmap: Some(&stages), controls: run.is_some().then_some(controls), + }, self.reduce_motion || self.product_view_detached(), |index| { + let row = &image_source[index]; + let status = match image_cells[index] { Cell::Verified => "已核验", Cell::Filled => "已上画布", Cell::Preview => "有候选待采纳", Cell::Empty => "待填" }; + format!("图片 {} · {} · {status}", index + 1, row["label"].as_str().unwrap_or("图位")) + }); + if let GoalBudget::Time { elapsed, .. } = budget + && !clock_paused + && !agent_motion::hidden(ui, result.rect) + { + // 首分钟显示秒,之后只在分钟数变化时刷新。 + let seconds = elapsed.as_secs(); + let next = if seconds < 60 { 1 } else { 60 - seconds % 60 }; + ui.ctx().request_repaint_after(Duration::from_secs(next)); + } + let worker_geometry = result.workers.into_iter().map(|mut row| { + if let Some(worker) = workers.iter().find(|worker| row["worker"] == worker.number) { + row["step"] = json!(worker.step); + row["review"] = json!(worker.review); + } + row + }).collect::>(); + let located = result.slot_clicked.and_then(|index| image_source.get(index)).filter(|row| row["slotId"].is_string()) + .map(|row| json!({"kind":"slot","slotId":row["slotId"],"outputId":progress["outputId"],"productVariantId":progress["variantId"]})); + self.panel_geometry["productionProgressTag"] = rect_value(result.toggle.rect); + self.panel_geometry["productionTitle"] = rect_value(result.title); + self.panel_geometry["productionProgress"] = rect_value(result.rect); + self.panel_geometry["productionShelf"] = rect_value(result.rect); + self.panel_geometry["productionProgressRail"] = result.rail.map_or(Value::Null, rect_value); + self.panel_geometry["productionImageCells"] = result.image_cells; + self.panel_geometry["productionCopyCells"] = result.copy_cells; + self.panel_geometry["productionWorkers"] = json!(worker_geometry); + if let Some(target) = located { self.canvas_locate(target); } + if let Some(stop) = result.stop { + self.panel_geometry["taskStop"] = rect_value(stop.rect); + if stop.clicked() { self.abort_chat_run(); } + } + if let Some(controls) = &result.controls { + use timeline::StopMode; + // "停止"沿用外部脚本已在读的 taskStop,点开是停止菜单;"只暂停"直接执行,另外两项先确认。 + let choice = |mode| controls.choices.iter().find(|(shown, _)| *shown == mode).map_or(Value::Null, |(_, rect)| rect_value(*rect)); + self.panel_geometry["taskStop"] = rect_value(controls.stop.rect); + self.panel_geometry["productionResume"] = controls.resume.as_ref().map_or(Value::Null, |resume| rect_value(resume.rect)); + self.panel_geometry["productionStopPause"] = choice(StopMode::Pause); + self.panel_geometry["productionStopEnd"] = choice(StopMode::End); + self.panel_geometry["productionStopDeliver"] = choice(StopMode::Deliver); + self.panel_geometry["productionStopStatus"] = controls.status.map_or(Value::Null, rect_value); + self.panel_geometry["productionBudget"] = controls.budget.map_or(Value::Null, rect_value); + if controls.resume.as_ref().is_some_and(Response::clicked) { + self.resume_product_production(app); + } + match controls.chosen { + Some(StopMode::Pause) => super::production_controls::queue_action(ui.ctx(), "production-stop", + super::production_controls::stop_input(StopMode::Pause)), + Some(mode) => super::production_controls::open_stop_confirm(ui.ctx(), mode), + None => {} + } + } + self.stop_confirm_ui(ui, head.phase().ready()); + ui.advance_cursor_after_rect(column.min_rect()); + ui.add_space(2.0); + } + + + pub(in crate::jiansun) fn production_assets_ui(&mut self, ui: &mut Ui, doc: u64) { + if super::stitch_ui::action_button(ui, "打开本地文件夹", super::stitch_ui::ButtonRole::Quiet, true).clicked() { + self.open_generated_folder(doc); + } + if let Some((id, message)) = &self.canvas_workspace.generated_folder_status + && *id == doc + { + super::stitch_ui::status_label(ui, message, super::stitch_ui::StatusTone::Neutral); + } + let mut locate = None; + egui::ScrollArea::vertical().id_salt("returned-assets").show(ui, |ui| { + let width = ui.available_width(); + let columns = ((width + 8.0) / 128.0).floor().max(1.0) as usize; + let cell = ((width + 8.0) / columns as f32 - 8.0).min(144.0); + egui::Grid::new("returned-assets-grid").num_columns(columns) + .min_col_width(cell).max_col_width(cell).spacing(vec2(8.0, 8.0)) + .show(ui, |ui| { + for (index, image) in self.production_assets().enumerate() { + if let Some(target) = self.image_result(ui, image, cell, None) { locate = Some(target); } + if (index + 1) % columns == 0 { ui.end_row(); } + } + }); + }); + if let Some(target) = locate { self.canvas_locate(target); } + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/production_reply_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/production_reply_ui.rs new file mode 100644 index 00000000..4e558fbc --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/production_reply_ui.rs @@ -0,0 +1,154 @@ +use super::super::{PhotocraftApp, Workspace}; +use super::super::{Arc, Ui, Value}; + +/// shared native label retains selectable text and its existing rich styling. +pub(in crate::jiansun) fn production_turn(command: Option<&str>) -> bool { + command.is_some_and(|command| { + matches!(command, "制作详情、主图和 SKU" | "继续整套制作" | "一键制作整套详情页") + || ["制作详情页 ·", "制作主图 ·", "制作 SKU ·"].iter().any(|prefix| command.starts_with(prefix)) + }) +} + +pub(in crate::jiansun) fn production_reply_text(text: &str, streaming: bool, workflow: &Value) -> String { + let mut labels = std::collections::HashMap::new(); + let mut insert = |id, label| { + labels.entry(id).and_modify(|current| { + if *current != Some(label) { + *current = None; + } + }).or_insert(Some(label)); + }; + for output in workflow["outputs"].as_array().into_iter().flatten() { + if let (Some(id), Some(name)) = (output["documentId"].as_str(), output["name"].as_str()) { + insert(id, name); + } + for field in output["fields"].as_array().into_iter().flatten() { + if let (Some(id), Some(label)) = (field["fieldId"].as_str(), field["label"].as_str()) { + insert(id, label); + } + } + } + let tool_tags = [("", ""), ("", "")]; + let mut visible = String::new(); + let mut remaining = text; + while let Some((index, start, end)) = tool_tags.iter() + .filter_map(|&(start, end)| remaining.find(start).map(|index| (index, start, end))) + .min_by_key(|&(index, _, _)| index) + { + visible.push_str(&remaining[..index]); + let body = &remaining[index + start.len()..]; + remaining = body.split_once(end).map_or("", |(_, tail)| tail); + } + if streaming && let Some(index) = remaining.rfind('<') + && tool_tags.iter().any(|(tag, _)| tag.starts_with(&remaining[index..])) + { + remaining = &remaining[..index]; + } + visible.push_str(remaining); + let text = visible.as_str(); + let mut value = String::with_capacity(text.len()); + let mut chars = text.char_indices().peekable(); + while let Some((start, c)) = chars.next() { + let is_word = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'); + if !is_word(c) { + value.push(c); + continue; + } + while chars.next_if(|&(_, c)| is_word(c)).is_some() {} + let end = chars.peek().map_or(text.len(), |&(end, _)| end); + let token = &text[start..end]; + if token.len() >= 16 && token.bytes().all(|ch| ch.is_ascii_hexdigit()) && token.bytes().any(|ch| ch.is_ascii_alphabetic()) { + value.push_str("内部编号"); + continue; + } + value.push_str(labels.get(token).copied().flatten().unwrap_or(match token { + "sources" => "资料来源", + "links" => "图文对应关系", + _ => crate::client_brand::reply_word(token), + })); + } + value.replace("分句编号", "句子对应关系").replace("分句索引", "句子对应关系") +} + +pub(in crate::jiansun) fn read_delivery_manifest(ui: &Ui, path: &str) -> Option> { + let folder = std::path::Path::new(path); + if !folder.is_absolute() { return None; } + let file = folder.join("交付清单.json"); + let metadata = file.metadata().ok()?; + let stamp = (metadata.modified().ok()?, metadata.len()); + let id = ui.scope_id().with("saved-delivery-manifest"); + type Cache = (std::path::PathBuf, (std::time::SystemTime, u64), Arc); + if let Some((_, _, manifest)) = ui.data(|data| data.get_temp::(id)) + .filter(|(cached_file, cached_stamp, _)| cached_file == &file && *cached_stamp == stamp) + { + return Some(manifest); + } + let manifest: Value = serde_json::from_slice(&std::fs::read(&file).ok()?).ok()?; + manifest["allOutputsCompleted"].as_bool()?; + let manifest = Arc::new(manifest); + ui.data_mut(|data| data.insert_temp(id, (file, stamp, Arc::clone(&manifest)))); + Some(manifest) +} + +pub(in crate::jiansun) fn recover_delivery_manifest(ui: &Ui, checkpoint: &Value) -> Option<(String, Arc)> { + let root = checkpoint["deliveryDir"].as_str()?; + if let Some(manifest) = read_delivery_manifest(ui, root) + && (checkpoint["deliveryId"].is_null() || manifest["deliveryId"] == checkpoint["deliveryId"]) + { + return Some((root.to_owned(), manifest)); + } + let delivery_id = checkpoint["deliveryId"].as_str()?; + let dir = std::path::Path::new(root); + if !dir.is_absolute() { return None; } + let stamp = dir.metadata().ok()?.modified().ok()?; + let id = ui.scope_id().with(("recover-delivery-path", root, delivery_id)); + type Cache = (std::time::SystemTime, Option); + let path = if let Some((_, path)) = ui.data(|data| data.get_temp::(id)).filter(|(time, _)| *time == stamp) { + path + } else { + let path = dir.read_dir().ok()?.flatten().filter_map(|entry| { + entry.file_type().ok()?.is_dir().then(|| entry.path().into_os_string().into_string().ok()).flatten() + }).find(|path| read_delivery_manifest(ui, path).is_some_and(|manifest| manifest["deliveryId"] == delivery_id)); + ui.data_mut(|data| data.insert_temp(id, (stamp, path.clone()))); + path + }?; + let manifest = read_delivery_manifest(ui, &path)?; + (manifest["deliveryId"] == delivery_id).then_some((path, manifest)) +} + +pub(in crate::jiansun) fn production_image_cells( + app: &PhotocraftApp, workspace: &Workspace, progress: &Value, cells: &mut [super::agent_stream::Cell], +) { + use super::agent_stream::Cell; + let Some((target, workflow)) = workspace.production_canvas(app) else { return }; + let Some(variant) = progress["variantId"].as_str() else { return }; + if workflow["canvasFirst"] != true || workflow["outputId"] != progress["outputId"] || workflow["variantId"] != variant { + return; + } + let Some(slots) = workflow["slots"].as_array() else { return }; + for (row, state) in progress["pictureCells"].as_array().into_iter().flatten().zip(cells) { + let Some(slot_id) = row["slotId"].as_str() else { continue }; + let Some(id) = slots.iter().find(|slot| slot["id"] == slot_id && slot["outputId"] == progress["outputId"] + && slot["variantId"] == variant).and_then(|slot| slot["nativeLayerId"].as_u64()) else { continue }; + let id = photocraft_doc::LayerId(id); + let visible = target.doc.layer(id).is_some_and(|layer| layer.visible && match &layer.content { + photocraft_doc::LayerContent::Smart(smart) => !matches!(&smart.source, + photocraft_doc::SmartSource::Embedded { file_name, .. } if file_name == "template-empty.png"), + photocraft_doc::LayerContent::Raster(_) => true, + _ => false, + }); + *state = if visible && *state == Cell::Verified + && super::canvas_workspace::adopted(&target.doc, slot_id, variant).is_some() { + Cell::Verified + } else if visible { + Cell::Filled + } else if app.has_slot_preview(&target.doc, id) || slots.iter().any(|slot| + slot["id"] == slot_id && slot["variantId"] == variant && slot["candidates"].as_array().into_iter() + .flatten().any(|candidate| candidate["status"] == "complete")) { + Cell::Preview + } else { + Cell::Empty + }; + } +} + diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/reference_shelf_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/reference_shelf_ui.rs new file mode 100644 index 00000000..dd37b157 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/reference_shelf_ui.rs @@ -0,0 +1,95 @@ +use super::super::{PhotocraftApp, RichText, Ui, Value, Workspace, composer_references, json, reference_media}; +use super::rect_value; +use super::artifact_preview_ui::activate_reference; +use super::turn_ui::{paint_reference_thumbnail, subject_label}; +use egui::{Frame, Response, vec2}; + +pub(in crate::jiansun) const REFERENCE_WIDTH: f32 = 132.0; +pub(in crate::jiansun) const REFERENCE_GAP: f32 = 4.0; + +pub(in crate::jiansun) fn reference_columns(width: f32) -> usize { + ((width + REFERENCE_GAP) / (REFERENCE_WIDTH + REFERENCE_GAP)).floor().max(1.0) as usize +} + +pub(in crate::jiansun) fn reference_shelf_height(count: usize, width: f32) -> f32 { + if count == 0 { return 0.0; } + let rows = count.div_ceil(reference_columns(width)).min(3); + rows as f32 * (24.0 + REFERENCE_GAP) - REFERENCE_GAP + 6.0 +} + + +impl Workspace { + pub(in crate::jiansun) fn reference_shelf(&mut self, app: &PhotocraftApp, ui: &mut Ui, references: &[Value], height: f32) { + let mut detach = None; + let mut target = None; + let mut rects = Vec::new(); + let columns = reference_columns(ui.available_width()); + egui::ScrollArea::vertical().id_salt("composer-reference-scroll").max_height(height) + .auto_shrink([false, true]).show(ui, |ui| { + let width = REFERENCE_WIDTH.min(ui.available_width()).max(1.0); + ui.spacing_mut().item_spacing = vec2(REFERENCE_GAP, REFERENCE_GAP); + ui.spacing_mut().interact_size.y = 24.0; + for (row, items) in references.chunks(columns).enumerate() { + ui.horizontal(|ui| { + for (column, reference) in items.iter().enumerate() { + let index = row * columns + column; + ui.push_id(index, |ui| { + let label = subject_label(reference, &self.template_workflow); + let glyph = if composer_references::image_reference(reference) { "image" } + else if matches!(reference["component"].as_str(), Some("pixelMask" | "vectorMask")) { "layer-mask" } + else if reference["layerKind"] == "Type" { "type" } else { "layers" }; + let task = reference["taskId"].as_str(); + let thumbnail = task.and_then(|id| self.agent_images.peek(id)).cloned(); + let (body, remove) = super::stitch_ui::reference_chip_with_preview(ui, glyph, &label, &label, 0.0, width, thumbnail.as_ref()); + let enter = |response: &Response| response.clicked() || response.has_focus() + && ui.input(|i| i.key_pressed(egui::Key::Enter) || i.key_pressed(egui::Key::Space)); + if enter(&remove) { detach = Some(index); } + if enter(&body) { target = activate_reference(ui, reference, None); } + if ui.is_rect_visible(body.rect) { + if let Some(task) = task { self.agent_images.mark_visible(task); } + let rect = body.rect.union(remove.rect); + rects.push(rect_value(rect)); + if index == 0 { + self.panel_geometry["subject"] = rect_value(rect); + self.panel_geometry["referenceRemove"] = rect_value(remove.rect); + } + } + if body.hovered() || body.has_focus() { + let thumbnail = thumbnail.or_else(|| reference_media::hover_image(app, ui.ctx(), reference)); + let mut tooltip = egui::Tooltip::for_widget(&body); + tooltip.popup = tooltip.popup.style(super::stitch_ui::scoped_popup_style(ui)); + if let Some(texture) = &thumbnail { + tooltip.popup = tooltip.popup + .align(egui::RectAlign::TOP_START) + .gap(6.0) + .width(148.0) + .frame(Frame::NONE); + tooltip.show(|ui| { + let rect = paint_reference_thumbnail(ui, texture, vec2(148.0, 144.0)); + self.panel_geometry["subjectTooltip"] = rect_value(rect); + }); + } else { + tooltip.popup = tooltip.popup.frame(super::stitch_ui::surface_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Menu).inner_margin(egui::Margin::same(8))); + tooltip.show(|ui| { + ui.set_max_width(148.0); + ui.add(egui::Label::new(RichText::new(label).size(12.0)).wrap()); + }); + } + } + }); + } + }); + } + }); + self.panel_geometry["referenceChips"] = json!(rects); + if let Some(index) = detach { + if let Err(error) = self.composer_reference_remove(app, index) { self.error = error; } + self.focus_composer = true; + } else if let Some(target) = target + && let Err(error) = self.locate_composer_reference(app, target) + { + self.error = error; + } + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/storage_events.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/storage_events.rs new file mode 100644 index 00000000..e2910ae2 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/storage_events.rs @@ -0,0 +1,178 @@ +use super::super::agent_panel::storage_settings_ui; +use super::super::{Value, Workspace}; + +impl Workspace { + pub(in crate::jiansun) fn receive_storage_event(&mut self, ctx: &egui::Context, method: &str, result: Result) { + let apply_migration_patch = |mig: &mut storage_settings_ui::MigrationStateView, patch: &Value| { + if let Some(phase) = patch["phase"].as_str() { + mig.phase = storage_settings_ui::MigrationPhase::parse(phase); + } + if let Some(target) = patch["targetRoot"].as_str().filter(|s| !s.is_empty()) { + mig.target_root = target.to_owned(); + } + if patch.get("targetFreeBytes").is_some() { + mig.target_free_bytes = patch["targetFreeBytes"].as_u64(); + } + if let Some(req) = patch["requiredBytes"].as_u64() { + mig.required_bytes = req; + } + if let Some(copied) = patch["copiedBytes"].as_u64() { + mig.copied_bytes = copied; + } + if let Some(total) = patch["totalBytes"].as_u64() { + mig.total_bytes = total; + } + if patch.get("validationError").is_some() { + mig.validation_error = patch["validationError"].as_str().filter(|s| !s.is_empty()).map(str::to_owned); + } + if let Some(warnings) = patch["validationWarnings"].as_array() { + mig.validation_warnings = warnings.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(); + } + if let Some(blocking) = patch["blockingProjects"].as_array() { + mig.blocking_projects = blocking.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(); + } else if !matches!(mig.phase, storage_settings_ui::MigrationPhase::ReadyToSwitch | storage_settings_ui::MigrationPhase::Idle) { + mig.blocking_projects.clear(); + } + if let Some(steps) = patch.get("switchSteps").or_else(|| patch.get("steps")).and_then(Value::as_array) { + mig.switch_steps = steps + .iter() + .map(|row| storage_settings_ui::SwitchStep { + id: row["id"].as_str().unwrap_or_default().to_owned(), + label: row["label"].as_str().unwrap_or_default().to_owned(), + state: storage_settings_ui::SwitchStepState::parse( + row["state"].as_str().or_else(|| row["status"].as_str()).unwrap_or("pending"), + ), + }) + .collect(); + } + if patch.get("error").is_some() { + mig.error = patch["error"].as_str().filter(|s| !s.is_empty()).map(str::to_owned); + } + if patch.get("rollbackNote").is_some() { + mig.rollback_note = patch["rollbackNote"].as_str().filter(|s| !s.is_empty()).map(str::to_owned); + } + }; + + match method { + "storage-status" => match result { + Ok(val) if val.get("mode").is_some() => { + let view = storage_settings_ui::StorageStatusView::from_json(&val); + storage_settings_ui::set_status(ctx, view); + if val["autoOpenReleaseModal"] == true { + storage_settings_ui::with_machine_state(ctx, |state| { + state.migrate_modal_open = true; + }); + } + } + Ok(_) => {} + Err(error) => { + storage_settings_ui::with_machine_state(ctx, |state| { + state.status.status_text = Some(error); + state.status.status_is_error = true; + }); + } + }, + "storage-status-refresh" => {} + "storage-scan" => match result { + Ok(val) => storage_settings_ui::set_scan(ctx, storage_settings_ui::StorageScanView::from_json(&val)), + Err(error) => { + storage_settings_ui::with_machine_state(ctx, |state| { + state.scan.scanning = false; + state.scan.error = Some(error); + }); + } + }, + "storage-cleanup" => match result { + Ok(val) => { + let mut scan = storage_settings_ui::StorageScanView::from_json(&val); + scan.scanning = false; + scan.cleanup_running = false; + storage_settings_ui::set_scan(ctx, scan); + } + Err(error) => { + storage_settings_ui::with_machine_state(ctx, |state| { + state.scan.cleanup_running = false; + state.scan.cleanup_result = Some(storage_settings_ui::CleanupResultView { + freed_bytes: 0, + message: String::new(), + error: Some(error), + }); + }); + } + }, + "storage-migrate" => match result { + Ok(val) => { + if val["requiresExit"] == true { + self.storage_switch_pending = true; + self.storage_restart_requested = true; + storage_settings_ui::with_machine_state(ctx, |state| { + apply_migration_patch(&mut state.status.migration, &val); + state.status.migration.phase = storage_settings_ui::MigrationPhase::Switching; + state.migrate_modal_open = true; + }); + } else if let Some(picked) = val["pickedRoot"].as_str() { + storage_settings_ui::with_machine_state(ctx, |state| { + state.target_input = picked.to_owned(); + if val["migration"].is_object() { + apply_migration_patch(&mut state.status.migration, &val["migration"]); + } + }); + } else if val["migration"].is_object() { + storage_settings_ui::with_machine_state(ctx, |state| { + apply_migration_patch(&mut state.status.migration, &val["migration"]); + }); + } else if val["deferred"] == true { + storage_settings_ui::with_machine_state(ctx, |state| { + state.migrate_modal_open = false; + }); + } else if val["cancelled"] == true { + storage_settings_ui::with_machine_state(ctx, |state| { + if state.status.migration.phase.is_non_closable() { + state.status.migration.phase = storage_settings_ui::MigrationPhase::ReadyToSwitch; + } + }); + } else if val["phase"].is_string() { + storage_settings_ui::with_machine_state(ctx, |state| { + apply_migration_patch(&mut state.status.migration, &val); + }); + } + } + Err(error) => { + storage_settings_ui::with_machine_state(ctx, |state| { + if matches!( + state.status.migration.phase, + storage_settings_ui::MigrationPhase::Idle | storage_settings_ui::MigrationPhase::Validating + ) { + state.status.migration.phase = storage_settings_ui::MigrationPhase::Idle; + state.status.migration.validation_error = Some(error); + } else { + state.status.migration.phase = storage_settings_ui::MigrationPhase::Failed; + state.status.migration.error = Some(error); + } + }); + } + }, + "storage-migrate-progress" => match result { + Ok(val) => { + storage_settings_ui::with_machine_state(ctx, |state| { + apply_migration_patch(&mut state.status.migration, &val); + if state.target_input.is_empty() && !state.status.migration.target_root.is_empty() { + state.target_input = state.status.migration.target_root.clone(); + } + if state.status.migration.phase.is_non_closable() { + state.migrate_modal_open = true; + } + }); + } + Err(error) => { + storage_settings_ui::with_machine_state(ctx, |state| { + state.status.migration.phase = storage_settings_ui::MigrationPhase::Failed; + state.status.migration.error = Some(error); + }); + } + }, + _ => {} + } + ctx.request_repaint(); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/tests.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/tests.rs new file mode 100644 index 00000000..6484b2d8 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/tests.rs @@ -0,0 +1,6023 @@ +use super::*; +use egui::Color32; + +#[cfg(test)] +fn tool_activity_label(event: &Value) -> Option<(String, super::stitch_ui::StatusTone)> { + use super::stitch_state::{ToolStatus, tool_label}; + if !is_tool_event(event) { return None; } + let status = ToolStatus::parse(event["status"].as_str().unwrap_or("")); + let tool = tool_label(event["toolName"].as_str().unwrap_or("")); + let mut label = format!("{} · {tool}", status.label()); + // Only a terminal event with an upstream-provided duration gets a timer. + // There is no local clock estimate or implied completion percentage. + if status.timed() + && let Some(ms) = event["durationMs"].as_u64().filter(|ms| *ms <= 9_007_199_254_740_991) + { + label.push_str(&format!(" · {}", duration_text(ms))); + } + Some((label, status.tone().into())) +} + + +#[cfg(test)] +fn activity_morph_id(conversation_id: Id, indices: &[usize]) -> Id { + conversation_id.with(("operations", indices.first().copied().unwrap_or(usize::MAX))) +} + + +/// Size a message to its actual shaped text, capped to the available column. +/// Manual allocation keeps the selectable label and its rounded surface in the +/// same right-aligned rectangle at all sidebar widths and DPI scales. +#[cfg(test)] +fn user_bubble(ui: &mut Ui, text: &str) -> Rect { + user_bubble_with_reveal(ui, text, None, true) +} + + +#[cfg(test)] +fn assistant_reply(ui: &mut Ui, id: Id, text: &str) -> Response { + timeline::reply(ui, id, timeline::Reply { text, streaming: false, animate_final: false }, false) +} + + +#[cfg(test)] +impl Workspace { + /// Content-only viewport for workflow-card unit tests. Production uses the + /// real PhotoCraft dock; its tab switching is tested below. + #[cfg(test)] + pub(in crate::jiansun) fn right(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + self.panel_geometry = json!({}); + egui::Panel::right("agent-workflow-fixture").exact_size(360.0).show(ui, |ui| self.agent_body(app, ui)); + } + + + #[cfg(test)] + pub(in crate::jiansun) fn seed_notifications_for_test(&self, ctx: &egui::Context, entries: &[&str]) { + if let Some(id) = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc) { + let mut history = AgentNotifications::default(); + for entry in entries { + history.add(entry); + } + ctx.data_mut(|data| data.insert_temp(id, history)); + } + } + +} + + use crate::jiansun::test_support::SettleUi; + use crate::jiansun::Event; + use std::sync::mpsc; + use egui::pos2; + + #[test] + fn production_delivery_card_opens_the_actual_saved_directory() { + use egui_kittest::{Harness, kittest::Queryable}; + + let root = tempfile::tempdir().unwrap(); + let folder = root.path().join("成品"); + std::fs::create_dir(&folder).unwrap(); + let path = folder.to_str().unwrap(); + for (done, full, label) in [(3, true, "打开交付文件夹"), (1, false, "打开导出文件夹")] { + std::fs::write(folder.join("交付清单.json"), json!({"allOutputsCompleted":full,"completedOutputs":done,"totalOutputs":3}).to_string()).unwrap(); + let (mut app, requests) = dock_fixture(); + let (opened, paths) = mpsc::channel(); + app.services.open_folder = Some(Box::new(move |path| { + opened.send(path.to_owned()).unwrap(); + Ok(()) + })); + let workspace = app.jiansun.as_mut().unwrap(); + workspace.product_checkpoint = json!({"deliveryDir": root.path().join("预设目录")}); + workspace.messages.push(json!({ + "role":"assistant", + "productionSummary":{"exported":0,"total":3,"slotCoverage":{"empty":3,"total":3}}, + "productionDelivery":{"state":"bundle_saved","path":path,"allOutputsCompleted":!full} + })); + let mut harness = Harness::builder().with_size(vec2(760.0, 380.0)) + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .build_ui_state(|ui, app: &mut PhotocraftApp| { + let mut workspace = app.jiansun.take().unwrap(); + workspace.production_outcome_ui(ui, false, app); + app.jiansun = Some(workspace); + }, app); + harness.run_steps(3); + harness.get_by_label(path); + harness.get_by_label(label).click(); + harness.run_steps(2); + assert_eq!(paths.try_recv().unwrap(), folder); + assert!(paths.try_recv().is_err()); + assert!(requests.try_recv().is_err()); + } + } + + #[test] + fn paused_production_can_open_the_saved_partial_delivery_from_its_checkpoint() { + use egui_kittest::{Harness, kittest::Queryable}; + + let folder = tempfile::tempdir().unwrap(); + std::fs::write(folder.path().join("交付清单.json"), br#"{"allOutputsCompleted":false}"#).unwrap(); + let (mut app, _) = dock_fixture(); + let (opened, paths) = mpsc::channel(); + app.services.open_folder = Some(Box::new(move |path| { + opened.send(path.to_owned()).unwrap(); + Ok(()) + })); + app.jiansun.as_mut().unwrap().product_checkpoint = json!({ + "phase":"paused", + "partialDelivered":true, + "deliveryDir":folder.path(), + "productionDelivery":{"state":"bundle_saved","allOutputsCompleted":false} + }); + let mut harness = Harness::builder().with_size(vec2(760.0, 380.0)) + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .build_ui_state(|ui, app: &mut PhotocraftApp| { + let mut workspace = app.jiansun.take().unwrap(); + workspace.production_outcome_ui(ui, false, app); + app.jiansun = Some(workspace); + }, app); + harness.run_steps(3); + harness.get_by_label(folder.path().to_str().unwrap()); + harness.get_by_label("打开导出文件夹").click(); + harness.run_steps(2); + assert_eq!(paths.try_recv().unwrap(), folder.path()); + assert!(harness.query_by_label("打开交付文件夹").is_none()); + } + + #[test] + fn production_counts_alone_do_not_confirm_delivery() { + use egui_kittest::{Harness, kittest::Queryable}; + + let folder = tempfile::tempdir().unwrap(); + let (app, _) = dock_fixture(); + let mut harness = Harness::builder().with_size(vec2(760.0, 380.0)) + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .build_ui_state(|ui, app: &mut PhotocraftApp| { + let mut workspace = app.jiansun.take().unwrap(); + workspace.production_outcome_ui(ui, false, app); + app.jiansun = Some(workspace); + }, app); + for path in [Value::Null, json!(folder.path().join("已移走")), json!(folder.path())] { + let workspace = harness.state_mut().jiansun.as_mut().unwrap(); + workspace.messages = vec![json!({ + "role":"assistant", + "productionSummary":{"exported":3,"total":3}, + "productionDelivery":{"state":"bundle_saved","allOutputsCompleted":true,"path":path} + })]; + harness.run_steps(2); + harness.get_by_label("成品交付尚未确认"); + assert!(harness.query_by_label("整套制作已完成 · 已交付 3/3 份").is_none()); + assert!(harness.query_by_label("打开交付文件夹").is_none()); + } + } + + #[test] + fn delivery_review_uses_the_mounted_variant_and_reports_a_missing_layer() { + let (mut workspace, app, _, layer, _) = super::super::canvas_workspace::tests::native_fixture(); + let ctx = egui::Context::default(); + let id = workspace.delivery_hint_id(); + for (native_layer, found) in [(layer, true), (u64::MAX, false)] { + workspace.canvas_workspace.locate_request = None; + ctx.data_mut(|data| data.insert_temp(id, ("detail".to_owned(), json!({"variantId":"wood","nativeLayerId":native_layer})))); + let mut response = ctx.settle_ui(egui::RawInput::default(), |ui| workspace.finish_delivery_hint(&app, ui)); + response.textures_delta.clear(); + if found { + let locate = workspace.canvas_workspace.locate_request.as_ref().unwrap(); + assert_eq!(locate["productVariantId"], "wood"); + assert_eq!(locate["targets"][0]["nativeLayerId"], layer); + } else { + assert!(workspace.canvas_workspace.locate_request.is_none()); + assert_eq!(workspace.error, "当前成品中已找不到该核对位置"); + } + } + } + + #[test] + fn asset_dock_open_folder_requests_the_current_project() { + let (mut workspace, app, requests, _, _) = super::super::canvas_workspace::tests::native_fixture(); + let doc = app.session.active().unwrap().doc.id.0; + let mut harness = egui_kittest::Harness::builder() + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .build_ui(move |ui| workspace.production_assets_ui(ui, doc)); + use egui_kittest::kittest::Queryable; + harness.get_by_label("打开本地文件夹").click(); + harness.run(); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected folder action") }; + assert_eq!(method, "open-generated-folder"); + assert_eq!(input, json!({"doc":doc,"accountId":"owner","origin":"https://local.test"})); + } + + #[test] + fn notification_badges_count_only_new_entries_in_the_current_history() { + let mut history=AgentNotifications::default(); + history.add("导出字体提示");history.add("导出字体提示"); + assert_eq!(history.unread,1); + history.unread=0; + history.add("导出字体提示"); + assert_eq!(history.unread,0,"viewed duplicates do not become unread again"); + history.add("需要核查原请求"); + assert_eq!(history.unread,1); + assert_eq!(history.entries.len(),2); + assert_eq!(AgentNotifications::default().unread,0,"a different account starts with its own history"); + } + + #[test] + fn settings_footer_remains_visible_in_small_viewports_with_key_editor_open() { + for (width, height, scale) in [(960.0, 720.0, 1.0), (1100.0, 760.0, 1.25), (960.0, 720.0, 1.5)] { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + ctx.set_pixels_per_point(scale); + let (mut app, _) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.model_settings = true; + w.key_settings = true; + for time in [0.0, 0.2, 0.6, 1.0, 1.4] { + let mut frame = ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width, height))), + time: Some(time), ..Default::default() + }, |ui| crate::panels::right_dock(&mut app, ui)); + frame.textures_delta.clear(); + } + let w = app.jiansun.as_ref().unwrap(); + let body = geometry(w, "settingsBody"); + assert!(Rect::from_min_size(egui::Pos2::ZERO, vec2(width, height)).contains_rect(body)); + assert!(w.panel_geometry.get("reduceMotion").is_none()); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn settings_glass_keeps_opaque_fallback_inside_paired_markers_on_popup_entry() { + use eframe::egui_wgpu::BackdropMarker; + let ctx = egui::Context::default(); + let mut open = true; + let mut result = None; + // Popup's first pass measures its position without painting. + for _ in 0..2 { + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| { + let anchor = ui.button("settings"); + egui::Popup::from_response(&anchor).frame(egui::Frame::NONE).open_bool(&mut open).show(|ui| { + let frame = super::super::stitch_ui::surface_frame(ui.ctx(), super::super::stitch_ui::SurfaceRole::Dialog); + show_settings_glass(ui, frame, Color32::from_rgb(38, 39, 43), 1.0, 1.0, |ui| { ui.label("settings"); }); + }); + }); + output.textures_delta.clear(); + result = Some(ctx.tessellate(output.shapes, output.pixels_per_point)); + } + let jobs = result.unwrap(); + let markers: Vec<_> = jobs.iter().enumerate().filter_map(|(index, job)| { + let egui::epaint::Primitive::Callback(callback) = &job.primitive else { return None }; + callback.callback.downcast_ref::().map(|marker| (index, marker, callback.rect)) + }).collect(); + assert_eq!(markers.len(), 2); + assert!(markers[0].1.blur_radius_points > 0.0); + assert_eq!(markers[1].1.blur_radius_points, 0.0); + assert_eq!(markers[0].2, markers[1].2); + assert_eq!(markers[1].0, markers[0].0 + 2); + let egui::epaint::Primitive::Mesh(fallback) = &jobs[markers[0].0 + 1].primitive else { panic!("missing fallback mesh") }; + assert!(fallback.vertices.iter().any(|vertex| vertex.color.a() == 255)); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn settings_glass_fallback_fades_with_the_retiring_panel() { + use eframe::egui_wgpu::BackdropMarker; + for opacity in [1.0_f32, 0.5, 0.1, 0.0] { + let ctx = egui::Context::default(); + let output = ctx.settle_ui(egui::RawInput::default(), |ui| { + let frame = super::super::stitch_ui::overlay_frame(ui.ctx(), super::super::stitch_ui::SurfaceRole::Dialog, opacity); + show_settings_glass(ui, frame, Color32::from_rgb(38, 39, 43), opacity, 0.12 + opacity * 0.88, |ui| { ui.label("settings"); }); + }); + let jobs = ctx.tessellate(output.shapes, output.pixels_per_point); + let markers: Vec<_> = jobs.iter().enumerate().filter_map(|(index, job)| { + let egui::epaint::Primitive::Callback(callback) = &job.primitive else { return None }; + callback.callback.downcast_ref::().map(|_| index) + }).collect(); + assert_eq!(markers.len(), 2); + let alpha = jobs[markers[0] + 1..markers[1]].iter().filter_map(|job| { + let egui::epaint::Primitive::Mesh(mesh) = &job.primitive else { return None }; + mesh.vertices.iter().map(|vertex| vertex.color.a()).max() + }).max().unwrap_or(0); + assert!(alpha <= (opacity * 255.0).ceil() as u8, "fallback must follow panel opacity {opacity}"); + if opacity > 0.0 { assert!(alpha > 0); } + } + } + + fn enter_event(modifiers: egui::Modifiers, repeat: bool) -> egui::Event { + egui::Event::Key { key: egui::Key::Enter, physical_key: Some(egui::Key::Enter), pressed: true, repeat, modifiers } + } + + fn enter_release() -> egui::Event { + egui::Event::Key { key: egui::Key::Enter, physical_key: Some(egui::Key::Enter), pressed: false, repeat: false, modifiers: egui::Modifiers::NONE } + } + + fn input_frame(ctx: &egui::Context, text: &mut String, events: Vec) -> bool { + let mut submit = false; + let _ = ctx.settle_ui(egui::RawInput { events, ..Default::default() }, |ui| { + let id = Id::unique("keyboard-acceptance"); + ui.memory_mut(|memory| memory.request_focus(id)); + submit = composer_enter(ui, id); + ui.add(egui::TextEdit::multiline(text).id(id).return_key(egui::KeyboardShortcut::new(egui::Modifiers::SHIFT, egui::Key::Enter))); + }); + submit + } + + #[test] + fn enter_submits_once_and_shift_enter_keeps_a_real_newline() { + let ctx = egui::Context::default(); + let mut text = "调整灯光".to_owned(); + input_frame(&ctx, &mut text, vec![]); + assert!(input_frame(&ctx, &mut text, vec![enter_event(egui::Modifiers::NONE, false)])); + assert!(!text.contains('\n')); + assert!(!input_frame(&ctx, &mut text, vec![enter_event(egui::Modifiers::NONE, true)])); + input_frame(&ctx, &mut text, vec![enter_release()]); + assert!(!input_frame(&ctx, &mut text, vec![enter_event(egui::Modifiers::SHIFT, false)])); + assert!(text.contains('\n')); + } + + #[test] + fn ime_preedit_commit_and_delayed_confirmation_never_submit() { + let ctx = egui::Context::default(); + let mut text = String::new(); + input_frame(&ctx, &mut text, vec![]); + assert!(!input_frame( + &ctx, + &mut text, + vec![egui::Event::Ime(egui::ImeEvent::Preedit { text: "deng".into(), active_range_chars: None }), enter_event(egui::Modifiers::NONE, false)] + )); + assert!(!input_frame(&ctx, &mut text, vec![egui::Event::Ime(egui::ImeEvent::Commit("灯".into())), enter_event(egui::Modifiers::NONE, false)])); + assert!(!input_frame(&ctx, &mut text, vec![enter_event(egui::Modifiers::NONE, false)])); + input_frame(&ctx, &mut text, vec![enter_release()]); + input_frame(&ctx, &mut text, vec![]); + assert!(input_frame(&ctx, &mut text, vec![enter_event(egui::Modifiers::CTRL, false)])); + assert!(text.contains('灯')); + } + + #[test] + fn shared_project_turns_keep_the_original_target_after_later_selection() { + let messages = vec![ + json!({"role":"user","text":"改首屏","target":{"kind":"slot","slotId":"first"}}), + json!({"role":"assistant","kind":"reply","text":"好的","target":{"kind":"slot","slotId":"first"}}), + json!({"role":"user","text":"再看第二屏","target":{"kind":"slot","slotId":"second"}}), + ]; + let grouped = turns(&messages); + assert_eq!(grouped.len(), 2); + assert_eq!(grouped[0].target.unwrap()["slotId"], "first"); + assert_eq!(grouped[1].target.unwrap()["slotId"], "second"); + assert_eq!(subject_label(&json!({"kind":"selection","selectedLayerIds":[1,2,3]}), &Value::Null), "已选 3 个对象"); + } + + #[test] + fn grouped_image_results_keep_their_individual_slot_and_color_targets() { + let messages = vec![ + json!({"role":"user","text":"看看结果"}), + json!({"role":"assistant","kind":"image","taskId":"task-a","slotId":"slot-a","productVariantId":"teak","outputId":"detail"}), + json!({"role":"assistant","kind":"image","taskId":"task-b","slotId":"slot-b","productVariantId":"walnut","outputId":"detail"}), + ]; + let grouped = turns(&messages); + assert_eq!(grouped.len(), 1); + let images: Vec<_> = grouped[0].images().collect(); + assert_eq!(images.len(), 2); + let first = image_location(images[0], "task-a"); + let second = image_location(images[1], "task-b"); + assert_eq!((first["slotId"].as_str(), first["productVariantId"].as_str(), first["candidateId"].as_str()), (Some("slot-a"), Some("teak"), Some("task-a"))); + assert_eq!((second["slotId"].as_str(), second["productVariantId"].as_str(), second["candidateId"].as_str()), (Some("slot-b"), Some("walnut"), Some("task-b"))); + } + + #[test] + fn assistant_reply_is_unframed_and_wraps_while_user_keeps_a_bubble() { + fn scan(shape: &egui::Shape, user_surface: &mut bool, old_assistant_surface: &mut bool, reply_rows: &mut usize, text: &str) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| scan(shape, user_surface, old_assistant_surface, reply_rows, text)), + egui::Shape::Rect(rect) if rect.corner_radius.nw >= 12 && rect.rect.width() < 150.0 && rect.fill.a() == 255 => *user_surface = true, + egui::Shape::Rect(rect) if rect.fill == Color32::from_rgb(40, 42, 46) => *old_assistant_surface = true, + egui::Shape::Text(shape) if shape.galley.text() == text => *reply_rows = shape.galley.rows.len(), + _ => {} + } + } + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let reply = "保持产品结构和真实花色,让首屏的自然光更柔和,并继续保留文字和其他可编辑图层。"; + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(240.0, 600.0))), ..Default::default() }, |ui| { + ui.set_width(200.0); + user_bubble(ui, "你好"); + assistant_reply(ui, Id::unique("assistant-reply-test"), reply); + }); + let (mut user_surface, mut old_assistant_surface, mut reply_rows) = (false, false, 0); + for shape in &output.shapes { scan(&shape.shape, &mut user_surface, &mut old_assistant_surface, &mut reply_rows, reply); } + assert!(user_surface, "the user message retains its bubble"); + assert!(!old_assistant_surface, "the assistant reply has no full-width solid card"); + assert!(reply_rows > 1, "a long Chinese reply wraps in the available width"); + } + + #[test] + fn sent_reference_paints_the_recorded_image_without_a_card() { + let (mut app, _) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let w = app.jiansun.as_mut().unwrap(); + w.composer.clear(); + let texture = ctx.load_texture("frozen-reference", egui::ColorImage::filled([8, 5], Color32::WHITE), egui::TextureOptions::LINEAR); + let id = texture.id(); + w.agent_images.insert("ref-frozen".into(), texture); + let message = json!({"role":"user","text":"图里有什么?", + "requestScope":{"references":[{"kind":"layer","label":"主图"}]}, + "referenceContent":[{"imageId":"ref-frozen"}]}); + let frame = || ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(260.0, 360.0))), + ..Default::default() + }, |ui| { w.sent_references(ui, &message); }); + frame().drop_without_applying_deltas(); + let mut output = frame(); + let has_frame = output.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(rect) + if rect.brush.is_none() && rect.rect.width() <= 150.0 + && (rect.fill != Color32::TRANSPARENT || rect.stroke != Stroke::NONE))); + let shown = ctx.tessellate(std::mem::take(&mut output.shapes), output.pixels_per_point).iter() + .any(|shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id)); + output.drop_without_applying_deltas(); + assert!(shown); + assert!(!has_frame); + } + + #[test] + fn sent_user_text_reveals_in_order_without_resizing_the_bubble() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&ctx); + let mut bounds = Vec::new(); + for time in [0.0, 0.2, 0.5, 1.0] { + let _ = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + ui.set_width(240.0); + bounds.push(user_bubble_with_reveal(ui, "保留产品结构,让光线更加柔和。", Some(0.0), false)); + }); + } + assert!(bounds.windows(2).all(|pair| pair[0] == pair[1])); + let arrivals=super::super::typing_text::staggered("保留产品结构,让光线更加柔和。",0.0); + assert!(arrivals[0]=0.220)); + } + + #[test] + fn user_bubble_fits_shaped_chinese_text_and_respects_available_width() { + for width in [200.0, 300.0, 420.0] { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&ctx); + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width + 20.0, 600.0))), ..Default::default() }, |ui| { + ui.set_width(width); + let right = ui.available_rect_before_wrap().right(); + let short = user_bubble(ui, "你好"); + let long = user_bubble(ui, "请保持产品原有结构与材质,让这一屏的自然光更柔和,并保留桌面和支架的真实比例。"); + assert!(short.width() < width * 0.55, "short messages must not stretch across the panel: {short:?}"); + assert!(long.width() <= width - 21.0, "long messages wrap without overflowing: {long:?}"); + assert!(long.height() > short.height(), "long Chinese text wraps inside the bubble"); + assert!((short.right() - right).abs() < 1.0 && (long.right() - right).abs() < 1.0, "both messages align to the right edge"); + }); + } + } + + fn only_layers(app: &mut PhotocraftApp) { + app.ui.panels.color = false; + app.ui.panels.properties = false; + app.ui.panels.history = false; + app.ui.panels.navigator = false; + app.ui.panels.brushes = false; + app.ui.panels.layers = true; + app.ui.panels.rail = false; + } + + fn dock_fixture() -> (PhotocraftApp, mpsc::Receiver) { + dock_fixture_with_size(3600) + } + + fn dock_fixture_with_size(height: u32) -> (PhotocraftApp, mpsc::Receiver) { + let (tx, requests) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + while requests.try_recv().is_ok() {} + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":1440,"height":height,"name":"小壹 · 本地界面验收"})).unwrap(); + let services = crate::Services { + import: Some(Box::new(|name, bytes, depth| { + photocraft_io::import_with_options(name, bytes, depth).map(|r| (r.document, r.warnings)).map_err(|error| error.to_string()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(session, services); + app.sync_views(); + only_layers(&mut app); + app.ui.panels.color = true; + app.ui.panels.properties = true; + app.ui.dock_tabs.color = 0; + w.busy = None; + w.account = json!({"id":"local-ui-fixture"}); + w.library = false; + w.key_saved = true; + w.model_ready = true; + w.image_ready = true; + w.model = "discussion".into(); + w.models = vec![json!({"key":"discussion","id":"对话模型"})]; + w.image_model = "image".into(); + w.image_models = vec![json!({"key":"image","id":"生图模型"})]; + w.loaded_draft = app.session.active().map(|state| state.doc.id.0); + w.composer = "保持木纹与结构,调整这张图的光线。".into(); + w.messages = vec![ + json!({"role":"user","text":"这一屏的光线柔和一点,保留产品原有结构。"}), + json!({"role":"assistant","kind":"reply","text":"可以。先保留当前版本,我会针对选中的图位提供候选;采纳后再替换画布中的图片。"}), + ]; + w.composer_reference_add(&app).unwrap(); + app.jiansun = Some(w); + (app, requests) + } + + #[test] + #[ignore="GPU production composer and image card; writes to PHOTOCRAFT_AGENT_QA_OUT"] + fn gpu_glow_pill_production_surfaces() { + let _guard=photocraft_testkit::gpu_lock(); + struct Preview {app:PhotocraftApp,elapsed:f64} + impl eframe::App for Preview { + fn ui(&mut self,ui:&mut Ui,_:&mut eframe::Frame) { + ui.set_width(500.0); + let mut w=self.app.jiansun.take().unwrap(); + w.panel_geometry["panel"]=json!([0,0,520,640]);w.panel_geometry["composerMorph"]=json!(1.0); + let now=ui.input(|input|input.time); + let identity=Id::unique(("jiansun-result-waiting",&w.origin,w.account["id"].as_str(),w.owner_doc,w.messages.iter().rposition(|message|message["role"]=="user"))); + ui.ctx().data_mut(|data|{ + data.insert_temp(Id::unique("composer-sent-glow"),now-self.elapsed); + data.insert_temp(Id::unique("glow-pill-image-clock"),(identity,now-(self.elapsed+0.36),self.elapsed+0.36)); + }); + w.processing_card_ui(&self.app,ui);ui.add_space(30.0);w.composer_ui(&mut self.app,ui); + self.app.jiansun=Some(w); + } + } + let (mut app,requests)=dock_fixture();app.jiansun.as_mut().unwrap().busy=Some("image".into()); + let mut h=egui_kittest::Harness::builder().with_size(vec2(530.0,420.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_eframe(move|cc|{ + PhotocraftApp::setup_context(&cc.egui_ctx,crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); + app.gpu_render_state=cc.wgpu_render_state.clone();Preview {app,elapsed:1.0} + }); + let directory=std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + h.run_steps(4); + for (name,elapsed) in [("rest",1.0),("rise",0.14),("peak",0.28),("settle",0.52)] { + h.state_mut().elapsed=elapsed; + h.run_steps(1);h.render().unwrap().save(directory.join(format!("surfaces-{name}.png"))).unwrap(); + } + let w=h.state().app.jiansun.as_ref().unwrap(); + assert_eq!(w.panel_geometry["processingIdentity"],"siri-orb"); + assert_eq!(w.composer,"保持木纹与结构,调整这张图的光线。"); + h.state_mut().app.jiansun.as_mut().unwrap().reduce_motion=true; + h.run_steps(4);h.render().unwrap().save(directory.join("surfaces-reduced.png")).unwrap(); + assert!(requests.try_recv().is_err(),"rendering dispatches no generation or canvas edit"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore="Production task and composer motion; writes to PHOTOCRAFT_AGENT_QA_OUT"] + fn gpu_glow_workspace_task_lifecycle() { + let _guard=photocraft_testkit::gpu_lock(); + struct Preview {app:PhotocraftApp} + impl eframe::App for Preview { + fn ui(&mut self,ui:&mut Ui,_:&mut eframe::Frame) { + ui.set_width(480.0); + let mut workspace=self.app.jiansun.take().unwrap(); + workspace.panel_geometry=json!({"panel":[0,0,500,700],"composerMorph":1.0}); + workspace.processing_card_ui(&self.app,ui); + ui.add_space(30.0); + workspace.composer_ui(&mut self.app,ui); + self.app.jiansun=Some(workspace); + } + } + let (mut app,requests)=dock_fixture(); + app.jiansun.as_mut().unwrap().busy=Some("image".into()); + let mut h=egui_kittest::Harness::builder().with_size(vec2(510.0,600.0)).with_step_dt(1.0/30.0).wgpu().build_eframe(move|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx,crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); + app.gpu_render_state=cc.wgpu_render_state.clone(); + Preview {app} + }); + let directory=std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + for index in 0..72 { + if index==30 {h.state_mut().app.jiansun.as_mut().unwrap().agent_effects_paused=true;} + if index==50 {h.state_mut().app.jiansun.as_mut().unwrap().busy=None;} + h.run_steps(1); + h.render().unwrap().save(directory.join(format!("lifecycle-{index:03}.png"))).unwrap(); + let workspace=h.state().app.jiansun.as_ref().unwrap(); + if index==24 {assert_eq!(workspace.panel_geometry["processingLightMode"],"glow-pill");} + if index==44 {assert_eq!(workspace.panel_geometry["processingLightMode"],"paused");} + if index==71 {assert!(workspace.panel_geometry["processing"].is_null());} + assert_eq!(workspace.panel_geometry["composerLightMode"],"glow-pill"); + assert_eq!(workspace.composer,"保持木纹与结构,调整这张图的光线。"); + } + assert!(requests.try_recv().is_err()); + } + + fn geometry(w: &Workspace, name: &str) -> Rect { + let value = &w.panel_geometry[name]; + let a = value.as_array().or_else(|| value["rect"].as_array()) + .unwrap_or_else(|| panic!("missing panel geometry for {name}: {value}")); + Rect::from_min_size( + pos2(a[0].as_f64().unwrap() as f32, a[1].as_f64().unwrap() as f32), + vec2(a[2].as_f64().unwrap() as f32, a[3].as_f64().unwrap() as f32), + ) + } + + fn dock_frame(ctx: &egui::Context, app: &mut PhotocraftApp, events: Vec) { + let mut output = ctx + .run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), events, ..Default::default() }, |ui| { + crate::panels::right_dock(app, ui) + }); + output.textures_delta.clear(); + } + + #[test] + fn production_hides_suggestions_and_followups_fill_without_sending() { + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.composer = "保留我的草稿".into(); + w.busy = Some("slot-apply-save".into()); + w.product_start_queued = true; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + dock_frame(&ctx, &mut app, vec![]); + let w = app.jiansun.as_mut().unwrap(); + assert!(w.panel_geometry["quickPrompts"].is_null(), "suggestions yield while a whole set is produced"); + assert!(w.panel_geometry["followupPrompts"].is_null()); + assert!(w.panel_geometry["taskStop"].is_array()); + assert!(w.panel_geometry["stop"].is_null()); + + w.busy = None; + w.product_start_queued = false; + w.messages.push(json!({"role":"assistant","kind":"reply","text":"已导出 2/3 份。", + "productionSummary":{"exported":2,"total":3}})); + for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } + let geometry = &app.jiansun.as_ref().unwrap().panel_geometry["followupPrompts"][0]; + assert_eq!(geometry["label"], "查看未完成项"); + let rect = geometry["rect"].as_array().unwrap(); + let value = |index: usize| rect[index].as_f64().unwrap() as f32; + let pos = pos2(value(0) + value(2) / 2.0, value(1) + value(3) / 2.0); + for pressed in [true, false] { + dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(pos), egui::Event::PointerButton { + pos,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE + }]); + } + let w = app.jiansun.as_ref().unwrap(); + assert!(w.composer.starts_with("保留我的草稿\n请梳理这轮未完成的文案")); + assert!(w.busy.is_none()); + assert!(!requests.try_iter().any(|request| matches!(request, Request::Action(method, _) if method == "agent" || method == "image"))); + } + + fn production_quick_actions_fixture() -> (PhotocraftApp, mpsc::Receiver) { + let (mut app, requests) = dock_fixture(); + let document = app.session.active().unwrap().doc.id.0; + let workspace = app.jiansun.as_mut().unwrap(); + workspace.open_projects.insert(document, workspace.local_identity("production-quick-actions")); + workspace.reduce_motion = true; + workspace.composer = "保留现有草稿".into(); + workspace.template_workflow = json!({"canvasFirst":true,"outputId":"detail"}); + workspace.messages.push(json!({"role":"assistant","kind":"reply","text":"本轮已完成 2 份输出,还有 1 份待制作。", + "productionSummary":{"exported":2,"total":3}})); + (app, requests) + } + + #[test] + fn production_quick_action_requires_stages_and_checkpoints_before_resuming() { + use egui_kittest::{Harness, kittest::Queryable}; + for width in [250.0, 360.0, 420.0] { + let (app, requests) = production_quick_actions_fixture(); + let mut harness = Harness::builder() + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(vec2(width, 520.0)) + .build_ui_state(|ui, app| { + if super::super::stitch_ui::ui_fonts_ready(ui) { super::super::agent_dock(app, ui); } + }, app); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); + harness.run_steps(5); + let workspace = harness.state().jiansun.as_ref().unwrap(); + assert_eq!(workspace.panel_geometry["followupPrompts"][0]["label"], "查看未完成项"); + assert!(harness.query_by_label("成品交付尚未确认").is_some()); + assert!(harness.query_by_label(CONTINUE_PRODUCTION).is_none()); + harness.state_mut().jiansun.as_mut().unwrap().template_workflow["productionStages"] = + json!([{"outputId":"detail","variantId":"wood"}]); + harness.run_steps(2); + let workspace = harness.state().jiansun.as_ref().unwrap(); + let prompts = workspace.panel_geometry["followupPrompts"].as_array().unwrap(); + let labels = [CONTINUE_PRODUCTION, "查看未完成项", "核对已有结果"]; + let composer_top = workspace.panel_geometry["composer"][1].as_f64().unwrap() as f32; + let first = harness.get_by_label(CONTINUE_PRODUCTION).rect(); + let mut previous = None::; + for (index, label) in labels.into_iter().enumerate() { + assert_eq!(prompts[index]["label"], label); + let accessible_label = if index == 0 { label.to_owned() } else { format!("填入输入框:{label}") }; + let rect = harness.get_by_label(&accessible_label).rect(); + assert!(rect.left() >= 0.0 && rect.right() <= width && rect.bottom() < composer_top, "{label} at {width}pt: {rect:?}"); + assert!((rect.center().y - first.center().y).abs() <= 1.0, "{label} wrapped at {width}pt: {first:?}, {rect:?}; {prompts:?}"); + assert!(previous.is_none_or(|prev| prev.right() <= rect.left())); + previous = Some(rect); + } + requests.try_iter().for_each(drop); + + harness.get_by_label("填入输入框:核对已有结果").click(); + harness.run_steps(2); + let draft = harness.state().jiansun.as_ref().unwrap().composer.clone(); + assert!(draft.contains("请检查目前已保留的文案和配图")); + assert!(!requests.try_iter().any(|request| matches!(request, Request::Action(method, _) if method == "agent" || method == "image"))); + + harness.get_by_label(CONTINUE_PRODUCTION).click(); + harness.run_steps(2); + let workspace = harness.state().jiansun.as_ref().unwrap(); + assert_eq!(workspace.pending_slot_apply.as_ref().unwrap()["resumeProduct"], true); + let queued: Vec<_> = requests.try_iter().collect(); + assert!(queued.iter().any(|request| matches!(request, Request::Save(..)))); + assert!(!queued.iter().any(|request| matches!(request, Request::Action(method, _) if method == "agent"))); + assert_eq!(harness.state().jiansun.as_ref().unwrap().composer, draft); + } + } + + fn live_production_fixture() -> (PhotocraftApp, mpsc::Receiver) { + live_production_fixture_with_size(3600) + } + + fn live_production_fixture_with_size(height: u32) -> (PhotocraftApp, mpsc::Receiver) { + let (mut app, requests) = dock_fixture_with_size(height); + let w = app.jiansun.as_mut().unwrap(); + w.composer.clear(); + w.pi_run = Some("offline-production".into()); + w.busy = Some("pi-agent".into()); + w.pi_product_production = true; + w.template_workflow = json!({"canvasFirst":true,"outputId":"detail","slots":[ + {"id":"hero","outputId":"detail","label":"首屏产品场景","frame":{"width":1440,"height":1800}}, + {"id":"scene","outputId":"detail","label":"空间搭配","frame":{"width":1600,"height":1200}} + ]}); + w.workflow.set_production_progress(&json!({ + "heading":"正在制作详情页","outputId":"detail","rendered":1,"total":3, + "pictureCells":[{"slotId":"hero","label":"首屏产品场景"},{"slotId":"scene","label":"空间搭配"}, + {"slotId":"finish","label":"材质细节","state":"verified"}], + "copyCells":[{"state":"verified"},{"state":"filled"},{}], + "workers":[{"number":1,"slotId":"hero","label":"首屏产品场景","step":"正在生图","active":true}, + {"slotId":"scene","label":"空间搭配","step":"生成","active":true}], + })); + let tool = |call: &str, name: &str, status: &str| json!({"role":"assistant","kind":"activity","text":"工具活动", + "event":{"version":1,"type":"tool","run":"offline-production","toolCallId":call,"toolName":name,"status":status,"durationMs":320}}); + w.messages = vec![ + json!({"role":"user","text":"制作详情、主图和 SKU 图。"}), + json!({"role":"assistant","kind":"thinking","active":false}), + json!({"role":"assistant","kind":"thinking","active":false}), + tool("read","canvas_read","started"), + tool("read","canvas_read","completed"), + tool("edit","canvas_edit","started"), + json!({"role":"assistant","kind":"image-job","taskId":"hero-job","run":"offline-production","workerNumber":1, + "slotLabel":"首屏产品场景","width":1440,"height":1800,"target":{"slotId":"hero","outputId":"detail"}}), + ]; + (app, requests) + } + + #[test] + fn production_projection_shares_worker_identity_and_yields_to_the_current_receipt() { + let (mut app, requests) = live_production_fixture(); + let w = app.jiansun.as_mut().unwrap(); + let before = w.messages.clone(); + let jobs = w.projected_worker_jobs(); + assert_eq!(jobs.len(), 1); + assert_eq!(jobs[0]["workerNumber"], 2); + assert_eq!(frame_image_ratio(&jobs[0]), Some(4.0 / 3.0)); + assert_eq!(w.messages, before); + assert!(requests.try_recv().is_err()); + let turn = turns(&w.messages).pop().unwrap(); + assert_eq!(turn.items.iter().filter(|row| matches!(row, TurnItem::Thinking(..))).count(), 1); + assert!(turn.items.iter().any(|row| matches!(row, TurnItem::Tools(rows) if rows.len() == 2))); + + w.messages.push(json!({"role":"assistant","kind":"image-job","taskId":"scene-job","run":"offline-production", + "target":{"slotId":"scene","outputId":"detail"}})); + assert!(w.projected_worker_jobs().is_empty()); + let mut progress = w.workflow.production_progress().clone(); + progress["reviews"] = json!([{"number":27,"active":true,"label":"木纹细节","step":"正在验图"}]); + w.workflow.set_production_progress(&progress); + let shown = w.production_workers(); + assert_eq!(shown.iter().map(|w| (w.number, w.stage)).collect::>(), + [(1, WorkerStage::Generating), (2, WorkerStage::Generating), (27, WorkerStage::Reviewing)]); + } + + #[test] + fn appended_tool_completion_changes_only_its_own_cached_item() { + let tool = |call: &str, status: &str| json!({"role":"assistant","kind":"activity", + "event":{"version":1,"type":"tool","run":"test","toolCallId":call,"toolName":"canvas_read","status":status}}); + let mut messages = vec![ + tool("earlier", "started"), + json!({"role":"assistant","kind":"activity","text":"画布已读取"}), + tool("later", "completed"), + json!({"role":"assistant","kind":"thinking","active":true}), + json!({"role":"assistant","kind":"copywriting-fields","optionsId":"copy","items":[{"applied":false}]}), + ]; + let layouts: Vec<_> = turns(&messages)[0].items.iter().map(|item| + (item.message_index(), TurnItemContent::capture(item, &messages))).collect(); + + messages.push(tool("earlier", "completed")); + messages[3]["active"] = json!(false); + messages[4]["items"][0]["applied"] = json!(true); + let transcript = turns(&messages); + let items = &transcript[0].items; + assert_eq!(items.len(), layouts.len()); + let unchanged: Vec<_> = items.iter().zip(&layouts).map(|(item, (index, content))| { + assert_eq!(item.message_index(), *index); + content.matches(item, &messages) + }).collect(); + assert_eq!(unchanged, [false, true, true, false, false]); + } + + #[test] + #[ignore = "600-frame offline production benchmark"] + fn long_conversation_frame_budget() { + use std::time::Instant; + + let (mut app, _requests) = live_production_fixture_with_size(34_838); + for index in 0..267 { + app.session.execute("layer.new.layer", json!({"name":format!("详情图层 {index}")})).unwrap(); + } + let fields = (0..33).map(|index| { + app.session.execute("type.create", json!({"text":format!("原始标题 {}", index + 1), + "x":40,"y":40 + index * 30})).unwrap(); + app.session.active().unwrap().selected_layers()[0].0 + }).collect::>(); + let state = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut state.doc); + let pages = json!([{"documentId":"S01","outputId":"detail","mapping":{"fields":[ + {"kind":"image","slotId":"hero"},{"kind":"image","slotId":"scene"} + ]}}]); + let mapping = json!({"version":1,"canvasFirst":true,"workspaceId":"offline", + "templateId":"chair","templateVersion":"1","templateHash":"offline", + "variantId":"wood","component":"detail","outputs":pages}); + doc.metadata.text.push(("jiansun.slot-mapping.v1".into(), mapping.to_string())); + let w = app.jiansun.as_mut().unwrap(); + for key in ["workspaceId", "templateId", "templateVersion", "templateHash", "variantId"] { + w.template_workflow[key] = mapping[key].clone(); + } + w.template_workflow["outputs"] = pages; + for slot in w.template_workflow["slots"].as_array_mut().unwrap() { + slot["documentId"] = json!("S01"); + slot["variantId"] = json!("wood"); + } + w.owner_doc = Some(doc.id.0); + w.observed_doc = w.owner_doc; + w.pi_binding = json!({"accountId":w.account["id"],"origin":w.origin}); + let mut progress = w.workflow.production_progress().clone(); + progress["pictureCells"] = json!((0..16).map(|i| json!({"slotId":format!("pic-{i}"),"label":format!("图位 {i}"),"state":"verified"})).collect::>()); + progress["copyCells"] = json!(vec![json!({"state":"filled"}); 33]); + w.workflow.set_production_progress(&progress); + // Match the production transcript: one start, then many tool and result rows in + // the same active turn. All message bodies and textures are offline fixtures. + let active_turn = std::mem::take(&mut w.messages); + w.messages.push(json!({"role":"user","text":"开始制作这把椅子的整套详情页。"})); + for index in 0..87 { + if index < 47 { + w.messages.push(json!({"role":"assistant","kind":"thinking","active":false})); + } + for call in 0..(6 + usize::from(index < 63)) { + w.messages.push(json!({"role":"assistant","kind":"activity","event":{ + "version":1,"type":"tool","run":"offline-history","toolCallId":format!("tool-{index}-{call}"), + "toolName":"canvas_read","status":"completed","durationMs":320 + }})); + } + w.messages.push(json!({"role":"assistant","kind":"activity","text":format!("第 {} 组已核对画布,保留结构、木纹和现有文字布局。", index + 1)})); + if index < 41 { + for variant in 0..(3 + usize::from(index == 0)) { + w.messages.push(json!({"role":"assistant","kind":"image","taskId":format!("candidate-{}", 3 * index + variant + usize::from(index > 0)), + "width":1440,"height":1800})); + } + } + if index % 13 == 0 { + w.messages.push(json!({"role":"assistant","kind":"reply", + "text":"候选图已生成。保留当前画布,确认光线和细节后可以采纳这张图。".repeat(12)})); + } + } + w.messages.push(json!({"role":"assistant","kind":"copywriting-fields","optionsId":"copy-33", + "items":fields.into_iter().enumerate().map(|(index, layer)| json!({"layer":layer,"name":format!("文案 {}",index+1), + "field":{"fieldId":format!("S01-T{index:02}"),"label":"标题","maxChars":16,"maxLines":1}, + "original":format!("原始标题 {}",index+1),"text":"自然木纹餐椅","applied":false})).collect::>(),"target":{}})); + w.messages.extend(active_turn.into_iter().filter(|message| message["role"] != "user")); + assert_eq!(turns(&w.messages).len(), 1); + let screenshots = std::env::var_os("PHOTOCRAFT_LONG_CONVERSATION_QA_OUT").map(std::path::PathBuf::from); + let full_transcript = std::env::var_os("PHOTOCRAFT_BENCH_FULL_TRANSCRIPT").is_some(); + let append = std::env::var_os("PHOTOCRAFT_BENCH_APPEND").is_some(); + let reset_on_append = std::env::var_os("PHOTOCRAFT_BENCH_RESET_ON_APPEND").is_some(); + let _gpu = screenshots.as_ref().map(|_| photocraft_testkit::gpu_lock()); + let builder = egui_kittest::Harness::builder() + .with_size(vec2(1440.0, 900.0)).with_max_steps(4); + let builder = if screenshots.is_some() { builder.wgpu() } else { builder }; + let builder = if append { builder.with_step_dt(1.0 / 60.0) } else { builder }; + let mut harness = builder.build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); + cc.egui_ctx.data_mut(|data| { + data.insert_temp(Id::unique("benchmark-full-transcript"), full_transcript); + data.insert_temp(Id::unique("benchmark-reset-on-append"), reset_on_append); + }); + let workspace = app.jiansun.as_mut().unwrap(); + workspace.pi_touched = Instant::now(); + let images = &mut workspace.agent_images; + for index in 64..124 { + let id = format!("candidate-{index}"); + let image = egui::ColorImage::filled([96, 120], Color32::from_rgb((index - 64) * 3, 92, 52)); + images.insert(id.clone(), cc.egui_ctx.load_texture(id, image, egui::TextureOptions::LINEAR)); + } + app + }); + harness.run_steps(24); + let app = harness.state_mut(); + let panel = &app.jiansun.as_ref().unwrap().panel_geometry; + assert_eq!(panel["open"], true); + assert!(panel["productionProgress"].is_array(), "{panel}"); + let point = geometry(app.jiansun.as_ref().unwrap(), "conversationClip").center(); + app.slow_frames.set_threshold_ms(0.0); + let tool_message = |index| json!({"role":"assistant","kind":"activity","event":{ + "version":1,"type":"tool","run":"offline-production", + "toolCallId":format!("append-{index}"),"toolName":"canvas_read", + "status":"completed","durationMs":320 + }}); + if screenshots.is_some() && append { + let w = app.jiansun.as_mut().unwrap(); + w.messages.extend((0..19).map(tool_message)); + harness.run_steps(24); + } + let panel_offset = harness.state().jiansun.as_ref().unwrap().panel_geometry["conversationScrollOffset"].as_f64().unwrap(); + let scroll = |harness: &mut egui_kittest::Harness<'_, PhotocraftApp>, delta| { + harness.event(egui::Event::PointerMoved(point)); + harness.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + phase: egui::TouchPhase::Move, + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, delta), + modifiers: egui::Modifiers::NONE, + }); + harness.step(); + harness.event(egui::Event::PointerGone); + harness.step(); + harness.run_steps(24); + }; + if let Some(directory) = screenshots { + std::fs::create_dir_all(&directory).unwrap(); + for (name, delta) in [("bottom", 0.0), ("middle", (panel_offset / 2.0) as f32), ("top", panel_offset as f32)] { + if delta != 0.0 { + scroll(&mut harness, delta); + } + harness.render().unwrap().save(directory.join(format!("{name}.png"))).unwrap(); + } + return; + } + + if append { + scroll(&mut harness, (panel_offset / 2.0) as f32); + assert!(harness.state().jiansun.as_ref().unwrap().panel_geometry["conversationBottomGap"].as_f64().unwrap() > 480.0); + } + + #[cfg(target_os = "windows")] + let thread_cpu_ticks = || { + let (_, _, kernel, user) = winsafe::HTHREAD::GetCurrentThread().GetThreadTimes().unwrap(); + u64::from(kernel) + u64::from(user) + }; + #[cfg(target_os = "windows")] + let cpu_start = (Instant::now(), thread_cpu_ticks()); + + let mut samples = Vec::with_capacity(600); + let mut total = 0.0; + let mut regions = [0.0; 6]; + let session_start = Instant::now(); + let mut next_append = Duration::from_secs(3); + let mut appended = 0; + let mut append_frames = Vec::new(); + while if append { session_start.elapsed() < Duration::from_secs(60) } else { samples.len() < 600 } { + let w = harness.state_mut().jiansun.as_mut().unwrap(); + w.pi_touched = Instant::now(); + let added = append && next_append < Duration::from_secs(60) && session_start.elapsed() >= next_append; + if added { + w.messages.push(tool_message(appended)); + appended += 1; + next_append += Duration::from_secs(3); + } + let started = Instant::now(); + harness.step(); + let elapsed = started.elapsed().as_secs_f64() * 1000.0; + samples.push(elapsed); + if added { + append_frames.push(elapsed); + assert!(harness.state().jiansun.as_ref().unwrap().panel_geometry["conversationBottomGap"].as_f64().unwrap() > 480.0); + } + let frame = harness.state().slow_frames.frames().next_back().unwrap(); + let ui = &frame.ui_regions; + total += frame.frame_ms; + for (sum, time) in regions.iter_mut().zip([ + ui.conversation, ui.production_head, ui.composer, ui.dock_panels, ui.canvas_overlays, ui.menu_status, + ]) { + *sum += time; + } + if append { + std::thread::sleep(Duration::from_secs_f64(1.0 / 60.0).saturating_sub(started.elapsed())); + } + } + if append { + assert_eq!(appended, 19); + append_frames.sort_unstable_by(f64::total_cmp); + eprintln!("{appended} appends: first-frame median {:.2} ms, max {:.2} ms", + append_frames[appended / 2], append_frames[appended - 1]); + } + #[cfg(target_os = "windows")] + { + let cpu_ms = (thread_cpu_ticks() - cpu_start.1) as f64 / 10_000.0; + let cpu_share = cpu_ms / (cpu_start.0.elapsed().as_secs_f64() * 10.0); + eprintln!("UI thread CPU: {cpu_ms:.1} ms ({cpu_share:.1}% of one core)"); + } + samples.sort_unstable_by(f64::total_cmp); + let frames = samples.len(); + let percentile = |p| samples[(frames * p as usize).div_ceil(100) - 1]; + let (p50, p95, p99, max) = (percentile(50), percentile(95), percentile(99), samples[frames - 1]); + let shares = regions.map(|time| time * 100.0 / total); + eprintln!("{frames} frames: p50 {p50:.2}, p95 {p95:.2}, p99 {p99:.2}, max {max:.2} ms"); + eprintln!("Frames above 33 ms: {}", samples.iter().filter(|&&ms| ms > 33.0).count()); + eprintln!("Percent of frame build (conversation, head, composer, dock, overlays, menu/status): {shares:.1?}"); + assert!(p95 <= 150.0, "long conversation p95 {p95:.2} ms"); + } + + #[test] + #[ignore = "GPU screenshots from the production dock with offline fixtures"] + fn agent_panel_batch2_gpu_evidence() { + use egui_kittest::kittest::Queryable; + let _gpu = photocraft_testkit::gpu_lock(); + let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + struct Preview(PhotocraftApp); + impl eframe::App for Preview { + fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { + super::super::agent_dock(&mut self.0, ui); + } + } + for (width, live, name) in [(360.0, true, "agent-panel-live-production-360.png"), + (420.0, false, "agent-panel-settled-420.png")] { + let (mut app, requests) = if live { live_production_fixture() } else { production_quick_actions_fixture() }; + let w = app.jiansun.as_mut().unwrap(); + w.composer.clear(); + if !live { + w.template_workflow["productionStages"] = json!([{"outputId":"sku_images","variantId":"wood"}]); + w.messages = vec![ + json!({"role":"user","text":"继续制作整套"}), + json!({"role":"assistant","kind":"image","taskId":"offline-hero","width":4,"height":5}), + json!({"role":"assistant","kind":"image","taskId":"offline-detail","width":4,"height":5}), + json!({"role":"assistant","kind":"reply","text":"本轮已交付详情页和主图,SKU 图还有一份待完成。", + "productionSummary":{"exported":2,"total":3}}), + ]; + } + let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 760.0)).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); + app.gpu_render_state = cc.wgpu_render_state.clone(); + if !live { + let w = app.jiansun.as_mut().unwrap(); + for (id, color) in [("offline-hero", Color32::from_rgb(120, 101, 84)), + ("offline-detail", Color32::from_rgb(96, 116, 104))] { + let image = egui::ColorImage::filled([48, 60], color); + w.agent_images.insert(id.into(), cc.egui_ctx.load_texture(id, image, Default::default())); + } + } + Preview(app) + }); + harness.run_steps(12); + let w = harness.state().0.jiansun.as_ref().unwrap(); + if live { + assert_eq!(w.production_workers().len(), 2); + assert_eq!(w.panel_geometry["productionImageCells"]["total"], 3); + assert_eq!(w.projected_worker_jobs().len(), 1); + } else { + assert_eq!(w.panel_geometry["followupPrompts"].as_array().unwrap().len(), 3); + assert!(harness.query_by_label("还有输出待完成,可继续制作整套").is_some()); + } + harness.render().unwrap().save(directory.join(name)).unwrap(); + if live { + harness.get_by_label("展开制作详情").click(); + harness.run_steps(24); + harness.get_by_label("首屏产品场景 · 生图中").click(); + harness.run_steps(2); + let w = harness.state().0.jiansun.as_ref().unwrap(); + assert_eq!(w.canvas_workspace.locate_request.as_ref().map(|target| &target["slotId"]), Some(&json!("hero"))); + } + assert!(requests.try_recv().is_err()); + } + } + + #[test] + #[ignore = "offscreen GPU visual evidence"] + fn composer_quick_actions_visual_evidence() { + let _gpu = photocraft_testkit::gpu_lock(); + let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory")); + std::fs::create_dir_all(&directory).unwrap(); + let (mut app, _) = production_quick_actions_fixture(); + app.jiansun.as_mut().unwrap().template_workflow["productionStages"] = + json!([{"outputId":"detail","variantId":"wood"}]); + let mut harness = egui_kittest::Harness::builder() + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(vec2(360.0, 480.0)).wgpu().build_ui_state(|ui, app| { + if super::super::stitch_ui::ui_fonts_ready(ui) { super::super::agent_dock(app, ui); } + }, app); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); + harness.run_steps(6); + harness.render().expect("GPU composer render").save(directory.join("composer-quick-actions.png")).unwrap(); + } + + #[test] + #[ignore = "offline GPU comparison of one image slot before and after its receipt"] + fn image_receipt_replaces_the_placeholder_in_place() { + use egui_kittest::kittest::Queryable; + + let _gpu = photocraft_testkit::gpu_lock(); + let out = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + let (app, requests) = live_production_fixture(); + let task = "hero-job"; + let mut harness = egui_kittest::Harness::builder().with_size(vec2(420.0, 395.0)).wgpu() + .build_ui_state(move |ui, app: &mut PhotocraftApp| { + if !super::super::stitch_ui::ui_fonts_ready(ui) { return; } + Frame::NONE.fill(Tokens::get(ui.ctx()).agent().dock).inner_margin(12).show(ui, |ui| { + let w = app.jiansun.as_ref().unwrap(); + let message = w.messages.iter().find(|message| message["taskId"] == task).unwrap(); + let width = ui.available_width(); + w.image_result(ui, message, width, None); + }); + }, app); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); + harness.run_steps(8); + let waiting = harness.get_by_label("首屏产品场景 · 正在生成图片…").rect(); + harness.render().unwrap().save(out.join("same-slot-waiting.png")).unwrap(); + + let original = egui::ColorImage::filled([48, 60], Color32::from_rgb(120, 101, 84)); + let texture = harness.ctx.load_texture(task, original, Default::default()); + let w = harness.state_mut().jiansun.as_mut().unwrap(); + let index = w.messages.iter().position(|message| message["taskId"] == task).unwrap(); + w.register_image(json!({"taskId":task,"slotId":"hero","outputId":"detail"})); + let message = &w.messages[index]; + assert_eq!(message["kind"], "image"); + assert_eq!(message["taskId"], task); + let target = image_location(message, task); + let (_, _, label) = image_result_labels(&target, &w.template_workflow, &w.creation_brief); + w.agent_images.insert(task.into(), texture); + let mut progress = w.workflow.production_progress().clone(); + progress["candidateReviews"][task]["status"] = json!("adopted"); + w.workflow.set_production_progress(&progress); + harness.run_steps(8); + let received = harness.get_by_label(format!("定位 {label}").as_str()).rect(); + assert_eq!(waiting, received); + harness.render().unwrap().save(out.join("same-slot-received.png")).unwrap(); + assert!(matches!(requests.try_recv(), Ok(Request::Action(method, _)) if method == "agent-image-preview")); + assert!(requests.try_recv().is_err()); + } + + #[test] + #[ignore = "offscreen GPU acceptance at Windows window widths, UI scales and dock widths"] + fn p1_workspace_visual_matrix() { + use egui_kittest::kittest::Queryable; + + let _gpu = photocraft_testkit::gpu_lock(); + let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + struct Preview(PhotocraftApp); + impl eframe::App for Preview { + fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { + let app = &mut self.0; + crate::panels::title_bar(app, ui); + crate::panels::options_bar(app, ui); + crate::panels::status_bar(app, ui); + crate::panels::toolbar(app, ui); + crate::panels::right_dock(app, ui); + } + } + + for width in [960.0, 1280.0, 1400.0] { + for scale in [1.0, 1.25, 1.5] { + for dock in [250.0, 360.0, 420.0] { + let (mut app, requests) = live_production_fixture(); + app.ui.dock_tabs.color = 4; + let doc = app.session.active().unwrap().doc.id.0; + let w = app.jiansun.as_mut().unwrap(); + w.open_projects.insert(doc, w.local_identity("p1-visual")); + w.reduce_motion = true; + w.template_workflow["workspaceId"] = json!("p1-visual"); + w.template_workflow["templateId"] = json!("fixture"); + w.template_workflow["templateVersion"] = json!("1"); + w.template_workflow["templateHash"] = json!("fixture"); + w.template_workflow["variantId"] = json!("wood"); + w.template_workflow["outputs"] = json!([{"outputId":"detail","documentId":"first"}]); + let mapping = json!({"version":1,"canvasFirst":true,"component":"detail","variantId":"wood", + "workspaceId":"p1-visual","templateId":"fixture","templateVersion":"1","templateHash":"fixture", + "outputs":[{"documentId":"first","mapping":{"fields":[]}}]}); + std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc) + .metadata.text.push(("jiansun.slot-mapping.v1".into(), mapping.to_string())); + let mut progress = w.workflow.production_progress().clone(); + progress["workers"][1]["step"] = json!("正在等待原请求"); + progress["workers"].as_array_mut().unwrap().push( + json!({"number":3,"slotId":"wood","label":"木纹细节","step":"正在准备","active":true})); + progress["workers"].as_array_mut().unwrap().extend([ + json!({"number":5,"slotId":"angle","label":"侧面角度","step":"正在生图","active":true}), + json!({"number":6,"slotId":"joinery","label":"连接结构","step":"正在准备","active":true}), + ]); + progress["copyCells"] = json!((0..45).map(|index| json!({ + "state": if index < 8 { "verified" } else if index < 37 { "filled" } else { "empty" } + })).collect::>()); + progress["reviews"] = json!([{"number":4,"slotId":"finish","label":"材质细节","step":"正在验图","active":true}]); + w.workflow.set_production_progress(&progress); + let mut harness = egui_kittest::Harness::builder().with_size(vec2(width / scale, 900.0 / scale)) + .with_pixels_per_point(scale).with_max_steps(64).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); + crate::panels::request_dock_width(&cc.egui_ctx, dock); + app.gpu_render_state = cc.wgpu_render_state.clone(); + Preview(app) + }); + harness.run_steps(12); + let stem = format!("{width}px-{scale}x-{dock}pt"); + let save = |harness: &mut egui_kittest::Harness, state| { + let shot = harness.render().expect("GPU workspace render"); + assert_eq!(shot.dimensions(), (width as u32, 900)); + shot.save(directory.join(format!("{stem}-{state}.png"))).unwrap(); + }; + assert!(harness.query_by_label("正在推进目标").is_some()); + save(&mut harness, "running"); + if (width, scale) == (960.0, 1.5) || (width, scale) == (1400.0, 1.0) { + harness.get_by_label("展开制作详情").click(); + harness.run_steps(12); + let w = harness.state().0.jiansun.as_ref().unwrap(); + assert_eq!(w.panel_geometry["productionWorkers"].as_array().unwrap().len(), 6); + save(&mut harness, "expanded"); + let app = &mut harness.state_mut().0; + app.session.execute("select.deselectLayers", json!({})).unwrap(); + let mut w = app.jiansun.take().unwrap(); + w.pi_run = None; + w.busy = None; + w.composer.clear(); + w.composer_reference_clear(app); + w.messages.push(json!({"role":"assistant","kind":"reply", + "text":"详情和主图已交付,SKU 图还有一份待完成。","productionSummary":{"exported":2,"total":3}})); + app.jiansun = Some(w); + harness.run_steps(12); + assert!(harness.query_by_label("继续制作整套").is_some()); + save(&mut harness, "settled"); + } + assert!(requests.try_recv().is_err(), "visual fixture dispatched a request at {stem}"); + } + } + } + } + + #[test] + fn conversation_scroll_keeps_reference_height_when_clipped() { + let (mut app, _) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + let ctx = egui::Context::default(); + let texture = ctx.load_texture("portrait", egui::ColorImage::filled([4, 7], Color32::WHITE), Default::default()); + w.agent_images.insert("reference".into(), texture); + let message = json!({"requestScope":{"references":[{"label":"Title"}]}, "referenceContent":[{"imageId":"reference"}]}); + let mut heights = Vec::new(); + for clip_top in [0.0, 200.0] { + let output = ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 350.0))), + ..Default::default() + }, |ui| { + ui.set_clip_rect(Rect::from_min_max(pos2(0.0, clip_top), pos2(300.0, 350.0))); + heights.push(ui.scope(|ui| w.sent_references(ui, &message)).response.rect.height()); + }); + output.drop_without_applying_deltas(); + } + assert!(heights[0] >= 110.0); + assert_eq!(heights[0], heights[1], "clipping a reference must not change the scroll extent"); + } + + #[test] + fn production_head_stays_pinned_while_reading_history() { + let (mut app, _) = dock_fixture(); + app.ui.dock_tabs.color = 4; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.composer.clear(); + w.busy = Some("pi-agent".into()); + w.pi_product_production = true; + w.messages.clear(); + for index in 0..16 { + w.messages.push(json!({"role":"user","text":format!("此前的输入 {index}")})); + w.messages.push(json!({"role":"assistant","text":"这张图片已有一版候选。"})); + } + w.messages.push(json!({"role":"user","text":"制作详情页 · 1/3"})); + w.stream_reply = "正在验图\n已回填 2/21 个图位\n准备核对扶手的木纹。".into(); + for _ in 0..5 { dock_frame(&ctx, &mut app, vec![]); } + let point = geometry(app.jiansun.as_ref().unwrap(), "conversationClip").center(); + dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(point), egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown,phase:egui::TouchPhase::Move,unit:egui::MouseWheelUnit::Point, + delta:vec2(0.0,500.0),modifiers:egui::Modifiers::NONE, + }]); + for _ in 0..12 { dock_frame(&ctx, &mut app, vec![]); } + let w = app.jiansun.as_ref().unwrap(); + assert!(w.panel_geometry["conversationBottomGap"].as_f64().unwrap() > 48.0); + let head = geometry(w, "productionProgress"); + assert!(head.height() >= 44.0); + assert!(head.bottom() <= geometry(w, "conversationClip").top() + 1.0, + "状态头固定在对话上方:conversation {:?}, head {head:?}", geometry(w, "conversationClip")); + assert!(head.contains_rect(geometry(w, "productionProgressRail"))); + assert!(w.panel_geometry["quickPrompts"].is_null(), "suggestions yield while a whole set is produced"); + assert!(w.panel_geometry["productionHistoryToggle"].is_null()); + assert!(w.panel_geometry["agentStatus"].is_null()); + } + + #[test] + fn production_head_rail_takes_the_amber_of_filled_cells_before_the_cells_exist() { + let (mut app, _) = dock_fixture(); + app.ui.dock_tabs.color = 4; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.composer.clear(); + w.busy = Some("pi-agent".into()); + w.pi_product_production = true; + w.messages.clear(); + w.stream_reply = "正在验图\n已回填 2/21 个图位\n准备核对扶手的木纹。".into(); + fn tinted(shape: &egui::Shape, fill: Color32, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| tinted(shape, fill, out)), + egui::Shape::Rect(rect) if rect.fill == fill => out.push(rect.rect), + _ => {} + } + } + let amber = super::super::agent_stream::cell_filled(&Tokens::get(&ctx).agent()); + let mut painted = Vec::new(); + for _ in 0..5 { + let output = ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), + ..Default::default() + }, |ui| crate::panels::right_dock(&mut app, ui)); + painted.clear(); + for shape in &output.shapes { tinted(&shape.shape, amber, &mut painted); } + output.drop_without_applying_deltas(); + } + let rail = geometry(app.jiansun.as_ref().unwrap(), "productionProgressRail"); + assert!(painted.iter().any(|rect| rail.contains_rect(*rect)), + "状态头的进度条用已填待验的琥珀色:{rail:?} 对 {painted:?}"); + } + + #[test] + fn production_head_and_open_list_agree_on_a_waiting_sub_agent() { + use super::super::agent_stream::{STAGE_WAITING, worker_stage}; + 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()), + _ => {} + } + } + fn running_dots(shape: &egui::Shape, color: Color32, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| running_dots(shape, color, out)), + egui::Shape::Circle(circle) if circle.radius == 2.25 && circle.fill == color => out.push(circle.center), + _ => {} + } + } + // Every step the workflow reports for a sub-agent still held by an + // earlier request, and three that are not. + for step in ["正在等待原请求", "正在等待原任务结果…", "正在核查原请求…", "正在核查原结果…", "正在核查原模型请求", "正在定位原请求…"] { + assert_eq!(worker_stage(step, false, false), STAGE_WAITING, "{step} 仍在等上一条请求的结果"); + } + for (step, stage) in [("正在生图", "生图"), ("正在准备提示词", "准备"), ("正在验图", "验图"), ("已排队", "排队")] { + assert_eq!(worker_stage(step, false, false), stage, "{step}"); + } + for dock in [250.0, 520.0] { + let (mut app, _) = dock_fixture(); + app.ui.dock_tabs.color = 4; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + crate::panels::request_dock_width(&ctx, dock); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.composer.clear(); + w.busy = Some("pi-agent".into()); + w.pi_run = Some("visual-qa".into()); + w.pi_product_production = true; + w.messages = vec![ + json!({"role":"user","text":"制作详情、主图和 SKU"}), + json!({"role":"assistant","kind":"reply","text":"先做首屏的产品场景图。"}), + json!({"role":"assistant","kind":"image-job","taskId":"qa-pending","run":"visual-qa", + "width":4,"height":5,"workerNumber":1,"slotLabel":"S01 - 首屏产品场景","step":"正在生图"}), + ]; + w.workflow.set_production_progress(&json!({"heading":"正在分派详情页图片","rendered":2,"total":21, + "workers":[{"number":1,"slotId":"hero","label":"首屏产品场景","step":"正在生图","active":true}, + {"number":2,"slotId":"space","label":"空间搭配图","step":"正在核查原请求…","active":true}, + {"number":3,"slotId":"detail","label":"同款细节图","step":"正在等待原请求","active":true}]})); + let mut seen = Vec::new(); + let mut dot_centers = Vec::new(); + let running_color = Tokens::get(&ctx).agent().accent_text; + let frame = |app: &mut PhotocraftApp, events: Vec, seen: &mut Vec, dots_out: &mut Vec| { + let output = ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), events, ..Default::default() + }, |ui| crate::panels::right_dock(app, ui)); + seen.clear(); + dots_out.clear(); + for shape in &output.shapes { + texts(&shape.shape, seen); + running_dots(&shape.shape, running_color, dots_out); + } + output.drop_without_applying_deltas(); + }; + let center = |rect: &Value| { + let (x, y, width, height) = (rect[0].as_f64().unwrap() as f32, rect[1].as_f64().unwrap() as f32, + rect[2].as_f64().unwrap() as f32, rect[3].as_f64().unwrap() as f32); + egui::pos2(x + width / 2.0, y + height / 2.0) + }; + let button = |pos: egui::Pos2, pressed: bool| vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ]; + for _ in 0..6 { frame(&mut app, vec![], &mut seen, &mut dot_centers); } + // Collapsed: the summary row names both waiting sub-agents the one way. + let shown = seen.join(" / "); + assert_eq!(seen.iter().filter(|text| text.ends_with(STAGE_WAITING)).count(), 2, "面板宽 {dock}:{shown}"); + assert!(seen.iter().all(|text| !text.contains("待查") && !text.contains("等回执")), "面板宽 {dock}:{shown}"); + // Open the head the way a pointer does. + let toggle = center(&app.jiansun.as_ref().unwrap().panel_geometry["productionProgressTag"]); + frame(&mut app, button(toggle, true), &mut seen, &mut dot_centers); + frame(&mut app, button(toggle, false), &mut seen, &mut dot_centers); + for _ in 0..3 { frame(&mut app, vec![], &mut seen, &mut dot_centers); } + let shown = seen.join(" / "); + let count_line = format!("生图 1 · {STAGE_WAITING} 2"); + assert!(seen.iter().any(|text| text == &count_line), "展开后的统计行,面板宽 {dock}:{shown}"); + let list = app.jiansun.as_ref().unwrap().panel_geometry["productionWorkers"].as_array().cloned().unwrap_or_default(); + assert_eq!(list.len(), 3, "展开后的列表,面板宽 {dock}:{shown}"); + for (number, expected) in [(1_usize, 1_usize), (2, 0), (3, 0)] { + let row = &list[number - 1]; + assert_eq!(row["worker"].as_u64(), Some(number as u64)); + let rect = &row["indicator"]; + let indicator = Rect::from_min_size(egui::pos2(rect[0].as_f64().unwrap() as f32, rect[1].as_f64().unwrap() as f32), + egui::vec2(rect[2].as_f64().unwrap() as f32, rect[3].as_f64().unwrap() as f32)); + let painted = dot_centers.iter().filter(|dot| indicator.contains(**dot)).count(); + assert_eq!(painted, expected, "子代理 {number} 的运行状态点,面板宽 {dock}"); + } + } + } + + #[test] + fn interactive_timeline_rows_light_up_for_keyboard_focus() { + use super::super::agent_stream::{EventRow, EventTone, RowAction}; + fn fills(shape: &egui::Shape, fill: Color32, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| fills(shape, fill, out)), + egui::Shape::Rect(rect) if rect.fill == fill => out.push(rect.rect), + _ => {} + } + } + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&ctx); + let hover = Tokens::get(&ctx).agent().hover; + let row = std::cell::Cell::new(Rect::NOTHING); + let frame = |events: Vec, lit: &mut Vec| { + let mut output = ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(600.0, 200.0))), events, ..Default::default() + }, |ui| { super::super::stitch_ui::scope_with_motion(ui, true, |ui| { + row.set(super::super::agent_stream::event_row(ui, Id::unique("focus-row"), EventRow { + glyph: "settings", text: "工具调用 · 1/2 已完成", meta: None, tone: EventTone::Quiet, + hint: None, action: RowAction::Expand(false), + }, true).rect); + }); }); + lit.clear(); + for shape in &output.shapes { fills(&shape.shape, hover, lit); } + output.textures_delta.clear(); + }; + let mut lit = Vec::new(); + frame(vec![], &mut lit); + frame(vec![], &mut lit); + assert!(lit.is_empty(), "an untouched row is not lit: {lit:?}"); + frame(vec![egui::Event::Key { key: egui::Key::Tab, physical_key: Some(egui::Key::Tab), pressed: true, + repeat: false, modifiers: egui::Modifiers::NONE }], &mut lit); + frame(vec![], &mut lit); + assert!(lit.iter().any(|rect| *rect == row.get()), "keyboard focus lights the row like hover: {:?} 对 {lit:?}", row.get()); + } + + #[test] + fn queued_image_slots_take_one_line_and_only_the_running_slot_takes_its_card() { + let (mut app, _) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.pi_run = Some("running".into()); + let job = |run: &str| json!({"role":"assistant","kind":"image-job","taskId":format!("job-{run}"),"run":run, + "width":4,"height":5,"workerNumber":1,"slotLabel":"第10屏 · 打磨与触感场景图","step":"正在生图"}); + fn canvas_rects(shape: &egui::Shape, canvas: Color32, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| canvas_rects(shape, canvas, out)), + egui::Shape::Rect(rect) if rect.fill == canvas => out.push(rect.rect.height()), + _ => {} + } + } + let canvas = crate::theme::Tokens::get(&ctx).agent().canvas; + let output = ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 900.0))), + ..Default::default() + }, |ui| { + ui.set_width(620.0); + ui.horizontal(|ui| { + w.image_result(ui, &job("running"), 300.0, None); + w.image_result(ui, &job("later"), 300.0, None); + }); + }); + let mut heights = Vec::new(); + for shape in &output.shapes { canvas_rects(&shape.shape, canvas, &mut heights); } + heights.sort_by(f32::total_cmp); + output.drop_without_applying_deltas(); + // 300pt at 4:5 is a 272×340 card; a queued slot keeps the height of one line. + assert_eq!(heights, vec![32.0, 340.0]); + } + + #[test] + fn starter_suggestions_sit_above_the_composer_and_only_fill_the_draft() { + use super::super::agent_stream::SUGGESTION_ROW_HEIGHT; + let (mut app, requests) = dock_fixture(); + app.ui.dock_tabs.color = 4; + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.composer.clear(); + w.messages.clear(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } + let w = app.jiansun.as_ref().unwrap(); + let prompts = w.panel_geometry["quickPrompts"].as_array().expect("starter suggestions sit above the composer").clone(); + assert_eq!(prompts.len(), 2); + assert_eq!(prompts[0]["label"], "梳理资料"); + assert!(w.panel_geometry["followupPrompts"].is_null(), "the starter pair and the follow-ups never stack"); + let first = &prompts[0]["rect"]; + let composer = geometry(w, "composer"); + let bottom = first[1].as_f64().unwrap() as f32 + first[3].as_f64().unwrap() as f32; + assert!(bottom <= composer.top() + 1.0 && bottom >= composer.top() - SUGGESTION_ROW_HEIGHT - 2.0, + "the row hugs the composer: chip bottom {bottom}, composer {composer:?}"); + let value = |index: usize| first[index].as_f64().unwrap() as f32; + let pos = pos2(value(0) + value(2) / 2.0, value(1) + value(3) / 2.0); + for pressed in [true, false] { + dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(pos), egui::Event::PointerButton { + pos, button:egui::PointerButton::Primary, pressed, modifiers:egui::Modifiers::NONE, + }]); + } + dock_frame(&ctx, &mut app, vec![]); + let w = app.jiansun.as_ref().unwrap(); + assert!(w.composer.contains("请读取当前项目资料"), "choosing a suggestion fills the draft: {}", w.composer); + assert!(w.busy.is_none()); + assert!(!requests.try_iter().any(|request| matches!(request, Request::Action(method, _) if method == "agent" || method == "image"))); + } + + #[test] + fn empty_conversation_says_what_xiaoyi_does_and_leaves_once_something_is_said() { + 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 app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.composer.clear(); + w.messages.clear(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let mut seen = Vec::new(); + let frame = |app: &mut PhotocraftApp, seen: &mut Vec| { + let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), ..Default::default() }, |ui| { + crate::panels::right_dock(app, ui) + }); + seen.clear(); + for clipped in &output.shapes { texts(&clipped.shape, seen); } + output.textures_delta.clear(); + }; + for _ in 0..3 { frame(&mut app, &mut seen); } + for line in ["小壹可以帮你", "为图位生成候选图,采纳后放进画布", "写详情页文案,并核对卖点依据", "整套制作详情、主图和 SKU", + "在下面的输入框里写下需求,或点一条建议开始。"] { + assert!(seen.iter().any(|text| text == line), "an empty conversation shows「{line}」"); + } + assert!(!seen.iter().any(|text| text == "我的项目"), "a project is open, so the projects entry stays out of the way"); + app.jiansun.as_mut().unwrap().messages = vec![json!({"role":"user","text":"这一屏的光线柔和一点"})]; + for _ in 0..3 { frame(&mut app, &mut seen); } + assert!(!seen.iter().any(|text| text == "小壹可以帮你"), "the guidance leaves with the first message"); + assert!(requests.try_recv().is_err(), "guidance sends nothing"); + } + + #[test] + fn picture_progress_counts_rendered_first_previews_and_ignores_unplaced_candidates() { + use super::super::agent_stream::Cell; + use photocraft_doc::{Layer, LayerContent}; + use photocraft_geom::Rect as PixelRect; + let (mut app, _requests) = dock_fixture(); + let mut doc = app.session.active().unwrap().doc.as_ref().clone(); + let mut pixels = photocraft_raster::Surface::new(doc.pixel_format()); + pixels.fill_rect(PixelRect::from_xywh(0, 0, 12, 12), &[0.25, 0.25, 0.25, 1.0]); + let applied = Layer::new("accepted", LayerContent::Raster(pixels.clone())); + let mut preview = Layer::new("first preview", LayerContent::Raster(pixels.clone())); + preview.visible = false; + let mut empty = Layer::new("empty", LayerContent::Raster(pixels)); + empty.visible = false; + let (adopted, first, spare) = (applied.id, preview.id, empty.id); + doc.metadata.text.extend([ + ("jiansun.slot-mapping.v1".into(), json!({"component":"detail","variantId":"wood"}).to_string()), + ("jiansun.adopted.wood.applied".into(), "accepted".into()), + ]); + doc.layers.extend([applied, preview.clone(), empty]); + app.session.add_document(doc, None); + let doc_id = app.session.active().unwrap().doc.id.0; + let slots = [("applied", adopted), ("first", first), ("spare", spare)]; + app.jiansun.as_mut().unwrap().template_workflow = json!({"canvasFirst":true,"outputId":"detail","variantId":"wood", + "slots":slots.map(|(id, layer)| json!({"id":id,"nativeLayerId":layer.0,"outputId":"detail","variantId":"wood"}))}); + let progress = json!({"outputId":"detail","variantId":"wood","pictureCells":slots.map(|(id, _)| json!({"slotId":id}))}); + let statuses = |app: &PhotocraftApp| { + let mut cells = [Cell::Verified, Cell::Empty, Cell::Filled]; + production_image_cells(app, app.jiansun.as_ref().unwrap(), &progress, &mut cells); + cells + }; + assert_eq!(statuses(&app), [Cell::Verified, Cell::Empty, Cell::Empty]); + let tx = app.jiansun.as_ref().unwrap().tx.clone(); + let binding = json!({"doc":doc_id,"nativeLayerId":first.0,"candidateId":"first-image"}); + app.queue_slot_preview(&tx, first, binding.clone()); + assert_eq!(statuses(&app), [Cell::Verified, Cell::Empty, Cell::Empty]); + preview.visible = true; + app.receive_slot_preview(&binding, Some(Box::new(preview))); + assert_eq!(statuses(&app), [Cell::Verified, Cell::Preview, Cell::Empty]); + } + + #[test] + fn cell_rail_wraps_distinct_cells_and_keeps_its_counts() { + use super::super::agent_stream::{Cell, ROW, cell_rail}; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let cells: Vec = (0..45).map(|index| if index < 8 { + Cell::Verified + } else if index < 37 { + Cell::Filled + } else { + Cell::Empty + }).collect(); + let mut rails = Vec::new(); + for width in [520.0, 250.0] { + ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 400.0))), + ..Default::default() + }, |ui| { + ui.set_width(width); + let before = ui.cursor().top(); + let rail = cell_rail(ui, Id::unique(("rail", width as u64)), "文案", &cells, false, |index| format!("第 {} 项", index + 1)); + let spent = ui.cursor().top() - before; + rails.push((rail["total"].clone(), rail["filled"].clone(), rail["verified"].clone(), rail["rect"][2].clone(), rail["rect"][3].clone(), rail["bar"].clone(), spent)); + }).drop_without_applying_deltas(); + } + for (total, filled, verified, rail_width, rail_height, bar, spent) in rails { + assert_eq!((total, filled, verified), (json!(45), json!(37), json!(8))); + assert_eq!(bar, false); + let width = rail_width.as_f64().unwrap(); + let height = rail_height.as_f64().unwrap() as f32; + assert_eq!(height > ROW, width < 300.0); + assert!((spent - height).abs() < 8.0); + + } + } + + #[test] + fn production_reply_uses_readable_references_in_live_and_saved_text() { + let workflow = json!({"outputs":[{"documentId":"front","name":"展示页","fields":[ + {"fieldId":"front-copy","kind":"text","label":"标题"}, + {"fieldId":"S09-T02","kind":"image","label":"产品全貌"} + ]}]}); + let display = |text, streaming| production_reply_text(text, streaming, &workflow); + assert_eq!(display("front 的 front-copy 对应 S09-T02,原图 P03。", false), + "展示页 的 标题 对应 产品全貌,原图 P03。"); + assert_eq!(display("正在修订 S09-T0", true), "正在修订 S09-T0"); + assert_eq!(display("已制作用于 SKU", true), "已制作用于 SKU"); + assert_eq!(display("核对 sources、links 和分句索引", false), + "核对 资料来源、图文对应关系 和句子对应关系"); + assert_eq!(display("正在补图。[{\"name\":\"delegate_image_slots\"}]继续验图。", false), + "正在补图。继续验图。"); + assert_eq!(display("正在补图。[{\"name\":", true), "正在补图。"); + assert_eq!(display("正在补图。 48.0); + app.jiansun.as_mut().unwrap().stream_reply.push_str("\n\nA second paragraph updates the active reply."); + dock_frame(&ctx, &mut app, vec![]); + assert!(panel(&app)["conversationBottomGap"].as_f64().unwrap() > 48.0, "reading history pauses automatic following"); + let jump = geometry(app.jiansun.as_ref().unwrap(), "latestMessage").center(); + for pressed in [true, false] { + dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(jump), egui::Event::PointerButton { + pos: jump, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, + }]); + } + for _ in 0..8 { + dock_frame(&ctx, &mut app, vec![]); + } + let gap = panel(&app)["conversationBottomGap"].as_f64().unwrap(); + assert!(gap < 1.0, "jump must reach the actual bottom, gap={gap}"); + app.jiansun.as_mut().unwrap().stream_reply.push_str("\n\nA third paragraph arrives after returning to the bottom."); + for _ in 0..4 { + dock_frame(&ctx, &mut app, vec![]); + } + let w = app.jiansun.as_ref().unwrap(); + assert!(panel(&app)["conversationBottomGap"].as_f64().unwrap() < 1.0); + assert!(geometry(w, "conversationClip").expand(1.0).contains_rect(geometry(w, "agentStatus"))); + } + + #[test] + fn composer_with_an_inline_reference_keeps_its_accessible_input_name() { + use egui_kittest::kittest::Queryable; + let (mut app, _) = dock_fixture(); + let mut workspace = app.jiansun.take().unwrap(); + workspace.composer.clear(); + workspace.reduce_motion = true; + let mut h = egui_kittest::Harness::builder().with_context_setup(crate::cjk_fonts::install_system_provider_for_tests).with_size(vec2(520.0, 300.0)).build_ui_state( + |ui, state: &mut (Workspace, PhotocraftApp)| state.0.composer_ui(&mut state.1, ui), (workspace, app)); + h.run_steps(3); + assert!(geometry(&h.state().0, "subject").width() > 0.0, "fixture must actually show an inline reference"); + h.check_accessibility(); + h.get_by_role_and_label(egui::accesskit::Role::MultilineTextInput, "小壹消息输入"); + } + + #[test] + fn candidate_trace_requires_one_real_matching_turn_and_rechecks_its_scope() { + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + let target = json!({"candidateId":"candidate-a","taskId":"task-a","slotId":"slot-a","productVariantId":"v-a"}); + let image = json!({"role":"assistant","kind":"image","taskId":"task-a", + "target":{"candidateId":"candidate-a","taskId":"task-a","slotId":"slot-a","productVariantId":"v-a"}}); + assert!(candidate_matches_message(&target, &image)); + assert!(!candidate_matches_message(&json!({"taskId":"task-a","slotId":"other"}), &image)); + assert!(!candidate_matches_message(&json!({"candidateId":"candidate-a","run":"different"}), &image)); + assert!(!candidate_matches_message(&json!({"slotId":"slot-a"}), &image)); + w.messages = vec![json!({"role":"user","text":"第一轮"}),image.clone()]; + w.trace_canvas_candidate(&app,target.clone()); + assert_eq!(w.pending_candidate_trace.as_ref().unwrap()["turn"],0); + w.pending_candidate_trace = None; + w.messages.extend([json!({"role":"user","text":"第二轮"}),image]); + w.trace_canvas_candidate(&app,target); + assert!(w.pending_candidate_trace.is_none(),"ambiguous history cannot select an arbitrary turn"); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn candidate_trace_scrolls_real_history_to_the_turn_and_stays_there() { + for reduced in [false, true] { + let (mut app, requests) = dock_fixture(); + app.ui.dock_tabs.color = 4; + let mut w = app.jiansun.take().unwrap(); + w.reduce_motion = reduced; + w.composer.clear(); + let target = json!({"candidateId":"candidate-a","taskId":"task-a","slotId":"slot-a"}); + w.messages.clear(); + for index in 0..18 { + w.messages.push(json!({"role":"user","text":format!("第 {index} 轮请求")})); + if index == 3 { + w.messages.push(json!({"role":"assistant","kind":"image","taskId":"task-a","target":target})); + } else { + w.messages.push(json!({"role":"assistant","kind":"reply","text":"本轮回复:保留产品结构与真实材质。"})); + } + } + app.jiansun = Some(w); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let frame = |app:&mut PhotocraftApp,time:f64| { + let _ = ctx.settle_ui(egui::RawInput { time:Some(time), + screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(960.0,600.0))), ..Default::default() + }, |ui| crate::panels::right_dock(app,ui)); + }; + for time in [0.0,0.1,0.2] { frame(&mut app,time); } + let initial = app.jiansun.as_ref().unwrap().panel_geometry["conversationScrollOffset"].as_f64().unwrap(); + let mut w = app.jiansun.take().unwrap(); + w.trace_canvas_candidate(&app,target.clone()); + app.jiansun = Some(w); + for time in [0.3,0.4,0.5,0.65,0.8] { frame(&mut app,time); } + let w = app.jiansun.as_ref().unwrap(); + let offset = w.panel_geometry["conversationScrollOffset"].as_f64().unwrap(); + assert!(offset < initial, "the chosen earlier turn moves into view"); + let turn = geometry(w,"candidateTraceRect"); + let clip = geometry(w,"conversationClip"); + assert!((turn.center().y-clip.center().y).abs() < 80.0, "target={turn:?}, viewport={clip:?}"); + frame(&mut app,1.0); + let settled = app.jiansun.as_ref().unwrap().panel_geometry["conversationScrollOffset"].as_f64().unwrap(); + assert!((settled-offset).abs() < 2.0, "the scroll area must not jump back to the bottom"); + let mut w = app.jiansun.take().unwrap(); + w.trace_canvas_candidate(&app,json!({"candidateId":"unknown"})); + app.jiansun = Some(w); + frame(&mut app,1.2); + assert!((app.jiansun.as_ref().unwrap().panel_geometry["conversationScrollOffset"].as_f64().unwrap()-settled).abs() < 2.0); + assert!(requests.try_recv().is_err()); + } + } + + #[test] + #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn candidate_trace_visual_acceptance() { + let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + let (mut app, requests) = dock_fixture(); + app.ui.dock_tabs.color = 4; + let target = json!({"candidateId":"candidate-a","taskId":"task-a","slotId":"slot-a"}); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = false; + w.composer.clear(); + w.messages.clear(); + for index in 0..18 { + w.messages.push(json!({"role":"user","text":format!("第 {index} 轮请求")})); + if index == 3 { + w.messages.push(json!({"role":"assistant","kind":"image","taskId":"task-a","target":target})); + } else { + w.messages.push(json!({"role":"assistant","kind":"reply","text":"本轮回复:保留产品结构与真实材质。"})); + } + } + let mut h = egui_kittest::Harness::builder().with_size(vec2(1280.0,800.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_ui_state( + |ui, app:&mut PhotocraftApp| { + if !ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } + crate::panels::title_bar(app,ui); + crate::panels::options_bar(app,ui); + crate::panels::status_bar(app,ui); + crate::panels::toolbar(app,ui); + crate::panels::right_dock(app,ui); + egui::CentralPanel::default().frame(Frame::NONE.fill(Tokens::get(ui.ctx()).canvas)) + .show(ui,|ui| crate::canvas::document_area(app,ui)); + },app); + PhotocraftApp::setup_context(&h.ctx,crate::theme::ThemeKind::ProMedium); + for time in [0.0,0.1,0.2] { h.input_mut().time=Some(time); h.step(); } + let old_offset = h.state().jiansun.as_ref().unwrap().panel_geometry["conversationScrollOffset"].as_f64().unwrap(); + let clip = geometry(h.state().jiansun.as_ref().unwrap(),"conversationClip"); + h.render().unwrap().save(std::path::Path::new(&directory).join("candidate-trace-before.png")).unwrap(); + { + let app = h.state_mut(); + let mut w = app.jiansun.take().unwrap(); + w.trace_canvas_candidate(app,target); + app.jiansun = Some(w); + } + let mut measurements = Vec::new(); + let mut lit_pixels = Vec::new(); + let mut settled_pixels = Vec::new(); + let mut image_width = 0usize; + for step in 0..=78 { + let time = 0.3 + f64::from(step) / 60.0; + h.input_mut().time=Some(time); h.step(); + let name = match step { 0 => "0ms", 9 => "150ms", 21 => "350ms", 22 => "366ms", 78 => "settled", _ => continue }; + let w = h.state().jiansun.as_ref().unwrap(); + let offset = w.panel_geometry["conversationScrollOffset"].as_f64().unwrap(); + measurements.push(json!({"frame":name,"time":time,"offset":offset, + "paintedTargetRect":w.panel_geometry["candidateTraceRect"],"clip":w.panel_geometry["conversationClip"]})); + let image = h.render().unwrap(); + if step == 22 { image_width = image.width() as usize; lit_pixels = image.as_raw().clone(); } + if step == 78 { settled_pixels = image.as_raw().clone(); } + image.save(std::path::Path::new(&directory).join(format!("candidate-trace-{name}.png"))).unwrap(); + } + let offset_150 = measurements[1]["offset"].as_f64().unwrap(); + let offset_350 = measurements[2]["offset"].as_f64().unwrap(); + let settled = measurements[4]["offset"].as_f64().unwrap(); + assert!(offset_150 < old_offset && offset_350 < offset_150,"the real scroll progresses toward the older turn"); + assert!((settled-offset_350).abs() < 2.0,"later frames do not pull the reader back to the bottom"); + let first = measurements[0]["paintedTargetRect"].as_array().unwrap(); + let first_rect = Rect::from_min_size(pos2(first[0].as_f64().unwrap() as f32,first[1].as_f64().unwrap() as f32), + vec2(first[2].as_f64().unwrap() as f32,first[3].as_f64().unwrap() as f32)); + assert!(!clip.intersects(first_rect),"the target begins outside the viewport"); + let centered = measurements[3]["paintedTargetRect"].as_array().unwrap(); + let target_rect = Rect::from_min_size(pos2(centered[0].as_f64().unwrap() as f32,centered[1].as_f64().unwrap() as f32), + vec2(centered[2].as_f64().unwrap() as f32,centered[3].as_f64().unwrap() as f32)); + assert!(clip.contains_rect(target_rect),"the target is visibly inside the viewport: {target_rect:?} in {clip:?}"); + assert!((target_rect.center().y-clip.center().y).abs() < 80.0,"the painted target is centered"); + let bounds = target_rect.intersect(clip); + let mut changed = 0usize; + for y in bounds.top().ceil() as usize..bounds.bottom().floor() as usize { + for x in bounds.left().ceil() as usize..bounds.right().floor() as usize { + let index = (y * image_width + x) * 4; + if lit_pixels.get(index..index+4) != settled_pixels.get(index..index+4) { changed += 1; } + } + } + assert!(changed > 20,"the visible target actually changes when its one-shot pulse exits"); + let evidence = json!({"initialOffset":old_offset,"initialTarget":rect_value(first_rect),"initialClip":rect_value(clip),"frames":measurements}); + std::fs::write(std::path::Path::new(&directory).join("candidate-trace.json"),serde_json::to_vec_pretty(&evidence).unwrap()).unwrap(); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn referencing_a_real_layer_opens_composer_and_accepts_keyboard_text() { + let (mut app, requests) = dock_fixture(); + app.session.execute("layer.new.layer", json!({"name":"引用目标"})).unwrap(); + let doc = app.session.active().unwrap().doc.id.0; + let layer = app.session.active().unwrap().selected_layers()[0].0; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + app.ui.dock_tabs.color = 0; + app.jiansun.as_mut().unwrap().composer.clear(); + assert!(super::super::action_in_ui(&mut app,&ctx,"composer-reference-add", + json!({"documentId":doc+1,"nativeLayerId":layer,"component":"layer"})).is_err()); + assert_eq!(app.ui.dock_tabs.color,0); + assert!(!ctx.memory(|memory| memory.has_focus(super::super::composer_input_id()))); + super::super::action_in_ui(&mut app,&ctx,"composer-reference-add", + json!({"documentId":doc,"nativeLayerId":layer,"component":"layer"})).unwrap(); + let frame = |app:&mut PhotocraftApp,time:f64,events| { + let _ = ctx.settle_ui(egui::RawInput { time:Some(time), events, + screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() + }, |ui| crate::panels::right_dock(app,ui)); + }; + for time in [0.0,0.2,0.4,0.6] { frame(&mut app,time,vec![]); } + assert_eq!(app.ui.dock_tabs.color,4); + assert_eq!(app.jiansun.as_ref().unwrap().panel_geometry["composerExpanded"],true); + assert!(ctx.memory(|memory| memory.has_focus(super::super::composer_input_id()))); + frame(&mut app,0.7,vec![egui::Event::Text("补充要求".into())]); + assert_eq!(app.jiansun.as_ref().unwrap().composer,"补充要求"); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn message_entry_keeps_following_content_fixed_at_zero_and_full_opacity() { + let render = |progress| { + let ctx = egui::Context::default(); + let mut result = None; + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(420.0,400.0))), ..Default::default() }, |ui| { + ui.set_width(320.0); + let message = agent_motion::message_visual(ui,progress,|ui| user_bubble(ui,"真实消息")); + let next = ui.label("下方消息"); + result = Some((message.response.rect,next.rect)); + }); + result.unwrap() + }; + let start = render(0.0); + let end = render(1.0); + assert_eq!(start.0,end.0,"entry owns its full layout from the first frame"); + assert_eq!(start.1,end.1,"following content cannot jump when the entrance ends"); + } + + #[test] + fn composer_send_pulse_belongs_to_the_accepted_action_and_never_to_history() { + for keyboard in [false, true] { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + w.reduce_motion = false; + let frame = |w: &mut Workspace, app: &mut PhotocraftApp, time: f64, events| { + let _ = ctx.settle_ui(egui::RawInput { time:Some(time), events, + screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), ..Default::default() }, |ui| { + w.composer_ui(app, ui); + }); + }; + frame(&mut w,&mut app,0.0,vec![]); + assert!(ctx.data(|data| data.get_temp::(Id::unique("composer-sent-glow"))).is_none()); + if keyboard { + ctx.memory_mut(|memory| memory.request_focus(Id::unique("jiansun-composer-input"))); + frame(&mut w,&mut app,0.3,vec![enter_event(egui::Modifiers::NONE,false)]); + } else { + let pos = geometry(&w,"send").center(); + for (time, pressed) in [(0.2,true),(0.3,false)] { + frame(&mut w,&mut app,time,vec![egui::Event::PointerMoved(pos),egui::Event::PointerButton { + pos,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); + } + } + assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,_) if method=="agent")); + let started = ctx.data(|data| data.get_temp::(Id::unique("composer-sent-glow"))).unwrap(); + assert_eq!(started,0.3); + let user_index=w.messages.iter().rposition(|message|message["role"]=="user").unwrap(); + assert_eq!(ctx.data(|data|data.get_temp::(w.user_reveal_id(Some(user_index)))),Some(started),"accepted submissions reveal even before the conversation baseline is drawn"); + frame(&mut w,&mut app,0.5,vec![]); + assert_eq!(ctx.data(|data| data.get_temp::(Id::unique("composer-sent-glow"))),Some(started), "repaint does not retrigger"); + w.reduce_motion = true; + frame(&mut w,&mut app,0.6,vec![]); + assert!(ctx.data(|data| data.get_temp::(Id::unique("composer-sent-glow"))).is_none()); + w.reduce_motion = false; + w.busy = None; + w.model_ready = false; + w.composer = "预检查失败仍保留".into(); + frame(&mut w,&mut app,1.0,vec![enter_release(),enter_event(egui::Modifiers::NONE,false)]); + assert_eq!(w.composer,"预检查失败仍保留"); + assert!(requests.try_recv().is_err()); + assert!(ctx.data(|data| data.get_temp::(Id::unique("composer-sent-glow"))).is_none()); + } + } + + #[test] + fn real_conversation_shapes_fit_narrow_and_wide_docks_without_clipping() { + fn collect(shape: &egui::Shape, ids: &[egui::TextureId], images: &mut Vec<(egui::TextureId, Rect)>, texts: &mut Vec<(String, Rect, usize)>) { + match shape { + egui::Shape::Vec(shapes) => { + for child in shapes { + collect(child, ids, images, texts); + } + } + egui::Shape::Rect(rect) if ids.contains(&rect.fill_texture_id()) => images.push((rect.fill_texture_id(), rect.rect)), + egui::Shape::Text(text) => texts.push((text.galley.text().to_owned(), Rect::from_min_size(text.pos, text.galley.size()), text.galley.rows.len())), + _ => {} + } + } + + let reply = "这是一段需要完整显示的长中文回复:请保留产品的真实外观、花色和结构,同时让自然光更柔和,让桌面细节清晰,确保所有内容按照当前侧栏宽度换行,不能被右边界裁掉。"; + for dock_width in [288.0, 320.0, 400.0] { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let mut ids = Vec::new(); + for index in 1..=3 { + let image = egui::ColorImage::filled([96, 128], Color32::from_rgb(65 * index as u8, 60, 40)); + let texture = ctx.load_texture(format!("layout-proof-{dock_width}-{index}"), image, egui::TextureOptions::LINEAR); + ids.push(texture.id()); + app.jiansun.as_mut().unwrap().agent_images.insert(format!("task-{index}"), texture); + } + { + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.creation_brief = json!({"variants":[{"id":"teak","name":"非常长的真实花色名称"}]}); + w.template_workflow = json!({"slots":[ + {"id":"slot-1","documentId":"P1","label":"首屏产品场景主图","candidates":[{"id":"task-1"},{"id":"task-2"}]}, + {"id":"slot-2","documentId":"P2","label":"木纹细节","candidates":[{"id":"task-3"}]} + ]}); + w.messages = vec![ + json!({"role":"user","text":"你好"}), + json!({"role":"assistant","kind":"reply","text":reply}), + json!({"role":"assistant","kind":"image","taskId":"task-1","slotId":"slot-1","productVariantId":"teak"}), + json!({"role":"assistant","kind":"image","taskId":"task-2","slotId":"slot-1","productVariantId":"teak"}), + json!({"role":"assistant","kind":"image","taskId":"task-3","slotId":"slot-2","productVariantId":"teak"}), + ]; + } + crate::panels::request_dock_width(&ctx, dock_width); + let mut output = None; + for _ in 0..4 { + let mut frame = ctx.settle_ui( + egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 1550.0))), ..Default::default() }, + |ui| crate::panels::right_dock(&mut app, ui), + ); + frame.textures_delta.clear(); + output = Some(frame); + } + let output = output.unwrap(); + let clip = geometry(app.jiansun.as_ref().unwrap(), "conversationClip"); + let mut images = Vec::new(); + let mut texts = Vec::new(); + for shape in &output.shapes { + collect(&shape.shape, &ids, &mut images, &mut texts); + } + let reply_shape = texts.iter().find(|(text, _, _)| text == reply).expect("the complete selectable reply must be painted"); + assert!(reply_shape.2 > 1, "long Chinese reply wraps at dock width {dock_width}"); + assert!(reply_shape.1.left() >= clip.left() && reply_shape.1.right() <= clip.right() + 1.0, "reply must fit its visible viewport at {dock_width}: {:?} in {clip:?}", reply_shape.1); + let mut image_rects = Vec::new(); + for (index, id) in ids.iter().enumerate() { + let image = images.iter().find(|(texture, _)| texture == id).expect("each result has one real image").1; + let (page, number) = if index == 2 { ("P2", "候选 1") } else if index == 1 { ("P1", "候选 2") } else { ("P1", "候选 1") }; + let caption = format!("{page} · {number}"); + assert!(texts.iter().any(|(text, rect, _)| text == &caption && image.contains_rect(*rect)), + "{caption} must be painted inside its own image at width {dock_width}"); + assert!(image.left() >= clip.left() && image.right() <= clip.right() + 1.0, "image exceeds the conversation at {dock_width}: {image:?}"); + image_rects.push(image); + } + if dock_width >= 400.0 { + assert!(image_rects[0].right() <= image_rects[1].left()); + assert!(image_rects[0].bottom() <= image_rects[2].top()); + } else if dock_width == 288.0 { + assert!(image_rects.windows(2).all(|pair| pair[0].bottom() <= pair[1].top())); + } + assert!(requests.try_recv().is_err(), "drawing result history must not issue a model request"); + } + } + + #[test] + fn image_light_surface_spans_the_conversation_column() { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + app.jiansun.as_mut().unwrap().busy = Some("slot-generate".into()); + for _ in 0..3 { + dock_frame(&ctx, &mut app, vec![]); + } + let workspace = app.jiansun.as_ref().unwrap(); + let processing = geometry(workspace, "processing"); + let panel = geometry(workspace, "panel"); + assert!(processing.width() >= panel.width() - 32.0, "the actual processing light must not collapse to a tiny status pill"); + assert!(geometry(workspace, "stop").right() <= panel.right(), "the real stop control stays usable"); + assert!(requests.try_recv().is_err(), "painting a running state never dispatches a model request"); + } + + #[test] + fn conversation_wait_uses_the_shared_unframed_loader_instead_of_the_image_task_surface() { + for busy in ["agent", "pi-agent", "slot-copy"] { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + app.jiansun.as_mut().unwrap().busy = Some(busy.into()); + for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } + let w = app.jiansun.as_ref().unwrap(); + assert!(w.panel_geometry["agentStatus"].is_array(), "{busy} keeps a stable AI Loader row"); + assert!(w.panel_geometry["processing"].is_null(), "{busy} must not use the image task frame"); + assert!(w.panel_geometry["processingPlaceholder"].is_null()); + assert!(w.panel_geometry["processingBlob"].is_null()); + assert_eq!(w.panel_geometry["processingLightMode"], "inactive"); + let status = geometry(w, "agentStatus"); + let stop = geometry(w, "taskStop"); + assert!(status.height() <= 30.0 && stop.height() <= 30.0, "{busy}: status={status:?}, stop={stop:?}"); + assert!(requests.try_recv().is_err(), "waiting UI never starts a real request"); + } + } + + #[test] + fn one_turn_keeps_reply_anchor_and_manual_disclosure_across_realistic_tool_gaps() { + fn collect(shape: &egui::Shape, out: &mut Vec<(String, Rect)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, out)), + egui::Shape::Text(text) => out.push((text.galley.text().to_owned(), Rect::from_min_size(text.pos, text.galley.size()))), + _ => {} + } + } + fn frame(ctx: &egui::Context, w: &Workspace, time: f64, events: Vec) -> Vec<(String, Rect)> { + let output = ctx.settle_ui(egui::RawInput { + screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,900.0))),time:Some(time),events,..Default::default() + }, |ui| { + ui.set_width(520.0); + let turn = turns(&w.messages).pop().unwrap(); + w.turn_ui(ui, turn, Id::unique("stable-conversation-trace"), w.messages.len(), true, false, None); + }); + let mut texts = Vec::new(); + for shape in &output.shapes { collect(&shape.shape, &mut texts); } + output.drop_without_applying_deltas(); + texts + } + fn click(ctx: &egui::Context, w: &Workspace, time: f64, pos: egui::Pos2) { + for (offset, pressed) in [(0.0, true),(0.1, false)] { + frame(ctx,w,time+offset,vec![egui::Event::PointerMoved(pos),egui::Event::PointerButton { + pos,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE + }]); + } + } + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.busy = Some("pi-agent".into()); + w.stream_reply = "标题已完成,继续补充细线。".into(); + w.messages = vec![json!({"role":"user","text":"请完成标题和细线"}), + json!({"role":"assistant","kind":"activity","text":"开始:组合画布操作","event":{ + "version":1,"type":"tool","run":"trace-run","toolCallId":"one","toolName":"codemode","status":"started"}})]; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let initial = frame(&ctx,w,0.0,vec![]); + let reply_top = initial.iter().find(|(text,_)|text==&w.stream_reply).unwrap_or_else(|| panic!("reply shape missing: {initial:?}")).1.top(); + let summary_top = initial.iter().find(|(text,_)|text == "正在组合画布操作…").unwrap().1.top(); + assert!(summary_top < reply_top, "the processing summary precedes the live reply"); + w.messages[1]["event"]["status"] = json!("completed"); + frame(&ctx,w,0.1,vec![]); + let gap = frame(&ctx,w,6.2,vec![]); + assert!(gap.iter().any(|(text,_)|text=="组合画布操作"), "completed tools stay expanded during a provider wait"); + assert!(gap.iter().find(|(text,_)|text == "已完成 · 组合画布操作").unwrap().1.top() < gap.iter().find(|(text,_)|text==&w.stream_reply).unwrap().1.top()); + let header = gap.iter().find(|(text,_)|text == "已完成 · 组合画布操作").unwrap().1.center(); + click(&ctx,w,6.3,header); + w.messages.push(json!({"role":"assistant","kind":"activity","text":"开始:执行原生操作","event":{ + "version":1,"type":"tool","run":"trace-run","toolCallId":"two","toolName":"native_call","status":"started"}})); + let closed = frame(&ctx,w,12.5,vec![]); + assert!(!closed.iter().any(|(text,_)|text=="组合画布操作" || text=="执行原生操作"), "new tools must respect the reader's collapsed state"); + assert!(closed.iter().find(|(text,_)|text == "已完成 1 项 · 正在执行原生操作…").unwrap().1.top() < closed.iter().find(|(text,_)|text==&w.stream_reply).unwrap().1.top()); + let header = closed.iter().find(|(text,_)|text == "已完成 1 项 · 正在执行原生操作…").unwrap().1.center(); + click(&ctx,w,12.6,header); + w.busy = None; + let held = frame(&ctx,w,20.0,vec![]); + assert!(held.iter().any(|(text,_)|text=="组合画布操作"), "manual expansion remains open after the whole turn ends"); + + let automatic = egui::Context::default(); + PhotocraftApp::setup_context(&automatic, crate::theme::ThemeKind::ProMedium); + w.busy = Some("pi-agent".into()); + frame(&automatic,w,30.0,vec![]); + w.busy = None; + frame(&automatic,w,31.0,vec![]); + assert!(frame(&automatic,w,31.4,vec![]).iter().any(|(text,_)|text=="组合画布操作")); + assert!(frame(&automatic,w,31.7,vec![]).iter().any(|(text,_)|text=="组合画布操作"), "the group stays visible during the completion hold"); + assert!(!frame(&automatic,w,32.9,vec![]).iter().any(|(text,_)|text=="组合画布操作")); + w.busy = Some("pi-agent".into()); + w.messages[2]["event"]["status"] = json!("completed"); + w.messages.push(json!({"role":"assistant","kind":"activity","text":"开始:读取画布","event":{ + "version":1,"type":"tool","run":"trace-run","toolCallId":"three","toolName":"canvas_read","status":"started"}})); + let next = frame(&automatic,w,33.0,vec![]); + assert!(next.iter().any(|(text,_)|text=="执行原生操作")); + assert!(next.iter().any(|(text,_)|text=="读取画布"), "new tool start and previous completion keep the disclosure open"); + assert!(requests.try_recv().is_err(), "the synthetic timing trace cannot issue a provider or native mutation"); + } + + #[test] + fn real_turn_layout_has_parallel_thinking_tools_and_response_with_one_loader() { + fn circles(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| circles(shape, out)), + egui::Shape::Circle(circle) if (circle.radius - 3.0).abs() < 0.01 => out.push(circle.center), + _ => {} + } + } + fn texts(shape: &egui::Shape, out: &mut Vec<(String, Rect)>) { + 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(), Rect::from_min_size(text.pos, text.galley.size()))), + _ => {} + } + } + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.busy = Some("pi-agent".into()); + w.stream_reply = "正式回复".into(); + w.messages = vec![json!({"role":"user","text":"用户请求"}), + json!({"role":"assistant","kind":"thinking","active":true,"text":"内部思考内容"}), + json!({"role":"assistant","kind":"activity","text":"工具一","event":{"version":1,"type":"tool","run":"r","toolCallId":"a","toolName":"codemode","status":"completed"}}), + json!({"role":"assistant","kind":"activity","text":"工具二","event":{"version":1,"type":"tool","run":"r","toolCallId":"b","toolName":"native_call","status":"started"}})]; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 900.0))), ..Default::default() }, |ui| { + ui.set_width(520.0); + let turn = turns(&w.messages).pop().unwrap(); + w.turn_ui(ui, turn, Id::unique("one-loader-test"), w.messages.len(), true, false, None); + w.agent_status_ui(ui, true); + }); + let mut labels = Vec::new(); + for shape in &output.shapes { texts(&shape.shape, &mut labels); } + let top = |label: &str| labels.iter().find(|(text, _)| text.starts_with(label)).unwrap_or_else(|| panic!("missing {label}: {labels:?}")).1.top(); + assert!(top("用户请求") < top("正在深度思考…") && top("正在深度思考…") < top("已完成 1 项 · 正在执行原生操作…")); + assert!(top("已完成 1 项 · 正在执行原生操作…") < top("正式回复")); + assert!(!labels.iter().any(|(text, _)| text == "内部思考内容")); + let mut dots = Vec::new(); + for shape in &output.shapes { circles(&shape.shape, &mut dots); } + assert_eq!(dots.len(), 3, "one three-dot loader for the entire turn"); + assert!((dots[0].y - dots[1].y).abs() < 0.01 && (dots[1].y - dots[2].y).abs() < 0.01); + assert!((dots[1].x - dots[0].x - 8.0).abs() < 0.01 && (dots[2].x - dots[1].x - 8.0).abs() < 0.01, + "the 6pt dots retain fixed, equally spaced positions"); + assert!(requests.try_recv().is_err()); + output.drop_without_applying_deltas(); + } + + #[test] + fn production_replies_are_inline_between_tools_and_thinking() { + fn texts(shape: &egui::Shape, out: &mut Vec<(String, Rect)>) { + 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(), Rect::from_min_size(text.pos, text.galley.size()))), + _ => {} + } + } + fn frame(ctx: &egui::Context, w: &Workspace, events: Vec) -> Vec<(String, Rect)> { + let mut out = Vec::new(); + let output = ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 900.0))), events, ..Default::default() + }, |ui| { + ui.set_width(520.0); + let turn = turns(&w.messages).pop().unwrap(); + w.turn_ui(ui, turn, Id::unique("narration-test"), w.messages.len(), true, false, None); + }); + for shape in &output.shapes { texts(&shape.shape, &mut out); } + output.drop_without_applying_deltas(); + out + } + let rows_of = |labels: &[(String, Rect)], prefix: &str| -> Vec { + labels.iter().filter(|(text, _)| text.starts_with(prefix)).map(|(_, rect)| rect.top()).collect() + }; + let shows = |labels: &[(String, Rect)], prefix: &str| labels.iter().any(|(text, _)| text.starts_with(prefix)); + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + { + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.busy = Some("pi-agent".into()); + w.stream_reply = "全部图位已完成。".into(); + w.messages = vec![json!({"role":"user","text":"制作详情、主图和 SKU"}), + json!({"role":"assistant","kind":"reply","text":"我先核对原图。"}), + json!({"role":"assistant","kind":"reply","text":"模板已就绪。"}), + json!({"role":"assistant","kind":"activity","text":"读取画布","event":{ + "version":1,"type":"tool","run":"fold","toolCallId":"read","toolName":"canvas_read","status":"completed"}}), + json!({"role":"assistant","kind":"reply","text":"正在安排图位。"}), + json!({"role":"assistant","kind":"thinking","active":false,"output":{}})]; + } + for _ in 0..2 { frame(&ctx, app.jiansun.as_ref().unwrap(), vec![]); } + let labels = frame(&ctx, app.jiansun.as_ref().unwrap(), vec![]); + assert!(!shows(&labels, "过程说明")); + let order = ["我先核对原图。", "模板已就绪。", "已完成 · 读取画布", "正在安排图位。", "已深度思考", "全部图位已完成。"]; + let positions: Vec<_> = order.iter().map(|prefix| rows_of(&labels, prefix)[0]).collect(); + assert!(positions.windows(2).all(|rows| rows[0] < rows[1]), "{labels:?}"); + assert!(requests.try_recv().is_err()); + + } + + type HandoffText = (String, Rect, u8, Vec); + type HandoffMesh = Vec<(egui::Pos2, u8)>; + + fn handoff_frame(ctx: &egui::Context, w: &Workspace, time: f64, conversation: Id) -> (Vec, Vec) { + fn collect(shape: &egui::Shape, texts: &mut Vec, meshes: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, texts, meshes)), + egui::Shape::Text(text) => { + let alpha = text.galley.rows.iter().flat_map(|row| &row.visuals.mesh.vertices).map(|vertex| vertex.color.a()).max().unwrap_or(0); + // The selectable label is intentionally transparent; inspect + // the real glyph layer and its per-section masks instead. + if alpha > 0 { texts.push((text.galley.text().to_owned(), Rect::from_min_size(text.pos, text.galley.size()), alpha, + text.galley.rows.iter().flat_map(|row| row.glyphs.iter().filter(|glyph| !glyph.uv_rect.is_nothing()) + .map(|glyph| row.visuals.mesh.vertices.get(glyph.first_vertex as usize).map_or(0, |vertex| vertex.color.a()))).collect())); } + } + egui::Shape::Mesh(mesh) => meshes.push(mesh.vertices.iter().map(|vertex| (vertex.pos, vertex.color.a())).collect()), + _ => {} + } + } + let output = ctx.settle_ui(egui::RawInput { + screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,900.0))),time:Some(time),..Default::default() + }, |ui| { + ui.set_width(520.0); + let turn = turns(&w.messages).pop().unwrap(); + w.turn_ui(ui,turn,conversation,w.messages.len(),true, false, None); + }); + let mut texts = Vec::new(); + let mut meshes = Vec::new(); + for shape in &output.shapes { collect(&shape.shape, &mut texts, &mut meshes); } + output.drop_without_applying_deltas(); + (texts, meshes) + } + + #[test] + fn thinking_is_a_status_during_and_after_a_turn_and_old_text_stays_hidden() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.busy = Some("pi-agent".into()); + w.messages = vec![json!({"role":"user","text":"请分析"}), + json!({"role":"assistant","kind":"thinking","active":true,"text":"独立思考原文", + "output":{"tokens":128,"tokensPerSecond":43.5,"estimated":true}})]; + let id = Id::unique("thinking-alone"); + let (running, _) = handoff_frame(&ctx, w, 0.0, id); + assert!(running.iter().any(|(text,_,_,_)| text == "正在深度思考…")); + assert!(!running.iter().any(|(text,_,_,_)| text.contains("tokens") || text.contains("tok/s"))); + assert!(!running.iter().any(|(text,_,_,_)| text == "独立思考原文")); + assert!(!running.iter().any(|(text,_,_,_)| text.starts_with("工具调用"))); + w.busy = None; + let (interrupted, _) = handoff_frame(&ctx, w, 0.2, id); + assert!(interrupted.iter().any(|(text,_,_,_)| text == "思考已中断")); + w.messages[1]["active"] = json!(false); + w.messages[1]["output"] = json!({"tokens":145,"tokensPerSecond":45.0,"estimated":false}); + w.messages.push(json!({"role":"assistant","kind":"activity","event":{ + "version":1,"type":"tool","run":"thinking-test","toolCallId":"read","toolName":"canvas_read", + "status":"completed","durationMs":12}})); + w.messages.push(json!({"role":"assistant","kind":"reply","text":"分析结论"})); + let (finished, _) = handoff_frame(&ctx, w, 0.3, id); + assert!(!finished.iter().any(|(text,_,_,_)| text == "独立思考原文")); + assert!(!finished.iter().any(|(text,_,_,_)| text.contains("tokens") || text.contains("tok/s"))); + assert!(finished.iter().any(|(text,_,_,_)| text == "12ms")); + let header = finished.iter().find(|(text,_,_,_)| text == "已深度思考").unwrap().1.center(); + for pressed in [true, false] { + ctx.settle_ui(egui::RawInput { time:Some(0.5), events:vec![egui::Event::PointerMoved(header), + egui::Event::PointerButton { pos:header, button:egui::PointerButton::Primary, pressed, modifiers:egui::Modifiers::NONE }], + screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,900.0))), ..Default::default() }, |ui| { + ui.set_width(520.0); + w.turn_ui(ui, turns(&w.messages).pop().unwrap(), id, w.messages.len(), true, false, None); + }).drop_without_applying_deltas(); + } + let (reopened, _) = handoff_frame(&ctx, w, 0.7, id); + assert!(!reopened.iter().any(|(text,_,_,_)| text == "独立思考原文")); + assert!(!reopened.iter().any(|(text,_,_,_)| text.starts_with("工具调用"))); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn a_final_receipt_and_lingering_stream_keep_one_response_and_finish_its_glow() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = false; + w.busy = Some("pi-agent".into()); + w.messages = vec![json!({"role":"user","text":"发送历史"})]; + w.stream_reply = "回复保持在原位置".into(); + let id = Id::unique("lingering-stream"); + handoff_frame(&ctx,w,0.0,id); + let (before,_) = handoff_frame(&ctx,w,0.3,id); + let top = before.iter().find(|(text,_,_,_)| text==&w.stream_reply).unwrap().1.top(); + w.messages.push(json!({"role":"assistant","kind":"reply","text":w.stream_reply})); + w.busy = None; + w.unknown = true; + let (after, meshes) = handoff_frame(&ctx,w,0.4,id); + let response:Vec<_> = after.iter().filter(|(text,_,_,_)| text==&w.stream_reply).collect(); + assert_eq!(response.len(),1); + assert_eq!(response[0].1.top(),top); + assert!(after.iter().any(|(text,_,_,_)| text=="输出未完成"), "handoff retains the real incomplete-output warning"); + assert!(!meshes.is_empty(), "the live reply carries its remaining glow across handoff"); + let (_, rested) = handoff_frame(&ctx, w, 3.2, id); + assert!(rested.is_empty(), "the lasting receipt never replays the finished glow"); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn live_receipt_overlap_keeps_one_body_and_one_anchor_while_the_turn_continues() { + for (live, receipt, expected) in [("答复前缀", "答复前缀", "答复前缀"), + ("答复前缀和新内容", "答复前缀", "答复前缀和新内容"), + ("答复前缀", "答复前缀和新内容", "答复前缀和新内容")] { + let ctx=egui::Context::default(); + PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let (mut app,requests)=dock_fixture(); + let w=app.jiansun.as_mut().unwrap(); + w.reduce_motion=true; + w.busy=Some("pi-agent".into()); + w.messages=vec![json!({"role":"user","text":"继续当前任务"})]; + w.stream_reply=live.into(); + let id=Id::unique("live-handoff-overlap"); + let (before,_)=handoff_frame(&ctx,w,0.0,id); + let top=before.iter().find(|(text,_,_,_)|text==live).unwrap().1.top(); + w.messages.push(json!({"role":"assistant","kind":"reply","text":receipt})); + let (after,_)=handoff_frame(&ctx,w,0.1,id); + let bodies:Vec<_>=after.iter().filter(|(text,_,_,_)|text.starts_with("答复前缀")).collect(); + assert_eq!(bodies.len(),1,"live={live}, receipt={receipt}"); + assert_eq!(bodies[0].0,expected); + assert_eq!(bodies[0].1.top(),top); + assert!(requests.try_recv().is_err()); + } + } + + #[test] + fn a_non_tool_activity_never_creates_a_processing_summary() { + let ctx=egui::Context::default(); + PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let (mut app,requests)=dock_fixture(); + let w=app.jiansun.as_mut().unwrap(); + w.reduce_motion=true; + w.messages=vec![json!({"role":"user","text":"确认记录"}), + json!({"role":"assistant","kind":"activity","text":"已采纳图片,可撤销"}), + json!({"role":"assistant","kind":"reply","text":"正文结论"})]; + let (texts,_)=handoff_frame(&ctx,w,0.0,Id::unique("activity-without-tools")); + assert!(!texts.iter().any(|(text,_,_,_)|text.starts_with("工具调用"))); + assert!(texts.iter().any(|(text,_,_,_)|text=="图片采纳记录")); + assert!(texts.iter().any(|(text,_,_,_)|text=="正文结论")); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn streamed_final_reply_keeps_its_anchor_and_only_fades_a_genuinely_new_suffix() { + for (stream, final_text, appending) in [ + ("已完成矩形", "已完成矩形", false), + ("准备处理。已完成矩形", "已完成矩形", false), + ("已完成矩形,并适配视图。", "已完成矩形", false), + ("已完成", "已完成矩形", true), + ] { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = false;w.busy = Some("pi-agent".into()); + w.messages = vec![json!({"role":"user","text":"完成当前操作"})]; + w.stream_reply = stream.into(); + let id = Id::unique("completed-stream-trace"); + handoff_frame(&ctx,w,0.0,id); + let (before, _) = handoff_frame(&ctx,w,0.70,id); + let top = before.iter().find(|(text,_,_,_)|text==stream).unwrap().1.top(); + w.messages.push(json!({"role":"assistant","kind":"reply","text":final_text})); + w.stream_reply.clear();w.busy = None; + let (first, _) = handoff_frame(&ctx,w,0.80,id); + let visible = if appending { "已完成矩" } else { final_text }; + let (_,rect,alpha,sections) = first.iter().find(|(text,_,_,_)|text==visible) + .expect("the already visible reply cannot disappear for its final message entrance"); + assert_eq!(rect.top(),top,"finishing the same turn cannot replay its five-point arrival offset"); + assert_eq!(*alpha,255,"the already displayed prefix stays fully opaque"); + if appending { + assert!(sections.first()==Some(&255) && sections.last()==Some(&0), "the old prefix remains opaque: {sections:?}"); + let (during, _) = handoff_frame(&ctx,w,0.90,id); + let (_,_,alpha,sections) = during.iter().find(|(text,_,_,_)| text==final_text).unwrap(); + assert_eq!(*alpha,255); + assert!(sections.first()==Some(&255) && sections.last().is_some_and(|alpha| *alpha > 0 && *alpha < 255)); + assert_eq!(during.iter().filter(|(text,_,_,_)| text==final_text).count(), 1); + let reveal = super::super::typing_text::ENTER + 2.0 * super::super::typing_text::STEP; + let (settled, _) = handoff_frame(&ctx,w,0.80 + reveal + 0.05,id); + let (_,_,alpha,sections) = settled.iter().find(|(text,_,_,_)| text==final_text).unwrap(); + assert_eq!(*alpha,255); + assert!(sections.iter().all(|alpha| *alpha == 255), "the final suffix settles after its glyphs arrive"); + } + assert!(requests.try_recv().is_err()); + } + } + + #[test] + fn legacy_stream_without_user_row_hands_off_to_the_same_visible_reply() { + fn collect(shape: &egui::Shape, out: &mut Vec<(Rect, u8)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, out)), + egui::Shape::Text(text) if text.galley.text() == "无用户行的流式回复" => { + let alpha = text.galley.rows.iter().flat_map(|row| &row.visuals.mesh.vertices) + .map(|vertex| vertex.color.a()).max().unwrap_or(0); + if alpha > 0 { out.push((Rect::from_min_size(text.pos, text.galley.size()), alpha)); } + } + _ => {} + } + } + let (mut app, requests) = dock_fixture(); + app.ui.dock_tabs.color = 4; + let w = app.jiansun.as_mut().unwrap(); + w.messages.clear(); + w.stream_reply = "无用户行的流式回复".into(); + w.busy = Some("pi-agent".into()); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let frame = |app: &mut PhotocraftApp, time| { + let output = ctx.settle_ui(egui::RawInput { + time:Some(time),screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() + }, |ui| crate::panels::right_dock(app, ui)); + let mut found = Vec::new(); + for shape in &output.shapes { collect(&shape.shape, &mut found); } + found + }; + frame(&mut app,0.0); + let before = frame(&mut app,0.65); + assert_eq!(before.len(), 1); + let w = app.jiansun.as_mut().unwrap(); + w.messages.push(json!({"role":"assistant","kind":"reply","text":"无用户行的流式回复"})); + w.stream_reply.clear(); + w.busy = None; + let after = frame(&mut app,0.75); + assert_eq!(after.len(), 1, "the final receipt must paint exactly once"); + assert_eq!(after[0].1, 255, "visible text must not restart its opacity entrance"); + assert_eq!(after[0].0.top(), before[0].0.top(), "the reply keeps its vertical anchor"); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn identical_final_reply_finishes_last_stream_batch_without_jumping() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.busy = Some("pi-agent".into()); + w.messages = vec![json!({"role":"user","text":"请回答"})]; + w.stream_reply = "已完成".into(); + let id = Id::unique("early-final-trace"); + handoff_frame(&ctx,w,0.0,id); + handoff_frame(&ctx,w,0.3,id); + w.stream_reply = "已完成矩形".into(); + let (during, _) = handoff_frame(&ctx,w,0.4,id); + let top = during.iter().find(|(text,_,_,_)|text=="已完成矩").unwrap().1.top(); + w.messages.push(json!({"role":"assistant","kind":"reply","text":"已完成矩形"})); + w.stream_reply.clear(); + w.messages.push(json!({"role":"assistant","kind":"activity","event":{ + "version":1,"type":"tool","run":"trace","toolCallId":"call_trace|fc_trace","toolName":"canvas_read","status":"started"}})); + let (after, _) = handoff_frame(&ctx,w,0.5,id); + let (_,rect,alpha,sections) = after.iter().find(|(text,_,_,_)|text=="已完成矩形").unwrap(); + assert_eq!(rect.top(), top); + assert_eq!(*alpha, 255); + assert!(sections.last().is_some_and(|alpha| *alpha > 0 && *alpha < 255)); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn a_different_or_unstreamed_reply_still_has_its_normal_message_entrance() { + for previous in [None,Some("这是另一段已显示的文字")] { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = false;w.busy = Some("pi-agent".into()); + w.messages = vec![json!({"role":"user","text":"请直接回答"})]; + w.stream_reply = previous.unwrap_or("").into(); + let id = Id::unique("new-reply-trace"); + handoff_frame(&ctx,w,0.0,id);handoff_frame(&ctx,w,0.3,id); + w.messages.push(json!({"role":"assistant","kind":"reply","text":"这是一条真正的新回复"})); + w.stream_reply.clear();w.busy = None; + let (first, _) = handoff_frame(&ctx,w,0.4,id); + let first = first.iter().find(|(text,_,_,_)|text=="这是一条真正的新回复"); + assert!(first.is_none_or(|(_,_,alpha,_)|*alpha<255), "new content starts its own message entrance"); + let (settled, _) = handoff_frame(&ctx,w,1.0,id); + assert_eq!(settled.iter().find(|(text,_,_,_)|text=="这是一条真正的新回复").unwrap().2,255); + assert!(requests.try_recv().is_err()); + } + } + + #[test] + fn historical_adoption_note_does_not_claim_live_undo_after_native_undo() { + fn labels(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| labels(shape, out)), + egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), + _ => {} + } + } + let (mut app, requests) = dock_fixture(); + app.session.execute("layer.new.layer", json!({"name":"临时编辑"})).unwrap(); + app.session.execute("edit.undo", json!({})).unwrap(); + let messages = vec![ + json!({"role":"user","text":"采纳这张图片"}), + json!({"role":"assistant","kind":"activity","text":"已采纳图片,可撤销"}), + json!({"role":"user","text":"检查其他操作"}), + json!({"role":"assistant","kind":"activity","text":"已完成:保留其他图层"}), + ]; + { + let w = app.jiansun.as_mut().unwrap(); + w.messages = messages.clone(); + w.reduce_motion = true; + } + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let mut output = None; + for _ in 0..3 { + output = Some(ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 1000.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui))); + } + let mut text = Vec::new(); + for shape in &output.unwrap().shapes { labels(&shape.shape, &mut text); } + assert!(text.iter().any(|label| label.contains("图片采纳记录")), "the painted history uses a past-tense label"); + assert!(text.iter().all(|label| !label.contains("已采纳图片,可撤销")), "undo must not leave a false live undo promise"); + assert!(text.iter().any(|label| label.contains("已完成:保留其他图层")), "unrelated activity text is unchanged"); + assert_eq!(app.jiansun.as_ref().unwrap().messages, messages, "rendering never rewrites stored conversation history"); + assert_eq!(activity_history_label("其他可撤销操作"), "其他可撤销操作", "only the known historical note is normalized"); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn structured_tool_activity_uses_real_status_and_never_displays_raw_fields() { + let statuses = [ + ("pending", "等待"), ("started", "进行中"), ("completed", "已完成"), + ("failed", "失败"), ("stopped", "已停止"), ("unexpected", "状态未知"), + ]; + for (state, label) in statuses { + let event = json!({"version":1,"type":"tool","status":state,"toolName":"canvas_read", + "summary":"secret summary","arguments":"secret argument","output":"secret output"}); + let (visible, _) = tool_activity_label(&event).unwrap(); + assert_eq!(visible, format!("{label} · 读取画布")); + assert!(!visible.contains("secret")); + } + let foreign = json!({"version":1,"type":"tool","status":"started","toolName":"secret tool"}); + assert_eq!(tool_activity_label(&foreign).unwrap().0, "进行中 · 工具"); + let timed = json!({"version":1,"type":"tool","status":"completed","toolName":"canvas_read","durationMs":1250}); + assert_eq!(tool_activity_label(&timed).unwrap().0, "已完成 · 读取画布 · 1.3s"); + assert_eq!((duration_text(25), duration_text(9_999), duration_text(27_400), duration_text(61_200)), + ("25ms".to_owned(), "10.0s".to_owned(), "27s".to_owned(), "1m01s".to_owned())); + let running = json!({"version":1,"type":"tool","status":"started","toolName":"canvas_read","durationMs":1250}); + assert_eq!(tool_activity_label(&running).unwrap().0, "进行中 · 读取画布", "never invent an elapsed time from a nonterminal event"); + let invalid = json!({"version":1,"type":"tool","status":"completed","toolName":"canvas_read","durationMs":-1}); + assert_eq!(tool_activity_label(&invalid).unwrap().0, "已完成 · 读取画布"); + let messages = vec![ + json!({"role":"user","text":"检查画布"}), + json!({"role":"assistant","kind":"activity","text":"legacy record"}), + json!({"role":"assistant","kind":"activity","text":"sanitized", "event":foreign}), + ]; + let grouped = turns(&messages); + assert!(matches!(grouped[0].items.as_slice(), + [TurnItem::Notice("legacy record", _), TurnItem::Tools(tools)] if tools.len() == 1)); + } + + #[test] + fn active_tool_timer_needs_a_matching_running_event_and_real_timestamp() { + let message = json!({"event":{"version":1,"type":"tool","run":"run-a","status":"started","timestampMs":10_000}}); + assert_eq!(active_tool_elapsed(std::slice::from_ref(&message), Some("run-a"), 12_500), Some(2_500)); + assert_eq!(active_tool_elapsed(std::slice::from_ref(&message), Some("run-b"), 12_500), None); + assert_eq!(active_tool_elapsed(std::slice::from_ref(&message), None, 12_500), None); + assert_eq!(active_tool_elapsed(std::slice::from_ref(&message), Some("run-a"), 9_999), None); + let completed = json!({"event":{"version":1,"type":"tool","run":"run-a","status":"completed","timestampMs":10_000}}); + assert_eq!(active_tool_elapsed(&[completed], Some("run-a"), 12_500), None); + let invalid = json!({"event":{"version":1,"type":"tool","run":"run-a","status":"started","timestampMs":-1}}); + assert_eq!(active_tool_elapsed(&[invalid], Some("run-a"), 12_500), None); + } + + #[test] + fn model_names_read_as_names_and_unknown_ids_stay_verbatim() { + assert_eq!(model_display_name("gpt-image-2.5-flare-burst"), "GPT Image 2.5 Flare Burst"); + assert_eq!(model_display_name("nano-banana-pro-4k-vip"), "Nano Banana Pro 4K VIP"); + assert_eq!(model_display_name("Copy One"), "Copy One"); + assert_eq!(model_display_name("discussion"), "discussion"); + assert_eq!(model_display_name("team-special-v2"), "team-special-v2", "one unknown word keeps the whole id"); + } + + #[test] + fn tool_activity_labels_real_reconcile_workflow_and_preview_without_accepting_unknown_names() { + for (name, expected) in [("native_reconcile","核查原生任务"),("workflow_execute","执行创作操作"), + ("canvas_preview","预览修改"),("unregistered_secret","工具")] { + let event=json!({"version":1,"type":"tool","status":"started","toolName":name}); + assert_eq!(tool_activity_label(&event).unwrap().0,format!("进行中 · {expected}")); + } + } + + #[test] + fn context_ring_real_click_opens_its_details() { + let ctx=egui::Context::default(); PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let screen=Rect::from_min_size(egui::Pos2::ZERO,vec2(600.0,400.0)); + let id=std::cell::Cell::new(Id::NULL); let rect=std::cell::Cell::new(Rect::NOTHING); + let frame=|events| { + let _=ctx.settle_ui(egui::RawInput { screen_rect:Some(screen),events,..Default::default() },|ui| { + let response=context_meter(ui,None,true,true); id.set(response.id); rect.set(response.rect); + }); + }; + frame(vec![]); let pos=rect.get().center(); + frame(vec![egui::Event::PointerMoved(pos)]); + for pressed in [true,false] { frame(vec![egui::Event::PointerButton {pos,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE}]); } + assert!(egui::Popup::is_id_open(&ctx,id.get().with("popup")),"a real click opens context details"); + } + + #[test] + fn hovering_context_ring_paints_only_one_capacity_tooltip() { + fn count(shape:&egui::Shape, wanted:&str) -> usize { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().map(|shape| count(shape,wanted)).sum(), + egui::Shape::Text(text) => usize::from(text.galley.text()==wanted), + _ => 0, + } + } + let ctx=egui::Context::default(); + PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + ctx.all_styles_mut(|style| style.interaction.tooltip_delay=0.0); + let rect=std::cell::Cell::new(Rect::NOTHING); + let frame=|time,events| ctx.settle_ui(egui::RawInput { time:Some(time),screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(600.0,300.0))),events,..Default::default() },|ui| { + rect.set(context_meter(ui,None,true,true).rect); + }); + frame(0.0,vec![]); + frame(1.0,vec![egui::Event::PointerMoved(rect.get().center())]); + let mut actual=0; + for index in 1..=8 { + let output=frame(1.0+f64::from(index)*0.1,vec![]); + actual=output.shapes.iter().map(|shape|count(&shape.shape,CONTEXT_PENDING)).sum(); + } + assert_eq!(actual,1,"the shared ring owns the sole tooltip"); + } + + #[test] + #[ignore = "offscreen GPU visual acceptance for the single shared context tooltip"] + fn context_tooltip_visual_acceptance() { + let directory=std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + let rect=std::cell::Cell::new(Rect::NOTHING); + let mut h=egui_kittest::Harness::builder().with_size(vec2(400.0,180.0)).with_pixels_per_point(1.5).with_step_dt(0.1).wgpu().build_ui(|ui| { + let t=Tokens::get(ui.ctx()).agent(); + ui.painter().rect_filled(ui.max_rect(),0.0,t.dock); + rect.set(context_meter(ui,None,true,true).rect); + }); + PhotocraftApp::setup_context(&h.ctx,crate::theme::ThemeKind::ProMedium); + h.ctx.all_styles_mut(|style|style.interaction.tooltip_delay=0.0); + h.run_steps(4); h.hover_at(rect.get().center()); h.run_steps(12); + h.render().unwrap().save(std::path::Path::new(&directory).join("context-single-tooltip.png")).unwrap(); + } + + + #[test] + fn context_meter_uses_selected_pi_capacity_with_the_existing_receipt() { + let models=vec![json!({"key":"grok","id":"grok-4.7","contextWindow":500000,"contextWindowSource":"pi-model-catalog:xai/grok-4.7"}),json!({"key":"other","id":"other","contextWindow":1000000,"contextWindowSource":"pi"})]; + let usage=json!({"version":1,"model":"grok-4.7","modelKey":"grok","contextTokens":17572,"contextSource":"pi-last-response","contextWindow":null}); + let selected=context_for_model(&usage,&models,"grok").unwrap();assert_eq!(context_label(Some(&selected)),"18K/500K"); + let other=context_for_model(&usage,&models,"other").unwrap();assert_eq!(context_fraction(Some(&other)),None);assert_eq!(other["contextWindow"],1000000); + assert!(!context_label(Some(&selected)).contains("tokens"));assert!(!context_label(Some(&other)).contains("未知")); + } + #[test] + fn model_visibility_hides_history_and_unready_chat_without_an_allowlist() { + for id in [ + "gpt-5.6-sol", "gpt-5.6-terra", "gpt-6-astra", "gpt-6-sol", "gpt-6.1-sol", + "gpt-6.1-terra", "gpt-6.2-astra", "glm-5.3", "glm-5.3-flashx", "glm-5.3-prime", + "claude-fable-5-1", "claude-opus-4-5-20251101", "claude-opus-4-6", "claude-opus-5-5", + "claude-haiku-4-5-20251001", "claude-sonnet-4-6", "gemini-3-flash", "gemini-3.1-pro", + "gemini-3.8-pro", "gemini-4-argon", "gemini-4-carbon", "grok-4.5", "grok-4.6", + "world-generation", "deepseek-ocr", + ] { + let model = json!({"id":id, "productionReady":true}); + assert!(is_hidden_model(ModelRole::Chat, &model), "{id}"); + assert!(is_hidden_model(ModelRole::Copy, &model), "{id}"); + } + for id in [ + "gpt-6.2-sol", "claude-sonnet-5-5", "claude-sonnet-5", "claude-haiku-5-5", + "gemini-4-hydrogen", "gemini-4-neon", "grok-4.7", "deepseek-v4.1-flash-1017", + "qwen4-max", "98k-future-visual", + ] { + assert!(!is_hidden_model(ModelRole::Chat, &json!({"id":id, "productionReady":true})), "{id}"); + } + let text_only = json!({"id":"text-only", "productionReady":false}); + assert!(is_hidden_model(ModelRole::Chat, &text_only)); + assert!(!is_hidden_model(ModelRole::Copy, &text_only)); + assert!(!is_hidden_model(ModelRole::Chat, &json!({"id":"98k-future"}))); + } + + #[test] + fn model_picker_preserves_saved_history_and_toggles_other_hidden_options() { + use egui_kittest::{Harness, kittest::Queryable}; + + for width in [960.0, 360.0] { + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + w.reduce_motion = true; + w.available_models = None; + w.model = "saved-alias".into(); + w.models = vec![ + json!({"key":"saved-alias","id":"claude-opus-4-6","productionReady":true,"productionVerified":true}), + json!({"key":"history","id":"grok-4.6","productionReady":true,"productionVerified":true}), + json!({"key":"text","id":"text-only","productionReady":false,"imageInputStatus":"disabled"}), + json!({"key":"new","id":"gpt-6.2-sol","productionReady":true,"productionVerified":true}), + json!({"key":"future","id":"98k-future-visual"}), + ]; + let snapshots = std::env::var_os("PHOTOCRAFT_MODEL_PICKER_SNAPSHOTS"); + let builder = Harness::builder().with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(vec2(width, 600.0)); + let builder = if snapshots.is_some() { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state(|ui, w: &mut Workspace| { + w.model_picker(ui, ModelRole::Chat, 180.0, true); + }, w); + let mut click = |label: &str| { + let point = h.get_by_label(label).rect().center(); + h.hover_at(point); + h.run_steps(2); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: point, button: egui::PointerButton::Primary, + pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(4); + }; + click("claude-opus-4-6"); + let toggle = "显示历史/全部模型"; + let legacy = "grok-4.6 · 可制作"; + let text_only = "text-only · 仅文本"; + for show_all in [false, true, false] { + assert_eq!(h.state().show_all_models, show_all); + assert!(h.query_by_label("claude-opus-4-6 · 可制作").is_some()); + assert!(h.query_by_label("gpt-6.2-sol · 可制作").is_some()); + assert!(h.query_by_label("98k-future-visual").is_some()); + assert_eq!(h.query_by_label(legacy).is_some(), show_all); + assert_eq!(h.query_by_label(text_only).is_some(), show_all); + if let Some(path) = &snapshots { + h.render().unwrap().save(std::path::Path::new(path).join(format!("models-{width}-{show_all}.png"))).unwrap(); + } + h.get_by_label(toggle).click(); + h.run_steps(4); + } + assert_eq!(h.state().model, "saved-alias"); + assert!(requests.try_recv().is_err()); + } + } + + #[test] + fn switching_a_model_saves_only_that_preference_with_the_connected_key() { + use egui_kittest::{Harness, kittest::Queryable}; + + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + w.reduce_motion = true; + w.copy_model = "one".into(); + w.copy_models = vec![json!({"key":"one","id":"Copy One"}), json!({"key":"two","id":"Copy Two"})]; + w.available_models = Some(vec!["Copy One".into(), "Copy Two".into()]); + w.copy_ready = true; + let mut h = Harness::builder().with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(vec2(600., 500.)).build_ui_state(|ui, w: &mut Workspace| { + w.model_picker(ui, ModelRole::Copy, 300., true); + }, w); + h.run_steps(5); + for label in ["Copy One", "Copy Two"] { + let point = h.get_by_label(label).rect().center(); + h.hover_at(point); + h.run_steps(2); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { + pos:point,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE, + }); + h.run_steps(1); + } + h.run_steps(4); + } + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected a local preference action") }; + assert_eq!(method, "select-model"); + assert_eq!(input["field"], "copyModel"); + assert_eq!(input["selection"], "two"); + assert!(input.get("key").is_none()); + assert!(h.state().model_ready && h.state().copy_ready && h.state().image_ready); + let w = h.state_mut(); + w.receive_model_preference(&input); + assert_eq!(w.copy_model, "two"); + assert_eq!(w.model, "discussion"); + assert_eq!(w.image_model, "image"); + assert!(w.model_ready && w.copy_ready && w.image_ready); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn model_menu_exit_stays_above_the_settings_panel() { + fn text_order(shape:&egui::Shape,labels:&mut Vec){match shape{egui::Shape::Vec(shapes)=>for shape in shapes{text_order(shape,labels)},egui::Shape::Text(text)=>labels.push(text.galley.text().into()),_=>{}}} + let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let (mut app,requests)=dock_fixture();let w=app.jiansun.as_mut().unwrap();w.model_settings=true;w.reduce_motion=false; + w.copy_models=vec![json!({"key":"a","id":"文案当前模型"}),json!({"key":"b","id":"文案备选模型"})];w.copy_model="a".into();w.available_models=None; + let frame=|w:&mut Workspace,time:f64,events|ctx.settle_ui(egui::RawInput{time:Some(time),events,screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(800.0,700.0))),..Default::default()},|ui|{let anchor=ui.button("设置");w.settings_popup(ui,&anchor);}); + for i in 0..20 {let _=frame(w,f64::from(i)*0.05,vec![]);} + let id=ctx.data(|data|data.get_temp::(Id::unique(("agent-model-last-popup",ModelRole::Copy,true)))).unwrap();egui::Popup::open_id(&ctx,id); + for i in 20..30 {let _=frame(w,f64::from(i)*0.05,vec![]);} + egui::Popup::close_id(&ctx,id); + for time in [1.501,1.55] { + let output=frame(w,time,vec![]);let mut labels=Vec::new();for clipped in &output.shapes{text_order(&clipped.shape,&mut labels);} + let panel=labels.iter().position(|label|label=="小壹设置").unwrap();let menu=labels.iter().position(|label|label=="文案备选模型").expect("the closing menu stays mounted");assert!(menu>panel,"the retained menu paints above its parent throughout exit"); + } + assert!(requests.try_recv().is_err());assert_eq!(w.copy_model,"a"); + } + #[test] + fn context_meter_keeps_chat_usage_when_copy_model_reports_usage() { + let (mut app,_requests)=dock_fixture();let w=app.jiansun.as_mut().unwrap(); + w.model="chat".into();w.models=vec![json!({"key":"chat","id":"chat-model"})]; + let chat=json!({"version":1,"model":"chat-model","modelKey":"chat","contextTokens":58000,"contextSource":"pi-last-response","contextWindow":1000000,"capacitySource":"pi-models"}); + w.receive_chat_context_usage(&chat);w.receive_chat_context_usage(&json!({"version":1,"model":"copy-model","modelKey":"copy","contextTokens":20000})); + assert_eq!(w.pi_context_usage,chat);assert_eq!(context_label(Some(&w.pi_context_usage)),"58K/1M"); + } + + #[test] + fn context_meter_never_treats_missing_or_invalid_measurement_as_zero() { + assert_eq!(context_fraction(None), None); + let mut usage=json!({"contextSource":"pi-session","contextTokens":25,"contextWindow":100,"capacitySource":"catalog", + "piContextUsage":{"tokens":25,"contextWindow":100,"percent":37.0}}); + assert_eq!(context_fraction(Some(&usage)), Some(0.37), "use Pi's percentage, not a local ratio"); + usage["piContextUsage"]["percent"]=Value::Null; assert_eq!(context_fraction(Some(&usage)), None); + usage["piContextUsage"]["percent"]=json!(101); assert_eq!(context_fraction(Some(&usage)), None); + usage["piContextUsage"]["percent"]=json!(25); usage["piContextUsage"]["contextWindow"]=json!(200); assert_eq!(context_fraction(Some(&usage)), None); + } + + #[test] + fn context_meter_shows_real_usage_without_inventing_capacity_or_crossing_models() { + let models = vec![json!({"key":"chat-a","id":"model-a"}), json!({"key":"chat-b","id":"model-b"})]; + let mut usage = json!({"version":1,"model":"model-a","modelKey":"chat-a","receipt":{"inputTokens":140,"cachedTokens":100}}); + assert_eq!(context_label(context_for_model(&usage, &models, "chat-a").as_ref()), CONTEXT_UNAVAILABLE); + assert_eq!(context_label(context_for_model(&usage, &models, "chat-b").as_ref()), CONTEXT_UNAVAILABLE); + usage["estimatedTokens"] = json!(200); + assert_eq!(context_label(Some(&usage)), CONTEXT_UNAVAILABLE, "discard the previous custom byte estimate"); + usage["contextTokens"] = json!(150); + usage["contextSource"] = json!("pi-last-response"); + assert_eq!(context_label(Some(&usage)), CONTEXT_UNAVAILABLE); + usage["contextTokens"] = json!(200); + usage["contextSource"] = json!("pi-session"); + usage["contextWindow"] = json!(1000); + assert_eq!(context_label(Some(&usage)), CONTEXT_UNAVAILABLE); + usage["capacitySource"] = json!("explicit-catalogue"); + usage["piContextUsage"] = json!({"tokens":200,"contextWindow":1000,"percent":20}); + assert_eq!(context_label(Some(&usage)), "200/1K"); + usage["contextTokens"] = json!(-1); + assert_eq!(context_label(Some(&usage)), "—/1K"); + } + + #[test] + fn readable_error_history_and_candidate_view_do_not_repeat_a_request_or_change_the_draft() { + let (mut app,requests)=dock_fixture(); + let mut w=app.jiansun.take().unwrap(); + w.origin="https://example.test".into(); + w.project_context=json!({"localId":"same-project"}); + w.owner_doc=app.session.active().map(|state|state.doc.id.0); + w.reduce_motion=true; + w.error="can't read smart source within the preview budget: pcraft: limit exceeded: canvas 1440x35827 exceeds 8192 pixels per side".into(); + w.template_workflow=json!({"slots":[{"candidates":[{"id":"retained-image","status":"complete"}]}]}); + let draft=w.composer.clone();let messages=w.messages.clone(); + let revision=app.session.active().unwrap().revision; + let ctx=egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let id=notification_id(&w.origin,&w.account,&w.project_context,w.owner_doc).unwrap(); + let mut history=AgentNotifications {open:true,..Default::default()}; + history.add("本地SDK操作失败;请检查原请求状态,勿重发"); + ctx.data_mut(|data|data.insert_temp(id,history)); + let out={ + let mut last=None; + for n in 0..5 { + last=Some(ctx.settle_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(500.,700.))),time:Some(n as f64*0.1),..Default::default()},|ui| {w.notifications_ui(ui);})); + } + last.unwrap() + }; + let text=out.shapes.iter().filter_map(|shape|match &shape.shape {egui::Shape::Text(text)=>Some(text.galley.text()),_=>None}).collect::>().join("\n"); + assert!(text.contains("当前问题")); + assert!(text.contains("图片暂时无法读取") && !text.contains("can't read smart source"),"technical details start collapsed"); + let rect:[f32;4]=serde_json::from_value(w.panel_geometry["notificationCandidates"].clone()).unwrap(); + let at=egui::pos2(rect[0]+rect[2]/2.,rect[1]+rect[3]/2.); + let mut clicked=false; + for (time,pressed) in [(0.6,true),(0.7,false)] { + let _=ctx.settle_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(500.,700.))),time:Some(time),events:vec![egui::Event::PointerMoved(at),egui::Event::PointerButton {pos:at,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE}],..Default::default()},|ui| {clicked|=w.notifications_ui(ui);}); + } + assert!(clicked); + assert!(requests.try_recv().is_err(),"viewing retained candidates must not call a model or send an operation"); + assert_eq!(w.composer,draft);assert_eq!(w.messages,messages); + assert_eq!(app.session.active().unwrap().revision,revision); + w.error.clear(); + ctx.data_mut(|data|data.get_temp_mut_or_default::(id).open=true); + let out=ctx.settle_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(500.,700.))),time:Some(1.),..Default::default()},|ui| {w.notifications_ui(ui);}); + let text=out.shapes.iter().filter_map(|shape|match &shape.shape {egui::Shape::Text(text)=>Some(text.galley.text()),_=>None}).collect::>().join("\n"); + assert!(text.contains("历史通知") && !text.contains("当前问题")); + assert_eq!(ctx.data(|data|data.get_temp::(id).unwrap().entries.len()),2,"historical records remain available after the active issue ends"); + } + + #[test] + fn notification_history_uses_real_errors_and_persisted_export_receipts() { + let mut history = AgentNotifications::default(); + let receipts = vec![ + json!({"text":"普通回复不会变成通知"}), + json!({"text":"保存副本时有导出提示:\n保留工程"}), + ]; + history.observe("", true, None, &[]); + history.observe("连接暂不可用", true, Some("提示库离线,本机内容已保留"), &receipts); + assert_eq!(history.entries.len(), 4); + history.observe("连接暂不可用", true, Some("提示库离线,本机内容已保留"), &receipts); + assert_eq!(history.entries.len(), 4, "a repaint cannot replay a notification"); + assert!(!history.entries.iter().any(|entry| entry.contains("普通回复"))); + history.observe("", false, None, &[]); + assert_eq!(history.entries.len(), 4, "resolved issues remain reviewable in the current session"); + for i in 0..45 { history.add(&format!("真实错误 {i}")); } + assert_eq!(history.entries.len(), 40, "session history stays bounded"); + } + + #[test] + fn notifications_fit_a_small_window_and_escape_preserves_history() { + let (tx, requests) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + while requests.try_recv().is_ok() {} + w.origin = "https://example.test".into(); + w.account = json!({"id":"owner"}); + w.project_context = json!({"localId":"qa"}); + w.owner_doc = Some(42); + w.reduce_motion = true; + let id = notification_id(&w.origin, &w.account, &w.project_context, w.owner_doc).unwrap(); + let ctx = egui::Context::default(); + let mut history = AgentNotifications { open:true, ..Default::default() }; + history.add(&"导出提示:请保留分层工程与原素材。".repeat(12)); + ctx.data_mut(|data| data.insert_temp(id, history)); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 300.0)); + for frame in 0..4 { + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(screen), time:Some(frame as f64 * 0.1), ..Default::default() }, |ui| {w.notifications_ui(ui);}); + } + let rect: [f32; 4] = serde_json::from_value(w.panel_geometry["notifications"].clone()).unwrap(); + assert!(screen.contains_rect(Rect::from_min_size(egui::pos2(rect[0],rect[1]),vec2(rect[2],rect[3]))), "long notifications must scroll inside the viewport: {rect:?}"); + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(screen), time:Some(0.5), events:vec![egui::Event::Key { + key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed:true, repeat:false, modifiers:egui::Modifiers::NONE, + }], ..Default::default() }, |ui| { + w.notifications_ui(ui); + assert!(!ui.input(|input| input.key_pressed(egui::Key::Escape)), "a handled close cannot leak to the underlying editor"); + }); + let history = ctx.data(|data| data.get_temp::(id)).unwrap(); + assert!(!history.open); + assert_eq!(history.entries.len(), 1, "closing a view never deletes its real warning"); + assert_eq!(w.panel_geometry["notificationsOpen"], false); + assert!(requests.try_recv().is_err(), "reviewing and closing notifications sends no backend request"); + } + + #[test] + fn notification_escape_has_priority_in_the_actual_composer_path() { + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + w.owner_doc = Some(app.session.active().unwrap().doc.id.0); + w.project_context = json!({"localId":"keyboard-review"}); + w.model_settings = true; + w.reduce_motion = true; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let id = notification_id(&w.origin, &w.account, &w.project_context, w.owner_doc).unwrap(); + ctx.data_mut(|data| data.insert_temp(id, AgentNotifications { open:true, ..Default::default() })); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0,600.0)); + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(screen), ..Default::default() }, |ui| w.composer_ui(&mut app, ui)); + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(screen), + events:vec![egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed:true, repeat:false, + modifiers:egui::Modifiers::NONE }], ..Default::default() }, |ui| w.composer_ui(&mut app, ui)); + assert!(!ctx.data(|data| data.get_temp::(id).unwrap().open)); + assert!(w.model_settings, "the underlying settings must not consume a close intended for the notification"); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn toast_and_morph_are_scoped_and_have_real_lifetimes() { + let toast = AgentToast { shown_at: 10.0 }; + assert!(toast_active(&toast, 10.0)); + assert!(toast_active(&toast, 12.39)); + assert!(!toast_active(&toast, 12.4)); + assert!(!toast_active(&toast, 9.9)); + assert!(!toast_active(&toast, f64::NAN)); + let account = json!({"id":"a"}); + let project = json!({"localId":"project"}); + let id = toast_id("https://one", &account, &project, Some(4)).unwrap(); + assert_ne!(Some(id), toast_id("https://other", &account, &project, Some(4))); + assert_ne!(Some(id), toast_id("https://one", &json!({"id":"b"}), &project, Some(4))); + assert_ne!(Some(id), toast_id("https://one", &account, &project, Some(5))); + assert_eq!(toast_id("https://one", &Value::Null, &project, Some(4)), None); + let conversation = Id::unique("project-a"); + assert_eq!(activity_morph_id(conversation, &[2, 5]), activity_morph_id(conversation, &[2, 5, 8])); + assert_ne!(activity_morph_id(conversation, &[2]), activity_morph_id(Id::unique("project-b"), &[2])); + assert_ne!(activity_morph_id(conversation, &[2]), activity_morph_id(conversation, &[3])); + } + + #[test] + fn copy_reply_emits_only_the_exact_visible_reply_on_user_click() { + let ctx = egui::Context::default(); + let mut rect = Rect::NOTHING; + let render = |time, events, rect: &mut Rect| ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 100.0))), time: Some(time), events, ..Default::default() + }, |ui| { *rect = copy_reply(ui, "真实中文回复").rect; }); + let idle = render(0.0, vec![], &mut rect); + assert!(idle.platform_output.commands.is_empty()); + let pos = rect.center(); + let pointer = |pressed| vec![egui::Event::PointerMoved(pos), egui::Event::PointerButton { + pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, + }]; + let _ = render(0.1, pointer(true), &mut rect); + let released = render(0.2, pointer(false), &mut rect); + assert_eq!(released.platform_output.commands, [egui::OutputCommand::CopyText("真实中文回复".into())]); + } + + #[test] + fn suggestions_preserve_draft_and_only_compare_real_candidates_in_the_selected_scope() { + let mut draft = "保留已有要求".to_owned(); + insert_suggestion(&mut draft, "先讨论画面"); + assert_eq!(draft, "保留已有要求\n先讨论画面"); + let mut empty = " ".to_owned(); + insert_suggestion(&mut empty, "梳理资料"); + assert_eq!(empty, "梳理资料"); + + let target = json!({"slotId":"one","productVariantId":"teak"}); + let mut workflow = json!({"slots":[{"id":"one","variantId":"teak","candidates":[ + {"id":"a","status":"complete"}, {"id":"b","status":"running"}, {"id":"c","status":"complete","variant":"walnut"} + ]}]}); + assert!(!has_comparable_candidates(&workflow, &target), "running or another variant is not a comparable result"); + workflow["slots"][0]["candidates"][1]["status"] = json!("complete"); + assert!(has_comparable_candidates(&workflow, &target)); + workflow["slots"][0]["candidates"][1]["id"] = json!("a"); + assert!(!has_comparable_candidates(&workflow, &target), "duplicate candidate IDs count only once"); + assert!(!has_comparable_candidates(&workflow, &json!({"slotId":"one"})), "unknown variant must not be guessed"); + } + + fn dock_click(ctx: &egui::Context, app: &mut PhotocraftApp, key: &str) { + let pos = geometry(app.jiansun.as_ref().unwrap(), key).center(); + for pressed in [true, false] { + dock_frame( + ctx, + app, + vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + dock_frame(ctx, app, vec![]); + } + + #[test] + fn conversation_places_choices_below_the_image_in_the_same_turn() { + fn label_top(shape: &egui::Shape, wanted: &str) -> Option { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().find_map(|shape| label_top(shape, wanted)), + egui::Shape::Text(text) if text.galley.text() == wanted => Some(text.pos.y), + _ => None, + } + } + let (mut app, _) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.messages = vec![ + json!({"role":"user","text":"生成首图"}), + json!({"role":"assistant","kind":"image","taskId":"layout-image"}), + json!({"role":"assistant","kind":"pi-ui-request","request":{"id":"choose","title":"首屏主图怎么处理"}}), + ]; + let mut output = ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(500.0, 800.0))), + ..Default::default() + }, |ui| { + let turn = turns(&w.messages).into_iter().next().unwrap(); + w.turn_ui(ui, turn, Id::unique("layout"), 1, true, false, None); + }); + output.textures_delta.clear(); + let top = |wanted| output.shapes.iter().find_map(|shape| label_top(&shape.shape, wanted)).unwrap(); + assert!(top("生成图片") < top("首屏主图怎么处理")); + } + + #[test] + fn conversation_preview_eviction_retains_measured_layout() { + let (mut app, _) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let frame = |app: &PhotocraftApp| { + let mut bounds = Rect::NOTHING; + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| { + let start = ui.cursor().min; + app.jiansun.as_ref().unwrap().image_result(ui, &json!({"taskId":"layout-image"}), 112.0, None); + bounds = Rect::from_min_max(start, ui.cursor().min); + }); + output.textures_delta.clear(); + bounds + }; + for size in [[100, 20], [20, 100]] { + let texture = ctx.load_texture("layout-image", egui::ColorImage::filled(size, Color32::WHITE), egui::TextureOptions::LINEAR); + app.jiansun.as_mut().unwrap().agent_images.insert("layout-image".into(), texture); + let hot = frame(&app); + app.jiansun.as_mut().unwrap().agent_images.remove("layout-image"); + assert_eq!(hot, frame(&app), "eviction must retain the measured image layout"); + } + } + + #[test] + fn conversation_result_preserves_image_ratio_and_overlays_the_caption() { + let (mut app, _) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + for dimensions in [[200, 100], [100, 200]] { + let texture = ctx.load_texture("result", egui::ColorImage::filled(dimensions, Color32::WHITE), egui::TextureOptions::LINEAR); + let texture_id = texture.id(); + let w = app.jiansun.as_mut().unwrap(); + w.agent_images.insert("result".into(), texture); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| { + w.image_result(ui, &json!({"taskId":"result"}), 200.0, None); + }); + output.textures_delta.clear(); + let image = output.shapes.iter().find_map(|shape| match &shape.shape { + egui::Shape::Rect(rect) if rect.fill_texture_id() == texture_id => Some(rect.rect), + _ => None, + }).expect("preview texture"); + let caption = output.shapes.iter().find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "候选图片" => Some(Rect::from_min_size(text.pos, text.galley.size())), + _ => None, + }).expect("image caption"); + assert!((image.width() / image.height() - dimensions[0] as f32 / dimensions[1] as f32).abs() < 0.01); + assert!(image.contains_rect(caption)); + } + } + + #[test] + fn offscreen_conversation_preview_does_not_refresh_texture_recency() { + let (mut app, _) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + for id in ["hidden", "recent"] { + let texture = ctx.load_texture(id, egui::ColorImage::filled([8, 8], Color32::WHITE), egui::TextureOptions::LINEAR); + app.jiansun.as_mut().unwrap().agent_images.insert(id.into(), texture); + } + ctx.settle_ui(egui::RawInput::default(), |ui| { + ui.set_clip_rect(Rect::from_min_size(pos2(5000.0, 5000.0), vec2(20.0, 20.0))); + app.jiansun.as_ref().unwrap().image_result(ui, &json!({"taskId":"hidden"}), 112.0, None); + }).textures_delta.clear(); + let cache = &app.jiansun.as_ref().unwrap().agent_images; + assert_eq!(cache.iter().next().map(|(key, _)| key.as_str()), Some("hidden")); + ctx.settle_ui(egui::RawInput::default(), |ui| { + app.jiansun.as_ref().unwrap().image_result(ui, &json!({"taskId":"hidden"}), 112.0, None); + }).textures_delta.clear(); + assert_eq!(cache.iter().next_back().map(|(key, _)| key.as_str()), Some("hidden")); + } + + #[test] + fn conversation_image_context_menu_uses_stitch_popup_and_keeps_its_own_target() { + fn scan(shape: &egui::Shape, texture: egui::TextureId, fill: Color32, image: &mut Option, frame: &mut Option, label: &mut Option) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| scan(shape, texture, fill, image, frame, label)), + egui::Shape::Rect(rect) if rect.fill_texture_id() == texture => *image = Some(rect.rect), + egui::Shape::Rect(rect) if rect.fill == fill && rect.corner_radius == egui::CornerRadius::same(8) => *frame = Some(rect.rect), + egui::Shape::Text(text) if text.galley.text() == "查看大图" => *label = Some(Rect::from_min_size(text.pos, text.galley.size())), + _ => {} + } + } + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let texture = ctx.load_texture("history-candidate", egui::ColorImage::filled([80, 80], Color32::WHITE), egui::TextureOptions::LINEAR); + let texture_id = texture.id(); + app.jiansun.as_mut().unwrap().agent_images.insert("image-a".into(), texture); + let value = json!({"taskId":"image-a", "slotId":"slot-a", "productVariantId":"color-a"}); + // Context popups have a real fade-in and an initial sizing pass. Advance + // time between frames before inspecting their final frame colors. + let time = std::cell::Cell::new(0.0); + let run = |ctx: &egui::Context, app: &PhotocraftApp, events| { + let current = time.get(); + time.set(current + 0.25); + let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), time: Some(current), events, ..Default::default() }, |ui| { + app.jiansun.as_ref().unwrap().image_result(ui, &value, 112.0, None); + }); + output.textures_delta.clear(); + output + }; + let first = run(&ctx, &app, vec![]); + let mut image = None; + let mut frame = None; + let mut label = None; + let fill = super::super::stitch_ui::menu_base(); + for shape in &first.shapes { scan(&shape.shape, texture_id, fill, &mut image, &mut frame, &mut label); } + let pos = image.expect("history result contains the actual preview texture").center(); + for pressed in [true, false] { + run(&ctx, &app, vec![egui::Event::PointerMoved(pos), egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }]); + } + let opened = run(&ctx, &app, vec![]); + image = None; frame = None; label = None; + for shape in &opened.shapes { scan(&shape.shape, texture_id, fill, &mut image, &mut frame, &mut label); } + let pos = label.expect("the context popup exposes original-image preview").center(); + let frame = frame.expect("the opened context popup uses the scoped Stitch frame after its fade-in"); + assert!((176.0..=208.0).contains(&frame.width()), "the menu stays compact instead of filling the canvas: {}", frame.width()); + for pressed in [true, false] { + run(&ctx, &app, vec![egui::Event::PointerMoved(pos), egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }]); + } + assert_eq!(ctx.data(|data| data.get_temp::(Id::unique("jiansun-image-expanded"))), Some("image-a".into())); + assert!(requests.try_recv().is_err(), "opening a preview never sends a model request"); + } + + #[test] + fn image_card_reference_menu_attaches_placeholder_and_loaded_images() { + use egui_kittest::kittest::Queryable; + for (width, theme, original) in [(520.0, crate::theme::ThemeKind::ProMedium, false), + (260.0, crate::theme::ThemeKind::ProLight, true)] { + let (mut app, requests) = dock_fixture(); + let doc = app.session.active().unwrap().doc.id.0; + let workspace = app.jiansun.as_mut().unwrap(); + workspace.reduce_motion = true; + workspace.composer.clear(); + workspace.messages.truncate(1); + let kind = if original { "template-image" } else { "image" }; + workspace.messages.push(json!({"role":"assistant","kind":kind,"taskId":"reference-card", + "documentId":doc,"fieldId":"hero","label":"首屏"})); + let directory = std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").map(std::path::PathBuf::from); + let mut builder = egui_kittest::Harness::builder().with_size(vec2(width, 680.0)) + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests).with_max_steps(64); + let _gpu = directory.as_ref().map(|_| photocraft_testkit::gpu_lock()); + if directory.is_some() { builder = builder.wgpu(); } + let mut harness = builder.build_ui_state(|ui, app| { + if super::super::stitch_ui::ui_fonts_ready(ui) { super::super::agent_dock(app, ui); } + }, app); + PhotocraftApp::setup_context(&harness.ctx, theme); + if !original { + let texture = harness.ctx.load_texture("reference-card", + egui::ColorImage::filled([80, 60], Color32::from_rgb(158, 113, 73)), Default::default()); + harness.state_mut().jiansun.as_mut().unwrap().agent_images.insert("reference-card".into(), texture); + } + harness.run_steps(8); + let card_label = if original { "模板原图加载中" } else { "定位 首屏" }; + let pos = harness.get_by_label(card_label).rect().center(); + for pressed in [true, false] { + harness.event(egui::Event::PointerMoved(pos)); + harness.event(egui::Event::PointerButton { pos, button:egui::PointerButton::Secondary, + pressed, modifiers:egui::Modifiers::NONE }); + harness.run_steps(2); + } + let item = harness.get_by_label("引用到小壹"); + assert!(item.rect().left() >= 0.0 && item.rect().right() <= width); + if let Some(directory) = &directory { + std::fs::create_dir_all(directory).unwrap(); + harness.render().unwrap().save(directory.join(format!("xiaoyi-image-reference-menu-{width}.png"))).unwrap(); + } + harness.get_by_label("引用到小壹").click(); + harness.run_steps(4); + let app = harness.state(); + let workspace = app.jiansun.as_ref().unwrap(); + let refs = workspace.composer_reference_snapshot(app).unwrap(); + let reference = refs.iter().find(|item| item["taskId"] == "reference-card").unwrap(); + assert_eq!(reference["kind"], kind); + assert_eq!(reference["fieldId"], "hero"); + assert!(harness.ctx.memory(|memory| memory.has_focus(super::super::composer_input_id()))); + assert!(requests.try_iter().all(|request| !matches!(request, Request::Action(method, _) if method == "agent"))); + } + } + + #[test] + fn model_menu_uses_stitch_rows_and_only_selects_available_models() { + fn labels(shape: &egui::Shape, out: &mut Vec<(String, Rect, usize)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| labels(shape, out)), + egui::Shape::Text(text) => out.push((text.galley.text().to_owned(), Rect::from_min_size(text.pos, text.galley.size()), text.galley.rows.len())), + _ => {} + } + } + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + { + let w = app.jiansun.as_mut().unwrap(); + w.key_saved = false; + w.models.push(json!({"key":"new-model","id":"测试模型甲"})); + w.models.push(json!({"key":"long-model","id":"测试超长名称模型用于验证菜单不会在窄窗口隐藏完整模型名称测试超长名称模型"})); + w.models.push(json!({"key":"blocked-model","id":"未开放模型乙"})); + w.available_models = Some(vec!["对话模型".into(), "测试模型甲".into(), "测试超长名称模型用于验证菜单不会在窄窗口隐藏完整模型名称测试超长名称模型".into()]); + } + for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } + dock_click(&ctx, &mut app, "settings"); + for _ in 0..18 { dock_frame(&ctx, &mut app, vec![]); } + dock_click(&ctx, &mut app, "chatModel"); + for _ in 0..18 { dock_frame(&ctx, &mut app, vec![]); } + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)); + let mut text = Vec::new(); + for shape in &output.shapes { labels(&shape.shape, &mut text); } + let unselected = text.iter().find(|(name, _, _)| name == "未选择").expect("the menu renders an unselected option").1; + assert!(text.iter().any(|(name, _, _)| name == "未开放模型乙 · Key未开放")); + let available = text.iter().find(|(name, _, _)| name == "测试模型甲").expect("the open menu renders an available model").1; + assert!((unselected.left() - available.left()).abs() < 2.0, "option text shares a left edge instead of being centered"); + let long = text.iter().find(|(name, _, _)| name == "测试超长名称模型用于验证菜单不会在窄窗口隐藏完整模型名称测试超长名称模型").expect("long model name is present"); + assert!(long.1.width() <= 560.0, "the full name fits or wraps within the responsive popup"); + assert!((unselected.left() - long.1.left()).abs() < 2.0, "wrapped option starts on the same left edge"); + let target = available.center(); + for pressed in [true, false] { + dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(target), egui::Event::PointerButton { pos: target, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }]); + } + assert_eq!(app.jiansun.as_ref().unwrap().model, "new-model"); + assert!(app.jiansun.as_ref().unwrap().key_settings, "choosing a model without a saved key opens connection setup"); + assert!(requests.try_recv().is_err(), "opening and selecting locally must not send a model request"); + } + + #[test] + fn model_menu_closes_on_scope_change_and_when_controls_are_disabled() { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let w = app.jiansun.as_mut().unwrap(); + let frame = |w: &mut Workspace| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), ..Default::default() }, + |ui| { w.model_picker(ui, ModelRole::Chat, 160.0, true); }); + }; + let last = Id::unique(("agent-model-last-popup", ModelRole::Chat, true)); + frame(w); + let first = ctx.data(|d| d.get_temp::(last)).unwrap(); + egui::Popup::open_id(&ctx, first); + assert!(egui::Popup::is_id_open(&ctx, first)); + w.project_context["localId"] = json!("another-project"); + frame(w); + let second = ctx.data(|d| d.get_temp::(last)).unwrap(); + assert_ne!(first, second); + assert!(!egui::Popup::is_id_open(&ctx, first)); + egui::Popup::open_id(&ctx, second); + w.busy = Some("pi-agent".into()); + frame(w); + assert!(!egui::Popup::is_id_open(&ctx, second)); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn thinking_picker_labels_the_automatic_setting_and_keeps_its_empty_value() { + use egui_kittest::kittest::Queryable; + for width in [250.0, 520.0] { + let (mut app, requests) = dock_fixture(); + let mut workspace = app.jiansun.take().unwrap(); + workspace.reduce_motion = true; + workspace.models[0]["reasoning"] = json!(true); + workspace.models[0]["reasoningEfforts"] = json!(["high"]); + workspace.thinking_by_model[workspace.model.as_str()] = json!("high"); + + let mut harness = egui_kittest::Harness::builder() + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(vec2(width, 240.0)) + .build_ui_state(|ui, workspace: &mut Workspace| workspace.thinking_picker(ui), workspace); + harness.run_steps(4); + harness.get_by_label("高").click(); + harness.run_steps(4); + harness.get_by_label("自动").click(); + harness.run_steps(4); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected a local preference action") }; + assert_eq!(method, "select-model"); + assert_eq!(input["field"], "thinkingLevel"); + assert_eq!(input["selection"], ""); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn thinking_picker_visual_acceptance() { + use egui_kittest::kittest::Queryable; + let _gpu = photocraft_testkit::gpu_lock(); + let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + struct Preview(PhotocraftApp); + impl eframe::App for Preview { + fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { + super::super::agent_dock(&mut self.0, ui); + } + } + for width in [250.0, 520.0] { + let (mut app, requests) = dock_fixture(); + let workspace = app.jiansun.as_mut().unwrap(); + workspace.reduce_motion = true; + workspace.model_settings = true; + workspace.models[0]["reasoning"] = json!(true); + workspace.models[0]["reasoningEfforts"] = json!(["low","medium","high"]); + let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 760.0)).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); + app.gpu_render_state = cc.wgpu_render_state.clone(); + Preview(app) + }); + harness.run_steps(6); + let trigger = geometry(harness.state().0.jiansun.as_ref().unwrap(), "thinkingLevel"); + assert!(trigger.left() >= 0.0 && trigger.right() <= width); + harness.get_by_label("自动").click(); + harness.run_steps(4); + harness.render().unwrap().save(directory.join(format!("thinking-picker-{width}.png"))).unwrap(); + harness.get_by_label("高").click(); + harness.run_steps(4); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected a local preference action") }; + assert_eq!(method, "select-model"); + assert_eq!(input["field"], "thinkingLevel"); + assert_eq!(input["selection"], "high"); + } + } + + #[test] + fn focused_model_picker_uses_the_list_without_a_duplicate_tooltip() { + fn labels(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| labels(shape, out)), + egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), + _ => {} + } + } + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let w = app.jiansun.as_mut().unwrap(); + let name = "很长的对话模型名称在狭窄侧栏中仍需可以通过键盘完整查看"; + w.models = vec![json!({"key":"long", "id":name})]; + w.model = "long".into(); + w.reduce_motion = true; + let frame = |w: &mut Workspace, events: Vec| { + let mut response_id = None; + let output = ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(360.0, 600.0))), + events, ..Default::default() + }, |ui| { response_id = Some(w.model_picker(ui, ModelRole::Chat, 80.0, true).id); }); + (output, response_id.unwrap()) + }; + let (_, id) = frame(w, vec![]); + ctx.memory_mut(|memory| memory.request_focus(id)); + let mut text = Vec::new(); + for _ in 0..4 { + let (focused, _) = frame(w, vec![]); + for shape in &focused.shapes { labels(&shape.shape, &mut text); } + } + assert!(ctx.memory(|memory| memory.has_focus(id)), "the model picker receives keyboard focus"); + assert!(!text.iter().any(|text| text == &format!("对话模型:{name}")), "focus does not add a duplicate native tooltip"); + frame(w, vec![enter_event(egui::Modifiers::NONE, false)]); + frame(w, vec![enter_release()]); + assert!(egui::Popup::is_id_open(&ctx, id.with("popup")), "Enter opens the focused model picker"); + text.clear(); + let (opened, _) = frame(w, vec![]); + for shape in &opened.shapes { labels(&shape.shape, &mut text); } + assert!(text.iter().any(|text| text.contains(name)), "the opened list exposes the full model name"); + frame(w, vec![egui::Event::Key { key: egui::Key::Escape, physical_key: Some(egui::Key::Escape), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]); + assert!(!egui::Popup::is_id_open(&ctx, id.with("popup")), "Escape closes the model picker"); + assert_eq!(w.model, "long"); + assert!(requests.try_recv().is_err(), "reading and dismissing the list cannot reconfigure or call a model"); + } + + #[test] + fn connection_popup_uses_generic_local_key_copy_and_does_not_send() { + fn labels(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| labels(shape, out)), + egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), + _ => {} + } + } + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + { + let w = app.jiansun.as_mut().unwrap(); + w.key_saved = false; + w.key_settings = true; + w.model_settings = true; + w.reduce_motion = true; + } + let mut output = None; + for _ in 0..3 { + let mut frame = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)); + frame.textures_delta.clear(); + output = Some(frame); + } + let mut text = Vec::new(); + for shape in &output.unwrap().shapes { labels(&shape.shape, &mut text); } + assert!(text.iter().any(|text| text == "小壹设置")); + assert!(!text.iter().any(|text| text == "连接信息保存在本机,可随时更换。")); + assert!(text.iter().any(|text| text == "输入个人 Key")); + assert!(!text.iter().any(|text| text == CONTEXT_UNAVAILABLE), "missing usage does not add a permanent warning to settings"); + assert!(text.iter().all(|text| !text.to_lowercase().contains("98k"))); + assert!(requests.try_recv().is_err(), "opening connection settings must not send a model request"); + } + + #[test] + fn connection_popup_exit_keeps_visual_and_clears_key() { + fn has_label(shape: &egui::Shape, label: &str) -> bool { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| has_label(shape, label)), + egui::Shape::Text(text) => text.galley.text() == label, + _ => false, + } + } + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + { + let w = app.jiansun.as_mut().unwrap(); + w.model_settings = true; + w.key_settings = true; + w.api_key = "temporary-secret".into(); + w.xiaoyi_key = "synthetic-xiaoyi-draft".into(); + w.reduce_motion = false; + } + let frame = |time: f64, app: &mut PhotocraftApp| { + ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), + time: Some(time), + ..Default::default() + }, |ui| crate::panels::right_dock(app, ui)) + }; + for time in [0.0, 0.1, 0.3, 0.4] { let _ = frame(time, &mut app); } + { + let w = app.jiansun.as_mut().unwrap(); + w.model_settings = false; + w.key_settings = false; + } + let exiting = frame(0.41, &mut app); + assert!(app.jiansun.as_ref().unwrap().api_key.is_empty(), "closing must clear the secret before visual exit"); + assert!(app.jiansun.as_ref().unwrap().xiaoyi_key.is_empty()); + assert!(exiting.shapes.iter().any(|shape| has_label(&shape.shape, "小壹设置")), "the closing surface remains visible during exit"); + let _ = frame(0.7, &mut app); + let closed = frame(1.2, &mut app); + assert!(!closed.shapes.iter().any(|shape| has_label(&shape.shape, "小壹设置")), "the surface is removed after exit"); + assert!(requests.try_recv().is_err(), "display and exit must not dispatch a model request"); + } + + #[test] + fn image_preview_zoom_preserves_pointer_position_and_physical_pixel_scale() { + let viewport = vec2(400.0, 300.0); + let image = vec2(1600.0, 1200.0); + let mut view = ArtifactPreviewView::default(); + let at = vec2(35.0, 25.0); + let before = view.center + at / (image * view.scale(viewport, image, 1.5)); + view.zoom_at(1.0, at, viewport, image, 1.5); + let after = view.center + at / (image * view.scale(viewport, image, 1.5)); + assert!((before - after).length() < 0.0001); + assert!((view.scale(viewport, image, 1.5) * 1.5 - 1.0).abs() < 0.0001, "100% maps a texture pixel to a physical screen pixel"); + } + + #[test] + fn image_preview_zoom_and_drag_are_local_and_new_images_start_fitted() { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let id = Id::unique("jiansun-image-expanded"); + let snapshot_id = id.with("exit-snapshot"); + let texture = ctx.load_texture("preview-navigation", egui::ColorImage::filled([1200, 900], Color32::WHITE), egui::TextureOptions::LINEAR); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.agent_images.insert("first".into(), texture.clone()); + w.agent_images.insert("second".into(), texture); + w.template_workflow = json!({"slots":[ + {"candidates":[{"taskId":"first","status":"complete"},{"taskId":"failed","status":"failed"},{"taskId":"second","status":"complete"}]}, + {"candidates":[{"taskId":"other-slot","status":"complete"}]} + ]}); + ctx.data_mut(|d| d.insert_temp(id, "first".to_owned())); + let frame = |time:f64, events| { + let mut output = ctx.settle_ui(egui::RawInput { + screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(800.0,600.0))), time:Some(time), events, ..Default::default() + }, |ui| w.artifact_window(ui)); + output.textures_delta.clear(); + }; + for time in [0.0, 0.1, 0.2] { let _ = frame(time,vec![]); } + let pos = pos2(400.0,350.0); + let _ = frame(0.3,vec![egui::Event::PointerMoved(pos), egui::Event::MouseWheel { + source:egui::MouseWheelSource::Unknown, phase:egui::TouchPhase::Move, + unit:egui::MouseWheelUnit::Point, delta:vec2(0.0,300.0), modifiers:egui::Modifiers::NONE }]); + let zoomed = ctx.data(|d| d.get_temp::(snapshot_id)).unwrap(); + assert!(zoomed.view.zoom.is_some_and(|zoom| zoom > 0.5), "wheel over preview zooms the actual image"); + let _ = frame(0.5,vec![egui::Event::PointerButton { pos, button:egui::PointerButton::Primary,pressed:true,modifiers:egui::Modifiers::NONE }]); + let _ = frame(0.6,vec![egui::Event::PointerMoved(pos + vec2(70.0,35.0))]); + let dragged = ctx.data(|d| d.get_temp::(snapshot_id)).unwrap(); + assert!(dragged.view.center.x < zoomed.view.center.x, "drag moves the viewport over the image"); + let _ = frame(0.7,vec![egui::Event::PointerButton { pos:pos+vec2(70.0,35.0),button:egui::PointerButton::Primary,pressed:false,modifiers:egui::Modifiers::NONE }]); + let _ = frame(0.75,vec![ + egui::Event::PointerButton { pos, button:egui::PointerButton::Primary,pressed:true,modifiers:egui::Modifiers::NONE }, + egui::Event::PointerMoved(pos + vec2(-40.0,-20.0)), + egui::Event::PointerButton { pos:pos+vec2(-40.0,-20.0),button:egui::PointerButton::Primary,pressed:false,modifiers:egui::Modifiers::NONE }, + ]); + let quick = ctx.data(|d| d.get_temp::(snapshot_id)).unwrap(); + assert!(quick.view.center.x > dragged.view.center.x, "a complete drag between rendered frames still moves the preview"); + assert!(quick.view.drag_position.is_none()); + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let _ = frame(0.8,vec![key(egui::Key::ArrowRight)]); + let _ = frame(0.9,vec![]); + let second = ctx.data(|d| d.get_temp::(snapshot_id)).unwrap(); + assert_eq!(second.key, "second"); + assert!(second.view.zoom.is_none()); + let _ = frame(1.0,vec![key(egui::Key::ArrowRight)]); + assert_eq!(ctx.data(|d| d.get_temp::(id)).as_deref(), Some("second")); + assert_eq!(second.view.center, Vec2::splat(0.5)); + assert!(requests.try_recv().is_err(), "preview navigation does not dispatch generation or adoption"); + } + + #[test] + fn image_preview_retains_texture_only_until_exit_or_scope_change() { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let id = Id::unique("jiansun-image-expanded"); + let texture = ctx.load_texture("preview-retained", egui::ColorImage::filled([8, 8], Color32::WHITE), egui::TextureOptions::LINEAR); + let w = app.jiansun.as_mut().unwrap(); + w.agent_images.insert("preview".into(), texture); + ctx.data_mut(|d| d.insert_temp(id, "preview".to_owned())); + let frame = |time: f64, w: &Workspace| { + let mut output = ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), + time: Some(time), ..Default::default() + }, |ui| w.artifact_window(ui)); + output.textures_delta.clear(); + }; + for time in [0.0, 0.1, 0.3] { let _ = frame(time, w); } + assert!(ctx.data(|d| d.get_temp::(id.with("exit-snapshot"))).is_some()); + ctx.data_mut(|d| d.remove::(id)); + w.agent_images.remove("preview"); + let _ = frame(0.31, w); + assert!(ctx.data(|d| d.get_temp::(id.with("exit-snapshot"))).is_some(), "closed preview retains its actual texture during exit"); + let _ = frame(0.6, w); + assert!(ctx.data(|d| d.get_temp::(id.with("exit-snapshot"))).is_none()); + let texture = ctx.load_texture("preview-other", egui::ColorImage::filled([8, 8], Color32::WHITE), egui::TextureOptions::LINEAR); + w.agent_images.insert("preview".into(), texture); + ctx.data_mut(|d| d.insert_temp(id, "preview".to_owned())); + let _ = frame(0.7, w); + w.account = json!({"id":"different-account"}); + let _ = frame(0.8, w); + assert!(ctx.data(|d| d.get_temp::(id)).is_none()); + assert!(ctx.data(|d| d.get_temp::(id.with("exit-snapshot"))).is_none(), "preview cannot survive an account change"); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn image_preview_scrim_closes_and_retains_the_real_texture_for_exit() { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let id = Id::unique("jiansun-image-expanded"); + let texture = ctx.load_texture("preview-scrim", egui::ColorImage::filled([8, 8], Color32::WHITE), egui::TextureOptions::LINEAR); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = false; + w.agent_images.insert("preview".into(), texture); + ctx.data_mut(|d| d.insert_temp(id, "preview".to_owned())); + let frame = |time:f64, events| { + let mut output = ctx.settle_ui(egui::RawInput { + screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,480.0))), time:Some(time), events, ..Default::default() + }, |ui| w.artifact_window(ui)); + output.textures_delta.clear(); + }; + let _ = frame(0.0,vec![]); + let _ = frame(0.3,vec![]); + let pos = pos2(12.0,12.0); + for (time,pressed) in [(0.31,true),(0.32,false)] { + let _ = frame(time,vec![egui::Event::PointerMoved(pos),egui::Event::PointerButton { + pos,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); + } + assert!(ctx.data(|d| d.get_temp::(id)).is_none(), "scrim click closes the preview"); + let _ = frame(0.33,vec![]); + assert!(ctx.data(|d| d.get_temp::(id.with("exit-snapshot"))).is_some(), "the real texture survives the exit"); + let _ = frame(0.51,vec![]); + assert!(ctx.data(|d| d.get_temp::(id.with("exit-snapshot"))).is_none()); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn native_agent_tab_keeps_draft_and_context_without_splitting_or_stealing_selection() { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + for _ in 0..3 { + dock_frame(&ctx, &mut app, vec![]); + } + assert_eq!(app.ui.dock_tabs.color, 4, "Agent opens by default on startup"); + assert!(geometry(app.jiansun.as_ref().unwrap(), "agentTab").left() < geometry(app.jiansun.as_ref().unwrap(), "colorTab").left()); + let original = app.jiansun.as_ref().unwrap().composer.clone(); + assert!(geometry(app.jiansun.as_ref().unwrap(), "panel").height() > 640.0, "Agent uses the whole sidebar"); + let panel = geometry(app.jiansun.as_ref().unwrap(), "panel"); + let group = crate::dock::last_rects(&ctx)[0].1; + assert!((panel.left() - group.left()).abs() <= 0.5, "no inherited nested-panel margin"); + assert!((panel.right() - group.right()).abs() <= 0.5); + assert!((panel.top() - geometry(app.jiansun.as_ref().unwrap(), "agentTab").bottom()).abs() <= 1.0); + assert_eq!(crate::dock::last_rects(&ctx).len(), 1); + dock_click(&ctx, &mut app, "colorTab"); + assert_eq!(crate::dock::last_rects(&ctx).len(), 3, "native Color, Properties and Layers return together"); + dock_click(&ctx, &mut app, "layersTab"); + assert_eq!(app.ui.dock_tabs.layers, 0); + assert!(app.jiansun.as_ref().unwrap().panel_geometry.get("input").is_none()); + let w = app.jiansun.as_mut().unwrap(); + w.canvas_workspace.context = Some(json!({"kind":"layer","nativeLayerId":42,"label":"另一图层"})); + w.messages.push(json!({"role":"assistant","kind":"reply","text":"候选已保留"})); + dock_frame(&ctx, &mut app, vec![]); + assert_eq!(app.ui.dock_tabs.layers, 0, "selection and completion never activate the Agent tab"); + dock_click(&ctx, &mut app, "channelsTab"); + assert_eq!(app.ui.dock_tabs.layers, 1); + dock_click(&ctx, &mut app, "pathsTab"); + assert_eq!(app.ui.dock_tabs.layers, 2); + dock_click(&ctx, &mut app, "agentTab"); + assert_eq!(app.ui.dock_tabs.color, 4); + let w = app.jiansun.as_ref().unwrap(); + assert_eq!(w.composer, original); + assert_eq!(w.messages.len(), 3); + assert_eq!(w.canvas_workspace.context.as_ref().unwrap()["nativeLayerId"], 42); + assert!( + w.panel_geometry.get("nativeDock").is_none() && w.panel_geometry.get("agentHeader").is_none(), + "one original tab group, no additional dock or header" + ); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn paused_production_card_shows_a_static_heading_and_elapsed_time() { + use egui_kittest::kittest::Queryable; + + let directory = std::env::var_os("PHOTOCRAFT_PAUSED_CARD_QA_OUT").map(std::path::PathBuf::from); + let _gpu = directory.as_ref().map(|_| photocraft_testkit::gpu_lock()); + for width in [520.0, 250.0] { + let (mut app, _) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + let doc = app.session.active().unwrap().doc.id.0; + w.open_projects.insert(doc, w.local_identity("project")); + w.template_workflow = json!({"canvasFirst":true,"workspaceId":"ws"}); + w.product_checkpoint = json!({"active":true,"phase":"paused","project":"project","workspaceId":"ws", + "startedAt":1_000,"clockSavedAt":1_300}); + w.restore_production_checkpoint(&app); + w.agent_effects_paused = true; + w.workflow.set_production_progress(&json!({"heading":"正在制作详情页"})); + let run = w.product_production.as_ref().unwrap(); + assert!(run.waiting_to_resume()); + assert!(!run.showing_agent_progress()); + assert_eq!(run.elapsed(), Duration::from_secs(300)); + app.jiansun = Some(w); + let builder = egui_kittest::Harness::builder().with_size(vec2(width, 680.0)) + .with_context_setup(|ctx| { + PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }); + let builder = if directory.is_some() { builder.wgpu() } else { builder }; + let mut harness = builder.build_ui_state(|ui, app| super::super::agent_dock(app, ui), app); + harness.run_steps(8); + assert!(harness.query_all_by_label("已暂停").next().is_some()); + assert!(harness.query_all_by_label("正在准备详情页").next().is_none()); + assert!(harness.query_all_by_label("正在推进目标").next().is_none()); + assert!(harness.query_all_by_label("继续制作").next().is_some()); + let w = harness.state_mut().jiansun.as_mut().unwrap(); + assert_eq!(w.product_production.as_ref().unwrap().elapsed(), Duration::from_secs(300)); + if let Some(directory) = &directory { + harness.render().unwrap().save(directory.join(format!("paused-{width}.png"))).unwrap(); + } + let w = harness.state_mut().jiansun.as_mut().unwrap(); + w.receive_library_status(&json!({"libraryStatus":"sign_in_required","libraryHttpStatus":401})); + w.product_production = None; + harness.run_steps(8); + assert!(harness.query_all_by_label("重新连接").next().is_some()); + if let Some(directory) = &directory { + harness.render().unwrap().save(directory.join(format!("reconnect-{width}.png"))).unwrap(); + } + } + } + + #[test] + fn reconnect_opens_account_authorization_without_erasing_drafts_or_replaying_a_request() { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let w = app.jiansun.as_mut().unwrap(); + w.library_status = "sign_in_required".into(); + w.library_http_status = Some(401); + let draft = w.composer.clone(); + let messages = w.messages.clone(); + for _ in 0..3 { + dock_frame(&ctx, &mut app, vec![]); + } + assert!(!app.jiansun.as_ref().unwrap().can_send(&app)); + app.jiansun.as_mut().unwrap().unknown = true; + // Re-observe the reserved status row before clicking its new layout. + for _ in 0..2 { + dock_frame(&ctx, &mut app, vec![]); + } + assert!(app.jiansun.as_ref().unwrap().panel_geometry["reconnect"].is_array()); + dock_click(&ctx, &mut app, "reconnect"); + let w = app.jiansun.as_ref().unwrap(); + assert!(w.config); + assert_eq!(w.login_origin.as_deref(), Some(w.origin.as_str())); + assert_eq!(w.account["id"], "local-ui-fixture"); + assert_eq!(w.composer, draft); + assert_eq!(w.messages, messages); + assert!(w.unknown); + assert!(requests.try_recv().is_err(), "opening authorization neither dispatches nor repeats a model request"); + } + + #[test] + fn candidate_recovery_targets_the_original_image_instead_of_legacy_chat() { + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + w.unknown = true; + w.template_workflow = json!({"canvasFirst":true,"pending":true,"recoveryCandidateId":"original-image"}); + w.recover(&app); + assert!(matches!(requests.try_recv().unwrap(), Request::Action(method, value) + if method == "slot-recover" && value["candidateId"] == "original-image")); + assert!(requests.try_recv().is_err()); + assert!(!w.allow_apply); + } + + #[test] + fn library_action_failure_stays_in_the_shared_modal_and_preserves_the_draft() { + let (mut app, _) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + let draft = w.composer.clone(); + w.unknown = true; + w.receive_json_error("pi-rules", "请先在素材库登录".into()); + assert!(!w.config, "opening a local project must not force an account dialog"); + assert!(w.error.is_empty()); + w.receive_json_error("slot-recover", "请先在素材库登录".into()); + assert!(w.config); + assert_eq!(w.library_message, "请先在素材库登录"); + assert!(w.error.is_empty()); + assert!(w.unknown); + assert_eq!(w.composer, draft); + } + + #[test] + fn refreshed_authorization_clears_stale_errors_without_dropping_existing_connection_or_drafts() { + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + let draft = w.composer.clone(); + let account = w.account.clone(); + w.account_error = "该素材库尚未开放客户端授权".into(); + w.receive_library_status(&json!({"libraryStatus":"connected","libraryHttpStatus":200,"libraryAuthorizationEnabled":false})); + assert_eq!(w.library_authorization_enabled, Some(false)); + assert!(w.can_send(&app), "a paused new-grant endpoint does not revoke a valid existing session"); + assert!(!w.account_error.is_empty()); + w.receive_library_status(&json!({"libraryStatus":"connected","libraryHttpStatus":200,"libraryAuthorizationEnabled":true})); + assert!(w.account_error.is_empty(), "a verified restored endpoint must retire its stale authorization error"); + assert_eq!(w.account, account); + assert_eq!(w.composer, draft); + assert!(requests.try_recv().is_err(), "a status receipt cannot dispatch anything"); + w.receive_library_status(&json!({"libraryStatus":"sign_in_required","libraryHttpStatus":401})); + assert_eq!(w.library_authorization_enabled, None); + assert!(!w.can_send(&app)); + } + + #[test] + fn a_disabled_library_preserves_the_account_and_suspends_cloud_polling_and_new_dispatch() { + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + assert!(w.can_send(&app)); + w.connection_received(&json!({"libraryStatus":"disabled","libraryHttpStatus":403,"libraryMessage":"服务开关未开放"})); + w.model_ready = true; + w.image_ready = true; + w.project_refresh = Instant::now() - std::time::Duration::from_secs(60); + w.dispatch_project_refresh(); + assert!(!w.can_send_with(&app, false)); + assert!(!w.can_send_with(&app, true)); + assert!(!w.needs_library_login(), "a service switch must not be labelled an expired login"); + assert_eq!(w.account["id"], "local-ui-fixture"); + assert!(!w.composer.is_empty()); + assert!(!w.messages.is_empty()); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn custom_native_workspace_migrates_old_agent_to_the_top_color_group() { + use craft_ui::docking::{Layout, Node}; + let (mut app, _) = dock_fixture(); + app.ui.docking = Some(craft_ui::docking::Workspace::new(Layout { + root: Some(Node::Split { + axis: craft_ui::layout::SplitAxis::Vertical, + size: craft_ui::layout::SplitSize::FixedFirst(190.0), + first: Box::new(Node::Tabs { panels: vec!["color".into(), "swatches".into()], active: 0 }), + second: Box::new(Node::Tabs { panels: vec!["xiaoyi".into(), "layers".into(), "channels".into()], active: 0 }), + }), + ..Default::default() + })); + super::super::begin_native_dock(&mut app); + let layout = app.ui.docking.as_ref().unwrap(); + assert!(layout.validate().is_ok()); + assert!( + matches!(layout.layout.root.as_ref(),Some(Node::Split{first,second,..}) if matches!(first.as_ref(), Node::Tabs{panels,active:0} if panels==&["canvas"]) && matches!(second.as_ref(), Node::Split{first,second,..} if matches!(first.as_ref(), Node::Tabs{panels,active:0} if panels==&["xiaoyi","color","swatches"]) && matches!(second.as_ref(), Node::Tabs{panels,..} if panels==&["layers","channels"]))) + ); + crate::panel_docking::leave_agent(&mut app).unwrap(); + app.run("window.panel.activate", json!({"panel":"layers"})).unwrap(); + super::super::begin_native_dock(&mut app); + assert!(!super::super::agent_selected(&app), "native mode is not stolen back"); + assert_eq!(app.ui.docking.as_ref().unwrap().layout.panels().len(), 6); + } + + #[test] + fn plain_photocraft_keeps_its_original_tabs_and_runtime_capability_is_not_saved() { + let mut dock = crate::dock::DockLayout::default(); + let native = dock.visible_tabs(crate::dock::Group::Color, true); + assert_eq!(native, vec![(0, "Color"), (1, "Swatches"), (2, "Gradients"), (3, "Patterns")]); + dock.agent_available = true; + assert_eq!(dock.visible_tabs(crate::dock::Group::Color, true).first(), Some(&(4, "小壹"))); + assert_eq!(dock.visible_tabs(crate::dock::Group::Layers, true), vec![(0, "Layers"), (1, "Channels"), (2, "Paths")]); + let restored: crate::dock::DockLayout = serde_json::from_value(serde_json::to_value(&dock).unwrap()).unwrap(); + assert!(!restored.agent_available); + assert_eq!(restored.visible_tabs(crate::dock::Group::Color, true), native); + } + + #[test] + fn agent_remains_the_top_sidebar_mode_across_native_themes() { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + for theme in [crate::theme::ThemeKind::ProMedium, crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::ProLight] { + app.set_theme(&ctx, theme); + for _ in 0..3 { + dock_frame(&ctx, &mut app, vec![]); + } + assert!(super::super::agent_selected(&app)); + assert!(geometry(app.jiansun.as_ref().unwrap(), "agentTab").left() < geometry(app.jiansun.as_ref().unwrap(), "colorTab").left()); + assert_eq!(crate::dock::last_rects(&ctx).len(), 1); + } + assert!(requests.try_recv().is_err()); + } + + #[test] + fn stop_preserves_request_and_replay_barrier_but_settles_local_motion() { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let w = app.jiansun.as_mut().unwrap(); + w.busy = Some("slot-generate".into()); + w.unknown = true; + for _ in 0..3 { + dock_frame(&ctx, &mut app, vec![]); + } + dock_click(&ctx, &mut app, "stop"); + let w = app.jiansun.as_mut().unwrap(); + assert!(w.agent_effects_paused && w.unknown); + assert_eq!(w.busy.as_deref(), Some("slot-generate")); + assert!(requests.try_recv().is_err()); + w.busy = None; + dock_frame(&ctx, &mut app, vec![]); + let w = app.jiansun.as_ref().unwrap(); + assert!(!w.agent_effects_paused); + assert!(w.result_needs_check()); + assert!(!w.can_send_with(&app, true)); + } + + #[test] + fn processing_card_only_uses_the_submitted_scope_and_never_dispatches() { + let (mut app, requests) = dock_fixture(); + let doc = app.session.active().unwrap().doc.id.0; + let w = app.jiansun.as_mut().unwrap(); + w.busy = Some("agent".into()); + w.owner_doc = Some(doc); + w.pi_request_scope = json!({"account":{"id":w.account["id"],"origin":w.origin},"project":{"documentId":doc}, + "subject":{"kind":"slot","slotId":"submitted-slot","label":"首屏"}}); + w.canvas_workspace.context = Some(json!({"kind":"slot","slotId":"later-selection","label":"另一屏"})); + assert_eq!(app.jiansun.as_ref().unwrap().processing_target(&app).unwrap()["slotId"], "submitted-slot"); + app.jiansun.as_mut().unwrap().account["id"] = json!("other-account"); + assert!(app.jiansun.as_ref().unwrap().processing_target(&app).is_none()); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn image_processing_has_one_neutral_placeholder_and_an_accessible_stop() { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + app.jiansun.as_mut().unwrap().busy = Some("slot-generate".into()); + for _ in 0..3 { + dock_frame(&ctx, &mut app, vec![]); + } + let w = app.jiansun.as_ref().unwrap(); + assert!(w.panel_geometry["processing"].is_array()); + assert!(w.panel_geometry["processingPlaceholder"].is_array()); + assert!(w.panel_geometry["processingBlob"].is_array(), "the task uses the same Siri Orb identity as the composer"); + assert_eq!(w.panel_geometry["processingBlobMoving"], true); + let placeholder: [f32; 4] = serde_json::from_value(w.panel_geometry["processingPlaceholder"].clone()).unwrap(); + let blob: [f32; 4] = serde_json::from_value(w.panel_geometry["processingBlob"].clone()).unwrap(); + assert_eq!(w.panel_geometry["processingPlaceholder"], w.panel_geometry["processing"], "image waiting uses the task surface without an inset panel"); + assert!(blob[2] <= 36.0 && blob[3] <= 36.0 && blob[0] >= placeholder[0] && blob[1] >= placeholder[1]); + assert!(w.panel_geometry["stop"].is_array()); + assert!(requests.try_recv().is_err(), "rendering progress must not send a model request"); + } + + #[test] + fn task_stop_and_completion_use_shared_material_and_fade_without_dispatch() { + for reduced in [false, true] { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let mut sample = |time: f64, pending: bool, paused: bool| { + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = reduced; + w.busy = pending.then(|| "slot-generate".into()); + w.agent_effects_paused = paused; + ctx.memory_mut(|memory| memory.request_focus(Id::unique("jiansun-composer-input"))); + let _ = ctx.settle_ui(egui::RawInput { time: Some(time), screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), ..Default::default() }, |ui| { + crate::panels::right_dock(&mut app, ui); + }); + app.jiansun.as_ref().unwrap().panel_geometry.clone() + }; + let running = sample(0.0, true, false); + assert_eq!(running["processingLightMode"], "glow-pill"); + assert_eq!(running["composerLightMode"], if reduced {"static"} else {"glow-pill"}); + let stopped = sample(1.0, true, true); + assert_eq!(stopped["processingLightMode"], "paused"); + assert_eq!(stopped["composerLightMode"], if reduced {"static"} else {"glow-pill"}); + assert_eq!(stopped["processingOpacity"], 1.0, "stopping retains the original pending request card"); + sample(1.2, true, true); + sample(2.0, false, false); + let leaving = sample(2.08, false, false); + if reduced { + assert!(leaving["processing"].is_null()); + } else { + let opacity = leaving["processingOpacity"].as_f64().unwrap(); + assert!(opacity > 0.0 && opacity < 1.0, "completed card fades as a whole, even after a local stop"); + } + assert!(sample(2.3, false, false)["processing"].is_null()); + assert!(ctx.data(|data|data.get_temp::(Id::unique("composer-sent-glow"))).is_none(),"task status never starts a composer send surge"); + assert!(requests.try_recv().is_err(), "state rendering cannot dispatch or repeat a request"); + } + } + + #[test] + fn image_processing_paints_neutral_status_without_the_upstream_name() { + fn collect_text(shape: &egui::Shape, texts: &mut Vec<(String, f32)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect_text(shape, texts)), + egui::Shape::Text(text) => texts.push((text.galley.text().to_owned(), text.pos.x)), + _ => {} + } + } + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let w = app.jiansun.as_mut().unwrap(); + w.busy = Some("slot-generate".into()); + w.image_progress = "98k 正在生成图片…".into(); + w.reduce_motion = true; + let mut output = None; + for _ in 0..3 { + let mut frame = ctx.settle_ui( + egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), ..Default::default() }, + |ui| crate::panels::right_dock(&mut app, ui), + ); + frame.textures_delta.clear(); + output = Some(frame); + } + let mut texts = Vec::new(); + for shape in &output.unwrap().shapes { + collect_text(&shape.shape, &mut texts); + } + let status_x = texts.iter().find(|(text, _)| text == "正在生成图片…") + .unwrap_or_else(|| panic!("real status should be painted as a neutral label: {texts:?}")).1; + let blob = &app.jiansun.as_ref().unwrap().panel_geometry["processingBlob"]; + let orb_right = (blob[0].as_f64().unwrap() + blob[2].as_f64().unwrap()) as f32; + assert!((0.0..=20.0).contains(&(status_x - orb_right)), "the status should sit beside the orb"); + assert!(!texts.iter().any(|(text, _)| text.contains("98k")), "status must not expose the upstream name"); + assert!(requests.try_recv().is_err(), "painting status must not dispatch a request"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn production_dock_visual_acceptance() { + use egui_kittest::kittest::Queryable; + let _gpu = photocraft_testkit::gpu_lock(); + let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + struct Preview(PhotocraftApp); + impl eframe::App for Preview { + fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { + super::super::agent_dock(&mut self.0, ui); + } + } + for width in [250.0, 520.0] { + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.composer.clear(); + w.reduce_motion = true; + w.pi_run = Some("visual-qa".into()); + w.busy = Some("pi-agent".into()); + w.pi_product_production = true; + let cells = |count, filled, verified| (0..count).map(|i| json!({ + "label":format!("第 {} 项", i + 1), + "state":if i < verified { "verified" } else if i < filled { "filled" } else { "empty" }, + })).collect::>(); + w.workflow.set_production_progress(&json!({"heading":"正在分派详情页图片","rendered":2,"total":21, + "pictureCells":cells(21, 6, 2),"copyCells":cells(45, 37, 8), + "copyPending":8,"workers":[ + {"number":1,"slotId":"hero","label":"首屏产品场景","step":"正在生图","active":true}, + {"number":2,"slotId":"scene","label":"空间搭配图","step":"正在准备","active":true}, + {"number":3,"slotId":"detail","label":"同款细节图","step":"正在等待原请求","active":true}], + "reviews":[{"number":4,"slotId":"finish","label":"材质图","step":"正在验图","active":true}]})); + w.messages = vec![ + json!({"role":"user","text":"制作详情、主图和 SKU"}), + json!({"role":"assistant","kind":"reply","text":"先做首屏的产品场景图,完成后核对产品结构。"}), + json!({"role":"assistant","kind":"image-job","taskId":"qa-pending","run":"visual-qa", + "width":4,"height":5,"workerNumber":1,"slotLabel":"S01 - 首屏产品场景","step":"正在生图"}), + ]; + let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 1040.0)).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); + app.gpu_render_state = cc.wgpu_render_state.clone(); + Preview(app) + }); + { + let w = harness.state_mut().0.jiansun.as_mut().unwrap(); + w.busy = None; + w.pi_run = None; + w.messages.push(json!({"role":"assistant","kind":"image","taskId":"previous-result"})); + } + harness.run_steps(4); + assert!(harness.state().0.jiansun.as_ref().unwrap().panel_geometry["productionProgressTag"].is_null()); + assert!(harness.state().0.jiansun.as_ref().unwrap().panel_geometry["productionShelf"].is_null()); + harness.render().unwrap().save(directory.join(format!("dock-{width}-idle.png"))).unwrap(); + { + let w = harness.state_mut().0.jiansun.as_mut().unwrap(); + w.messages.pop(); + w.messages.push(json!({"role":"assistant","kind":"image","taskId":"returned-result"})); + // A slot queued behind the running one keeps the height of one line. + w.messages.push(json!({"role":"assistant","kind":"image-job","taskId":"qa-queued","run":"later", + "width":4,"height":5,"workerNumber":2,"slotLabel":"S02 - 细节特写","step":"正在生图"})); + w.busy = Some("pi-agent".into()); + w.pi_run = Some("visual-qa".into()); + } + harness.run_steps(12); + let w = harness.state().0.jiansun.as_ref().unwrap(); + assert_eq!(w.panel_geometry["productionImageCells"]["total"], 21); + assert_eq!(w.panel_geometry["productionImageCells"]["filled"], 6); + assert_eq!(w.panel_geometry["productionImageCells"]["verified"], 2); + let copy = &w.panel_geometry["productionCopyCells"]; + assert_eq!(copy["total"], 45); + assert_eq!(copy["filled"], 37); + assert_eq!(copy["verified"], 8); + assert_eq!(copy["bar"], false); + assert_eq!(w.panel_geometry["productionImageCells"]["bar"], false); + // The head is pinned above the timeline and stays compact. + let head = geometry(w, "productionShelf"); + let clip = geometry(w, "conversationClip"); + assert!(head.bottom() <= clip.top() + 1.0, "状态头固定在对话上方:面板宽 {width}, 状态头 {head:?}, 对话 {clip:?}"); + assert!(head.bottom() < geometry(w, "composer").top(), "进度格换行后仍保留输入区:面板宽 {width}, {head:?}"); + let pictures = geometry(w, "productionImageCells"); + assert!(geometry(w, "productionProgressTag").bottom() <= pictures.top() && geometry(w, "taskStop").bottom() <= pictures.top(), + "停止键与展开钮在标题行,进度格在其下"); + assert!(geometry(w, "productionCopyCells").bottom() <= head.bottom() && pictures.top() > head.top(), + "图片格与文案默认可见:面板宽 {width}"); + let name = geometry(w, "productionTitle"); + assert!(head.contains_rect(name) && name.right() <= geometry(w, "productionProgressTag").left(), + "标题与展开钮互不遮挡:面板宽 {width}, {name:?}"); + harness.render().unwrap().save(directory.join(format!("dock-{width}-progress.png"))).unwrap(); + let click = |harness: &mut egui_kittest::Harness, key: &str| { + let point = geometry(harness.state().0.jiansun.as_ref().unwrap(), key).center(); + harness.hover_at(point); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos:point, button:egui::PointerButton::Primary, + pressed, modifiers:egui::Modifiers::NONE }); + harness.run_steps(1); + } + harness.run_steps(12); + }; + // The head opens in place for the per-slot detail of every sub-agent. + click(&mut harness, "productionProgressTag"); + let w = harness.state().0.jiansun.as_ref().unwrap(); + assert!(w.panel_geometry["productionWorkers"].is_array()); + assert!(geometry(w, "productionShelf").bottom() <= geometry(w, "conversationClip").top() + 1.0); + assert_eq!(harness.query_all_by_label("D").count(), 0, "复核使用图位名称:面板宽 {width}"); + let rows = w.panel_geometry["productionWorkers"].as_array().unwrap(); + assert_eq!(rows.len(), 4, "面板宽 {width}"); + assert_eq!(rows[rows.len() - 1]["review"], true); + let footprint = |row: &Value| { + let a = row["indicator"].as_array().unwrap(); + Rect::from_min_size(pos2(a[0].as_f64().unwrap() as f32, a[1].as_f64().unwrap() as f32), + vec2(a[2].as_f64().unwrap() as f32, a[3].as_f64().unwrap() as f32)) + }; + let columns = if width == 250.0 { 1 } else { 2 }; + for (index, row) in rows.iter().enumerate() { + let (mine, lead) = (footprint(row), footprint(&rows[index % columns])); + assert!((mine.width() - lead.width()).abs() < 0.01 && (mine.left() - lead.left()).abs() < 0.01, + "子代理状态点对齐:面板宽 {width}, {mine:?} 对 {lead:?}"); + } + harness.render().unwrap().save(directory.join(format!("dock-{width}-workers.png"))).unwrap(); + click(&mut harness, "productionProgressTag"); + assert!(requests.try_recv().is_err()); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn empty_dock_visual_acceptance() { + let _gpu = photocraft_testkit::gpu_lock(); + let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + struct Preview(PhotocraftApp); + impl eframe::App for Preview { + fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { + super::super::agent_dock(&mut self.0, ui); + } + } + for width in [250.0, 520.0] { + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.composer.clear(); + w.messages.clear(); + w.reduce_motion = true; + let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 760.0)).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); + app.gpu_render_state = cc.wgpu_render_state.clone(); + Preview(app) + }); + harness.run_steps(6); + assert!(harness.state().0.jiansun.as_ref().unwrap().panel_geometry["quickPrompts"].is_array(), + "starter suggestions sit under the guidance: 面板宽 {width}"); + harness.render().unwrap().save(directory.join(format!("dock-{width}-empty.png"))).unwrap(); + assert!(requests.try_recv().is_err()); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn project_page_dock_visual_acceptance() { + let _gpu = photocraft_testkit::gpu_lock(); + let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + struct Preview(PhotocraftApp); + impl eframe::App for Preview { + fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { + super::super::agent_dock(&mut self.0, ui); + } + } + let projects = |count: usize| (0..count).map(|index| json!({"id":format!("project-{index}"),"source":"native", + "name":if index % 3 == 1 { format!("客厅沙发 · 带贵妃位的加长版本 · 第 {index} 稿") } else { format!("客厅沙发 · 第 {index} 稿") }, + "updatedAt":format!("2026-11-{:02}T09:00:00Z", 28 - index)})).collect::>(); + // (state, whether a canvas is open behind the page, how many projects) + for width in [250.0, 520.0] { + for (name, canvas_open, count) in [("projects", true, 8), ("projects-home", false, 3), ("projects-none", false, 0)] { + let (mut app, requests) = dock_fixture(); + { + let w = app.jiansun.as_mut().unwrap(); + w.composer.clear(); + w.messages.clear(); + w.reduce_motion = true; + w.projects = projects(count); + } + if canvas_open { + app.jiansun.as_mut().unwrap().show_center(CenterView::Projects, true); + } else if let Some(closed) = app.session.close(0) { + let w = app.jiansun.as_mut().unwrap(); + w.open_projects.remove(&closed.doc.id.0); + w.loaded_draft = None; + w.owner_doc = None; + app.sync_views(); + } + let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 760.0)).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); + app.gpu_render_state = cc.wgpu_render_state.clone(); + Preview(app) + }); + harness.run_steps(6); + { + let app = &harness.state().0; + let w = app.jiansun.as_ref().unwrap(); + assert_eq!(w.agent_page(app), "projects", "{name} · 面板宽 {width}"); + assert!(w.panel_geometry["workspaceSearch"].is_null(), "{name} · 面板宽 {width}: the dock repeats no search"); + assert_eq!(w.panel_geometry["workspaceReturn"].is_array(), canvas_open, "{name} · 面板宽 {width}: the way back exists exactly when a canvas is open"); + } + harness.render().unwrap().save(directory.join(format!("dock-{width}-{name}.png"))).unwrap(); + assert!(requests.try_recv().is_err(), "{name} · 面板宽 {width}: rendering sends nothing"); + } + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn review_surfaces_visual_acceptance() { + struct Preview(PhotocraftApp); + impl eframe::App for Preview { + fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) { + super::super::agent_dock(&mut self.0, ui); + } + } + fn text_layers(app: &mut PhotocraftApp, texts: &[&str]) -> Vec { + texts.iter().map(|text| { + app.session.execute("type.create", json!({"text":text,"x":40,"y":40})).unwrap(); + app.session.active().unwrap().selected_layers()[0].0 + }).collect() + } + let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + type Setup = Box; + // One fresh dock per state. `notices` opens the notification window + // with that history. + let render = |width: f32, name: &str, setup: Setup, notices: Option>| { + let (mut app, requests) = dock_fixture(); + let mut workspace = app.jiansun.take().unwrap(); + setup(&mut workspace, &mut app); + app.jiansun = Some(workspace); + let notices = notices.map(|entries| { + let w = app.jiansun.as_ref().unwrap(); + (notification_id(&w.origin, &w.account, &w.project_context, w.owner_doc).expect("a scoped notification history"), entries) + }); + let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, 760.0)).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&cc.egui_ctx); + if let Some((id, entries)) = notices { + cc.egui_ctx.data_mut(|data| data.insert_temp(id, AgentNotifications { + entries, unread: 0, last_error: String::new(), last_unknown: false, open: true, + })); + } + app.gpu_render_state = cc.wgpu_render_state.clone(); + Preview(app) + }); + harness.run_steps(8); + harness.render().unwrap().save(directory.join(format!("dock-{width}-{name}.png"))).unwrap(); + assert!(requests.try_recv().is_err(), "{name} · 面板宽 {width}: rendering sends nothing"); + }; + for width in [250.0, 520.0] { + render(width, "copy-options", Box::new(|w, _| { + w.composer.clear(); + w.origin = "https://fixture.invalid".into(); + w.owner_doc = w.loaded_draft; + w.observed_doc = w.loaded_draft; + w.messages = vec![ + json!({"role":"user","text":"帮我提炼这款电脑桌的卖点"}), + json!({"role":"assistant","kind":"reply","text":"整理了 5 条候选卖点,选好以后点「使用所选」。"}), + json!({"role":"assistant","kind":"copywriting-options","optionsId":"selling-visual","selected":[0,2], + "items":["实木桌板,承重稳定","桌面带走线孔,线材不外露","可调节脚垫,地面不平也放得稳","三种尺寸,适配不同房间","免工具安装,十分钟装好"], + "missing":["承重的具体数值待确认","有没有环保检测报告"],"target":{}}), + ]; + }), None); + render(width, "copy-fields", Box::new(|w, app| { + w.composer.clear(); + let doc = app.session.active().unwrap().doc.id.0; + let layers = text_layers(app, &["原始主标题", "原始副标题", "原始卖点"]); + app.session.execute("select.deselectLayers", json!({})).unwrap(); + w.owner_doc = Some(doc); + w.observed_doc = Some(doc); + let field = |id: &str, label: &str, max: u64| json!({"fieldId":id,"label":label,"maxChars":max,"maxLines":1}); + w.messages = vec![ + json!({"role":"user","text":"给首屏这三处文字各写一版候选"}), + json!({"role":"assistant","kind":"reply","text":"每格都给了候选。原文保留,预览满意后再采纳。"}), + json!({"role":"assistant","kind":"copywriting-fields","optionsId":"copy-visual","items":[ + {"layer":layers[0],"name":"主标题","field":field("S01-T01","主标题",12),"original":"原始主标题","text":"实木电脑桌","applied":false}, + {"layer":layers[1],"name":"副标题","field":field("S01-T02","副标题",24),"original":"原始副标题","text":"桌面带走线孔,线材不外露,居家办公更整洁","applied":false}, + {"layer":layers[2],"name":"卖点","field":field("S01-T03","卖点",16),"original":"原始卖点","text":"原始卖点","applied":false}, + ],"target":{}}), + ]; + }), None); + render(width, "notifications", Box::new(|w, _| { + w.origin = "https://fixture.invalid".into(); + w.owner_doc = w.loaded_draft; + }), Some(vec![ + "can't read smart source within the preview budget: pcraft: limit exceeded: canvas 1440x35827 exceeds 8192 pixels per side".into(), + "素材库请求失败(HTTP 503)".into(), + "模型服务暂时限流".into(), + ])); + render(width, "references", Box::new(|w, app| { + w.composer.clear(); + let doc = app.session.active().unwrap().doc.id.0; + for layer in text_layers(app, &["主标题图层", "副标题图层", "价格标签图层"]) { + w.composer_reference_add_target(app, &json!({"documentId":doc,"nativeLayerId":layer,"component":"layer"})).unwrap(); + } + app.session.execute("select.deselectLayers", json!({})).unwrap(); + }), None); + } + } + + #[test] + #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn tool_timeline_visual_acceptance() { + use egui_kittest::kittest::Queryable; + + let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + for width in [250.0, 520.0] { + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.messages = vec![ + json!({"role":"user","text":"制作详情、主图和 SKU"}), + json!({"role":"assistant","kind":"activity","text":"已接收制作任务。正在保存当前资料,接下来会按模板准备画布。"}), + json!({"role":"assistant","kind":"thinking","active":false,"output":{ + "tokens":518,"tokensPerSecond":147.0,"estimated":false}}), + json!({"role":"assistant","kind":"reply","text":"我先核对商品原图和模板,再安排制作。"}), + json!({"role":"assistant","kind":"activity","text":"读取画布","event":{ + "version":1,"type":"tool","run":"timeline","toolCallId":"read","toolName":"canvas_read","status":"completed","durationMs":120}}), + json!({"role":"assistant","kind":"activity","text":"读取制作规则","event":{ + "version":1,"type":"tool","run":"timeline","toolCallId":"rules","toolName":"workflow_read","status":"completed","durationMs":240}}), + json!({"role":"assistant","kind":"thinking","active":false,"output":{ + "tokens":293,"tokensPerSecond":92.0,"estimated":false}}), + ]; + w.stream_reply = "已找到模板中的 21 个图位。我会先规划文案,再按各屏卖点制作配图。".into(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(width, 520.0)).wgpu() + .build_ui_state(|ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } + Frame::NONE.fill(Tokens::get(ui.ctx()).dock).inner_margin(12).show(ui, |ui| { + let w = app.jiansun.as_ref().unwrap(); + let turn = turns(&w.messages).pop().unwrap(); + w.turn_ui(ui, turn, Id::unique("tool-timeline-visual"), w.messages.len(), true, false, None); + }); + }, app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(8); + let save = |h: &mut egui_kittest::Harness, state: &str| { + let path = std::path::Path::new(&directory).join(format!("timeline-{width}-{state}.png")); + h.render().unwrap().save(path).unwrap(); + }; + save(&mut h, "collapsed"); + let button = h.get_by_label("已完成 2 项操作").rect().center(); + h.hover_at(button); + h.run_steps(2); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { + pos: button, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, + }); + h.run_steps(1); + } + h.run_steps(8); + save(&mut h, "expanded"); + assert!(h.query_by_label("我先核对商品原图和模板,再安排制作。").is_some()); + assert!(h.query_by_label("过程说明").is_none()); + assert!(requests.try_recv().is_err()); + } + } + + #[test] + #[ignore = "offscreen GPU timeline with a real-format tool receipt and a new inline reply"] + fn live_timeline_motion_visual_evidence() { + let _gpu = photocraft_testkit::gpu_lock(); + let out = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.busy = Some("pi-agent".into()); + w.messages = vec![ + json!({"role":"user","text":"核对当前画布后继续制作。"}), + json!({"role":"assistant","kind":"reply","text":"先看首屏卖点和原片是否一致。"}), + json!({"role":"assistant","kind":"thinking","active":false,"output":{"tokens":293}}), + json!({"role":"assistant","kind":"activity","event":{"version":1,"type":"tool","run":"visual", + "toolCallId":"call_4fca7b5|fc_0c72ae9","toolName":"canvas_read","status":"started"}}), + json!({"role":"assistant","kind":"activity","text":"模板已就绪。"}), + ]; + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(360.0, 520.0)).with_step_dt(1.0 / 120.0).wgpu() + .build_ui_state(|ui, app: &mut PhotocraftApp| { + if !super::super::stitch_ui::ui_fonts_ready(ui) { return; } + Frame::NONE.fill(Tokens::get(ui.ctx()).agent().dock).inner_margin(12).show(ui, |ui| { + let w = app.jiansun.as_ref().unwrap(); + w.turn_ui(ui, turns(&w.messages).pop().unwrap(), Id::unique("live-tool-visual"), w.messages.len(), true, false, None); + }); + }, app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.ctx.all_styles_mut(|style| style.animation_time = egui::Style::default().animation_time); + let save = |h: &mut egui_kittest::Harness, name| { + h.render().unwrap().save(out.join(format!("v2-{name}.png"))).unwrap(); + }; + h.run_steps(48); + save(&mut h, "tool-running"); + let w = h.state_mut().jiansun.as_mut().unwrap(); + w.messages[3]["event"]["status"] = json!("completed"); + w.messages[3]["event"]["durationMs"] = json!(320); + w.messages.push(json!({"role":"assistant","kind":"reply","text":"首屏原片与文案一致,接下来核对主图的构图和规格。"})); + h.run_steps(19); + save(&mut h, "inline-reveal"); + h.state_mut().jiansun.as_mut().unwrap().busy = None; + h.run_steps(204); + save(&mut h, "tool-completion-hold"); + h.run_steps(20); + save(&mut h, "tool-collapsing"); + h.run_steps(160); + save(&mut h, "tool-folded"); + assert!(requests.try_recv().is_err()); + } + + #[test] + #[ignore = "offscreen GPU visual evidence for the reply reveal frontier"] + fn typing_frontier_visual_evidence() { + let _gpu = photocraft_testkit::gpu_lock(); + let out = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + let reply = "已核对主图构图和原片,结果一致。继续检查每屏卖点和商品规格。\n```text\n主图:保留商品结构\n详情:核对材质和尺寸\n收尾:复查文字与图位\n```\n检查完成后即可保存。"; + for width in [270.0, 520.0] { + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = false; + w.busy = Some("pi-agent".into()); + w.messages = vec![ + json!({"role":"user","text":"核对主图和详情页。"}), + json!({"role":"assistant","kind":"thinking","active":true, + "output":{"tokens":84,"tokensPerSecond":17}}), + json!({"role":"assistant","kind":"activity","event":{ + "version":1,"type":"tool","run":"reveal-visual","toolCallId":"read", + "toolName":"canvas_read","status":"completed","durationMs":12}}), + ]; + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(width, 360.0)).with_step_dt(1.0 / 120.0).wgpu() + .build_ui_state(|ui, app: &mut PhotocraftApp| { + if !super::super::stitch_ui::ui_fonts_ready(ui) { return; } + Frame::NONE.fill(Tokens::get(ui.ctx()).agent().dock).inner_margin(12).show(ui, |ui| { + let w = app.jiansun.as_ref().unwrap(); + w.turn_ui(ui, turns(&w.messages).pop().unwrap(), Id::unique("typing-frontier-visual"), w.messages.len(), true, false, None); + }); + }, app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + let save = |h: &mut egui_kittest::Harness, frame| { + h.render().unwrap().save(out.join(format!("typing-{width}-{frame}.png"))).unwrap(); + }; + h.run_steps(40); + save(&mut h, "thinking"); + let w = h.state_mut().jiansun.as_mut().unwrap(); + w.messages[1]["active"] = json!(false); + w.stream_reply = reply.into(); + h.run_steps(28); + save(&mut h, "streaming"); + let w = h.state_mut().jiansun.as_mut().unwrap(); + w.messages.push(json!({"role":"assistant","kind":"reply","text":reply})); + w.stream_reply.clear(); + w.busy = None; + h.run_steps(67); + save(&mut h, "draining"); + h.run_steps(360); + save(&mut h, "settled"); + assert!(requests.try_recv().is_err()); + } + } + + #[test] + #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn response_refinement_visual_acceptance() { + let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + for (width, height, dock, scale) in [(1280.0,800.0,520.0,1.0),(1100.0,720.0,250.0,1.5)] { + let (mut app, requests) = dock_fixture(); + app.ui.dock_tabs.color = 4; + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = false; + w.focus_composer = true; + w.busy = Some("pi-agent".into()); + w.messages = vec![json!({"role":"user","text":"请保留木纹,检查当前图位。"}), + json!({"role":"assistant","kind":"thinking","text":"先核对产品原有结构与画布内容,再确认本次处理范围。"}), + json!({"role":"assistant","kind":"activity","text":"读取画布","event":{ + "version":1,"type":"tool","run":"visual-fixture","toolCallId":"one","toolName":"canvas_read","status":"completed","durationMs":27}}), + json!({"role":"assistant","kind":"activity","text":"检查范围","event":{ + "version":1,"type":"tool","run":"visual-fixture","toolCallId":"two","toolName":"workflow_read","status":"started"}})]; + w.stream_reply = "已核对当前画布,保留**产品结构**、木纹与花色。\n\n这里只调整光线,不生成图片。".into(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(width,height)).with_pixels_per_point(scale) + .with_step_dt(1.0/120.0).with_max_steps(64).wgpu().build_ui_state( + |ui, app:&mut PhotocraftApp| { + if !ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { return; } + crate::panels::title_bar(app,ui); + crate::panels::options_bar(app,ui); + crate::panels::status_bar(app,ui); + crate::panels::toolbar(app,ui); + crate::panels::right_dock(app,ui); + egui::CentralPanel::default().frame(Frame::NONE.fill(Tokens::get(ui.ctx()).canvas)) + .show(ui,|ui| crate::canvas::document_area(app,ui)); + },app); + PhotocraftApp::setup_context(&h.ctx,crate::theme::ThemeKind::ProMedium); + crate::panels::request_dock_width(&h.ctx,dock); + h.run_steps(4); + let save = |h:&mut egui_kittest::Harness,name:&str| { + h.render().unwrap().save(std::path::Path::new(&directory).join(format!("response-{dock}-{name}.png"))).unwrap(); + }; + save(&mut h,"streaming"); + h.state_mut().jiansun.as_mut().unwrap().stream_reply.push_str("新的句子平滑出现,标点保持原位。"); + h.run_steps(6); + save(&mut h,"new-batch"); + h.run_steps(20); + { + let w=h.state_mut().jiansun.as_mut().unwrap(); + w.messages.push(json!({"role":"assistant","kind":"reply","text":w.stream_reply})); + w.stream_reply.clear(); + w.busy=None; + } + h.run_steps(24); + save(&mut h,"completed"); + let now=h.ctx.input(|input|input.time); + h.ctx.data_mut(|data| data.insert_temp(Id::unique("composer-sent-glow"),now)); + h.run_steps(16); + save(&mut h,"send-glow"); + h.state_mut().jiansun.as_mut().unwrap().reduce_motion=true; + h.run_steps(4); + save(&mut h,"reduced"); + { + let w = h.state_mut().jiansun.as_mut().unwrap(); + w.messages = vec![json!({"role":"user","text":"制作详情、主图和 SKU"}), + json!({"role":"assistant","kind":"activity","text":"已接收制作任务。正在保存当前资料,接下来会按模板准备画布。"})]; + w.composer.clear(); + w.reduce_motion = false; + w.product_start_queued = true; + w.busy = Some("slot-apply-save".into()); + w.template_progress = json!({"phase":"save"}); + } + h.run_steps(4); + save(&mut h, "production-start"); + { + let w = h.state_mut().jiansun.as_mut().unwrap(); + w.product_start_queued = false; + w.busy = Some("pi-agent".into()); + w.pi_run = Some("goal-fixture".into()); + w.pi_product_production = true; + w.workflow.set_production_progress(&json!({"heading":"正在制作详情页","total":21,"rendered":2, + "workers":[{"number":1,"label":"首屏完整产品场景图","step":"正在生图","active":true}]})); + w.messages.push(json!({"role":"assistant","kind":"reply","text":"我先核对商品原图和模板,再安排制作。"})); + w.messages.push(json!({"role":"assistant","kind":"activity","text":"完成:读取画布","event":{ + "version":1,"type":"tool","run":"goal-fixture","toolCallId":"goal-read","toolName":"canvas_read","status":"completed"}})); + w.messages.push(json!({"role":"assistant","kind":"activity","text":"开始:分派生图","event":{ + "version":1,"type":"tool","run":"goal-fixture","toolCallId":"goal-stage","toolName":"delegate_image_slots","status":"started"}})); + w.stream_reply = "正在制作详情页。".into(); + } + h.run_steps(32); + save(&mut h, "production-streaming"); + h.state_mut().jiansun.as_mut().unwrap().stream_reply.push_str("首屏的配图已经开始生成。"); + h.run_steps(1); + save(&mut h, "production-new-batch"); + h.run_steps(32); + save(&mut h, "production-settled"); + { + let w = h.state_mut().jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.stream_reply.push_str("我会继续复核其余图位。"); + } + h.run_steps(2); + save(&mut h, "production-reduced"); + h.state_mut().jiansun.as_mut().unwrap().reduce_motion = false; + { + let w = h.state_mut().jiansun.as_mut().unwrap(); + w.messages.push(json!({"role":"assistant","kind":"reply","text":std::mem::take(&mut w.stream_reply)})); + w.pi_run = None; + w.busy = None; + w.messages.push(json!({"role":"assistant","kind":"reply","text":"已导出 2/3 份,待处理输出保留在项目中。", + "productionSummary":{"exported":2,"total":3}})); + } + h.run_steps(4); + save(&mut h, "production-followups"); + assert!(requests.try_recv().is_err(),"visual fixtures never dispatch a model or native operation"); + } + } + + #[test] + #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn native_agent_visual_acceptance() { + let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + let (mut app, requests) = dock_fixture(); + if let Ok(path) = std::env::var("PHOTOCRAFT_AGENT_QA_DOCUMENT") { + app.open_path(&path).expect("read-only local QA document"); + app.sync_views(); + } + let mut h = egui_kittest::Harness::builder().with_size(vec2(1280.0, 800.0)).with_pixels_per_point(1.5).with_max_steps(64).wgpu().build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::title_bar(app, ui); + crate::panels::options_bar(app, ui); + crate::panels::status_bar(app, ui); + crate::panels::toolbar(app, ui); + crate::panels::right_dock(app, ui); + egui::CentralPanel::default().frame(Frame::NONE.fill(Tokens::get(ui.ctx()).canvas)).show(ui, |ui| crate::canvas::document_area(app, ui)); + if let Some(workspace) = app.jiansun.as_mut() { workspace.account_dialog(ui); } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(4); + h.state_mut().run("view.fitOnScreen", Value::Null).unwrap(); + for (name, pending, paused, tab) in [ + ("idle", false, false, 4), + ("processing", true, false, 4), + ("takeover", true, true, 4), + ("native-only", false, false, 0), + ("swatches", false, false, 1), + ] { + let app = h.state_mut(); + app.ui.dock_tabs.color = tab; + let w = app.jiansun.as_mut().unwrap(); + w.busy = pending.then(|| "slot-generate".into()); + w.agent_effects_paused = paused; + h.run_steps(4); + h.render().expect("native offscreen render").save(std::path::Path::new(&directory).join(format!("{name}.png"))).unwrap(); + } + h.state_mut().ui.dock_tabs.color = 4; + h.state_mut().jiansun.as_mut().unwrap().busy = Some("slot-generate".into()); + h.run_steps(4); + let first = h.render().unwrap(); + h.run_steps(30); + let second = h.render().unwrap(); + assert_ne!(first.as_raw(), second.as_raw(), "real pending state animates"); + second.save(std::path::Path::new(&directory).join("processing-later.png")).unwrap(); + h.state_mut().jiansun.as_mut().unwrap().reduce_motion = true; + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join("reduced-motion.png")).unwrap(); + let w = h.state_mut().jiansun.as_mut().unwrap(); + w.busy = None; + w.unknown = true; + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join("unknown-retained.png")).unwrap(); + { + let w = h.state_mut().jiansun.as_mut().unwrap(); + w.unknown = false; + w.model_settings = true; + w.library_status = "connected".into(); + w.image_models = ["gpt-image-2", "gpt-image-2-vip", "gpt-image-2.5", "gpt-image-2.5-flare", "gpt-image-2.5-flare-burst", "nano-banana-2", "nano-banana-2-cl"] + .into_iter().map(|name| json!({"key":name,"id":name})).collect(); + w.image_model = "nano-banana-2".into(); + } + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join("settings-with-usage.png")).unwrap(); + let settings_body = geometry(h.state().jiansun.as_ref().unwrap(), "settingsBody"); + h.event(egui::Event::PointerMoved(settings_body.center())); + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, phase: egui::TouchPhase::Move, + unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, -400.0), modifiers: egui::Modifiers::NONE, + }); + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join("settings-enterprise-knowledge.png")).unwrap(); + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, phase: egui::TouchPhase::Move, + unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, 400.0), modifiers: egui::Modifiers::NONE, + }); + h.run_steps(4); + let model_popup = h.ctx.data(|data| data.get_temp::(Id::unique(("agent-model-last-popup", ModelRole::Image, true)))).unwrap(); + egui::Popup::open_id(&h.ctx, model_popup); + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join("model-menu-alignment.png")).unwrap(); + egui::Popup::close_id(&h.ctx, model_popup); + { + let w = h.state_mut().jiansun.as_mut().unwrap(); + w.model_settings = false; + w.config = true; + } + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join("account-shared-dialog.png")).unwrap(); + { + let app = h.state_mut(); + app.ui.dock_tabs.color = 4; + let doc = app.session.active().unwrap().doc.id.0; + let w = app.jiansun.as_mut().unwrap(); + w.config = false; + w.reduce_motion = true; + w.busy = None; + w.unknown = false; + w.origin = "https://fixture.invalid".into(); + w.open_projects.insert(doc,w.local_identity("visual-test")); + w.composer = "用于检查拖放热区的本地草稿".into(); + w.focus_composer = true; + } + crate::panels::request_dock_width(&h.ctx,250.0); + h.run_steps(8); + let more = geometry(h.state().jiansun.as_ref().unwrap(),"composerMore"); + let composer = geometry(h.state().jiansun.as_ref().unwrap(),"composer"); + let send = geometry(h.state().jiansun.as_ref().unwrap(),"send"); + assert!(composer.contains_rect(send)); + h.render().unwrap().save(std::path::Path::new(&directory).join("composer-narrow-150.png")).unwrap(); + let at = more.center(); + for pressed in [true,false] { + h.input_mut().events = vec![egui::Event::PointerMoved(at),egui::Event::PointerButton { + pos:at,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]; + h.step(); + } + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join("composer-overflow-150.png")).unwrap(); + egui::Popup::close_all(&h.ctx); + h.run_steps(4); + let point = composer.center(); + h.state_mut().services.cursor_pos = Some(Box::new(move |_| Some(point))); + let before = h.render().unwrap(); + h.input_mut().hovered_files = vec![egui::HoveredFile { path:Some(std::env::temp_dir().join("fixture.png")), ..Default::default() }]; + h.step(); + let hovered = h.render().unwrap(); + assert_ne!(before.as_raw(),hovered.as_raw(),"a real hovered-file event paints feedback on the active composer"); + hovered.save(std::path::Path::new(&directory).join("composer-file-hover-150.png")).unwrap(); + h.input_mut().hovered_files.clear(); + h.set_pixels_per_point(1.25); + crate::panels::request_dock_width(&h.ctx,250.0); + h.run_steps(8); + let w = h.state().jiansun.as_ref().unwrap(); + assert!(geometry(w,"composer").contains_rect(geometry(w,"send"))); + let at = geometry(w,"composerMore").center(); + h.render().unwrap().save(std::path::Path::new(&directory).join("composer-narrow-125.png")).unwrap(); + for pressed in [true,false] { + h.input_mut().events = vec![egui::Event::PointerMoved(at),egui::Event::PointerButton { + pos:at,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]; + h.step(); + } + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join("composer-overflow-125.png")).unwrap(); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn replay_protection_during_an_active_request_is_not_a_terminal_unknown_status() { + let (tx, _) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + w.unknown = true; + for method in ["agent", "pi-agent", "recover", "image", "image-recover", "slot-generate", "slot-append", "slot-recover", "slot-copy"] { + w.busy = Some(method.into()); + assert!(w.pending()); + assert!(!w.result_needs_check()); + assert!(w.unknown, "display state must not clear the replay barrier"); + } + w.busy = None; + assert!(w.result_needs_check()); + w.unknown = false; + assert!(!w.result_needs_check()); + } + + #[test] + fn handing_over_a_candidate_keeps_original_request_and_prevents_late_adoption() { + let (tx, requests) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + let _ = requests.try_recv(); + w.busy = Some("slot-append".into()); + w.unknown = true; + w.canvas_workspace.pending_adoption = Some(json!({"candidateId":"original"})); + w.handover(); + assert!(w.canvas_workspace.handed_over); + assert!(w.canvas_workspace.pending_adoption.is_none()); + assert_eq!(w.busy.as_deref(), Some("slot-append")); + assert!(w.unknown); + assert!(requests.try_recv().is_err(), "handover neither retries nor cancels the upstream request"); + let count = w.messages.len(); + w.handover(); + assert_eq!(w.messages.len(), count); + } + + #[test] + fn adjacent_tool_groups_keep_their_place_between_replies() { + fn tool(id: &str, name: &str, status: &str) -> Value { + json!({"role":"assistant","kind":"activity","text":name,"event":{ + "version":1,"type":"tool","run":"timeline-run","toolCallId":id,"toolName":name,"status":status}}) + } + fn collect(shape: &egui::Shape, labels: &mut Vec<(String, f32)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, labels)), + egui::Shape::Text(text) => labels.push((text.galley.text().into(), text.pos.y)), + _ => {} + } + } + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.messages = vec![ + json!({"role":"user","text":"制作整套"}), + json!({"role":"assistant","kind":"reply","text":"先核对商品原片"}), + tool("one","canvas_read","started"), + tool("two","context_read","completed"), + json!({"role":"assistant","kind":"reply","text":"原片核对完成,接着制作"}), + tool("one","canvas_read","completed"), + tool("three","produce_current_output","completed"), + json!({"role":"assistant","kind":"reply","text":"成品已导出"}), + ]; + let turn = turns(&w.messages).pop().unwrap(); + assert!(matches!(&turn.items[..], + [TurnItem::Reply(_,1), TurnItem::Tools(first), TurnItem::Reply(_,4), + TurnItem::Tools(second), TurnItem::Reply(_,7)] + if first.len()==2 && first[0].1==2 && first[0].0["status"]=="completed" && second.len()==1)); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + for width in [250.0, 520.0] { + let output = ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(650.0, 900.0))), + ..Default::default() + }, |ui| { + ui.set_width(width); + w.turn_ui(ui, turns(&w.messages).pop().unwrap(), Id::unique(("timeline-order", width as u64)), w.messages.len(), true, false, None); + }); + let mut labels = Vec::new(); + for shape in &output.shapes { collect(&shape.shape, &mut labels); } + let heads: Vec<_> = labels.iter().filter(|(s, _)| s=="已完成 2 项操作" || s.starts_with("已完成 · ")).map(|(_, y)| *y).collect(); + let y = |name: &str| labels.iter().find(|(s, _)| s==name).unwrap().1; + assert_eq!(heads.len(), 2, "visible timeline labels at {width}: {labels:?}"); + assert!(y("先核对商品原片") < heads[0] && heads[0] < y("原片核对完成,接着制作")); + assert!(y("原片核对完成,接着制作") < heads[1] && heads[1] < y("成品已导出")); + output.drop_without_applying_deltas(); + } + assert!(requests.try_recv().is_err()); + } + + #[test] + fn operations_are_grouped_under_the_actual_user_turn_without_losing_history() { + let messages = vec![ + json!({"role":"user","text":"精修产品"}), + json!({"role":"assistant","text":"图片已生成"}), + json!({"role":"assistant","kind":"activity","text":"已替换当前屏图片"}), + json!({"role":"assistant","kind":"reply","text":"已保留原有字体。"}), + json!({"role":"user","text":"修改标题"}), + ]; + let turns = turns(&messages); + assert_eq!(turns.len(), 2); + assert!(matches!(turns[0].items.as_slice(), + [TurnItem::Notice(..), TurnItem::Notice(..), TurnItem::Reply("已保留原有字体。", _)])); + assert_eq!(turns[1].user, Some("修改标题")); + } + + #[test] + fn repeated_status_keeps_only_its_latest_line() { + let saved = "详情页编辑稿已保存。小壹会自动核查 4 条原请求,确认结果后继续处理对应图位。"; + let again = "详情页编辑稿已保存。小壹会自动核查 1 条原请求,确认结果后继续处理对应图位。"; + let received = "已接收制作任务。正在保存当前资料,接下来会按模板准备画布。"; + let messages = vec![ + json!({"role":"user","text":"继续整套制作"}), + json!({"role":"assistant","kind":"activity","text":saved}), + json!({"role":"assistant","kind":"activity","text":received}), + json!({"role":"assistant","kind":"activity","text":again}), + json!({"role":"assistant","kind":"activity","text":received}), + ]; + let notices: Vec<_> = turns(&messages).into_iter().flat_map(|turn| turn.items).filter_map(|item| match item { + TurnItem::Notice(text, _) => Some(text), + _ => None, + }).collect(); + assert_eq!(notices, vec![saved, again, received]); + } + #[test] + fn failed_image_preflight_keeps_composer_and_never_dispatches_a_request() { + let (tx, requests) = mpsc::channel(); + let (_events, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + let _ = requests.try_recv(); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); + let app = PhotocraftApp::new(session, crate::Services::default()); + w.loaded_draft = app.session.active().map(|state| state.doc.id.0); + w.busy = None; + w.image_ready = true; + w.image_mode = "regenerate".into(); + w.composer = "保留产品,调整背景".into(); + w.send_composer(&app); + assert_eq!(w.composer, "保留产品,调整背景"); + assert!(requests.try_recv().is_err()); + assert!(!w.error.is_empty()); + } + #[test] + fn composer_steers_an_active_chat_and_keeps_image_generation_disabled() { + let (mut app,requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + let doc = app.session.active().unwrap().doc.id.0; + let draft = w.composer.clone(); + let messages = w.messages.clone(); + w.pi_run = Some("12345678-1234-1234-1234-123456789012".into()); + w.busy = Some("agent".into()); + w.owner_doc = Some(doc); + w.pi_request_scope = json!({"project":{"documentId":doc},"subject":{"kind":"project"}}); + w.stream_reply = "未结束的回复".into(); + let scope = w.pi_request_scope.clone(); + assert!(w.can_send_with(&app,false)); + assert!(!w.can_send_with(&app,true)); + w.send_composer(&app); + let Request::Action(method,input) = requests.try_recv().unwrap() else { panic!("expected an action") }; + assert_eq!(method, "agent-steer"); + assert_eq!(input["text"], draft); + assert_eq!(input["behavior"], "steer"); + assert_eq!(input["doc"], doc); + assert!(w.composer.is_empty()); + assert_eq!(w.messages,messages); + assert_eq!(w.pi_request_scope,scope); + assert_eq!(w.busy.as_deref(),Some("agent")); + assert!(w.pi_run.is_some()); + assert_eq!(w.stream_reply,"未结束的回复"); + assert!(requests.try_recv().is_err()); + + w.pi_product_production = true; + w.canvas_workspace.output = "sku".into(); + w.composer = "补充详情页的安排".into(); + assert!(w.can_steer(&app)); + w.send_composer(&app); + assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent-steer" && input["doc"] == doc)); + assert_eq!(w.canvas_workspace.output, "sku"); + } + + #[test] + fn live_composer_renders_stop_beside_send_and_accepts_enter() { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let doc = app.session.active().unwrap().doc.id.0; + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.owner_doc = Some(doc); + w.busy = Some("agent".into()); + w.pi_run = Some("12345678-1234-1234-1234-123456789012".into()); + w.pi_queued_steering = vec!["保留高光".into()]; + w.pi_queued_followup = vec!["说明用色".into()]; + for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } + let w = app.jiansun.as_ref().unwrap(); + let send = geometry(w, "send"); + let stop = geometry(w, "stop"); + assert!(!send.intersects(stop)); + assert!(geometry(w, "composer").contains_rect(send.union(stop))); + ctx.memory_mut(|memory| memory.request_focus(super::super::composer_input_id())); + dock_frame(&ctx, &mut app, vec![egui::Event::Key { + key:egui::Key::Enter,physical_key:None,pressed:true,repeat:false,modifiers:egui::Modifiers::NONE, + }]); + assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent-steer" && input["doc"] == doc)); + app.jiansun.as_mut().unwrap().composer = "保留草稿".into(); + let center = stop.center(); + for pressed in [true, false] { + dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(center), egui::Event::PointerButton { + pos:center,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE, + }]); + } + assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent-abort" && input["doc"] == doc)); + assert!(app.jiansun.as_ref().unwrap().pi_queued_steering.is_empty()); + } + + #[test] + fn pending_steering_and_followup_render_above_the_composer_and_can_be_cleared() { + use egui_kittest::kittest::Queryable; + let (mut app, requests) = dock_fixture(); + let doc = app.session.active().unwrap().doc.id.0; + let mut w = app.jiansun.take().unwrap(); + w.owner_doc = Some(doc); + w.pi_run = Some("12345678-1234-1234-1234-123456789012".into()); + w.pi_queued_steering = vec!["保留高光".into()]; + w.pi_queued_followup = vec!["说明用色".into()]; + let mut harness = egui_kittest::Harness::builder() + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(vec2(520.0, 300.0)) + .build_ui_state(|ui, (w, app): &mut (Workspace, PhotocraftApp)| w.composer_ui(app, ui), (w, app)); + harness.run_steps(3); + assert_eq!(harness.query_all_by_label("待插话 · 当前步骤后注入 保留高光").count(), 1); + assert_eq!(harness.query_all_by_label("已排队 · 本轮结束后发送 说明用色").count(), 1); + let clear = harness.get_by_role_and_label(egui::accesskit::Role::Button, "清空待发送消息"); + assert!(clear.rect().bottom() <= geometry(&harness.state().0, "composer").top()); + clear.click(); + harness.run_steps(2); + assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent-clear-queue" && input["doc"] == doc)); + } + + #[test] + #[ignore = "Offscreen composer evidence; writes to PHOTOCRAFT_AGENT_QA_OUT"] + fn gpu_steering_composer_at_desktop_and_narrow_widths() { + use egui_kittest::kittest::Queryable; + let _guard = photocraft_testkit::gpu_lock(); + let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap()); + for width in [520.0, 260.0] { + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + w.reduce_motion = true; + w.busy = Some("agent".into()); + w.pi_run = Some("12345678-1234-1234-1234-123456789012".into()); + w.owner_doc = w.loaded_draft; + w.pi_queued_steering = vec!["保留高光与木纹细节".into()]; + w.pi_queued_followup = vec!["说明本轮用色".into()]; + let mut harness = egui_kittest::Harness::builder() + .with_context_setup(|ctx| { + PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }) + .with_size(vec2(width, 300.0)) + .wgpu() + .build_ui_state(|ui, (w, app): &mut (Workspace, PhotocraftApp)| w.composer_ui(app, ui), (w, app)); + harness.run_steps(3); + let w = &harness.state().0; + let composer = geometry(w, "composer"); + let stop = geometry(w, "stop"); + let send = geometry(w, "send"); + assert!(composer.contains_rect(stop.union(send))); + assert!(!stop.intersects(send)); + let clear = harness.get_by_role_and_label(egui::accesskit::Role::Button, "清空待发送消息"); + assert!(clear.rect().bottom() <= composer.top()); + assert!(requests.try_recv().is_err()); + harness.render().unwrap().save(directory.join(format!("steering-composer-{width}.png"))).unwrap(); + } + } + + #[test] + fn rejected_steering_resubmits_when_idle_and_preserves_an_unsent_draft_on_error() { + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + let doc = app.session.active().unwrap().doc.id.0; + let ctx = egui::Context::default(); + w.composer.clear(); + let mut receipt = json!({"accountId":w.account["id"],"origin":w.origin,"doc":doc, + "accepted":false,"reason":"not_streaming","text":"补充一下排版"}); + w.receive_json_event(&mut app, &ctx, "agent-steer".into(), Ok(receipt.clone())); + assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent" && input["text"] == receipt["text"])); + receipt["reason"] = json!("starting"); + receipt["error"] = json!("本轮正在连接"); + w.receive_json_event(&mut app, &ctx, "agent-steer".into(), Ok(receipt)); + assert_eq!(w.composer, "补充一下排版"); + assert_eq!(w.error, "本轮正在连接"); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn only_delivered_steering_has_the_timeline_tag() { + use egui_kittest::kittest::Queryable; + let (mut app, _) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + w.reduce_motion = true; + w.messages = vec![ + json!({"role":"user","text":"普通消息"}), + json!({"role":"user","kind":"steer","delivered":true,"text":"保留高光"}), + ]; + let h = egui_kittest::Harness::builder().with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(vec2(300.0, 260.0)).build_ui_state( + |ui, w: &mut Workspace| { + for turn in turns(&w.messages) { + w.turn_ui(ui, turn, Id::NULL, w.messages.len(), false, false, None); + } + }, w); + assert_eq!(h.query_all_by_label("已插话").count(), 1); + } + + #[test] + fn project_discussion_needs_a_model_but_no_brand_rules_or_canvas_write_grant() { + let (tx, requests) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + let _ = requests.try_recv(); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); + let app = PhotocraftApp::new(session, crate::Services::default()); + w.loaded_draft = app.session.active().map(|state| state.doc.id.0); + w.busy = None; + w.model_ready = true; + w.image_mode = "chat".into(); + w.composer = "先讨论排版,不修改画布".into(); + assert!(w.agent_rule.is_null()); + assert!(w.can_send(&app)); + w.send_composer(&app); + assert!(matches!(requests.try_recv().unwrap(),Request::Action(method,_) if method=="agent")); + assert!(!w.allow_apply); + assert!(!w.pi_write_blocked); + w.busy = None; + w.unknown = true; + w.composer = "不能借聊天重发原请求".into(); + assert!(!w.can_send(&app)); + w.send_composer(&app); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn ordinary_send_uses_pi_even_after_a_previous_explicit_image_action() { + let (tx, requests) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + let _ = requests.try_recv(); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); + let app = PhotocraftApp::new(session, crate::Services::default()); + w.loaded_draft = app.session.active().map(|state| state.doc.id.0); + w.busy = None; + w.model_ready = true; + w.image_ready = false; + w.image_mode = "generate".into(); + w.composer = "先讨论这一屏,不生成图片".into(); + w.send_discussion(&app); + assert_eq!(w.image_mode, "chat"); + assert!(matches!(requests.try_recv().unwrap(),Request::Action(method,_) if method=="agent")); + assert!(requests.try_recv().is_err(), "ordinary Send creates exactly one chat action, never an image action"); + } + + #[test] + fn explicit_image_action_keeps_unknown_request_and_draft_untouched() { + let (tx, requests) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + let _ = requests.try_recv(); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); + let app = PhotocraftApp::new(session, crate::Services::default()); + w.busy = None; + w.unknown = true; + w.image_ready = true; + w.image_mode = "regenerate".into(); + w.composer = "保留这段未发送的要求".into(); + w.send_image_once(&app); + assert!(w.unknown); + assert_eq!(w.composer, "保留这段未发送的要求"); + assert!(requests.try_recv().is_err(), "a new-looking UI action cannot replay an unknown request"); + } + + #[test] + fn canvas_first_image_action_requires_the_current_slot_variant_and_dispatch_capability() { + let (tx, requests) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + let _ = requests.try_recv(); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); + let app = PhotocraftApp::new(session, crate::Services::default()); + w.loaded_draft = app.session.active().map(|state| state.doc.id.0); + w.busy = None; + w.model_ready = true; + w.image_ready = true; + w.composer = "保留原图,追加暖光候选".into(); + w.canvas_workspace.variant = "brown".into(); + w.template_workflow = json!({"canvasFirst":true,"slots":[{"id":"current-slot"}],"capabilities":{"imageDispatchAllowed":true}}); + assert!(!w.can_send_with(&app, true), "project-level discussion does not guess an image target"); + assert!(w.can_send_with(&app, false)); + w.canvas_workspace.context = Some(json!({"slotId":"other-slot","productVariantId":"brown"})); + assert!(!w.can_send_with(&app, true)); + w.canvas_workspace.context = Some(json!({"slotId":"current-slot","productVariantId":"other-color"})); + assert!(!w.can_send_with(&app, true)); + w.canvas_workspace.context = Some(json!({"slotId":"current-slot","productVariantId":"brown"})); + assert!(w.can_send_with(&app, true)); + w.template_workflow["capabilities"]["imageDispatchAllowed"] = json!(false); + assert!(!w.can_send_with(&app, true)); + w.send_image_once(&app); + assert_eq!(w.composer, "保留原图,追加暖光候选"); + assert!(requests.try_recv().is_err()); + w.template_workflow["capabilities"]["imageDispatchAllowed"] = json!(true); + w.unknown = true; + assert!(!w.can_send_with(&app, true)); + w.send_image_once(&app); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn candidate_context_shows_its_page_variant_and_actual_candidate_ordinal() { + let workflow = json!({"slots":[{"id":"slot-1","candidates":[{"id":"first"},{"id":"second"},{"id":"third"}]}]}); + let subject = json!({"kind":"candidate","pageId":"S02","slotId":"slot-1","label":"木纹细节","variantLabel":"柚木色","candidateId":"third"}); + assert_eq!(subject_label(&subject, &workflow), "S02 · 木纹细节 · 柚木色 · 候选 3"); + assert_eq!(subject_label(&json!({"kind":"project","label":"当前项目"}), &workflow), "当前项目"); + assert_eq!(notice_kind("读取当前图位"), NoticeKind::Info, "a read is not falsely marked as a completed edit"); + assert_eq!(notice_kind("原请求待核查"), NoticeKind::NeedsCheck); + } + + #[test] + fn image_result_short_labels_follow_the_real_slot_order_and_keep_full_context() { + let workflow = json!({"slots":[ + {"id":"hero", "documentId":"S01", "label":"首屏产品场景主图", "candidates":[{"id":"a"},{"id":"b"},{"id":"c"}]}, + {"id":"detail", "documentId":"S02", "label":"木纹细节", "candidates":[{"id":"d"}]} + ]}); + let brief = json!({"variants":[{"id":"teak","name":"柚木色"}]}); + let target = image_location(&json!({"slotId":"hero","productVariantId":"teak","candidateId":"c"}), "task-2"); + let (page, short, full) = image_result_labels(&target, &workflow, &brief); + assert_eq!(page, "S01"); + assert_eq!(short, "候选 3", "the task/message order is irrelevant"); + assert_eq!(full, "S01 · 首屏产品场景主图 · 柚木色 · 候选 3"); + let other = image_location(&json!({"slotId":"detail","productVariantId":"teak","candidateId":"d"}), "task-1"); + assert_eq!(image_result_labels(&other, &workflow, &brief).0, "S02"); + assert_eq!(image_result_labels(&other, &workflow, &brief).1, "候选 1"); + let unknown = image_location(&json!({"slotId":"hero","productVariantId":"teak","candidateId":"missing"}), "task-3"); + assert_eq!(image_result_labels(&unknown, &workflow, &brief).1, "候选图片"); + assert_eq!(candidate_ordinal(&json!({"slotId":"hero"}), &workflow), None); + assert_eq!(candidate_ordinal(&json!({"candidateId":"a"}), &workflow), None); + let ambiguous = json!({"slots":[{"id":"hero","candidates":[{"id":"a"},{"id":"a"}]}]}); + assert_eq!(candidate_ordinal(&json!({"slotId":"hero","candidateId":"a"}), &ambiguous), None); + } + + #[test] + fn context_capsule_only_requests_native_location_and_never_sends_a_model_action() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + w.composer.clear(); + let subject = json!({"kind":"candidate","label":"主视觉","pageId":"S01","slotId":"slot","outputId":"detail","productVariantId":"brown","candidateId":"candidate-3"}); + w.template_workflow = json!({"templateId":"pack","canvasFirst":true,"slots":[{"id":"slot","outputId":"detail","label":"主视觉","variantId":"brown","candidates":[{"id":"candidate-3"}]}]}); + w.canvas_workspace.context = Some(subject.clone()); + w.composer_reference_clear(&app); + w.composer_reference_add(&app).expect("attach the selected candidate to the draft"); + w.library = false; + w.focus_composer = true; + w.reduce_motion = true; + only_layers(&mut app); + app.ui.dock_tabs.color = 4; + app.jiansun = Some(w); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0)); + for _ in 0..2 { + let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + let mut workspace = app.jiansun.take().unwrap(); + workspace.right(&mut app, ui); + app.jiansun = Some(workspace); + }); + output.textures_delta.clear(); + } + let expected_reference = app.jiansun.as_ref().unwrap().composer_reference_list(&app).into_iter() + .find(|reference| reference["candidateId"] == subject["candidateId"]).expect("the attached candidate remains available"); + assert_eq!(expected_reference["candidateId"], subject["candidateId"]); + let rect = app.jiansun.as_ref().unwrap().panel_geometry["subject"].as_array().unwrap(); + let at = + pos2((rect[0].as_f64().unwrap() + 12.0) as f32, (rect[1].as_f64().unwrap() + rect[3].as_f64().unwrap() / 2.0) as f32); + let mut hovered = ctx.settle_ui( + egui::RawInput { screen_rect: Some(screen), events: vec![egui::Event::PointerMoved(at)], ..Default::default() }, + |ui| { + let mut workspace = app.jiansun.take().unwrap(); + workspace.right(&mut app, ui); + app.jiansun = Some(workspace); + }, + ); + hovered.textures_delta.clear(); + for pressed in [true, false] { + let mut output = ctx.settle_ui( + egui::RawInput { + screen_rect: Some(screen), + events: vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ..Default::default() + }, + |ui| { + let mut workspace = app.jiansun.take().unwrap(); + workspace.right(&mut app, ui); + app.jiansun = Some(workspace); + }, + ); + output.textures_delta.clear(); + } + let w = app.jiansun.as_ref().unwrap(); + let located = w.canvas_workspace.locate_request.as_ref().unwrap_or_else(|| panic!("reference click did not locate: {}", w.panel_geometry)); + assert_eq!(located["candidateId"], expected_reference["candidateId"]); + assert_eq!(located["slotId"], expected_reference["slotId"]); + assert_eq!(located["productVariantId"], expected_reference["productVariantId"]); + assert_eq!(w.composer_reference_list(&app), vec![expected_reference]); + assert!(requests.try_recv().is_err()); + assert!(w.composer.is_empty()); + } + #[test] + fn streamed_text_is_scoped_and_cannot_apply_incomplete_edits() { + let ctx = egui::Context::default(); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + app.sync_views(); + let id = app.session.active().unwrap().doc.id.0; + let revision = app.session.active().unwrap().revision; + let (tx, _requests) = mpsc::channel(); + let (events, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + w.account = json!({"id":"a"}); + w.observed_doc = Some(id); + w.busy = Some("agent".into()); + for (account, doc, text) in [("b", id, "其他账户"), ("a", id + 1, "其他文档"), ("a", id, "正在调整中文")] { + events.send(Event::Json("agent-stream".into(), Ok(json!({"doc":doc,"accountId":account,"origin":w.origin,"text":text})))).unwrap(); + } + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + output.textures_delta.clear(); + assert_eq!(w.stream_reply, "正在调整中文"); + assert!(w.queue.is_empty()); + assert_eq!(app.session.active().unwrap().revision, revision); + w.unknown = true; + w.model_ready = true; + w.composer = "不要重发".into(); + w.busy = None; + assert!(!w.can_send(&app)); + } + #[test] + fn native_dock_keeps_input_and_actions_inside_supported_window_sizes() { + for (width, height) in [(1100.0, 720.0), (1280.0, 800.0), (1440.0, 900.0), (1920.0, 1080.0), (960.0, 600.0)] { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let (tx, _requests) = mpsc::channel(); + let (_events, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + let mut app_session = photocraft_engine::Session::new(); + app_session.execute("file.new",json!({"width":1440,"height":1800})).unwrap(); + let mut app = PhotocraftApp::new(app_session, crate::Services::default()); + app.sync_views(); + w.busy = None; + w.library = false; + w.account = json!({"id":"a"}); + w.key_saved = true; + w.composer = "很长的产品要求也只在输入区域内部滚动。\n".repeat(40); + w.messages = vec![json!({"role":"user","text":"用户要求"}), json!({"role":"assistant","kind":"reply","text":"这是答复"})]; + only_layers(&mut app); + app.ui.dock_tabs.color = 4; + app.jiansun = Some(w); + for _ in 0..2 { + let mut output = ctx + .run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width, height))), ..Default::default() }, |ui| { + crate::panels::right_dock(&mut app, ui) + }); + output.textures_delta.clear(); + } + let w = app.jiansun.as_ref().unwrap(); + let value = |name: &str| { + let a = w.panel_geometry[name].as_array().unwrap(); + Rect::from_min_size( + pos2(a[0].as_f64().unwrap() as f32, a[1].as_f64().unwrap() as f32), + vec2(a[2].as_f64().unwrap() as f32, a[3].as_f64().unwrap() as f32), + ) + }; + let panel = value("panel"); + let composer = value("composer"); + assert!(panel.contains_rect(composer), "{width}x{height}: panel={panel:?}, composer={composer:?}, geometry={}", w.panel_geometry); + let controls = vec!["input", "send", "settings", "composerOrb", "imageGenerate", "composerMore"]; + for key in controls { + assert!(composer.contains_rect(value(key)), "{key} at {width}x{height}"); + } + assert!(composer.height() <= height*0.5+1.0, "long drafts remain bounded at {width}x{height}: {}", composer.height()); + assert!(w.panel_geometry.get("chatModel").is_none() && w.panel_geometry.get("imageModel").is_none(), "model controls belong to settings only"); + assert!(w.panel_geometry.get("contextMeter").is_none(), "unavailable usage must not add noise to the composer"); + assert!(w.panel_geometry.get("rules").is_none(), "project rules do not become a second composer selector"); + assert!(w.panel_geometry.get("chatMode").is_none() && w.panel_geometry.get("imageMode").is_none(), "there is no persistent task-mode picker"); + } + } + + #[test] + fn composer_notices_keep_mini_input_inside_dock() { + for width in [250.0, 520.0] { + for notice in ["none", "error", "review", "unknown", "login", "key", "combined"] { + let (mut app, _) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.composer.clear(); w.focus_composer = false; w.reduce_motion = true; + if matches!(notice, "error" | "combined") { w.error = "原项目已关闭或移除,结果未写入其他项目".into(); } + w.pi_review = matches!(notice, "review" | "combined"); + w.unknown = notice == "unknown"; + if matches!(notice, "login" | "combined") { w.library_status = "disabled".into(); } + w.key_saved = notice != "key"; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + crate::panels::request_dock_width(&ctx, width); + for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } + let w = app.jiansun.as_ref().unwrap(); + let composer = geometry(w, "composer"); + let panel = geometry(w, "panel"); + assert!((composer.height() - 56.0 - reference_shelf_height(1, width - 28.0)).abs() < 1.0); + assert!(composer.bottom() <= panel.bottom() - 9.5, "{notice} at {width}: {composer:?} exceeds {panel:?}"); + assert!(composer.contains_rect(geometry(w, "input"))); + } + } + } + + #[test] + fn empty_unfocused_composer_keeps_references_above_the_native_input() { + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.composer.clear(); + w.focus_composer = false; + w.composer_attachments = Default::default(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + for _ in 0..3 { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)).drop_without_applying_deltas(); + } + let w = app.jiansun.as_ref().unwrap(); + assert!(!w.panel_geometry["composerExpanded"].as_bool().unwrap()); + let subject = geometry(w, "subject"); + assert!(subject.height() <= 24.0, "reference chip: {subject:?}"); + assert!(subject.bottom() <= geometry(w, "input").top()); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn empty_caret_and_repeated_clicks_stay_in_the_native_input_below_references() { + let (mut app, requests) = dock_fixture(); + let w = app.jiansun.as_mut().unwrap(); + w.composer.clear(); + w.focus_composer = false; + w.reduce_motion = true; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0)); + let frame = |app: &mut PhotocraftApp, events| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, + |ui| crate::panels::right_dock(app, ui)).drop_without_applying_deltas(); + }; + for _ in 0..3 { frame(&mut app, vec![]); } + let input = geometry(app.jiansun.as_ref().unwrap(), "input"); + let click = |app: &mut PhotocraftApp, at| { + for pressed in [true, false] { + frame(app, vec![egui::Event::PointerMoved(at), egui::Event::PointerButton { + pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, + }]); + } + for _ in 0..3 { frame(app, vec![]); } + }; + click(&mut app, input.left_top() + vec2(140.0, 10.0)); + for fraction in [0.35, 0.85, 0.55, 0.05] { + let w = app.jiansun.as_ref().unwrap(); + let input = geometry(w, "input"); + click(&mut app, pos2(input.right() - 20.0, input.top() + input.height() * fraction)); + let w = app.jiansun.as_ref().unwrap(); + assert!(w.panel_geometry["composerExpanded"].as_bool().unwrap()); + assert!(w.panel_geometry["composerFocused"].as_bool().unwrap()); + assert!(geometry(w, "input").contains(geometry(w, "inputCaret").left_top())); + assert!(geometry(w, "inputCaret").top() >= geometry(w, "subject").bottom()); + } + frame(&mut app, vec![egui::Event::Text("窗边光线".into())]); + frame(&mut app, vec![egui::Event::Key { key: egui::Key::Home, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]); + frame(&mut app, vec![]); + let w = app.jiansun.as_ref().unwrap(); + assert_eq!(w.composer, "窗边光线"); + assert!(geometry(w, "inputCaret").top() >= geometry(w, "subject").bottom()); + assert!(requests.try_recv().is_err(), "focus interactions never dispatch requests"); + } + + #[test] + fn pinned_production_stop_pauses_without_discarding_the_task() { + let (mut app, requests) = dock_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let w = app.jiansun.as_mut().unwrap(); + w.busy = Some("pi-agent".into()); + w.pi_product_production = true; + w.messages.push(json!({"role":"user","text":"一键制作整套详情页"})); + w.composer.clear(); + w.focus_composer = false; + w.reduce_motion = true; + for _ in 0..4 { dock_frame(&ctx, &mut app, vec![]); } + let w = app.jiansun.as_ref().unwrap(); + assert_eq!(w.panel_geometry["composerExpanded"], false); + let stop = geometry(w, "taskStop"); + assert!(geometry(w, "productionShelf").contains_rect(stop)); + assert!(!geometry(w, "composer").intersects(stop)); + assert!(w.panel_geometry["stop"].is_null()); + for pressed in [true,false] { + dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(stop.center()),egui::Event::PointerButton { + pos:stop.center(),button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE, + }]); + } + let w = app.jiansun.as_ref().unwrap(); + assert!(w.agent_effects_paused); + assert_eq!(w.busy.as_deref(), Some("pi-agent")); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn composer_actions_share_one_bottom_row_in_a_narrow_dock() { + for dock_width in [250.0, 288.0, 360.0, 520.0] { + let (mut app, _requests) = dock_fixture(); + app.ui.dock_tabs.color = 4; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + crate::panels::request_dock_width(&ctx, dock_width); + for _ in 0..2 { + let mut output = ctx.settle_ui(egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(960.0, 600.0))), + ..Default::default() + }, |ui| crate::panels::right_dock(&mut app, ui)); + output.textures_delta.clear(); + } + let w = app.jiansun.as_ref().unwrap(); + let composer = geometry(w, "composer"); + let controls = vec!["subject", "input", "send", "composerOrb", "imageGenerate", "settings", "composerMore"]; + for key in controls { + assert!(composer.contains_rect(geometry(w, key)), "{key} must remain accessible in the compact composer"); + } + let row_y = geometry(w, "composerOrb").center().y; + let mut previous = geometry(w, "composerOrb"); + let row = vec!["composerMore", "imageGenerate", "settings", "send"]; + for key in row { + let control = geometry(w, key); + assert!((control.center().y - row_y).abs() < 1.0, "{key} must share the same bottom row"); + assert!(control.left() >= previous.right(), "{key} must not overlap its neighbour"); + previous = control; + } + assert!(composer.height() <= 252.0, "an empty attachment picker must not add another row: {}", composer.height()); + } + } + + + #[test] + fn composer_auto_height_grows_with_real_wrapped_draft_and_stays_inside_window() { + for size in [vec2(1518.0,1032.0),vec2(1100.0,720.0)] { + let (mut app,_requests)=dock_fixture();app.ui.dock_tabs.color=4;{let w=app.jiansun.as_mut().unwrap();w.reduce_motion=true;w.focus_composer=true;w.composer="短句".into();} + let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let frame=|app:&mut PhotocraftApp|{let _=ctx.settle_ui(egui::RawInput{screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,size)),..Default::default()},|ui|crate::panels::right_dock(app,ui));}; + for _ in 0..4{frame(&mut app);}let short=geometry(app.jiansun.as_ref().unwrap(),"composer").height(); + let text="请保留原来的产品结构、字体和字号,分别为本次引用的文字格生成候选文案。\n".repeat(8);app.jiansun.as_mut().unwrap().composer=text.clone(); + for _ in 0..4{frame(&mut app);}let w=app.jiansun.as_ref().unwrap();let surface=geometry(w,"composer");assert!(surface.height()>short+48.0);assert!(surface.height()<=size.y*0.5+1.0);assert!(surface.bottom()<=size.y);assert_eq!(w.composer,text); + } + } + #[test] + fn composer_paste_and_resize_keep_the_focused_caret_visible() { + let (mut app,_requests)=dock_fixture();app.ui.dock_tabs.color=4;{let w=app.jiansun.as_mut().unwrap();w.reduce_motion=true;w.focus_composer=true;w.composer.clear();} + let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let frame=|app:&mut PhotocraftApp,size,events|{let _=ctx.settle_ui(egui::RawInput{screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,size)),events,..Default::default()},|ui|crate::panels::right_dock(app,ui));}; + for _ in 0..4 {frame(&mut app,vec2(1518.0,1032.0),vec![]);} + frame(&mut app,vec2(1518.0,1032.0),vec![egui::Event::Text("请分别修改引用的文字格,保留字体字号和排版。".repeat(36))]); + for size in [vec2(1518.0,1032.0),vec2(1100.0,720.0)] {for _ in 0..4 {frame(&mut app,size,vec![]);}let w=app.jiansun.as_ref().unwrap();let caret=geometry(w,"inputCaret");let input=geometry(w,"input");assert!(input.expand(1.0).contains_rect(caret),"input={input:?}, caret={caret:?}");} + } + #[test] + fn composer_scrolling_input_keeps_the_shared_glass_background() { + let (mut app,_requests)=dock_fixture();app.ui.dock_tabs.color=4;{let w=app.jiansun.as_mut().unwrap();w.reduce_motion=true;w.focus_composer=true;w.composer="请保留文字格的原有排版。".repeat(40);} + let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let mut output=None;for _ in 0..4 {output=Some(ctx.settle_ui(egui::RawInput{screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1100.0,720.0))),..Default::default()},|ui|crate::panels::right_dock(&mut app,ui)));} + let input=geometry(app.jiansun.as_ref().unwrap(),"input");assert!(app.jiansun.as_ref().unwrap().panel_geometry["inputContentHeight"].as_f64().unwrap()>input.height() as f64); + fn masks(shape:&egui::Shape,input:Rect)->bool {match shape {egui::Shape::Mesh(mesh)=>{let bounds=mesh.calc_bounds();bounds.width()>input.width()*0.8&&bounds.height()<=24.0&&(bounds.bottom()-input.bottom()).abs()<1.0},egui::Shape::Vec(shapes)=>shapes.iter().any(|shape|masks(shape,input)),_=>false}} + assert!(!output.unwrap().shapes.iter().any(|shape|masks(&shape.shape,input)),"scrolling text must not add an opaque edge over the shared glass"); + } + #[test] + fn composer_reference_shelf_leaves_the_caret_in_the_first_text_row() { + let (mut app,_requests)=dock_fixture();app.ui.dock_tabs.color=4;let w=app.jiansun.as_mut().unwrap();w.reduce_motion=true;w.focus_composer=true;w.composer.clear(); + let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + for _ in 0..4{dock_frame(&ctx,&mut app,vec![]);}let w=app.jiansun.as_ref().unwrap();let row=geometry(w,"inputFirstRow");let chip=geometry(w,"subject");let caret=geometry(w,"inputCaret"); + assert!(row.top()>=chip.bottom(),"row={row:?}, chip={chip:?}");assert!(row.expand(1.0).contains(caret.left_top()));assert!(geometry(w,"input").expand(0.5).contains_rect(caret));assert!(w.panel_geometry["composerFocused"].as_bool().unwrap()); + dock_frame(&ctx, &mut app, vec![egui::Event::Text("Test color".into())]); + dock_frame(&ctx, &mut app, vec![]); + let w = app.jiansun.as_ref().unwrap(); + assert_eq!(w.composer, "Test color"); + assert!(geometry(w, "inputFirstRow").top() >= geometry(w, "subject").bottom()); + assert!(geometry(w, "inputCaret").left() > geometry(w, "input").left()); + } + #[test] + fn references_do_not_cover_loading_or_ready_input() { + for ready in [false, true] { + let (mut app, _) = dock_fixture(); + app.ui.dock_tabs.color=4; + let w=app.jiansun.as_mut().unwrap(); + w.reduce_motion=true; w.composer.clear(); + if !ready { w.loaded_draft=None; } + let ctx=egui::Context::default(); PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + for _ in 0..4 { dock_frame(&ctx,&mut app,vec![]); } + let w=app.jiansun.as_ref().unwrap(); + let chip=geometry(w,"subject"); let input=geometry(w,"input"); + assert!(input.top() >= chip.bottom(), "ready={ready}, chip={chip:?}, input={input:?}"); + } + } + + #[test] + fn composer_rejects_text_while_draft_load_is_pending() { + let (mut app, _) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + w.composer.clear(); w.loaded_draft = None; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let id = super::super::composer_input_id(); + ctx.memory_mut(|m| m.request_focus(id)); + let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), events, ..Default::default() }, |ui| w.composer_ui(app,ui)); + }; + frame(&mut w,&mut app,vec![]); + frame(&mut w,&mut app,vec![egui::Event::Text("不得丢失".into())]); + assert!(w.composer.is_empty(), "loading editor must not accept input it cannot preserve"); + let doc=app.session.active().unwrap().doc.id.0; + w.loaded_draft=Some(doc); + w.receive_composer_draft(&ctx,doc,&json!({"localId":"a","composer":"已存草稿","composerDraftToken":"token","composerDraftGeneration":0})); + assert_eq!(w.composer,"已存草稿"); + w.focus_composer=true; frame(&mut w,&mut app,vec![]); + frame(&mut w,&mut app,vec![egui::Event::Text("续写".into())]); + assert!(w.composer.contains("续写")); + } + + #[test] + fn composer_escape_collapses_selection_then_consumes_without_losing_text_or_focus() { + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + w.composer = "保留这段文字".into(); + w.reduce_motion = true; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let id = super::super::composer_input_id(); + ctx.memory_mut(|memory| memory.request_focus(id)); + let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { + let mut leaked = false; + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), events, ..Default::default() }, |ui| { + w.composer_ui(app,ui); + leaked = ui.input(|input| input.key_pressed(egui::Key::Escape)); + }); + leaked + }; + frame(&mut w,&mut app,vec![]); + let mut state = egui::text_edit::TextEditState::load(&ctx,id).unwrap(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0),egui::text::CCursor::new(3)))); + state.store(&ctx,id); + let escape = || egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed:true, repeat:false, modifiers:egui::Modifiers::NONE }; + assert!(!frame(&mut w,&mut app,vec![escape()])); + let range = egui::text_edit::TextEditState::load(&ctx,id).unwrap().cursor.char_range().unwrap(); + assert_eq!(range.primary,range.secondary); + assert_eq!(w.composer,"保留这段文字"); + assert!(ctx.memory(|memory| memory.has_focus(id))); + assert!(!frame(&mut w,&mut app,vec![escape()])); + assert!(ctx.memory(|memory| memory.has_focus(id))); + assert_eq!(w.composer,"保留这段文字"); + w.composer.clear(); + w.focus_composer = true; + assert!(!frame(&mut w,&mut app,vec![escape()])); + assert!(!ctx.memory(|memory| memory.has_focus(id))); + assert!(!w.focus_composer); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn composer_escape_yields_to_top_modal_and_active_ime() { + let (mut app, requests) = dock_fixture(); + let mut w = app.jiansun.take().unwrap(); + w.composer = "保留输入内容".into(); + w.reduce_motion = true; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let id = super::super::composer_input_id(); + let modal = Id::unique("escape-priority-modal"); + let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events, show_modal:bool| { + let mut closed = false; + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), events, ..Default::default() }, |ui| { + w.composer_ui(app,ui); + if show_modal { closed = egui::Modal::new(modal).show(ui.ctx(),|ui| { ui.label("模态内容"); }).should_close(); } + }); + closed + }; + ctx.memory_mut(|memory| memory.request_focus(id)); + frame(&mut w,&mut app,vec![],true); + frame(&mut w,&mut app,vec![],true); + ctx.memory_mut(|memory| memory.request_focus(id)); + let escape = || egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed:true, repeat:false, modifiers:egui::Modifiers::NONE }; + assert!(frame(&mut w,&mut app,vec![escape()],true),"the top modal owns Escape"); + assert_eq!(w.composer,"保留输入内容"); + frame(&mut w,&mut app,vec![],false); + frame(&mut w,&mut app,vec![],false); + ctx.memory_mut(|memory| memory.request_focus(id)); + frame(&mut w,&mut app,vec![egui::Event::Ime(egui::ImeEvent::Preedit { text:"ni".into(), active_range_chars:None }),escape()],false); + assert_eq!(w.composer,"保留输入内容", "IME Escape cannot delete the draft"); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn composer_keeps_send_and_add_within_narrow_widths_and_scales() { + for width in [125.0,150.0,250.0] { + for scale in [1.0,1.25,1.5] { + let (mut app, _) = dock_fixture(); let mut w=app.jiansun.take().unwrap(); + w.reduce_motion=true; w.focus_composer=true; + let ctx=egui::Context::default(); PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); ctx.set_pixels_per_point(scale); + for _ in 0..4 { + let _=ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(width,500.0))), ..Default::default() }, |ui| { + ui.set_width(width); w.composer_ui(&mut app,ui); + }); + } + let composer=geometry(&w,"composer"); + assert!(composer.contains_rect(geometry(&w,"send")),"send must fit {width}pt at {scale}"); + assert!(composer.contains_rect(geometry(&w,"composerMore")),"add must fit {width}pt at {scale}"); + } + } + } + + #[test] + fn empty_composer_stays_open_during_internal_controls_at_high_dpi() { + for scale in [1.0,1.25,1.5] { + let (mut app, _) = dock_fixture(); app.ui.dock_tabs.color=4; + let w=app.jiansun.as_mut().unwrap(); w.composer.clear(); w.reduce_motion=true; w.focus_composer=true; + let ctx=egui::Context::default(); PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + ctx.set_pixels_per_point(scale); crate::panels::request_dock_width(&ctx,250.0); + for _ in 0..4 { dock_frame(&ctx,&mut app,vec![]); } + let original=geometry(app.jiansun.as_ref().unwrap(),"composer"); + for control in ["composerMore", "settings"] { + dock_click(&ctx,&mut app,control); + for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } + let w=app.jiansun.as_ref().unwrap(); + assert_eq!(w.panel_geometry["composerExpanded"],true,"{control}, scale={scale}"); + let now=geometry(w,"composer"); + assert!((now.height()-original.height()).abs()<1.0,"{control} must not move its composer, {original:?} -> {now:?}"); + dock_frame(&ctx,&mut app,vec![egui::Event::Key {key:egui::Key::Escape,physical_key:Some(egui::Key::Escape),pressed:true,repeat:false,modifiers:egui::Modifiers::NONE}]); + dock_frame(&ctx,&mut app,vec![egui::Event::Key {key:egui::Key::Escape,physical_key:Some(egui::Key::Escape),pressed:false,repeat:false,modifiers:egui::Modifiers::NONE}]); + for _ in 0..2 { dock_frame(&ctx,&mut app,vec![]); } + } + } + } + + #[test] + fn one_canvas_click_closes_an_open_add_menu_and_releases_the_empty_composer() { + let (mut app, _requests) = dock_fixture(); + app.ui.dock_tabs.color = 4; + let w = app.jiansun.as_mut().unwrap(); + w.composer.clear(); w.reduce_motion = true; w.focus_composer = true; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + crate::panels::request_dock_width(&ctx,250.0); + for _ in 0..4 { dock_frame(&ctx,&mut app,vec![]); } + dock_click(&ctx,&mut app,"composerMore"); + assert!(egui::Popup::is_id_open(&ctx,Id::unique("jiansun-composer-more-popup"))); + let outside = egui::pos2(100.0,100.0); + for pressed in [true,false] { dock_frame(&ctx,&mut app,vec![egui::Event::PointerMoved(outside),egui::Event::PointerButton { + pos:outside,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); } + for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } + assert!(!egui::Popup::is_id_open(&ctx,Id::unique("jiansun-composer-more-popup"))); + assert_eq!(app.jiansun.as_ref().unwrap().panel_geometry["composerExpanded"],false); + assert!(!ctx.memory(|memory| memory.has_focus(super::super::composer_input_id()))); + } + + #[test] + fn narrow_high_dpi_composer_overflow_exposes_real_secondary_actions() { + fn texts(shape:&egui::Shape, out:&mut Vec<(String,Rect)>) { + 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(),Rect::from_min_size(text.pos,text.galley.size()))), + _ => {} + } + } + for scale in [1.25,1.5] { + let (mut app, _requests) = dock_fixture(); + app.ui.dock_tabs.color = 4; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + ctx.set_pixels_per_point(scale); + crate::panels::request_dock_width(&ctx,250.0); + for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } + let w = app.jiansun.as_ref().unwrap(); + assert!(geometry(w,"composer").contains_rect(geometry(w,"send"))); + assert!(w.panel_geometry["composerMore"].is_array()); + dock_click(&ctx,&mut app,"composerMore"); + let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app,ui)); + let mut labels = Vec::new(); + for shape in &output.shapes { texts(&shape.shape,&mut labels); } + assert!(labels.iter().any(|(text,_)| text == "添加本地参考图")); + let prompt = labels.iter().find(|(text,_)|text == "常用提示词").unwrap().1.center(); + for pressed in [true,false] { dock_frame(&ctx,&mut app,vec![egui::Event::PointerMoved(prompt),egui::Event::PointerButton { + pos:prompt,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); } + assert!(app.jiansun.as_ref().unwrap().prompt_library.is_open(),"the menu invokes the existing prompt-library action"); + } + } + + #[test] + fn empty_composer_more_keeps_its_position_through_press_and_menu_then_collapses() { + fn collect(shape:&egui::Shape, out:&mut Vec<(String,Rect)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape,out)), + egui::Shape::Text(text) => out.push((text.galley.text().to_owned(),Rect::from_min_size(text.pos,text.galley.size()))), + _ => {} + } + } + let (mut app, _requests) = dock_fixture(); + app.ui.dock_tabs.color = 4; + let w = app.jiansun.as_mut().unwrap(); + w.reduce_motion = true; + w.composer.clear(); + w.focus_composer = true; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + crate::panels::request_dock_width(&ctx,250.0); + for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } + let more = geometry(app.jiansun.as_ref().unwrap(),"composerMore"); + let point = more.center(); + dock_frame(&ctx,&mut app,vec![egui::Event::PointerMoved(point),egui::Event::PointerButton { + pos:point,button:egui::PointerButton::Primary,pressed:true,modifiers:egui::Modifiers::NONE }]); + for _ in 0..4 { + dock_frame(&ctx,&mut app,vec![]); + let w=app.jiansun.as_ref().unwrap(); + assert_eq!(w.panel_geometry["composerExpanded"],true,"holding the press cannot collapse the composer"); + assert_eq!(geometry(w,"composerMore"),more,"the release target remains at the pressed position"); + } + dock_frame(&ctx,&mut app,vec![egui::Event::PointerButton { + pos:point,button:egui::PointerButton::Primary,pressed:false,modifiers:egui::Modifiers::NONE }]); + for _ in 0..2 { dock_frame(&ctx,&mut app,vec![]); } + let popup = Id::unique("jiansun-composer-more-popup"); + assert!(egui::Popup::is_id_open(&ctx,popup),"a real click opens the overflow menu with an empty draft"); + let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app,ui)); + let mut labels=Vec::new(); + for shape in &output.shapes { collect(&shape.shape,&mut labels); } + assert!(labels.iter().any(|(text,_)| text=="添加本地参考图")); + assert!(labels.iter().any(|(text,_)| text=="常用提示词")); + dock_frame(&ctx,&mut app,vec![egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed:true, repeat:false, modifiers:egui::Modifiers::NONE }]); + assert!(!egui::Popup::is_id_open(&ctx,popup), "Escape closes the real add menu"); + for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } + assert_eq!(app.jiansun.as_ref().unwrap().panel_geometry["composerExpanded"],true,"closing an internal menu keeps the composer expanded"); + let outside=egui::pos2(100.0,100.0); + for pressed in [true,false] { dock_frame(&ctx,&mut app,vec![egui::Event::PointerMoved(outside),egui::Event::PointerButton { pos:outside,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); } + for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } + assert_eq!(app.jiansun.as_ref().unwrap().panel_geometry["composerExpanded"],false,"an external click collapses an empty composer"); + assert!((geometry(app.jiansun.as_ref().unwrap(),"composer").height()-56.0-reference_shelf_height(1, 250.0-28.0)).abs()<1.0); + app.jiansun.as_mut().unwrap().focus_composer = true; + for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } + dock_click(&ctx,&mut app,"composerMore"); + let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app,ui)); + labels.clear(); + for shape in &output.shapes { collect(&shape.shape,&mut labels); } + let prompt = labels.iter().find(|(text,_)|text=="常用提示词").unwrap().1.center(); + for pressed in [true,false] { dock_frame(&ctx,&mut app,vec![egui::Event::PointerMoved(prompt),egui::Event::PointerButton { + pos:prompt,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); } + assert!(app.jiansun.as_ref().unwrap().prompt_library.is_open(),"the empty-draft menu invokes the real prompt library"); + } + + #[test] + fn workflow_card_distinguishes_a_screen_from_the_whole_output_and_current_canvas_export() { + let workflow = json!({"slots":[{"id":"detail-slot","documentId":"S01","fieldId":"S01-I01"},{"id":"sku-slot","documentId":"K02","fieldId":"K02-I02"}]}); + assert_eq!(workflow_scope(&json!({"intent":"fill_output","outputId":"detail","slotId":"detail-slot"}), &workflow), "详情 · S01"); + assert_eq!(workflow_scope(&json!({"intent":"fill_output","outputId":"main_images"}), &workflow), "主图 · 全组"); + assert_eq!(workflow_scope(&json!({"intent":"review_candidates","outputId":"sku_images","slotId":"sku-slot"}), &workflow), "SKU · K02"); + assert_eq!(workflow_scope(&json!({"intent":"export","outputId":"main_images"}), &workflow), "当前画布"); + assert_eq!(workflow_scope(&json!({"intent":"export_psd"}), &workflow), "当前画布"); + assert_eq!( + workflow_scope(&json!({"intent":"generate_candidate","outputId":"sku_images","slotId":"sku-slot","variant":"B"}), &workflow), + "SKU · K02-I02 · B" + ); + } + + #[test] + fn inline_reference_detaches_without_changing_canvas_or_draft_and_can_be_added_again() { + let (mut app, requests) = dock_fixture(); + app.ui.dock_tabs.color = 4; + app.jiansun.as_mut().unwrap().reduce_motion = true; + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); } + let revision = app.session.active().unwrap().revision; + let selected = app.session.active().unwrap().selected_layers(); + let draft = app.jiansun.as_ref().unwrap().composer.clone(); + let click = |app: &mut PhotocraftApp, at| { + for pressed in [true, false] { + dock_frame(&ctx, app, vec![egui::Event::PointerMoved(at), egui::Event::PointerButton { + pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, + }]); + } + for _ in 0..3 { dock_frame(&ctx, app, vec![]); } + }; + let detach = geometry(app.jiansun.as_ref().unwrap(), "referenceRemove").center(); + click(&mut app, detach); + let w = app.jiansun.as_ref().unwrap(); + assert!(w.composer_reference_list(&app).is_empty()); + assert_eq!(w.composer, draft); + assert!(w.panel_geometry.get("subject").is_none()); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.session.active().unwrap().selected_layers(), selected); + let add_menu = geometry(w, "composerMore").center(); + click(&mut app, add_menu); + let add = geometry(app.jiansun.as_ref().unwrap(), "referenceAdd").center(); + click(&mut app, add); + assert!(!app.jiansun.as_ref().unwrap().composer_reference_list(&app).is_empty()); + assert!(requests.try_recv().is_err(), "reference controls never dispatch a model"); + } + + #[test] + fn detached_reference_cannot_survive_as_a_hidden_request_target() { + let (mut app, requests) = dock_fixture(); + super::super::action(&mut app, "composer-reference-remove", json!({"index":0})).unwrap(); + let selected = app.session.active().unwrap().selected_layers(); + assert!(!selected.is_empty()); + super::super::action(&mut app, "agent", json!({"text":"只讨论整体设计"})).unwrap(); + let Request::Action(method, request) = requests.try_recv().unwrap() else { panic!("local request"); }; + assert_eq!(method, "agent"); + let scope = &request["context"]["requestScope"]; + assert_eq!(scope["subject"]["kind"], "project"); + assert_eq!(scope["references"], json!([])); + assert_eq!(scope["selected"], json!([])); + assert!(requests.try_recv().is_err()); + } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/turn_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/turn_ui.rs new file mode 100644 index 00000000..a57cecc3 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/turn_ui.rs @@ -0,0 +1,533 @@ +use super::super::{ + RichText, Tokens, Ui, Value, Workspace, agent_motion, + pi_bridge, + stitch_state::{NoticeKind, ToolStatus}, + stitch_timeline as timeline, +}; +use super::artifact_preview_ui::activate_reference; +use super::composer_ui::copy_reply; +use super::models::usage_count; +use super::production_reply_ui::{production_reply_text, production_turn}; +use super::turns::{ReplyHandoff, StreamHandoffs, Turn, TurnItem, TurnItemContent, TurnItemLayout, TurnItemLayouts, activity_history_label, duration_text}; +use crate::icons; +use egui::{Align, Color32, FontId, Id, Layout, Rect, Sense, Vec2, vec2}; + +pub(in crate::jiansun) fn thinking_ui(ui: &mut Ui, thinking: &Value, turn_running: bool, reduced: bool) -> egui::Response { + let status = match (thinking["active"] == true, turn_running) { + (true, true) => timeline::ThinkingStatus::Active, + (true, false) => timeline::ThinkingStatus::Interrupted, + (false, _) => timeline::ThinkingStatus::Done, + }; + timeline::thinking_row(ui, ui.next_auto_id().with("thinking"), status, None, reduced) +} + +pub(in crate::jiansun) fn turn_reply_id(conversation_id: Id, user_index: Option) -> Id { + conversation_id.with(("turn-reply", user_index)) +} + +/// One caption for every image and waiting card: white 12pt on a scrim at the +/// bottom-left, one line, never wider than the card. +pub(in crate::jiansun) fn paint_image_caption(painter: &egui::Painter, rect: Rect, text: &str) { + if !(rect.width() >= 64.0 && rect.height() >= 34.0) { return; } + let mut job = egui::text::LayoutJob::simple_singleline(text.to_owned(), FontId::proportional(super::agent_stream::TEXT_META), Color32::WHITE); + job.wrap.max_width = (rect.width() - 22.0).max(1.0); + job.wrap.max_rows = 1; + let caption = painter.layout_job(job); + let pos = rect.left_bottom() + vec2(10.0, -8.0 - caption.size().y); + painter.rect_filled(Rect::from_min_size(pos, caption.size()).expand2(vec2(5.0, 3.0)), 6.0, Color32::from_black_alpha(188)); + painter.galley(pos, caption, Color32::WHITE); +} + +pub(in crate::jiansun) fn remember_visible_stream(ui: &Ui, id: Id, text: &str) { + let mut end = text.len().min(65_000); + while end > 0 && !text.is_char_boundary(end) { end -= 1; } + let text = text.get(..end).unwrap_or_default(); + ui.data_mut(|data| { + let cache = data.get_temp_mut_or_default::(Id::unique("jiansun-stream-handoffs")); + if let Some((_, previous)) = cache.0.iter_mut().find(|(candidate, _)| *candidate == id) { + if previous != text { text.clone_into(previous); } + } else { + // One public stream is at most the bridge's 65KB limit. Keep only + // recent scoped turns, never an unbounded copy of the transcript. + if cache.0.len() >= 16 { cache.0.remove(0); } + cache.0.push((id, text.to_owned())); + } + }); +} + +pub(in crate::jiansun) fn final_handoff(ui: &Ui, id: Id, text: &str) -> Option { + if text.is_empty() { return None; } + ui.data_mut(|data| { + let cache = data.get_temp_mut_or_default::(Id::unique("jiansun-stream-handoffs")); + cache.0.iter().find(|(candidate, _)| *candidate == id).and_then(|(_, stream)| { + if stream.starts_with(text) || stream.ends_with(text) { Some(ReplyHandoff::Displayed) } + else if !stream.is_empty() && text.starts_with(stream.as_str()) { Some(ReplyHandoff::Append) } + else { None } + }) + }) +} + +/// A UI mount time, a previous turn or a future/invalid clock is not evidence. +pub(in crate::jiansun) fn active_tool_elapsed(messages: &[Value], run: Option<&str>, now_ms: u64) -> Option { + let run = run.filter(|run| !run.is_empty())?; + messages.iter().rev().find_map(|message| { + let event = &message["event"]; + if event["version"] != 1 || event["type"] != "tool" || event["run"] != run || event["status"] != "started" { + return None; + } + let started = event["timestampMs"].as_u64()?; + now_ms.checked_sub(started) + }) +} + + +/// The bubble itself lives in the kit (`stitch_ui::user_bubble_with_reveal`), together with +/// the per-character reveal and its glow. `reduced` is always passed through: reduced motion +/// shows the whole message at once and never starts the reveal or its repaint loop. +pub(in crate::jiansun) fn user_bubble_with_reveal(ui: &mut Ui, text: &str, started: Option, reduced: bool) -> Rect { + timeline::user_message(ui, text, started, reduced) +} + +pub(in crate::jiansun) fn paint_reference_thumbnail(ui: &mut Ui, texture: &egui::TextureHandle, limit: Vec2) -> Rect { + let source = texture.size_vec2(); + let size = source * (limit.x / source.x).min(limit.y / source.y); + ui.add(egui::Image::new(texture).fit_to_exact_size(size).corner_radius(6.0)).rect +} + + +pub(in crate::jiansun) fn frame_image_ratio(frame: &Value) -> Option { + let width = frame["width"].as_f64()?; + let height = frame["height"].as_f64()?; + (width > 0.0 && height > 0.0).then_some((width / height) as f32).filter(|ratio| ratio.is_finite() && *ratio > 0.0) +} + +pub(in crate::jiansun) fn image_card_size(width: f32, ratio: f32) -> egui::Vec2 { + let width = width.min(340.0 * ratio); + vec2(width, width / ratio) +} + +pub(in crate::jiansun) fn icon(ui: &mut Ui, name: &str, tint: Color32) { + ui.add(icons::image(name, 14.0, tint)); +} + +/// Candidate numbers are the actual canvas order, never the message order. +/// If either identity is absent or ambiguous, show no invented ordinal. +pub(in crate::jiansun) fn candidate_ordinal(subject: &Value, workflow: &Value) -> Option { + let slot_id = subject["slotId"].as_str().filter(|id| !id.is_empty())?; + let candidate_id = subject["candidateId"].as_str().filter(|id| !id.is_empty())?; + let mut slots = workflow["slots"].as_array()?.iter().filter(|slot| slot["id"].as_str() == Some(slot_id)); + let slot = slots.next()?; + if slots.next().is_some() { return None; } + let mut matches = slot["candidates"].as_array()?.iter().enumerate() + .filter(|(_, candidate)| candidate["id"].as_str() == Some(candidate_id)); + let (index, _) = matches.next()?; + if matches.next().is_some() { return None; } + Some(index + 1) +} + +pub(in crate::jiansun) fn subject_label(subject: &Value, workflow: &Value) -> String { + if subject["kind"] == "selection" { + let count = subject["selectedLayerIds"].as_array().map_or_else(|| subject["targets"].as_array().map_or(0, Vec::len), Vec::len); + return format!("已选 {count} 个对象"); + } + let mut parts = Vec::::new(); + for field in ["pageId", "label", "variantLabel"] { + if let Some(text) = subject[field].as_str().filter(|text| !text.trim().is_empty()) { + let text = text.chars().take(160).collect::(); + if !parts.iter().any(|part| part == &text || part.starts_with(&format!("{text} ·"))) { + parts.push(text); + } + } + } + if subject["kind"] == "candidate" { + let ordinal = candidate_ordinal(subject, workflow); + parts.push( + subject["candidateLabel"] + .as_str() + .map(str::to_owned) + .unwrap_or_else(|| ordinal.map_or_else(|| "候选".into(), |index| format!("候选 {index}"))), + ); + } + if parts.is_empty() { "当前项目".into() } else { parts.join(" · ") } +} + +pub(in crate::jiansun) fn image_result_labels(target: &Value, workflow: &Value, brief: &Value) -> (String, String, String) { + let short = candidate_ordinal(target, workflow).map_or_else(|| "候选图片".to_owned(), |ordinal| format!("候选 {ordinal}")); + let slot = workflow["slots"].as_array().into_iter().flatten() + .find(|slot| target["slotId"].as_str().is_some_and(|id| !id.is_empty() && slot["id"].as_str() == Some(id))); + let page = slot.and_then(|slot| slot["documentId"].as_str()).unwrap_or(""); + let slot_label = slot.and_then(|slot| slot["label"].as_str()).unwrap_or(""); + let variant = brief["variants"].as_array().into_iter().flatten() + .find(|variant| target["productVariantId"].as_str().is_some_and(|id| !id.is_empty() && variant["id"].as_str() == Some(id))) + .and_then(|variant| variant["name"].as_str()).unwrap_or(""); + let title = subject_label(target, workflow); + let full = [page, slot_label, variant, title.as_str()].into_iter().filter(|part| !part.is_empty()).collect::>().join(" · "); + (page.to_owned(), short, full) +} + +pub(in crate::jiansun) fn notice_kind(text: &str) -> NoticeKind { + if text.contains("失败") { NoticeKind::Failed } + else if text.contains("核查") || text.contains("无法确认") || text.contains("未执行") { NoticeKind::NeedsCheck } + else if text.starts_with("正在") { NoticeKind::Waiting } + else if text.starts_with("图片已生成") { NoticeKind::Produced } + else if ["已完成", "已替换", "已置入", "已采用", "已回填", "已导出"] + .iter().any(|prefix| text.starts_with(prefix)) { NoticeKind::Saved } + else { NoticeKind::Info } +} + + +impl Workspace { + pub(in crate::jiansun) fn user_reveal_id(&self,index:Option)->Id { + Id::unique(("user-text-arrival",&self.origin,self.account["id"].as_str(),self.project_context["localId"].as_str(),self.observed_doc,index)) + } + pub(in crate::jiansun) fn reveal_sent_user_text(&self,ui:&Ui,after:usize) { + if self.reduce_motion {return;} + let now=ui.input(|input|input.time); + for (index,_) in self.messages.iter().enumerate().skip(after).filter(|(_,message)|message["role"]=="user") { + ui.data_mut(|data|data.insert_temp(self.user_reveal_id(Some(index)),now)); + } + } + pub(in crate::jiansun) fn sent_references(&self, ui: &mut Ui, message: &Value) -> Option { + let references = message["requestScope"]["references"].as_array().filter(|items| !items.is_empty())?; + let mut locate = None; + let available = ui.available_width().max(1.0); + let width = available.min(120.0); + let spacing = ui.spacing().item_spacing.x; + let columns = (((available + spacing) / (width + spacing)).floor() as usize).max(1); + let caption_color = Tokens::get(ui.ctx()).agent().text_dim; + for (row, items) in references.chunks(columns).enumerate() { + ui.allocate_ui_with_layout(vec2(available, 1.0), Layout::right_to_left(Align::Min), |ui| { + for (column, reference) in items.iter().enumerate().rev() { + let index = row * columns + column; + let detail = &message["referenceContent"][index]; + ui.allocate_ui_with_layout(vec2(width, 1.0), Layout::top_down(Align::Max), |ui| { + ui.set_width(width); + let label = reference["label"].as_str().filter(|label| !label.is_empty()) + .map(str::to_owned).unwrap_or_else(|| subject_label(reference, &self.template_workflow)); + let image_size = vec2(width, 110.0); + let image_area = Rect::from_min_size(ui.max_rect().min, image_size); + if let Some(id) = detail["imageId"].as_str().or_else(|| reference["taskId"].as_str()) { + if ui.is_rect_visible(image_area) { + self.agent_images.mark_visible(id); + } + // Keep the transcript height independent of the scroll clip. + if let Some(image) = self.agent_images.peek(id) { + let rect = paint_reference_thumbnail(ui, image, image_size); + let preview = ui.interact(rect, ui.scope_id().with(("sent-reference-image", index)), Sense::click()) + .on_hover_text(label.as_str()); + if preview.clicked() { locate = activate_reference(ui, reference, Some(id)); } + } + } + let caption = ui.add(egui::Label::new(RichText::new(label).size(12.0).color(caption_color)) + .truncate().sense(Sense::click())); + if caption.clicked() { locate = activate_reference(ui, reference, detail["imageId"].as_str()); } + if let Some(text) = detail["text"].as_str().filter(|text| !text.is_empty()) { + ui.add(egui::Label::new(RichText::new(text.chars().take(96).collect::()).size(12.0)).wrap()); + } + }); + } + }); + } + locate + } + + pub(in crate::jiansun) fn turn_ui(&self, ui: &mut Ui, turn: Turn<'_>, conversation_id: Id, count: usize, current_turn: bool, tracing: bool, doc: Option<&super::Document>) -> Option { + let t = Tokens::get(ui.ctx()).agent(); + let batch_progress = self.batch_progress_visible(); + let product = production_turn(turn.user) + || (current_turn && self.pi_product_production); + let live_reply = if self.pi_product_production { + self.stream_reply.as_str() + } else if batch_progress && self.workflow.production_progress().is_object() { + "" + } else if batch_progress { + self.stream_reply.splitn(3, '\n').nth(2).unwrap_or("") + } else { + self.stream_reply.as_str() + }; + let stream = current_turn.then_some(live_reply).filter(|text| !text.is_empty()); + let turn_running = current_turn && self.pending() && !self.agent_effects_paused + && (self.pi_run.is_some() || matches!(self.busy.as_deref(), Some("agent" | "pi-agent"))); + let projected = if current_turn && batch_progress { self.projected_worker_jobs() } else { Vec::new() }; + let merged_images = matches!(turn.items.last(), Some(TurnItem::Images(..))); + let last_position = turn.items.len().saturating_sub(1); + let mut locate = None; + let mut flow = super::agent_stream::Flow::default(); + if let Some(text) = turn.user { + let enter = agent_motion::message_enter(ui, conversation_id, turn.user_index.unwrap_or(usize::MAX), count, self.reduce_motion); + let reveal_id = self.user_reveal_id(turn.user_index); + let now = ui.input(|input| input.time); + let started = if self.reduce_motion {ui.data_mut(|data|data.remove::(reveal_id));None} else { + ui.data_mut(|data| { + if enter < 1.0 { data.get_temp_mut_or_insert_with(reveal_id, || now); } + data.get_temp::(reveal_id) + }) + }; + let response = agent_motion::message_visual(ui, enter, |ui| { + if let Some(index) = turn.user_index { + if let Some(reference) = self.sent_references(ui, &self.messages[index]) { + locate = Some(reference); + } + } + user_bubble_with_reveal(ui, text, started, self.reduce_motion); + if turn.user_index.is_some_and(|index| self.messages[index]["kind"] == "steer" && self.messages[index]["delivered"] == true) { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.label(RichText::new("已插话").size(11.0).color(t.text_dim)); + }); + } + }); + agent_motion::message_repaint(ui, response.response.rect, enter); + ui.add_space(18.0); + } + if !turn.items.is_empty() || stream.is_some() { + if let Some(target) = turn.target.filter(|target| target["kind"] != "project") { + let label = subject_label(target, &self.template_workflow); + let row = timeline::target_row(ui, conversation_id.with(("turn-target", turn.user_index)), &label, self.reduce_motion); + if row.clicked() { locate = Some(target.clone()); } + } + let reply_id = turn_reply_id(conversation_id, turn.user_index); + let latest_reply = turn.items.iter().rev().find_map(|item| match item { + TurnItem::Reply(_, index) => Some(*index), + _ => None, + }); + let tail_reply = match turn.items.last() { + Some(TurnItem::Reply(text, index)) => Some((*text, *index)), + _ => None, + }; + let stream_is_persisted = stream.is_some_and(|stream| tail_reply.is_some_and(|(text, _)| + text == stream || text.starts_with(stream) || (!turn_running && final_handoff(ui, reply_id, text).is_some()))); + let stream_extends_receipt = !stream_is_persisted && stream.is_some_and(|stream| + tail_reply.is_some_and(|(text, _)| !text.is_empty() && stream.starts_with(text))); + let paint_stream = |ui: &mut Ui, text: &str| { + remember_visible_stream(ui, reply_id, text); + ui.push_id(reply_id, |ui| { + let display = product.then(|| production_reply_text(text, turn_running, &self.template_workflow)); + timeline::reply(ui, reply_id, timeline::Reply { text: display.as_deref().unwrap_or(text), streaming: turn_running, animate_final: false }, self.reduce_motion); + }); + ui.add_space(8.0); + }; + let layouts_id = reply_id.with("turn-item-layouts"); + let virtualized = current_turn && turn.items.len() >= 32; + #[cfg(test)] + let virtualized = virtualized && !ui.data(|data| + data.get_temp::(Id::unique("benchmark-full-transcript")).unwrap_or(false)); + let mut layouts = TurnItemLayouts::default(); + let now = ui.input(|input| input.time); + if virtualized { + layouts = ui.data_mut(|data| data.remove_temp(layouts_id)).unwrap_or_default(); + #[cfg(test)] + { + let reset_on_append = ui.data(|data| + data.get_temp::(Id::unique("benchmark-reset-on-append")).unwrap_or(false)); + if reset_on_append && layouts.benchmark_count != count { + layouts.items.clear(); + } + layouts.benchmark_count = count; + } + let key = Some((ui.available_width().to_bits(), ui.pixels_per_point().to_bits(), + Tokens::get(ui.ctx()).kind, self.reduce_motion, turn_running)); + if layouts.key.is_some_and(|(_, _, _, _, running)| running) && !turn_running { + layouts.disclose_until = now + super::stitch_ui::TOOL_DISCLOSURE_SETTLE_SECONDS; + } + if layouts.key != key { + layouts.key = key; + layouts.items.clear(); + } + layouts.items.resize(count, None); + } + let viewport = ui.clip_rect().expand2(vec2(0.0, 240.0)); + let focused_rect = virtualized.then(|| { + ui.memory(|memory| memory.focused()).and_then(|id| ui.ctx().read_response(id)).map(|r| r.rect) + }).flatten(); + + for (position, item) in turn.items.into_iter().enumerate() { + let use_layout = virtualized && position != last_position; + let item_index = item.message_index(); + let mut cached = if use_layout { layouts.items[item_index].take() } else { None }; + let origin = ui.next_widget_position().to_vec2(); + let mut texture_sizes = Vec::new(); + if use_layout { + let live = match &item { + TurnItem::Thinking(value, _) => turn_running && value["active"] == true, + TurnItem::Tools(rows) => now < layouts.disclose_until || turn_running && rows.iter().any(|(event, _)| + ToolStatus::parse(event["status"].as_str().unwrap_or("")).running()), + TurnItem::Images(_, images) => { + let mut live = false; + for image in images { + let id = image["taskId"].as_str().or_else(|| image["id"].as_str()).unwrap_or(""); + texture_sizes.push(self.agent_images.peek(id).map(egui::TextureHandle::size)); + live |= turn_running && image["kind"] == "image-job" && image["finished"].is_null() + && self.pi_run.as_deref().is_some_and(|run| image["run"] == run); + live |= self.canvas_workspace.preview_arrival(id).is_some_and(|started| + agent_motion::image_enter(now - started, 1.0, self.reduce_motion).0 < 1.0); + } + live + } + TurnItem::Reply(_, index) => latest_reply == Some(*index) && stream.is_some() + || agent_motion::message_enter(ui, conversation_id, *index, count, self.reduce_motion) < 1.0, + _ => false, + }; + cached = cached.filter(|layout| + layout.texture_sizes == texture_sizes && layout.content.matches(&item, &self.messages)); + if !live && !tracing + && let Some(layout) = &cached + && layout.settled_at <= now + { + let bounds = layout.bounds.translate(origin); + if !bounds.intersects(viewport) && !ui.rect_contains_pointer(bounds) + && focused_rect.is_none_or(|focus| !bounds.intersects(focus)) + { + ui.expand_to_include_rect(bounds); + ui.add_space(layout.advance); + ui.skip_ahead_auto_ids(1); + flow.restore_anchor(layout.rail.map(|rail| rail.translate(origin))); + layouts.items[item_index] = cached; + continue; + } + } + } + // Each cached item owns stable widget IDs even when earlier + // items are replaced by their layout. + let content = use_layout.then(|| { + let previous = cached.take(); + let settled = previous.as_ref().map(|layout| (layout.advance, layout.settled_at)); + let content = previous.map_or_else(|| TurnItemContent::capture(&item, &self.messages), |layout| layout.content); + (content, settled) + }); + let mut item_ui = use_layout.then(|| ui.new_child(egui::UiBuilder::new().id_salt(("turn-item", item_index)))); + { + let ui = item_ui.as_mut().unwrap_or(&mut *ui); + match item { + TurnItem::Thinking(thinking, _) => { + let row = thinking_ui(ui, thinking, turn_running, self.reduce_motion); + flow.connect(ui, row.rect); + } + TurnItem::Notice(text, _) => { + let text = activity_history_label(text); + let display = crate::client_brand::user_error( + &production_reply_text(text, false, &self.template_workflow), "本轮操作有一条更新"); + let row = timeline::notice_row(ui, ui.next_auto_id().with("notice"), timeline::Notice { + kind: notice_kind(text), text: &display, hint: None, + }, self.reduce_motion); + flow.connect(ui, row.rect); + } + TurnItem::Tools(tasks) => { + let Some((_, first)) = tasks.first() else { continue }; + let id = conversation_id.with(("public-reasoning", first)); + let elapsed: Vec<_> = tasks.iter().map(|(event, _)| { + let status = ToolStatus::parse(event["status"].as_str().unwrap_or("")); + status.timed().then(|| usage_count(&event["durationMs"]).map(duration_text)).flatten() + }).collect(); + let rows: Vec<_> = tasks.iter().zip(&elapsed).map(|((event, _), elapsed)| { + let tool = event["toolName"].as_str().unwrap_or(""); + let status = ToolStatus::parse(event["status"].as_str().unwrap_or("")); + timeline::ToolRow { tool, name: super::stitch_state::tool_label(tool), + status: if status == ToolStatus::Started && !turn_running { ToolStatus::Unknown } else { status }, + elapsed: elapsed.as_deref(), summary:event["summary"].as_str(), + failure_category:event["failureCategory"].as_str(), + failure_detail:event["failureDetail"]["message"].as_str(), + copy_updates: pi_bridge::copy_updates(event) } + }).collect(); + let row = timeline::tool_group(ui, id, timeline::ToolGroupHead { + total: rows.len(), + completed: rows.iter().filter(|row| row.status == ToolStatus::Completed).count(), + failed: rows.iter().filter(|row| row.status == ToolStatus::Failed).count(), + active: turn_running && rows.iter().any(|row| row.status.running()), + turn_running, + }, &rows, self.reduce_motion); + flow.connect(ui, row.rect); + ui.add_space(8.0); + } + TurnItem::Reply(text, index) => { + flow.break_run(); + let is_last_reply = tail_reply.is_some_and(|(_, last)| index == last); + if is_last_reply && stream_extends_receipt && let Some(text) = stream { + paint_stream(ui, text); + continue; + } + let handoff = (current_turn && latest_reply == Some(index)) + .then(|| final_handoff(ui, reply_id, text)).flatten(); + let arrival = agent_motion::message_enter(ui, conversation_id, index, count, self.reduce_motion); + let anchor = reply_id.with(index); + let clean = production_reply_text(text, false, &self.template_workflow); + let text = clean.as_str(); + let copy_id = anchor.with("copy"); + // The copy action keeps its row but shows only while the + // reply is pointed at or the button itself holds focus. + let previous = ui.data(|data| data.get_temp::(copy_id.with("shown"))); + let (reply_rect, copy_focused) = ui.data(|data| ( + data.get_temp::(copy_id.with("reply-rect")), + data.get_temp::(copy_id.with("focus")).unwrap_or(false), + )); + let shown = copy_focused || reply_rect.is_some_and(|rect| ui.rect_contains_pointer(rect)); + if previous != Some(shown) { + ui.ctx().request_repaint(); + ui.data_mut(|data| data.insert_temp(copy_id.with("shown"), shown)); + } + let response = ui.push_id(anchor, |ui| { + if let Some(handoff) = handoff + && super::stitch_ui::move_response_arrival(ui, reply_id, anchor) + && handoff == ReplyHandoff::Displayed + { + super::stitch_ui::prepare_final_handoff(ui, anchor, text); + } + timeline::reply(ui, anchor, timeline::Reply { text, streaming: false, animate_final: arrival < 1.0 }, self.reduce_motion); + ui.allocate_ui_with_layout(vec2(ui.available_width(), 24.0), Layout::right_to_left(Align::Center), |ui| { + ui.set_opacity(if shown { 1.0 } else { 0.0 }); + let focused = copy_reply(ui, text).has_focus(); + ui.data_mut(|data| data.insert_temp(copy_id.with("focus"), focused)); + }); + }); + ui.data_mut(|data| data.insert_temp(copy_id.with("reply-rect"), response.response.rect)); + ui.add_space(8.0); + } + TurnItem::Images(first, images) => { + let images = images.into_iter().chain(projected.iter().filter(|_| position == last_position)).collect::>(); + if let Some(target) = self.timeline_images(ui, conversation_id.with(("image-results", first)), &images, &mut flow, doc) { + locate = Some(target); + } + } + TurnItem::Choice(index) => { + flow.break_run(); + let action = match self.messages.get(index).and_then(|message| message["kind"].as_str()) { + Some("pi-ui-request") => self.pi_ui_render(ui, index), + kind => timeline::interaction_card(ui, timeline::InteractionCard { title: None, note: None }, |ui| { + if kind == Some("copywriting-fields") { self.copy_fields_ui(ui, index) } + else { self.copy_options_ui(ui, index) } + }).inner, + }; + if let Some(action) = action { locate = Some(action); } + ui.add_space(8.0); + } + } + } + if let (Some(child), Some((content, previous))) = (item_ui, content) { + let bounds = child.min_rect().translate(-origin); + let advance = child.next_widget_position().y - origin.y; + let rail = flow.anchor().map(|anchor| anchor.translate(-origin)); + let settled_at = previous.filter(|(height, _)| *height == advance) + .map_or(now + 0.25, |(_, settled_at)| settled_at); + ui.expand_to_include_rect(child.min_rect()); + ui.add_space(advance); + layouts.items[item_index] = Some(TurnItemLayout { content, bounds, advance, rail, settled_at, texture_sizes }); + } + } + if virtualized { + ui.data_mut(|data| data.insert_temp(layouts_id, layouts)); + } + if let Some(text) = stream.filter(|_| !stream_is_persisted && !stream_extends_receipt) { + flow.break_run(); + paint_stream(ui, text); + } + if stream.is_some() && self.unknown && !batch_progress { + ui.label(RichText::new("输出未完成").small().color(t.warning)); + } + } + if !projected.is_empty() && !merged_images { + let images: Vec<_> = projected.iter().collect(); + self.timeline_images(ui, conversation_id.with(("worker-jobs", turn.user_index)), &images, &mut flow, doc); + } + locate + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/turns.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/turns.rs new file mode 100644 index 00000000..f6380520 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel/turns.rs @@ -0,0 +1,248 @@ +use egui::{Id, Rect}; +use super::super::{Value, Workspace, stitch_state::WorkerStage}; + +pub(in crate::jiansun) struct ProductionWorker<'a> { + pub(in crate::jiansun) row: &'a Value, + pub(in crate::jiansun) number: u64, + pub(in crate::jiansun) active: bool, + pub(in crate::jiansun) stage: WorkerStage, + pub(in crate::jiansun) step: String, + pub(in crate::jiansun) review: bool, + pub(in crate::jiansun) slot: String, + pub(in crate::jiansun) frame: Value, +} + +#[derive(Default)] +pub(in crate::jiansun) struct Turn<'a> { + pub(in crate::jiansun) user: Option<&'a str>, + pub(in crate::jiansun) user_index: Option, + pub(in crate::jiansun) target: Option<&'a Value>, + pub(in crate::jiansun) items: Vec>, + pub(in crate::jiansun) last_reply: Option<(&'a str, usize)>, +} + +pub(in crate::jiansun) enum TurnItem<'a> { + Reply(&'a str, usize), + Notice(&'a str, usize), + Thinking(&'a Value, usize), + Tools(Vec<(&'a Value, usize)>), + Images(usize, Vec<&'a Value>), + Choice(usize), +} + +impl TurnItem<'_> { + pub(in crate::jiansun) fn message_index(&self) -> usize { + match self { + Self::Reply(_, index) | Self::Notice(_, index) | Self::Thinking(_, index) + | Self::Images(index, _) | Self::Choice(index) => *index, + Self::Tools(rows) => rows[0].1, + } + } +} + +#[derive(Clone)] +pub(in crate::jiansun) enum TurnItemContent { + Reply(String), + Notice(String), + Thinking(bool), + Tools(Vec), + Images(Vec), + Choice(Value), +} + +impl TurnItemContent { + pub(in crate::jiansun) fn capture(item: &TurnItem<'_>, messages: &[Value]) -> Self { + match item { + TurnItem::Reply(text, _) => Self::Reply((*text).to_owned()), + TurnItem::Notice(text, _) => Self::Notice((*text).to_owned()), + TurnItem::Thinking(value, _) => Self::Thinking(value["active"] == true), + TurnItem::Tools(rows) => Self::Tools(rows.iter().map(|(value, _)| (*value).clone()).collect()), + TurnItem::Images(_, images) => Self::Images(images.iter().map(|value| (*value).clone()).collect()), + TurnItem::Choice(index) => Self::Choice(messages[*index].clone()), + } + } + + pub(in crate::jiansun) fn matches(&self, item: &TurnItem<'_>, messages: &[Value]) -> bool { + match (self, item) { + (Self::Reply(previous), TurnItem::Reply(text, _)) + | (Self::Notice(previous), TurnItem::Notice(text, _)) => previous.as_str() == *text, + (Self::Thinking(previous), TurnItem::Thinking(value, _)) => *previous == (value["active"] == true), + (Self::Tools(previous), TurnItem::Tools(rows)) => + previous.iter().eq(rows.iter().map(|(value, _)| *value)), + (Self::Images(previous), TurnItem::Images(_, images)) => + previous.iter().eq(images.iter().copied()), + (Self::Choice(previous), TurnItem::Choice(index)) => previous == &messages[*index], + _ => false, + } + } +} + +impl<'a> Turn<'a> { + pub(in crate::jiansun) fn images(&self) -> impl Iterator + '_ { + self.items.iter().flat_map(|item| match item { + TurnItem::Images(_, images) => images.as_slice(), + _ => &[], + }).copied() + } +} + +#[derive(Clone, Default)] +pub(in crate::jiansun) struct StreamHandoffs(pub(in crate::jiansun) Vec<(Id, String)>); + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(in crate::jiansun) enum ReplyHandoff { Displayed, Append } + + + +/// A settled turn owns no request, pause or unresolved result. Follow-ups and +/// composer suggestions both wait for it. +#[derive(Clone, Default)] +pub(in crate::jiansun) struct ConversationRows { + pub(in crate::jiansun) layout: Option<(Id, usize, u32, u32, crate::theme::ThemeKind)>, + pub(in crate::jiansun) rects: Vec>, +} + +#[derive(Clone)] +pub(in crate::jiansun) struct TurnItemLayout { + pub(in crate::jiansun) content: TurnItemContent, + pub(in crate::jiansun) bounds: Rect, + pub(in crate::jiansun) advance: f32, + pub(in crate::jiansun) rail: Option, + pub(in crate::jiansun) settled_at: f64, + pub(in crate::jiansun) texture_sizes: Vec>, +} + +#[derive(Clone, Default)] +pub(in crate::jiansun) struct TurnItemLayouts { + pub(in crate::jiansun) key: Option<(u32, u32, crate::theme::ThemeKind, bool, bool)>, + #[cfg(test)] + pub(in crate::jiansun) benchmark_count: usize, + pub(in crate::jiansun) disclose_until: f64, + pub(in crate::jiansun) items: Vec>, +} + +pub(in crate::jiansun) fn conversation_settled(workspace: &Workspace, production: bool) -> bool { + !production && workspace.turn_idle() && !workspace.unknown && !workspace.pi_review + && !workspace.agent_effects_paused && workspace.error.is_empty() && workspace.stream_reply.is_empty() +} + + +/// A tool's public label is constructed locally, never from its arguments, +/// output, arbitrary summary or error string. Unknown values stay unknown. +/// The name and status tables live in the kit (`stitch_state`), so a tool reads +/// the same here as in its row badge; this only assembles the legacy line. +pub(in crate::jiansun) fn is_tool_event(event: &Value) -> bool { + event["version"] == 1 && event["type"] == "tool" +} + +/// People read durations coarsely: milliseconds under a second, tenths below +/// ten, whole seconds below a minute, then minutes. +pub(in crate::jiansun) fn duration_text(ms: u64) -> String { + super::stitch_state::duration_text(ms) +} + +pub(in crate::jiansun) fn activity(message: &Value) -> bool { + if message["kind"] == "reply" { + return false; + } + if message["kind"] == "activity" { + return true; + } + let text = message["text"].as_str().unwrap_or(""); + ["已完成:", "图片已生成", "图片已保留", "已替换当前屏", "已置入生成", "已接手", "画布已修改", "98k图片结果"].iter().any(|prefix| text.starts_with(prefix)) +} + +/// Historical activity is not a live undo capability. Keep the original +/// journal intact while avoiding a stale promise after native undo or redo. +pub(in crate::jiansun) fn activity_history_label(text: &str) -> &str { + if text == "已采纳图片,可撤销" { "图片采纳记录" } else if text.starts_with("专业编辑已回填") { "专业编辑回填记录 · 编辑源文件保留" } else { text } +} + +pub(in crate::jiansun) fn turns(messages: &[Value]) -> Vec> { + let mut out = Vec::new(); + let mut current = Turn::default(); + let mut call_rows = std::collections::HashMap::<(&str, &str), (usize, usize)>::new(); + for (index, message) in messages.iter().enumerate() { + if message["role"] == "user" { + if current.user.is_some() || !current.items.is_empty() { + out.push(std::mem::take(&mut current)); + call_rows.clear(); + } + current.user = message["text"].as_str(); + current.user_index = Some(index); + } else if matches!(message["kind"].as_str(), Some("copywriting-options" | "copywriting-fields" | "pi-ui-request")) { + current.items.push(TurnItem::Choice(index)); + } else if message["kind"] == "pi-ui-decoration" { + continue; + } else if matches!(message["kind"].as_str(), Some("image" | "template-image" | "image-job")) { + if let Some(TurnItem::Images(_, images)) = current.items.last_mut() { + images.push(message); + } else { + current.items.push(TurnItem::Images(index, vec![message])); + } + } else if message["kind"] == "thinking" { + if let Some(TurnItem::Thinking(previous, previous_index)) = current.items.last_mut() { + *previous = message; + *previous_index = index; + } else { + current.items.push(TurnItem::Thinking(message, index)); + } + } else if activity(message) && is_tool_event(&message["event"]) { + let event = &message["event"]; + let identity = event["run"].as_str().zip(event["toolCallId"].as_str()); + if let Some(&(group, row)) = identity.and_then(|key| call_rows.get(&key)) + && let Some(TurnItem::Tools(tools)) = current.items.get_mut(group) + && let Some((previous, _)) = tools.get_mut(row) + { + if matches!(previous["status"].as_str(), Some("started" | "pending")) { + *previous = event; + } + continue; + } + let len = current.items.len(); + let location = if let Some(TurnItem::Tools(tools)) = current.items.last_mut() { + let row = tools.len(); + tools.push((event, index)); + (len - 1, row) + } else { + current.items.push(TurnItem::Tools(vec![(event, index)])); + (len, 0) + }; + if let Some(key) = identity { call_rows.insert(key, location); } + } else if let Some(text) = message["text"].as_str().filter(|s| !s.is_empty()) { + if activity(message) { + current.items.push(TurnItem::Notice(text, index)); + } else { + current.items.push(TurnItem::Reply(text, index)); + current.last_reply = Some((text, index)); + } + } + if current.target.is_none() { + current.target = message.get("target").filter(|target| target.is_object()); + } + } + if current.user.is_some() || !current.items.is_empty() { + out.push(current); + } + // The same status can be recorded again each time a stage resumes. The + // transcript keeps every record; the timeline shows only the latest copy. + let mut latest = std::collections::HashMap::new(); + for (turn_index, turn) in out.iter().enumerate() { + for (item_index, item) in turn.items.iter().enumerate() { + if let TurnItem::Notice(text, _) = item { latest.insert(*text, (turn_index, item_index)); } + } + } + for (turn_index, turn) in out.iter_mut().enumerate() { + let mut item_index = 0; + turn.items.retain(|item| { + let keep = match item { + TurnItem::Notice(text, _) => latest.get(text).copied() == Some((turn_index, item_index)), + _ => true, + }; + item_index += 1; + keep + }); + } + out +} + 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 3c0c96da..39c91b83 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs @@ -1,2859 +1,54 @@ //! Native creation controls. Model execution and files stay in the backend worker. -use super::{stitch_kit, stitch_state::Tone, stitch_ui}; -use super::{json, Value, Ui, Tokens, PhotocraftApp, Workspace, Document, Request, Instant, Duration}; -use crate::theme::agent_scale::{control, icon, radius, space, Type}; -use crate::theme::AGENT_SEMANTIC; -use egui::vec2; -use std::collections::{HashMap, HashSet}; +mod barcode; +mod brief; +mod brief_footer_ui; +mod form_barcode_ui; +mod form_identity_ui; +mod form_widgets_ui; +mod gallery_ui; +mod intake; +mod plan_ui; +mod project; +mod reducers; +mod references_ui; +mod review_hints; +mod structure_preview_ui; +mod taxonomy_select_ui; +mod template_select_ui; +mod test_preset_ui; +mod wizard_ui; + +#[allow(unused_imports)] +use super::{ + CenterView, action, canvas_workspace, creation_reads, operation_error, product_form_open, + product_production, template_slots, +}; +use super::{PhotocraftApp, Request, Tokens, Ui, Workspace, json, stitch_ui}; +use reducers::form_editable; + +pub use brief::{incomplete_brief_stage, saved_creation_draft_brief}; +#[cfg(test)] +pub(super) use brief::sku_display_label; +pub(super) use brief::{ + brief_readiness, empty_brief, image_rows, normalized_product_summary, + selected_template, selected_visual_asset_count, + template_compatibility_warnings, +}; +pub(crate) use form_widgets_ui::creation_escape_active; +pub(super) use form_widgets_ui::{creation_editor_id, wizard_barcode_editor}; +pub use super::creation_reads::wizard::CreationStage; +pub(super) use reducers::{ + allowed, canvas_received, finished_web_received, listing_status_received, received, + sync_received, +}; const PICKER_HEIGHT: f32 = 280.0; const PICKER_ROW_HEIGHT: f32 = 36.0; const MATERIAL_THUMB_SIDE: f32 = 32.0; const REFERENCE_DROP_HINT: &str = "请将图片拖入素材上传框内"; - -use super::creation_reads::{TEST_PRESETS, wizard::{self, WizardFooterOutcome, WizardFooterState}}; -pub use wizard::CreationStage; - const WIZARD_WIDTH: f32 = 800.0; -fn wizard_column(ui: &mut Ui, draw: impl FnOnce(&mut Ui)) { - let width = ui.available_width().min(WIZARD_WIDTH); - let inset = (ui.available_width() - width) / 2.0; - let gap = ui.spacing().item_spacing.x; - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - ui.add_space(inset); - ui.vertical(|ui| { - ui.spacing_mut().item_spacing.x = gap; - ui.set_width(width); - draw(ui); - }); - }); -} - -fn rect_value(rect: egui::Rect) -> Value { - json!([rect.min.x, rect.min.y, rect.width(), rect.height()]) -} - -fn preview_frame(value: &Value, width: f64, height: f64, line: bool) -> Option<[f32; 4]> { - let (x, y, w, h) = (value["x"].as_f64()?, value["y"].as_f64()?, value["width"].as_f64()?, value["height"].as_f64()?); - if ![x, y, w, h].iter().all(|n| n.is_finite()) || x < 0.0 || y < 0.0 || w <= 0.0 || h < 0.0 || (!line && h == 0.0) - || x + w > width + 0.01 || y + h > height + 0.01 { return None; } - Some([x as f32, y as f32, w as f32, h as f32]) -} - -fn preview_color(value: &Value) -> Option { - let value = value.as_str()?; - if value.len() != 7 || !value.starts_with('#') || !value[1..].bytes().all(|b| b.is_ascii_hexdigit()) { return None; } - let n = u32::from_str_radix(&value[1..], 16).ok()?; - Some(egui::Color32::from_rgb((n >> 16) as u8, (n >> 8) as u8, n as u8)) -} - -/// Only accept a geometry preview attached to the exact selected immutable -/// package and current brand/category. It is never a product photograph. -fn verified_structure_preview<'a>(row: &'a Value, selected: &Value, brand: &str, category: &str) -> Option<&'a Value> { - if brand.is_empty() || category.is_empty() || row["brandId"] != brand || row["categoryId"] != category - || row["id"] != selected["id"] || row["version"] != selected["version"] || row["contentHash"] != selected["contentHash"] - || !template_identity(row) { return None; } - let preview = &row["structurePreview"]; - if preview["contentHash"] != row["contentHash"] || preview["outputId"].as_str().is_none_or(str::is_empty) { return None; } - let width = preview["width"].as_f64()?; - let height = preview["height"].as_f64()?; - if !matches!(preview["width"].as_u64(), Some(750 | 1440)) || !height.is_finite() || !(1.0..=30_000.0).contains(&height) - || (!preview["background"].is_null() && preview_color(&preview["background"]).is_none()) { return None; } - let slots = preview["slots"].as_array().filter(|items| !items.is_empty() && items.len() <= 120)?; - if slots.iter().any(|slot| !matches!(slot["kind"].as_str(), Some("image" | "text")) || preview_frame(&slot["frame"], width, height, false).is_none()) { return None; } - let decorations = preview["decorations"].as_array().filter(|items| items.len() <= 120)?; - if decorations.iter().any(|item| { - let kind = item["kind"].as_str(); - !matches!(kind, Some("rect" | "line")) || preview_frame(&item["frame"], width, height, kind == Some("line")).is_none() - || preview_color(&item["color"]).is_none() || !item["opacity"].as_f64().is_some_and(|n| n.is_finite() && (0.0..=1.0).contains(&n)) - }) { return None; } - Some(preview) -} - -/// Paint only validated template geometry. This is a structural diagram, -/// never a substitute for an authorized template cover photograph. -fn paint_template_structure(ui: &Ui, preview: &Value, area: egui::Rect) { - let width = preview["width"].as_f64().unwrap_or(1.0) as f32; - let height = preview["height"].as_f64().unwrap_or(1.0) as f32; - let scale = (area.width() / width).min(area.height() / height); - let page = egui::Rect::from_center_size(area.center(), vec2(width * scale, height * scale)); - let painter = ui.painter().with_clip_rect(page); - painter.rect_filled(page, 2.0, preview_color(&preview["background"]).unwrap_or(egui::Color32::WHITE)); - let paint_frame = |frame: [f32; 4]| egui::Rect::from_min_size(page.min + vec2(frame[0] * scale, frame[1] * scale), vec2(frame[2] * scale, frame[3] * scale)); - let decorations = |above: bool| { - for item in preview["decorations"].as_array().into_iter().flatten().filter(|item| (item["aboveImages"] == true) == above) { - if let (Some(frame), Some(color), Some(opacity)) = (preview_frame(&item["frame"], width as f64, height as f64, item["kind"] == "line"), preview_color(&item["color"]), item["opacity"].as_f64()) { - let rect = paint_frame(frame); - let color = color.gamma_multiply(opacity as f32); - if item["kind"] == "line" { painter.line_segment([rect.left_top(), rect.right_bottom()], egui::Stroke::new(1.0, color)); } - else { painter.rect_filled(rect, 0, color); } - } - } - }; - let t = Tokens::get(ui.ctx()).agent(); - decorations(false); - for slot in preview["slots"].as_array().into_iter().flatten().filter(|slot| slot["kind"] == "image") { - if let Some(frame) = preview_frame(&slot["frame"], width as f64, height as f64, false) { painter.rect_filled(paint_frame(frame), 0, t.text_dim); } - } - decorations(true); - for slot in preview["slots"].as_array().into_iter().flatten().filter(|slot| slot["kind"] == "text") { - if let Some(frame) = preview_frame(&slot["frame"], width as f64, height as f64, false) { - let rect = paint_frame(frame); - painter.rect_stroke(rect, 0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); - } - } -} - -fn structure_preview_card( - ui: &mut Ui, - preview: Option<&Value>, - cover: Option<&egui::TextureHandle>, - name: &str, - version: &str, - screen_count: Option, - canvas_width: u32, - status: Option<&str>, -) { - let t = Tokens::get(ui.ctx()).agent(); - ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = space::MD; - let thumb_size = if cover.is_some() || preview.is_some() { vec2(136.0, 184.0) } else { vec2(96.0, 128.0) }; - let (area, _) = ui.allocate_exact_size(thumb_size, egui::Sense::hover()); - ui.painter().rect_filled(area, radius::CONTROL, t.dock); - ui.painter().rect_stroke(area, radius::CONTROL, egui::Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); - if let Some(texture) = cover { - let size = preview_size(texture.size_vec2(), area.shrink(4.0).size()); - let rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, area); - ui.painter().image(texture.id(), rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text); - } else if let Some(preview) = preview { - paint_template_structure(ui, preview, area.shrink(4.0)); - } else { - crate::icons::paint(ui, area.translate(vec2(0.0, -10.0)), "layers", icon::LG, t.text_dim); - ui.painter().text( - egui::pos2(area.center().x, area.center().y + 18.0), - egui::Align2::CENTER_CENTER, - "暂无预览图", - Type::Meta.font_id(), - t.text_dim, - ); - } - ui.vertical(|ui| { - ui.spacing_mut().item_spacing.y = space::XS; - ui.add(egui::Label::new(egui::RichText::new(name).font(Type::Body.semibold()).color(t.text)).wrap()); - let mut facts = Vec::new(); - if let Some(count) = screen_count { - facts.push(format!("{count} 屏")); - } - if canvas_width > 0 { - facts.push(format!("{canvas_width} px")); - } - if !version.is_empty() { - facts.push(version.to_owned()); - } - if let Some(status) = status { - facts.push(status.to_owned()); - } - if !facts.is_empty() { - stitch_kit::label(ui, facts.join(" · "), Type::Meta, Tone::Quiet); - } - if cover.is_some() { - stitch_kit::caption(ui, "模板原稿预览"); - } else if preview.is_some() { - stitch_kit::caption(ui, "首屏结构示意"); - } else { - stitch_kit::caption(ui, "模板已就绪(当前组件未附带预览图)"); - } - }); - }); -} - -fn drop_contains(value: &Value, point: egui::Pos2) -> bool { - let Some(values) = value.as_array() - .filter(|rect| rect.len() == 4) - .and_then(|rect| rect.iter().map(Value::as_f64).collect::>>()) else { return false }; - values.iter().all(|value| value.is_finite()) && values[2] > 0.0 && values[3] > 0.0 - && egui::Rect::from_min_size( - egui::pos2(values[0] as f32, values[1] as f32), - vec2(values[2] as f32, values[3] as f32), - ).contains(point) -} - -fn reference_image_path(path: &std::path::Path) -> bool { - path.extension().and_then(|ext| ext.to_str()) - .is_some_and(|ext| ["png", "jpg", "jpeg", "webp"].iter().any(|allowed| ext.eq_ignore_ascii_case(allowed))) -} - -fn reference_folder_paths(folder: &std::path::Path) -> Result, String> { - let mut paths = Vec::new(); - for entry in std::fs::read_dir(folder).map_err(|_| "无法读取所选文件夹")? { - let path = entry.map_err(|_| "无法读取所选文件夹")?.path(); - if path.is_file() && reference_image_path(&path) { - if paths.len() == 8 { return Err("文件夹内图片超过 8 张,请改用文件选择".into()); } - paths.push(path.into_os_string().into_string().map_err(|_| "文件名无效")?); - } - } - if paths.is_empty() { return Err("文件夹里没有 PNG、JPG 或 WebP 图片".into()); } - paths.sort(); - Ok(paths) -} - -impl PhotocraftApp { - pub(crate) fn creation_reference_drop( - &mut self, ctx: &egui::Context, files: &[egui::DroppedFileHandle], at: Option, - ) -> bool { - if self.file_dialog_open() { - return false; - } - let product_form_open = super::product_form_open(self); - let Some(w) = self.jiansun.as_mut() else { return false }; - let staged = w.creation_reads.staged_new_project && w.creation_open - && w.creation_step == 0 && !w.library && !w.material; - if !product_form_open && !staged { - return false; - } - let doc = self.session.active().map(|state| state.doc.id.0); - let target = at.and_then(|at| { - let layer = ctx.layer_id_at(at); - w.creation_view_geometry["imageSlots"].as_object().into_iter().flat_map(|slots| slots.values()) - .chain(std::iter::once(&w.creation_view_geometry["referenceDrop"])) - .find(|target| target["doc"] == json!(doc) && target["accountId"] == w.account["id"] - && target["origin"] == w.origin && target["viewport"].as_u64() == Some(ctx.viewport_id().0.value()) - && drop_contains(&target["rect"], at) - && layer.is_none_or(|layer| layer.order == egui::Order::Background - || target["layer"].as_u64() == Some(layer.id.value()))) - }); - let Some(target) = target else { - if files.iter().any(|file| file.path().is_dir() || file.path().extension().and_then(|ext| ext.to_str()) - .is_some_and(|ext| photocraft_codecs::from_extension(ext).is_some() || ext.eq_ignore_ascii_case("svg"))) - { - w.creation_reads.reference_import_error = REFERENCE_DROP_HINT.into(); - return true; - } - return false; - }; - let slot = target["slot"].clone(); - let reject = if (!staged && w.creation_doc != doc) || w.busy.is_some() { - Some("请等待当前操作完成,再添加参考图") - } else if w.unknown { - Some("原请求结果待核查,请先核查后再添加参考图") - } else if slot["multiple"] == false && files.len() != 1 { - Some("此图片框一次只能添加一张图片") - } else if files.is_empty() || files.len() > 8 { - Some("每次请选择 1 至 8 张参考图片") - } else { - None - }; - if let Some(error) = reject { - w.creation_reads.reference_import_error = error.into(); - return true; - } - let paths = if slot.is_null() && matches!(files, [file] if file.path().is_dir()) { - reference_folder_paths(files[0].path()) - } else { - files.iter().map(|file| { - let path = file.path(); - let valid = path.is_absolute() && reference_image_path(path); - valid.then(|| path.to_str().map(str::to_owned)).flatten() - }).collect::>>().ok_or_else(|| "请选择 PNG、JPG 或 WebP 格式的本机图片".to_owned()) - }; - let paths = match paths { - Ok(paths) => paths, - Err(error) => { - w.creation_reads.reference_import_error = error; - return true; - } - }; - if let Err(error) = self.import_reference_paths(paths, slot) - && let Some(w) = self.jiansun.as_mut() - { - w.creation_reads.reference_import_error = error; - } - true - } - fn import_reference_paths(&mut self, paths: Vec, slot: Value) -> Result { - let native = self.session.authorize.is_none(); - if slot.is_object() && self.jiansun.as_ref().is_none_or(|w| !current_image_slot(&w.creation_brief, &slot)) { - return Err("图片框已变化,请重新选择".into()); - } - let result = super::action(self, "creation-import", json!({"paths":paths,"imageSlot":slot}))?; - if let Some(w) = self.jiansun.as_mut() { - w.creation_reads.reference_import_error.clear(); - if native && result["submitted"] == true { - w.creation_reads.reference_import_paths = Some(paths); - } - } - Ok(result) - } - -} - -pub(crate) fn creation_escape_active(app: &PhotocraftApp) -> bool { - app.jiansun.as_ref().is_some_and(|workspace| - workspace.creation_open && workspace.creation_step != 3 && !workspace.library && !workspace.material) -} - -/// Constrain the native ComboBox before its first measuring pass. Its default -/// popup extends labels and shrinks loading content to one row, producing a -/// different menu on first open and after the asynchronous catalogue arrives. -fn picker(ui: &mut Ui, id: &str, width: f32, selected: &str, contents: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse> { - picker_height(ui, id, width, PICKER_HEIGHT, selected, egui::PopupCloseBehavior::CloseOnClick, contents) -} - -fn picker_height(ui: &mut Ui, id: &str, width: f32, height: f32, selected: &str, close_behavior: egui::PopupCloseBehavior, contents: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse> { - ui.scope(|ui| { - ui.set_width(width); - let t = Tokens::get(ui.ctx()).agent(); - ui.spacing_mut().interact_size.y = 34.0; - ui.spacing_mut().button_padding = vec2(10.0, 7.0); - let visuals = ui.visuals_mut(); - visuals.widgets.inactive.corner_radius = egui::CornerRadius::same(9); - visuals.widgets.hovered.corner_radius = egui::CornerRadius::same(9); - visuals.widgets.inactive.weak_bg_fill = t.field; - visuals.widgets.inactive.bg_stroke = egui::Stroke::new(1.0, t.field_border); - stitch_ui::halo_select_with_behavior(ui, id, width, selected, ui.style().animation_time == 0.0, close_behavior, |ui| { - // Reserve the same scrollbar gutter before and after data arrives. - ui.set_width( - (width - ui.spacing().menu_margin.sum().x - ui.spacing().scroll.allocated_width() - ui.spacing().scroll.content_margin.sum().x).max(120.0), - ); - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); - egui::ScrollArea::vertical().max_height(height).min_scrolled_height(height) - .auto_shrink([false, true]).show(ui, contents).inner - }, - ) - }) - .inner -} - -fn picker_row(ui: &mut Ui, selected: bool, label: &str, enabled: bool) -> egui::Response { - // add_sized centers its child and reports the text's intrinsic width on the - // first sizing pass. An explicit native minimum keeps the whole left-aligned - // row the same size before and after the popup's layout cache is populated. - let size = vec2(ui.available_width(), PICKER_ROW_HEIGHT); - ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { - // The shared option inherits wrap mode; clamp long template names to - // the space left after the preview instead of widening the popup. - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); - stitch_ui::select_option_sized(ui, label, selected, enabled, size) - }) - .inner -} - -fn template_picker_row(ui: &mut Ui, selected: bool, label: &str, enabled: bool, preview: Option<&Value>) -> egui::Response { - if let Some(preview) = preview { - ui.horizontal(|ui| { - let (area, thumbnail) = ui.allocate_exact_size(vec2(26.0, PICKER_ROW_HEIGHT), if enabled { egui::Sense::click() } else { egui::Sense::hover() }); - paint_template_structure(ui, preview, area.shrink(2.0)); - let thumbnail = thumbnail.on_hover_text("首屏结构示意,不含图片"); - picker_row(ui, selected, label, enabled).union(thumbnail) - }).inner - } else { - picker_row(ui, selected, label, enabled) - } -} - -fn picker_toggle_row(ui: &mut Ui, selected: bool, label: &str, enabled: bool) -> egui::Response { - let size = vec2(ui.available_width(), PICKER_ROW_HEIGHT); - ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { - stitch_ui::menu_toggle_sized(ui, label, selected, enabled, size) - }).inner -} - -fn picker_notice(ui: &mut Ui, loading: bool, error: Option<&str>, empty: bool, empty_label: &str) -> bool { - let mut retry = false; - if loading { - ui.horizontal(|ui| { - let reduced = ui.style().animation_time == 0.0; - stitch_ui::ai_loader(ui, egui::Id::unique("creation-catalog-loader"), true, reduced); - ui.label("正在读取…"); - }); - } else if let Some(error) = error { - stitch_ui::status_label(ui, "读取失败", stitch_ui::StatusTone::Error).on_hover_text(error); - retry = stitch_ui::action_button(ui, "重新读取", stitch_ui::ButtonRole::Secondary, true).clicked(); - } else if empty { - stitch_ui::status_label(ui, empty_label, stitch_ui::StatusTone::Neutral); - retry = stitch_ui::action_button(ui, "重新读取", stitch_ui::ButtonRole::Secondary, true).clicked(); - } - retry -} - -fn preview_size(size: egui::Vec2, max: egui::Vec2) -> egui::Vec2 { - if !size.is_finite() || size.x <= 0.0 || size.y <= 0.0 { - return egui::Vec2::ZERO; - } - size * (max.x / size.x).min(max.y / size.y) -} - -fn material_thumbnail(ui: &mut Ui, texture: Option<&egui::TextureHandle>, loading: bool, failed: bool) -> egui::Response { - let (rect, response) = - ui.allocate_exact_size(vec2(MATERIAL_THUMB_SIDE, MATERIAL_THUMB_SIDE), if failed { egui::Sense::click() } else { egui::Sense::hover() }); - let t = Tokens::get(ui.ctx()).agent(); - ui.painter().rect_filled(rect, t.radius_sm, t.field); - ui.painter().rect_stroke(rect, t.radius_sm, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); - if let Some(texture) = texture { - let size = preview_size(texture.size_vec2(), rect.size()); - let image_rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, rect); - ui.painter().image(texture.id(), image_rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), egui::Color32::WHITE); - } else if loading { - let mut child = ui.new_child(egui::UiBuilder::new().id_salt(response.id.with("loader")).max_rect(rect.shrink(3.0))); - child.set_clip_rect(rect.intersect(ui.clip_rect())); - let reduced = ui.style().animation_time == 0.0; - stitch_ui::ai_loader(&mut child, response.id.with("loader"), true, reduced); - } else if failed { - crate::icons::paint(ui, rect.shrink(8.0), "triangle-alert", 14.0, t.text_dim); - } - response -} - -pub(super) fn empty_brief() -> Value { - json!({"source":"upload","name":"","brandId":"","brandName":"","categoryId":"","categoryName":"","identifierType":"spu","identifier":"","barcodeBindings":{},"variant":"","colorMaterialId":"","colorName":"","variants":[],"templateSelection":null,"dimensions":{"length":"","width":"","height":"","unit":"mm"},"images":[],"note":""}) -} - -fn variant_identity(material: &str) -> String { - if material.len() == 36 - && material.bytes().enumerate().all(|(index, byte)| if [8, 13, 18, 23].contains(&index) { byte == b'-' } else { byte.is_ascii_hexdigit() }) - { - return material.to_ascii_lowercase(); - } - // Application-defined UUIDv8 for non-UUID legacy material identifiers. It - // is persisted with the selected row; no order/index becomes its identity. - let left = egui::Id::unique(("material-variant-a-v1", material)).value(); - let right = egui::Id::unique(("material-variant-b-v1", material)).value(); - format!( - "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}", - left >> 32, - (left >> 16) & 0xffff, - (left & 0x0fff) | 0x8000, - ((right >> 48) & 0x0fff) | 0x8000, - right & 0xffff_ffff_ffff - ) -} - -fn brief_variants(brief: &Value) -> Vec { - if let Some(rows) = brief["variants"].as_array().filter(|rows| !rows.is_empty()) { - return rows.clone(); - } - let Some(material) = brief["colorMaterialId"].as_str().filter(|id| !id.is_empty()) else { return vec![] }; - let name = brief["colorName"].as_str().filter(|name| !name.is_empty()).unwrap_or("花色"); - vec![json!({"id":variant_identity(material),"name":name,"colorMaterialId":material,"colorName":brief["colorName"],"images":[]})] -} - -fn set_brief_variants(brief: &mut Value, rows: Vec) { - brief["colorMaterialId"] = rows.first().map(|row| row["colorMaterialId"].clone()).unwrap_or(json!("")); - brief["colorName"] = rows.first().map(|row| row["colorName"].clone()).unwrap_or(json!("")); - brief["variants"] = json!(rows); - // brief.variant is the original product option text, not the selected color. -} - -fn template_identity(value: &Value) -> bool { - value["id"].as_str().is_some_and(|id| !id.is_empty() && id.chars().count() <= 160) - && value["version"].as_str().is_some_and(|version| !version.is_empty() && version.chars().count() <= 100) - && value["contentHash"].as_str().is_some_and(|hash| hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))) -} - -pub(super) fn template_compatibility_warnings(sources: &[&Value]) -> Vec { - let mut out = Vec::new(); - for source in sources { - for key in ["compatibilityWarnings", "warnings"] { - for item in source[key].as_array().into_iter().flatten() { - let Some(text) = item.as_str().map(str::trim).filter(|s| !s.is_empty()) else { continue }; - let text = text.chars().take(400).collect::(); - if !out.contains(&text) { - out.push(text); - if out.len() >= 20 { - return out; - } - } - } - } - } - out -} - -fn default_resource_component(parts: &[Value]) -> Option<&Value> { - if let [only] = parts { - return Some(only); - } - let mut detail = parts.iter().filter(|part| part["kind"] == "detail"); - let candidate = detail.next()?; - detail.next().is_none().then_some(candidate) -} - -pub(super) fn selected_template(brief: &Value, workflow: &Value, canonical_brief: &Value) -> Value { - let selected = &brief["templateSelection"]; - if template_identity(selected) - && selected.get("brandId").is_none_or(|id| *id == brief["brandId"]) - && selected.get("categoryId").is_none_or(|id| *id == brief["categoryId"]) - { - return selected.clone(); - } - if brief["brandId"] != canonical_brief["brandId"] || brief["categoryId"] != canonical_brief["categoryId"] { - return Value::Null; - } - let installed = json!({"id":workflow["templateId"],"version":workflow["templateVersion"],"contentHash":workflow["templateHash"],"name":workflow["templateName"],"brandId":brief["brandId"],"categoryId":brief["categoryId"]}); - if template_identity(&installed) { installed } else { Value::Null } -} - -pub(super) fn image_rows(brief: &Value) -> Vec<(Value, String)> { - let mut rows = brief["images"].as_array().into_iter().flatten().cloned().map(|image| (image, String::new())).collect::>(); - for variant in brief_variants(brief) { - let owner = variant["id"].as_str().unwrap_or("").to_owned(); - rows.extend(variant["images"].as_array().into_iter().flatten().cloned().map(|image| (image, owner.clone()))); - } - rows -} - -fn store_image_rows(brief: &mut Value, rows: Vec<(Value, String)>) -> Result<(), String> { - if !brief.is_object() { - return Err("产品资料格式无效,未更改图片归属".into()); - } - let mut variants = brief_variants(brief); - if rows.iter().any(|(_, owner)| !owner.is_empty() && !variants.iter().any(|variant| variant["id"] == owner.as_str())) { - return Err("图片所属花色已变化,请重新选择归属".into()); - } - for variant in &mut variants { - variant["images"] = json!([]); - } - let mut common = Vec::new(); - for (image, owner) in rows { - if let Some(variant) = variants.iter_mut().find(|row| row["id"] == owner) { - let Some(images) = variant["images"].as_array_mut() else { return Err("花色图片记录无效,未更改图片归属".into()) }; - images.push(image); - } else { - common.push(image); - } - } - let removed = brief["images"].as_array().into_iter().flatten() - .filter(|old| old["barcode"].is_string() && !common.iter().any(|image| image["source"] == old["source"] - && image["barcode"] == old["barcode"] && image["fieldKey"] == old["fieldKey"])) - .cloned().collect::>(); - for row in brief["barcodeEntries"].as_array_mut().into_iter().flatten() { - if let Some(pictures) = row["images"].as_array_mut() { - pictures.retain(|picture| !removed.iter().any(|old| old["source"] == picture["source"] - && old["barcode"] == picture["barcode"] && old["fieldKey"] == picture["fieldKey"])); - } - } - brief["images"] = json!(common); - if brief.get("variants").is_some() || !variants.is_empty() { - set_brief_variants(brief, variants); - } - Ok(()) -} - -pub(super) struct ReadinessItem { - pub(super) field_key: String, - pub(super) label: String, - pub(super) message: String, - pub(super) ready: bool, -} - -#[derive(Clone, Debug, Default)] -pub(super) struct NormalizedProductSummary { - pub(super) has_platform_data: bool, - pub(super) spu: String, - pub(super) platform_brand: String, - pub(super) platform_category: String, - pub(super) series_or_model: String, - pub(super) dimensions_display: Option, - pub(super) materials: Vec, - pub(super) attributes: Vec<(String, String)>, - pub(super) summary: String, - pub(super) selling_points: Vec, - pub(super) trace_source: String, - #[cfg(test)] - pub(super) fetched_at: String, - pub(super) raw_field_warnings: Vec, -} - -#[derive(Clone, Debug, Default)] -struct NormalizedSkuRow { - barcode: String, - #[cfg(test)] - color_name: String, - #[cfg(test)] - spec: String, - #[cfg(test)] - dimensions_display: Option, - #[cfg(test)] - image_count: usize, -} - -#[derive(Clone, Debug, Default)] -struct NormalizedColorGroup { - id: String, - color_name: String, - skus: Vec, -} - -fn non_empty_str(value: &Value) -> Option<&str> { - value.as_str().map(str::trim).filter(|s| !s.is_empty()) -} - -fn string_list(value: &Value) -> Vec { - match value { - Value::String(text) => text - .split(['\n', '、', ',', ',', ';', ';']) - .map(str::trim) - .filter(|item| !item.is_empty()) - .map(str::to_owned) - .collect(), - Value::Array(items) => items - .iter() - .filter_map(non_empty_str) - .map(str::to_owned) - .collect(), - _ => Vec::new(), - } -} - -fn dedupe_strings(items: Vec) -> Vec { - let mut seen = HashSet::new(); - items.into_iter().filter(|item| seen.insert(item.to_lowercase())).collect() -} - -pub(super) fn normalized_product_summary(brief: &Value) -> NormalizedProductSummary { - let np = &brief["normalizedProduct"]; - let pf = &brief["platformFacts"]; - if np.is_object() { - let identity = &np["identity"]; - let specs = &np["specs"]; - let copy = &np["copy"]; - let trace = &np["trace"]; - let dims = if specs["dimensions"].is_object() { - non_empty_str(&specs["dimensions"]["display"]) - .map(str::to_owned) - .or_else(|| dimension_text(&specs["dimensions"])) - } else { - None - }; - let materials = dedupe_strings(string_list(&specs["materials"])); - let mut seen_attr = HashSet::new(); - let mut attributes = Vec::new(); - for attr in specs["attributes"].as_array().into_iter().flatten() { - let label = non_empty_str(&attr["label"]).or_else(|| non_empty_str(&attr["key"])); - let value = non_empty_str(&attr["value"]); - if let (Some(label), Some(value)) = (label, value) { - let lower = label.to_lowercase(); - if matches!(label, "尺寸" | "产品尺寸" | "长" | "宽" | "高" | "品牌" | "品类" | "颜色" | "花色") - && (dims.is_some() || !materials.is_empty()) - { - continue; - } - if seen_attr.insert(format!("{lower}:{value}")) { - attributes.push((label.to_owned(), value.to_owned())); - } - } - } - return NormalizedProductSummary { - has_platform_data: true, - spu: non_empty_str(&identity["spu"]).or_else(|| non_empty_str(&trace["upstreamSpu"])).or_else(|| non_empty_str(&brief["identifier"])).unwrap_or("").to_owned(), - platform_brand: non_empty_str(&identity["platformBrand"]).unwrap_or("").to_owned(), - platform_category: non_empty_str(&identity["platformCategory"]).unwrap_or("").to_owned(), - series_or_model: non_empty_str(&identity["seriesOrModel"]).unwrap_or("").to_owned(), - dimensions_display: dims, - materials, - attributes, - summary: non_empty_str(©["summary"]).unwrap_or("").to_owned(), - selling_points: dedupe_strings(string_list(©["sellingPoints"])), - trace_source: non_empty_str(&trace["source"]).unwrap_or("产品平台").to_owned(), - #[cfg(test)] - fetched_at: non_empty_str(&trace["fetchedAt"]).unwrap_or("").to_owned(), - raw_field_warnings: dedupe_strings(string_list(&trace["rawFieldWarnings"])), - }; - } - if pf.is_object() { - let shared = &pf["shared"]; - let dims = dimension_text(&shared["dimensions"]); - let materials = dedupe_strings(string_list(&shared["material"])); - let mut attributes = Vec::new(); - if let Some(map) = shared["attributes"].as_object() { - for (k, v) in map { - if let Some(text) = non_empty_str(v) - && !matches!(k.as_str(), "尺寸" | "产品尺寸" | "长" | "宽" | "高") - { - attributes.push((k.clone(), text.to_owned())); - } - } - } - return NormalizedProductSummary { - has_platform_data: true, - spu: non_empty_str(&pf["spu"]).or_else(|| non_empty_str(&brief["identifier"])).unwrap_or("").to_owned(), - platform_brand: non_empty_str(&shared["brandName"]).or_else(|| non_empty_str(&pf["brandName"])).unwrap_or("").to_owned(), - platform_category: non_empty_str(&shared["categoryName"]).or_else(|| non_empty_str(&pf["categoryName"])).unwrap_or("").to_owned(), - series_or_model: non_empty_str(&brief["variant"]).unwrap_or("").to_owned(), - dimensions_display: dims, - materials, - attributes, - summary: non_empty_str(&shared["description"]).unwrap_or("").to_owned(), - selling_points: dedupe_strings(string_list(&shared["sellingPoints"])), - trace_source: "产品平台".into(), - #[cfg(test)] - fetched_at: String::new(), - raw_field_warnings: Vec::new(), - }; - } - NormalizedProductSummary::default() -} - -pub(super) fn sku_display_label(brief: &Value, barcode: &str) -> String { - let mut color = String::new(); - let mut spec = String::new(); - if let Some(variants) = brief["normalizedProduct"]["variants"].as_array() { - 'outer: for variant in variants { - let v_color = non_empty_str(&variant["colorName"]).unwrap_or(""); - for row in variant["barcodes"].as_array().into_iter().flatten() { - if non_empty_str(&row["barcode"]) == Some(barcode) { - color = v_color.to_owned(); - let s = non_empty_str(&row["spec"]) - .or_else(|| non_empty_str(&row["skuName"])) - .map(str::to_owned) - .or_else(|| non_empty_str(&row["dimensions"]["display"]).map(str::to_owned)) - .or_else(|| dimension_text(&row["dimensions"])) - .unwrap_or_default(); - spec = s; - break 'outer; - } - } - } - } - if color.is_empty() && spec.is_empty() { - let pf = &brief["platformFacts"]["barcodes"][barcode]; - if pf.is_object() { - color = non_empty_str(&pf["colorName"]).unwrap_or("").to_owned(); - spec = non_empty_str(&pf["spec"]) - .or_else(|| non_empty_str(&pf["sizeText"])) - .map(str::to_owned) - .or_else(|| dimension_text(&pf["dimensions"])) - .unwrap_or_default(); - } - } - if color.is_empty() { - for variant in brief_variants(brief) { - if let Some(id) = variant["id"].as_str() - && binding_barcodes(&brief["barcodeBindings"][id]).any(|code| code == barcode) - { - color = non_empty_str(&variant["colorName"]) - .or_else(|| non_empty_str(&variant["name"])) - .unwrap_or("") - .to_owned(); - break; - } - } - } - // Deduplicate color prefix if spec already includes the color name. - if !color.is_empty() && !spec.is_empty() && spec.eq_ignore_ascii_case(&color) { - spec.clear(); - } - match (color.is_empty(), spec.is_empty()) { - (false, false) => format!("{color} · {spec} ({barcode})"), - (false, true) => format!("{color} ({barcode})"), - (true, false) => format!("{spec} ({barcode})"), - (true, true) => barcode.to_owned(), - } -} - -pub(super) fn sku_short_label(brief: &Value, barcode: &str) -> String { - let full = sku_display_label(brief, barcode); - full.strip_suffix(&format!(" ({barcode})")).unwrap_or(&full).to_owned() -} - -fn normalized_color_groups(brief: &Value) -> Vec { - let mut groups: Vec = Vec::new(); - let mut seen_barcodes: HashSet = HashSet::new(); - #[cfg(test)] - let image_count_for = |code: &str, asset_ids: Option<&[Value]>| -> usize { - let explicit_ids = asset_ids.map(|arr| arr.len()).unwrap_or(0); - let brief_imgs = brief["images"] - .as_array() - .into_iter() - .flatten() - .filter(|img| img["barcode"] == code) - .count(); - let norm_imgs = brief["normalizedProduct"]["assets"] - .as_array() - .into_iter() - .flatten() - .filter(|asset| asset["barcode"] == code && asset["selectedForProject"] != false) - .count(); - explicit_ids.max(brief_imgs).max(norm_imgs) - }; - - if let Some(np_variants) = brief["normalizedProduct"]["variants"].as_array().filter(|a| !a.is_empty()) { - for variant in np_variants { - let color_name = non_empty_str(&variant["colorName"]).unwrap_or("默认花色").to_owned(); - let id = non_empty_str(&variant["id"]).unwrap_or(&color_name).to_owned(); - let mut skus = Vec::new(); - for row in variant["barcodes"].as_array().into_iter().flatten() { - let Some(code) = non_empty_str(&row["barcode"]) else { continue }; - if !seen_barcodes.insert(code.to_owned()) { - continue; - } - skus.push(NormalizedSkuRow { - barcode: code.to_owned(), - #[cfg(test)] - color_name: color_name.clone(), - #[cfg(test)] - spec: non_empty_str(&row["spec"]) - .or_else(|| non_empty_str(&row["skuName"])) - .filter(|spec| !spec.eq_ignore_ascii_case(&color_name)) - .unwrap_or("") - .to_owned(), - #[cfg(test)] - dimensions_display: non_empty_str(&row["dimensions"]["display"]) - .map(str::to_owned) - .or_else(|| dimension_text(&row["dimensions"])), - #[cfg(test)] - image_count: image_count_for(code, row["imageIds"].as_array().map(Vec::as_slice)), - }); - } - if !skus.is_empty() { - groups.push(NormalizedColorGroup { id, color_name, skus }); - } - } - } - - // Merge any manual / legacy barcodeBindings not yet covered by normalizedProduct.variants. - let variants = brief_variants(brief); - let mut binding_groups: Vec<(String, String)> = variants - .iter() - .filter_map(|v| Some((v["id"].as_str()?.to_owned(), v["name"].as_str().unwrap_or("默认花色").to_owned()))) - .collect(); - if binding_groups.is_empty() || binding_barcodes(&brief["barcodeBindings"]["default"]).next().is_some() { - binding_groups.insert(0, ("default".into(), "默认花色".into())); - } - for (group_id, group_label) in binding_groups { - let codes: Vec = binding_barcodes(&brief["barcodeBindings"][&group_id]) - .filter(|code| seen_barcodes.insert((*code).to_owned())) - .map(str::to_owned) - .collect(); - for code in codes { - let pf = &brief["platformFacts"]["barcodes"][&code]; - let color_name = non_empty_str(&pf["colorName"]) - .map(str::to_owned) - .unwrap_or_else(|| group_label.clone()); - let row = NormalizedSkuRow { - #[cfg(test)] - color_name: color_name.clone(), - #[cfg(test)] - spec: non_empty_str(&pf["spec"]) - .or_else(|| non_empty_str(&pf["sizeText"])) - .filter(|spec| !spec.eq_ignore_ascii_case(&color_name)) - .unwrap_or("") - .to_owned(), - #[cfg(test)] - dimensions_display: dimension_text(&pf["dimensions"]), - #[cfg(test)] - image_count: image_count_for(&code, None), - barcode: code, - }; - if let Some(existing) = groups.iter_mut().find(|g| g.color_name == color_name) { - existing.skus.push(row); - } else { - groups.push(NormalizedColorGroup { - id: if group_id == "default" { color_name.clone() } else { group_id.clone() }, - color_name, - skus: vec![row], - }); - } - } - } - groups -} - -pub(super) fn selected_output_scopes(brief: &Value) -> Vec { - if let Some(arr) = brief["outputScopes"].as_array() { - let items: Vec = arr - .iter() - .filter_map(Value::as_str) - .filter(|s| matches!(*s, "detail" | "main_images" | "sku_images")) - .map(str::to_owned) - .collect(); - if !items.is_empty() { - return items; - } - } - vec!["detail".into(), "main_images".into(), "sku_images".into()] -} - -pub(super) fn selected_visual_asset_count(brief: &Value) -> usize { - let mut sources = HashSet::new(); - let mut count = 0usize; - for (image, _) in image_rows(brief) { - if let Some(src) = non_empty_str(&image["source"]) { - if sources.insert(src.to_owned()) { - count += 1; - } - } else { - count += 1; - } - } - for asset in brief["normalizedProduct"]["assets"].as_array().into_iter().flatten() { - if asset["selectedForProject"] == false { - continue; - } - if let Some(src) = non_empty_str(&asset["localSource"]).or_else(|| non_empty_str(&asset["url"])).or_else(|| non_empty_str(&asset["id"])) { - if sources.insert(src.to_owned()) { - count += 1; - } - } - } - count -} - -fn has_selected_product_image(brief: &Value) -> bool { - selected_product_image(brief, |_| true) -} - -fn selected_product_image(brief: &Value, local_exists: impl Fn(&str) -> bool) -> bool { - let mut platform_assets = brief["normalizedProduct"]["assets"].as_array().into_iter().flatten(); - let local_ok = reference_images(brief).any(|image| { - image["purpose"] == "product" && (image["barcode"].is_null() || image["barcode"] == brief["detailBarcode"]) - && non_empty_str(&image["source"]).is_some_and(&local_exists) - && !(image["platformImage"] == true && platform_assets.clone().any(|asset| { - asset["localSource"] == image["source"] && asset["selectedForProject"] == false - })) - }); - if local_ok || brief["barcodeEntries"].as_array().into_iter().flatten().any(|row| { - (brief["detailBarcode"].is_null() || row["barcode"] == brief["detailBarcode"]) - && row["images"].as_array().into_iter().flatten().any(|image| { - image["purpose"] == "product" && non_empty_str(&image["source"]).is_some_and(&local_exists) - }) - }) { - return true; - } - platform_assets.any(|asset| { - asset["selectedForProject"] != false - && matches!(asset["kind"].as_str(), Some("whiteBackground" | "main")) - && (asset["barcode"].is_null() - || non_empty_str(&asset["barcode"]).is_none() - || asset["barcode"] == brief["detailBarcode"]) - && (non_empty_str(&asset["localSource"]).is_some_and(&local_exists) || non_empty_str(&asset["url"]).is_some()) - }) -} - -fn reference_images(brief: &Value) -> impl Iterator { - brief["images"].as_array().into_iter().flatten().chain( - brief["variants"].as_array().into_iter().flatten() - .flat_map(|variant| variant["images"].as_array().into_iter().flatten()), - ) -} - -/// The canvas may save a form snapshot before the initial creation read returns revision zero. -pub fn saved_creation_draft_brief<'a>(record: &Value, draft: &'a Value) -> Option<&'a Value> { - (draft["brief"].is_object() - && (draft["revision"] == record["revision"] || draft["revision"].is_null() && record["revision"] == 0)) - .then_some(&draft["brief"]) -} - -/// Use the same required fields as the wizard when classifying a saved brief. -pub fn incomplete_brief_stage(brief: &Value, workflow: &Value, local_exists: impl Fn(&str) -> bool) -> Option { - if workflow["canvasFirst"] == true { - return None; - } - let template = selected_template(brief, workflow, brief); - let has_template = template_identity(&template); - let has_source = reference_images(brief).any(|image| non_empty_str(&image["source"]).is_some_and(&local_exists)) - || ["normalizedProduct", "platformFacts"].into_iter().any(|key| { - brief[key].as_object().is_some_and(|fields| !fields.is_empty()) - }) - || (brief["source"] == "library" && non_empty_str(&brief["name"]).is_some() - && non_empty_str(&brief["identifier"]).is_some()); - if !has_template && !has_source { - return Some(CreationStage::Source); - } - let readiness = brief_readiness_with_images(brief, &template, selected_product_image(brief, local_exists)); - if readiness.iter().any(|item| !item.ready && matches!(item.field_key.as_str(), "brand" | "category" | "template")) { - Some(CreationStage::Template) - } else { - readiness.iter().any(|item| !item.ready).then_some(CreationStage::Details) - } -} - -fn intake_value_filled(field: &Value, value: &Value) -> bool { - match field["type"].as_str() { - Some("boolean") => value.is_boolean(), - Some("number") => value.is_number() || value.as_str().is_some_and(|s| !s.trim().is_empty()), - _ => value.as_str().is_some_and(|s| !s.trim().is_empty()), - } -} - -pub(super) fn brief_readiness(brief: &Value, template: &Value) -> Vec { - brief_readiness_with_images(brief, template, has_selected_product_image(brief)) -} - -fn brief_readiness_with_images(brief: &Value, template: &Value, product_image_ready: bool) -> Vec { - let filled = |field: &str| brief[field].as_str().is_some_and(|value| !value.trim().is_empty()); - let mut items = vec![ - ReadinessItem { field_key: "brand".into(), label: "品牌".into(), message: "请选择品牌".into(), ready: filled("brandId") }, - ReadinessItem { field_key: "category".into(), label: "品类".into(), message: "请选择品类".into(), ready: filled("categoryId") }, - ReadinessItem { field_key: "template".into(), label: "模板".into(), message: "请选择项目模板".into(), ready: template_identity(template) }, - ReadinessItem { field_key: "name".into(), label: "产品名称".into(), message: "请输入产品名称".into(), ready: filled("name") }, - ReadinessItem { field_key: "images".into(), label: "产品图".into(), message: "添加或勾选至少一张商品主体图".into(), ready: product_image_ready }, - ]; - if project_barcodes(brief).next().is_some() { - items.push(ReadinessItem { - field_key: "identifier".into(), - label: "SPU 型号".into(), - message: "请填写 SPU 型号".into(), - ready: filled(spu_field(brief)), - }); - } - if project_barcodes(brief).nth(1).is_some() { - let ready = brief["detailBarcode"].as_str().is_some_and(|selected| project_barcodes(brief).any(|code| code == selected)); - items.push(ReadinessItem { - field_key: "detail-barcode".into(), - label: "详情主款".into(), - message: "请选择一个款式条码作为详情主款".into(), - ready, - }); - } - if brief["intake"]["schema"]["version"] == 1 { - let product_values = &brief["intake"]["productValues"]; - for field in brief["intake"]["schema"]["productFields"].as_array().into_iter().flatten() { - if field["required"] == true && field_kind(field) != "image" && !is_product_name_field(field) { - let Some(id) = field["id"].as_str().filter(|id| !id.trim().is_empty()) else { continue }; - let label = field["label"].as_str().unwrap_or(id); - items.push(ReadinessItem { - field_key: format!("intake-product:{id}"), - label: label.to_owned(), - message: format!("请填写必填字段「{label}」"), - ready: intake_value_filled(field, &product_values[id]), - }); - } - } - let active_code = brief["detailBarcode"].as_str().or_else(|| project_barcodes(brief).next()); - if let Some(code) = active_code { - let barcode_values = &brief["intake"]["barcodeValues"][code]; - for field in brief["intake"]["schema"]["barcodeFields"].as_array().into_iter().flatten() { - if field["required"] == true && field_kind(field) != "image" { - let Some(id) = field["id"].as_str().filter(|id| !id.trim().is_empty()) else { continue }; - let label = field["label"].as_str().unwrap_or(id); - items.push(ReadinessItem { - field_key: format!("intake-barcode:{code}:{id}"), - label: label.to_owned(), - message: format!("请填写主款必填字段「{label}」"), - ready: intake_value_filled(field, &barcode_values[id]), - }); - } - } - } - } - items -} - -fn merge_dimensions(current: &Value, incoming: &Value, cleared: impl Fn(&str) -> bool) -> Value { - let mut merged = incoming.clone(); - if !current.is_object() { return merged; } - let axes = ["length", "width", "height", "depth", "secondaryHeight"]; - let keep_unit = cleared("unit") || axes.iter().any(|axis| non_empty_str(¤t[*axis]).is_some() - || current[*axis].is_number()); - let mm = |unit: &Value| match unit.as_str() { - Some("m" | "米") => 1000.0, Some("cm" | "厘米") => 10.0, _ => 1.0, - }; - if keep_unit { - let scale = mm(&incoming["unit"]) / mm(¤t["unit"]); - if scale != 1.0 { - for axis in axes { - if let Some(value) = incoming[axis].as_f64().or_else(|| incoming[axis].as_str()?.parse().ok()) { - merged[axis] = json!(((value * scale * 1000.0).round() / 1000.0).to_string()); - } - } - } - merged["unit"] = current["unit"].clone(); - } - for axis in axes { - let value = ¤t[axis]; - if non_empty_str(value).is_some() || value.is_number() || cleared(axis) { - merged[axis] = value.clone(); - } - } - merged -} - -pub(super) fn merge_platform_brief_preserving_manual_edits(current: &Value, incoming: &Value, edited: &HashSet) -> (Value, usize) { - let mut merged = incoming.clone(); - let mut preserved = 0; - for (key, fields) in [ - ("name", &["name"][..]), ("note", &["note"][..]), - ("brand", &["brandId", "brandName"][..]), ("category", &["categoryId", "categoryName"][..]), - ("outputScopes", &["outputScopes"][..]), - ] { - if edited.contains(key) || fields.iter().any(|field| non_empty_str(¤t[*field]).is_some()) { - for field in fields { - if let Some(value) = current.get(field) { merged[*field] = value.clone(); } - } - preserved += usize::from(edited.contains(key)); - } - } - if edited.contains("dimensions") { - preserved += 1; - } - if incoming["dimensions"].is_object() { - merged["dimensions"] = merge_dimensions(¤t["dimensions"], &incoming["dimensions"], - |axis| edited.contains("dimensions") || edited.contains(&format!("dimensions:{axis}"))); - } - - if merged["intake"]["schema"]["version"] == 1 && merged["intake"]["templateId"] == current["intake"]["templateId"] { - for (field, value) in current["intake"]["productValues"].as_object().into_iter().flatten() { - merged["intake"]["productValues"][field] = value.clone(); - preserved += usize::from(edited.contains(&format!("intake-product:{field}"))); - } - for (code, row) in current["intake"]["barcodeValues"].as_object().into_iter().flatten() { - for (field, value) in row.as_object().into_iter().flatten() { - merged["intake"]["barcodeValues"][code][field] = value.clone(); - preserved += usize::from(edited.contains(&format!("intake-barcode:{code}:{field}"))); - } - } - } - (merged, preserved) -} - -fn merge_platform_barcode_cards(current: &Value, brief: &mut Value, edited: &HashSet) { - if let Some(fields) = brief.as_object_mut() { fields.remove("barcodeEntries"); } - wizard::ensure_default_barcode(brief); - let mut old = current.clone(); - wizard::ensure_default_barcode(&mut old); - let mut rows = old["barcodeEntries"].as_array().cloned().unwrap_or_default(); - if current["barcodeEntries"].is_null() { rows.retain(|row| non_empty_str(&row["barcode"]).is_some()); } - for incoming in brief["barcodeEntries"].as_array().into_iter().flatten() { - let Some(code) = non_empty_str(&incoming["barcode"]) else { continue; }; - if let Some(row) = rows.iter_mut().find(|row| row["barcode"] == code) { - let id = row["id"].as_str().unwrap_or("").to_owned(); - row["dimensions"] = merge_dimensions(&row["dimensions"], &incoming["dimensions"], - |axis| edited.contains(&format!("barcode-card:{id}:dimensions.{axis}"))); - for field in ["material", "boardType", "colorName", "specId", "specName", "spec", "skuName", "variantName"] { - if non_empty_str(&row[field]).is_none() && !edited.contains(&format!("barcode-card:{id}:{field}")) - && let Some(value) = incoming.get(field) - { - row[field] = value.clone(); - } - } - if row["variantId"].is_null() { row["variantId"] = incoming["variantId"].clone(); } - } else if !edited.contains(&format!("removed-barcode:{code}")) { - rows.push(incoming.clone()); - } - } - if rows.is_empty() && current["barcodeEntries"].is_null() { - return; - } - let mut variants = brief_variants(brief); - for variant in brief_variants(current) { - if let Some(fresh) = variants.iter_mut().find(|row| row["id"] == variant["id"]) { - if variant["images"].as_array().is_some_and(|images| !images.is_empty()) { - fresh["images"] = variant["images"].clone(); - } - } else if rows.iter().any(|row| row["variantId"] == variant["id"]) { - variants.push(variant); - } - } - set_brief_variants(brief, variants); - let dimensions = brief["dimensions"].clone(); - write_legacy_barcode_fields(brief, &mut rows, &Value::Null); - brief["dimensions"] = dimensions; - brief["barcodeEntries"] = json!(rows); - update_detail_barcode(brief); -} - -fn canvas_entry_missing(brief: &Value, template: &Value) -> Vec<&'static str> { - let filled = |field: &str| brief[field].as_str().is_some_and(|value| !value.trim().is_empty()); - [ - (filled("brandId"), "品牌"), - (filled("categoryId"), "品类"), - (template_identity(template), "模板"), - (filled("name"), "产品名称"), - (has_selected_product_image(brief), "产品图"), - (project_barcodes(brief).next().is_none() || filled(spu_field(brief)), "SPU 型号"), - (project_barcodes(brief).nth(1).is_none() || - brief["detailBarcode"].as_str().is_some_and(|selected| project_barcodes(brief).any(|code| code == selected)), "详情页出图条码"), - ] - .into_iter() - .filter_map(|(present, label)| (!present).then_some(label)) - .collect() -} - -fn edit(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &mut Value, width: f32, multiline: bool, name: &str) -> bool { - edit_named(ui, id, value, width, multiline, "", name) -} - -#[derive(Clone, Default)] -struct MaterialSearchPending { query: String, changed_at: f64, pending: bool } - -fn material_search_due(state: &mut MaterialSearchPending, query: &str, changed: bool, enter: bool, now: f64) -> bool { - if changed { - state.query = query.to_owned(); - state.changed_at = now; - state.pending = true; - } - if enter || (state.pending && (query.is_empty() || now - state.changed_at >= 0.3)) { - state.pending = false; - return true; - } - false -} - -#[cfg(test)] -fn edit_hint(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &mut Value, width: f32, multiline: bool, hint: &str) -> bool { - edit_named(ui, id, value, width, multiline, hint, hint) -} - -fn edit_named(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &mut Value, width: f32, multiline: bool, hint: &str, name: &str) -> bool { - edit_named_with_error(ui, id, value, width, multiline, hint, name, None, false).0 -} - -fn edit_named_with_error( - ui: &mut Ui, - id: impl std::hash::Hash + std::fmt::Debug, - value: &mut Value, - width: f32, - multiline: bool, - hint: &str, - name: &str, - error: Option<&str>, - focus_and_scroll: bool, -) -> (bool, egui::Response) { - let mut text = match value { - Value::String(text) => text.clone(), - Value::Number(number) => number.to_string(), - _ => String::new(), - }; - let hint = egui::RichText::new(hint).color(Tokens::get(ui.ctx()).agent().text_dim); - let mut field = stitch_ui::text_input(&mut text, "", multiline).hint_text(hint); - if multiline { - field = field.desired_rows(3); - } - let response = form_editor_with_error(ui, id, field, width, name, error); - if focus_and_scroll { - response.scroll_to_me(Some(egui::Align::Center)); - response.request_focus(); - } - let changed = response.changed(); - if changed { *value = json!(text); } - (changed, response) -} - -fn form_editor_with_error( - ui: &mut Ui, - id: impl std::hash::Hash + std::fmt::Debug, - field: egui::TextEdit<'_>, - width: f32, - name: &str, - error: Option<&str>, -) -> egui::Response { - // Halo Field consumes 10pt inner margin plus its 1pt stroke on each side. - let content_width = (width - 22.0).max(0.0); - let editor = creation_editor_id(ui, id); - let field = field.desired_width(content_width).id(editor).frame(egui::Frame::NONE); - let reduced = ui.style().animation_time == 0.0; - stitch_ui::halo_field(ui, editor.with("halo"), error, reduced, |ui| ui.add(field).accessible_name(name)) -} - -pub(super) fn creation_editor_id(ui: &Ui, id: impl std::hash::Hash + std::fmt::Debug) -> egui::Id { - let editor = egui::Id::unique("creation-field").with(id).with("editor"); - ui.data_mut(|data| data.get_temp_mut_or_default::>(egui::Id::unique("creation-active-editors")).push(editor)); - editor -} - -fn field_group(ui: &mut Ui, width: f32, label: &str, contents: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse { - ui.vertical(|ui| { - ui.set_width(width); - ui.spacing_mut().item_spacing.y = space::XS + space::XXS; - ui.label(egui::RichText::new(label).font(Type::Meta.font_id()).color(Tokens::get(ui.ctx()).agent().text_dim)); - contents(ui) - }) -} - -fn intake_columns(width: f32) -> usize { - if width >= 420.0 { 3 } else if width >= 152.0 { 2 } else { 1 } -} - -fn product_intake_columns(width: f32) -> usize { - if width >= 560.0 { 2 } else { 1 } -} - -fn is_product_name_field(field: &Value) -> bool { - field["type"] == "text" - && field["label"].as_str().is_some_and(|label| { - matches!(label.trim().trim_end_matches(['*', '*']).trim(), "产品名称" | "产品名" | "商品名称" | "商品名") - }) -} - -fn intake_multiline(field: &Value) -> bool { - field["type"] == "text" && field["multiline"].as_bool().unwrap_or_else(|| { - matches!(field["label"].as_str().map(str::trim), - Some("核心卖点" | "产品卖点" | "卖点描述" | "注意事项" | "产品描述" | "产品介绍" | "使用说明")) - }) -} - -fn intake_hint(field: &Value) -> &str { - ["placeholder", "hint", "example", "promptHint", "description", "help"].into_iter() - .filter_map(|key| non_empty_str(&field[key])) - .find(|hint| *hint != "按本款确认资料填写;尺寸注明单位,暂无资料可留空。") - .unwrap_or(match field_kind(field).as_str() { - Some("number") => "数字", - Some("select") => "请选择", - Some("image") => "拖放图片或点击选择", - _ => "", - }) -} - -fn reveal_template_intake(ui: &mut Ui, id: egui::Id, open: bool, reduced: bool, contents: impl FnOnce(&mut Ui)) { - let height_id = id.with("intake-height"); - stitch_ui::morph_surface(ui, id, open, reduced, |ui| { - if open { - contents(ui); - let height = ui.min_rect().height(); - ui.data_mut(|data| data.insert_temp(height_id, height)); - } else if let Some(height) = ui.data(|data| data.get_temp::(height_id)) { - // Field definitions can disappear when a template is cleared. Keep - // the measured space while it collapses without mounting stale fields. - ui.add_space(height); - } - }); -} - -#[derive(Clone, Copy)] -enum IntakeScope { - Product, - Barcode, -} - -#[cfg(test)] -fn intake_fields(ui: &mut Ui, scope: egui::Id, width: f32, fields: &[&Value], kind: IntakeScope, values: &mut Value, reduced: bool) -> bool { - let mut errors = HashMap::new(); - let mut scroll = None; - let mut edited = HashSet::new(); - intake_fields_with_errors(ui, scope, width, fields, kind, values, reduced, None, &mut errors, &mut scroll, &mut edited) -} - -#[allow(clippy::too_many_arguments)] -fn intake_fields_with_errors( - ui: &mut Ui, - scope: egui::Id, - width: f32, - fields: &[&Value], - kind: IntakeScope, - values: &mut Value, - reduced: bool, - barcode: Option<&str>, - inline_errors: &mut HashMap, - scroll_to_field: &mut Option, - manual_edited: &mut HashSet, -) -> bool { - let (columns, gap) = match kind { - IntakeScope::Product => (product_intake_columns(width), space::MD), - IntakeScope::Barcode => (intake_columns(width), space::SM), - }; - let spans_row = |field: &Value| match kind { - IntakeScope::Product => intake_multiline(field), - IntakeScope::Barcode => !matches!(field["type"].as_str(), Some("number" | "select" | "boolean")), - }; - let column_width = (width - gap * (columns - 1) as f32) / columns as f32; - let mut changed = false; - ui.scope(|ui| { - ui.spacing_mut().item_spacing.y = space::MD; - let mut remaining = fields; - while let Some((first, _)) = remaining.split_first() { - let full_width = spans_row(first); - let count = if full_width { 1 } else { - remaining.iter().take(columns).take_while(|field| !spans_row(field)).count() - }; - let (row, rest) = remaining.split_at(count); - let field_width = if full_width { width } else { column_width }; - ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = gap; - let label_height = row.iter().map(|field| ui.painter().layout( - intake_label(field), Type::Meta.font_id(), Tokens::get(ui.ctx()).agent().text_dim, field_width, - ).size().y).fold(0.0_f32, f32::max); - for field in row { - let raw_hint = intake_hint(field); - let fallback; - let effective_hint = if !raw_hint.is_empty() { - raw_hint - } else { - let clean_label = field["label"].as_str().unwrap_or("").trim().trim_end_matches(['*', '*']).trim(); - fallback = match clean_label { - "" => String::new(), - "核心卖点" => "输入核心卖点、材质亮点或使用场景优势".to_owned(), - "注意事项" => "输入安装、保养或画面避坑注意事项(选填)".to_owned(), - other if field["required"] == true => format!("输入{other}"), - other => format!("输入{other}(选填)"), - }; - fallback.as_str() - }; - changed |= intake_field( - ui, scope, field_width, label_height, field, effective_hint, - values, reduced, barcode, inline_errors, scroll_to_field, manual_edited, - ); - } - }); - remaining = rest; - } - }); - changed -} - -fn intake_label(field: &Value) -> String { - let name = field["label"].as_str().or(field["id"].as_str()).unwrap_or("未命名字段"); - format!("{}{}{}", name, - field["unit"].as_str().map(|unit| format!(" ({unit})")).unwrap_or_default(), - if field["required"] == true { " *" } else { "" }) -} - -#[allow(clippy::too_many_arguments)] -fn intake_field( - ui: &mut Ui, - scope: egui::Id, - width: f32, - label_height: f32, - field: &Value, - hint: &str, - values: &mut Value, - reduced: bool, - barcode: Option<&str>, - inline_errors: &mut HashMap, - scroll_to_field: &mut Option, - manual_edited: &mut HashSet, -) -> bool { - let label = intake_label(field); - let Some(id) = field["id"].as_str().filter(|id| !id.trim().is_empty()) else { - stitch_ui::status_label(ui, &format!("{label}缺少字段编号"), stitch_ui::StatusTone::Warning); - return false; - }; - let error_key = match barcode { - Some(code) => format!("intake-barcode:{code}:{id}"), - None => format!("intake-product:{id}"), - }; - let field_error = inline_errors.get(&error_key).cloned(); - let should_scroll = scroll_to_field.as_deref() == Some(error_key.as_str()); - if should_scroll { - *scroll_to_field = None; - } - let mut changed = false; - ui.vertical(|ui| { - ui.set_width(width); - ui.spacing_mut().item_spacing.y = space::XS + space::XXS; - let text_dim = Tokens::get(ui.ctx()).agent().text_dim; - ui.allocate_ui(vec2(width, label_height), |ui| { - ui.set_min_height(label_height); - ui.add(egui::Label::new(egui::RichText::new(&label).font(Type::Meta.font_id()).color(text_dim)).wrap()); - }); - match field["type"].as_str() { - Some("text" | "number") => { - let mut value = values[id].clone(); - let (edited, _) = edit_named_with_error( - ui, scope.with(id), &mut value, width, intake_multiline(field), hint, &label, - field_error.as_deref(), should_scroll, - ); - if edited { - values[id] = value; - changed = true; - } - } - Some("select") => { - let selected = values[id].as_str().filter(|value| !value.is_empty()).map(str::to_owned); - let response = stitch_ui::halo_select_hint(ui, scope.with(id), width, selected.as_deref(), hint, reduced, |ui| { - for option in field["options"].as_array().into_iter().flatten().filter_map(Value::as_str) { - if stitch_ui::select_option_sized(ui, option, values[id] == option, true, vec2(ui.available_width(), control::STANDARD)).clicked() { - values[id] = json!(option); - changed = true; - ui.close(); - } - } - }); - let resp = response.response.accessible_name(&label); - if should_scroll { - resp.scroll_to_me(Some(egui::Align::Center)); - resp.request_focus(); - } - if let Some(err) = field_error.as_deref() { - stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error); - } - } - Some("boolean") => { - let value = values[id] == true; - let resp = stitch_ui::toggle_option_sized(ui, "是", value, true, vec2(width, control::STANDARD)).accessible_name(&label); - if should_scroll { - resp.scroll_to_me(Some(egui::Align::Center)); - resp.request_focus(); - } - if resp.clicked() { - values[id] = json!(!value); - changed = true; - } - } - _ => { - let kind = field["type"].as_str().unwrap_or("未指定"); - stitch_ui::status_label(ui, &format!("暂不支持此字段类型({kind})"), stitch_ui::StatusTone::Warning); - } - } - }); - if changed { - inline_errors.remove(&error_key); - manual_edited.insert(error_key); - } - changed -} - -fn spu_field(brief: &Value) -> &'static str { - if brief["identifierType"] == "spu" { "identifier" } else { "deliverySpu" } -} - -fn field_kind(field: &Value) -> &Value { field.get("type").unwrap_or(&field["kind"]) } - -fn field_key(field: &Value) -> &Value { field.get("id").unwrap_or(&field["key"]) } - -fn image_slot(template: &Value, field: &Value, barcode: Option<&str>) -> Value { - json!({"templateId":template,"fieldKey":field_key(field),"barcode":barcode, - "imageRole":field["imageRole"].as_str().or_else(|| field_key(field).as_str()), - "multiple":field["multiple"] != false, - "purpose":if field["imageRole"].as_str().is_none_or(|role| matches!(role, "product" | "detail")) { "product" } else { "scene" }}) -} - -fn current_image_slot(brief: &Value, slot: &Value) -> bool { - let intake = &brief["intake"]; - let barcode = slot["barcode"].as_str(); - if slot["scope"] == "barcode" { - return barcode.is_some_and(|barcode| project_barcodes(brief).any(|code| code == barcode)); - } - let scope = if barcode.is_some() { "barcodeFields" } else { "productFields" }; - barcode.is_none_or(|barcode| project_barcodes(brief).any(|code| code == barcode)) - && intake["schema"][scope].as_array().into_iter().flatten().any(|field| - field_kind(field) == "image" && image_slot(&intake["templateId"], field, barcode) == *slot) -} - -fn in_image_slot(image: &Value, slot: &Value) -> bool { - image["barcode"] == slot["barcode"] - && (slot["scope"] == "barcode" || (image["fieldKey"] == slot["fieldKey"] && image["templateId"] == slot["templateId"])) -} - -fn uses_template_images(brief: &Value) -> bool { - ["productFields", "barcodeFields"].into_iter().any(|scope| - brief["intake"]["schema"][scope].as_array().into_iter().flatten().any(|field| field_kind(field) == "image")) -} - -fn assign_platform_images(brief: &mut Value) { - let intake = brief["intake"].clone(); - if let Some(images) = brief["images"].as_array_mut() { - for image in images.iter_mut().filter(|image| image["platformImage"] == true) { - let scope = if image["barcode"].is_string() { "barcodeFields" } else { "productFields" }; - if let Some(field) = intake["schema"][scope].as_array().into_iter().flatten().find(|field| - field_kind(field) == "image" && field["imageRole"] == "product" && field["multiple"] != false) { - image["fieldKey"] = field_key(field).clone(); - image["templateId"] = intake["templateId"].clone(); - } else if let Some(row) = image.as_object_mut() { - row.remove("fieldKey"); - row.remove("templateId"); - } - } - } -} - -fn add_slot_images(brief: &mut Value, slot: &Value, images: &[Value]) -> Result<(), String> { - if !current_image_slot(brief, slot) { - return Err("图片框已变化,请重新选择".into()); - } - let mut current = brief["images"].as_array().cloned().unwrap_or_default(); - if slot["multiple"] == false { - current.retain(|image| !in_image_slot(image, slot)); - } - for mut image in images.iter().take(if slot["multiple"] == false { 1 } else { 8 }).cloned() { - if current.iter().any(|row| in_image_slot(row, slot) && row["source"] == image["source"]) { continue; } - for key in ["fieldKey","templateId","imageRole","barcode"] { - if !slot[key].is_null() { image[key] = slot[key].clone(); } - } - image["purpose"] = slot["purpose"].clone(); - current.push(image); - } - if current.len() > 8 { return Err("共用及条码图片最多 8 张,请先删除不用的图片".into()); } - brief["images"] = json!(current); - if let Some(code) = slot["barcode"].as_str() - && let Some(row) = brief["barcodeEntries"].as_array_mut().into_iter().flatten() - .find(|row| row["barcode"] == code) - { - let mut pictures = row["images"].as_array().cloned().unwrap_or_default(); - if slot["multiple"] == false { pictures.retain(|image| !in_image_slot(image, slot)); } - for image in current.into_iter().filter(|image| in_image_slot(image, slot)) { - if !pictures.contains(&image) { pictures.push(image); } - } - row["images"] = json!(pictures); - } - Ok(()) -} - -fn field_fact(field: &Value, facts: &Value) -> Option { - let lookup = |name: &str| -> Option { - let alias = match name { - "颜色" | "花色" | "color" => "colorName", - "商品名" | "产品名称" | "name" => "productName", - "条码" | "商品条码" => "barcode", - "SKU 编号" | "SKU编码" => "skuCode", - "规格" | "规格型号" => "spec", - "尺寸" | "产品尺寸" | "size" => "sizeText", - "材质" | "主要材质" => "material", - "说明" | "产品说明" | "产品描述" | "描述" => "description", - "卖点" | "产品卖点" => "sellingPoints", - "长" | "长度" => "length", - "宽" | "宽度" => "width", - "高" | "高度" => "height", - "深" | "进深" => "depth", - _ => name, - }; - if matches!(alias, "length" | "width" | "height" | "depth" | "secondaryHeight") { - let dimension = &facts["dimensions"]; - let value = dimension.get(alias).or_else(|| (alias == "width").then(|| dimension.get("depth")).flatten()) - .or_else(|| facts.get(alias))?; - let numeric = value.as_f64().or_else(|| value.as_str()?.parse::().ok())?; - if !field["unit"].is_string() || dimension["unit"] == field["unit"] { - return Some(value.clone()); - } - let millimetres = |unit: &Value| match unit.as_str()? { - "mm" => Some(1.0), "cm" => Some(10.0), "m" => Some(1000.0), _ => None, - }; - let converted = numeric * millimetres(&dimension["unit"])? / millimetres(&field["unit"])?; - return converted.is_finite().then(|| json!(converted)); - } - facts.get(alias).or_else(|| facts["attributes"].get(name)) - .or_else(|| match alias { - "sizeText" => facts.get("spec").or_else(|| facts.get("dimensions")), - "spec" => facts.get("sizeText"), - _ => None, - }).filter(|value| !value.is_null()).cloned() - }; - let key = field_key(field).as_str()?; - let label = field["label"].as_str().unwrap_or(key); - let value = lookup(key).or_else(|| lookup(label))?; - match field_kind(field).as_str()? { - "text" if value.is_number() => Some(json!(value.to_string())), - "text" if value.is_string() => Some(value), - "text" if value.is_array() => Some(json!(value.as_array()?.iter().filter_map(Value::as_str).collect::>().join("\n"))), - "text" if value.is_object() => dimension_text(&value).map(Value::String), - "number" if value.is_number() || value.as_str().is_some_and(|s| s.parse::().is_ok_and(f64::is_finite)) => Some(value), - "select" if field["options"].as_array().is_some_and(|options| options.contains(&value)) => Some(value), - "boolean" if value.is_boolean() => Some(value), - _ => None, - } -} - -fn dimension_text(dimensions: &Value) -> Option { - let axes = [("length", "长"), ("width", "宽"), ("height", "高")].into_iter() - .filter_map(|(axis, label)| dimensions[axis].as_number().map(|value| format!("{label} {value}"))) - .collect::>(); - (!axes.is_empty()).then(|| match dimensions["unit"].as_str() { - Some(unit) => format!("{} {unit}", axes.join(" × ")), - None => axes.join(" × "), - }) -} - -fn fill_platform_intake(brief: &mut Value) { - if brief["intake"]["schema"]["version"] != 1 { return; } - let fill = |fields: &Value, facts: &Value| -> serde_json::Map { - fields.as_array().into_iter().flatten().filter_map(|field| - Some((field_key(field).as_str()?.to_owned(), field_fact(field, facts)?))).collect() - }; - let fill_missing = |answers: &mut Value, values: serde_json::Map| { - for (key, value) in values { - if answers.get(&key).is_none() { answers[&key] = value; } - } - }; - if brief["normalizedProduct"].is_object() { - let np = &brief["normalizedProduct"]; - let mut shared = json!({ - "productName": brief["name"].clone(), - "dimensions": np["specs"]["dimensions"].clone(), - "description": np["copy"]["summary"].clone(), - "sellingPoints": np["copy"]["sellingPoints"].clone(), - }); - let mats = dedupe_strings(string_list(&np["specs"]["materials"])); - if !mats.is_empty() { - shared["material"] = json!(mats.join("、")); - } - let mut attr_map = serde_json::Map::new(); - for attr in np["specs"]["attributes"].as_array().into_iter().flatten() { - if let (Some(k), Some(v)) = (non_empty_str(&attr["label"]).or_else(|| non_empty_str(&attr["key"])), non_empty_str(&attr["value"])) { - attr_map.insert(k.to_owned(), json!(v)); - } - } - shared["attributes"] = Value::Object(attr_map); - let mut barcodes = std::collections::BTreeMap::new(); - for variant in np["variants"].as_array().into_iter().flatten() { - let color = variant["colorName"].clone(); - for row in variant["barcodes"].as_array().into_iter().flatten() { - let Some(code) = non_empty_str(&row["barcode"]) else { continue }; - let mut facts = row.clone(); - facts["barcode"] = json!(code); - facts["colorName"] = color.clone(); - barcodes.insert(code.to_owned(), fill(&brief["intake"]["schema"]["barcodeFields"], &facts)); - } - } - let shared_values = fill(&brief["intake"]["schema"]["productFields"], &shared); - fill_missing(&mut brief["intake"]["productValues"], shared_values); - for (code, values) in barcodes { - fill_missing(&mut brief["intake"]["barcodeValues"][code], values); - } - return; - } - if brief["platformFacts"]["spu"] != brief["identifier"] { return; } - let mut shared = brief["platformFacts"]["shared"].clone(); - if !shared.is_object() { return; } - shared["productName"] = brief["name"].clone(); - let mut barcodes = std::collections::BTreeMap::new(); - if let Some(rows) = brief["platformFacts"]["barcodes"].as_object() { - for (code, row) in rows { - let mut facts = row.clone(); - facts["barcode"] = json!(code); - barcodes.insert(code.clone(), fill(&brief["intake"]["schema"]["barcodeFields"], &facts)); - } - } - let shared_values = fill(&brief["intake"]["schema"]["productFields"], &shared); - fill_missing(&mut brief["intake"]["productValues"], shared_values); - for (code, values) in barcodes { - fill_missing(&mut brief["intake"]["barcodeValues"][code], values); - } -} - -fn set_intake(brief: &mut Value, template_id: &Value, schema: &Value) { - if schema["version"] != 1 { - if let Some(fields) = brief.as_object_mut() { - fields.remove("intake"); - } - } else if brief["intake"]["templateId"] != *template_id || brief["intake"]["schema"]["version"] != 1 { - brief["intake"] = json!({"templateId":template_id,"schema":schema,"productValues":{},"barcodeValues":{}}); - fill_platform_intake(brief); - assign_platform_images(brief); - } else { - wizard::refresh_intake_schema_from_catalog(brief, &json!({"id": template_id, "intake": schema})); - } -} - -const BARCODE_HINT: &str = "如 DNZ030516N717V01"; -const BARCODE_SEPARATORS: [char; 7] = ['\r', '\n', ',', ',', '、', ';', ';']; - -#[cfg(test)] -fn barcode_editor(ui: &mut Ui, id: egui::Id, value: &mut String, width: f32, name: &str) -> egui::Response { - let id = creation_editor_id(ui, id); - use crate::theme::agent_scale::Type; - let font_size = if width >= 128.0 { Type::Meta } else { Type::Caption }.size(); - // A one-row multiline editor preserves embedded line breaks in pasted barcodes. - ui.add(stitch_ui::text_input(value, BARCODE_HINT, true) - .desired_rows(1).lock_focus(false).return_key(None) - .id(id).font(egui::FontId::monospace(font_size)).margin(egui::Margin::symmetric(2, 6)) - .desired_width((width - 4.0).max(1.0))).accessible_name(name) -} - -fn binding_barcodes(binding: &Value) -> impl Iterator { - let legacy = binding.as_str().into_iter().flat_map(|text| text.split(BARCODE_SEPARATORS)); - let current = binding.as_array().into_iter().flatten().filter_map(Value::as_str); - let mut seen = std::collections::HashSet::new(); - legacy.chain(current).map(str::trim) - .filter(move |barcode| !barcode.is_empty() && seen.insert(*barcode)) -} - -fn project_barcodes(brief: &Value) -> impl Iterator { - let has_cards = brief["barcodeEntries"].is_array(); - let from_cards = brief["barcodeEntries"].as_array().into_iter().flatten() - .filter_map(|row| non_empty_str(&row["barcode"])); - let from_bindings = brief["barcodeBindings"].as_object().into_iter().flat_map(|groups| groups.values()).flat_map(binding_barcodes); - let from_normalized = brief["normalizedProduct"]["variants"] - .as_array() - .into_iter() - .flatten() - .flat_map(|variant| variant["barcodes"].as_array().into_iter().flatten()) - .filter_map(|row| non_empty_str(&row["barcode"])); - let mut seen = HashSet::new(); - from_cards.chain(from_bindings.chain(from_normalized).filter(move |_| !has_cards)) - .filter(move |code| seen.insert(*code)) -} - -#[cfg(test)] -fn barcode_issue(brief: &Value, text: &str) -> Option<&'static str> { - let text = text.trim(); - if text.is_empty() { - Some("请输入产品条码") - } else if project_barcodes(brief).any(|barcode| barcode == text) { - Some("此条码已录入当前项目") - } else { - None - } -} - -fn structured_barcode_field(field: &Value) -> bool { - match (field_key(field).as_str(), field_kind(field).as_str()) { - (Some("length" | "width" | "height"), Some("number")) => true, - (Some("colorName" | "material" | "boardType"), Some("text")) => true, - _ => false, - } -} - -fn write_legacy_barcode_fields(brief: &mut Value, rows: &mut [Value], schema: &Value) { - let mut variants = brief_variants(brief); - let mut bindings = serde_json::Map::new(); - let mut owners = std::collections::HashMap::new(); - for row in rows.iter() { - if let Some(owner) = non_empty_str(&row["variantId"]) { - *owners.entry(owner.to_owned()).or_insert(0) += 1; - } - } - for row in rows.iter_mut() { - let Some(code) = non_empty_str(&row["barcode"]).map(str::to_owned) else { continue; }; - let color = non_empty_str(&row["colorName"]); - let matching = variants.iter().find(|variant| color.is_some_and(|color| variant["colorName"] == color || variant["name"] == color)); - let current = variants.iter().position(|variant| variant["id"] == row["variantId"]); - row["variantId"] = if let Some(variant) = matching { - variant["id"].clone() - } else if let Some(index) = current - && let Some(color) = color - && non_empty_str(&variants[index]["colorMaterialId"]).is_none() - && row["variantId"].as_str().and_then(|id| owners.get(id)) == Some(&1) - { - variants[index]["name"] = json!(color); - variants[index]["colorName"] = json!(color); - variants[index]["id"].clone() - } else if let Some(color) = color && variants.len() < 64 { - let id = uuid::Uuid::new_v4().to_string(); - variants.push(json!({"id":id,"name":color,"colorName":color,"colorMaterialId":"","images":[]})); - json!(id) - } else { - current.and_then(|index| variants.get(index)).or_else(|| variants.first()) - .map_or(Value::Null, |variant| variant["id"].clone()) - }; - let owner = row["variantId"].as_str().unwrap_or("default"); - let codes = bindings.entry(owner.to_owned()).or_insert_with(|| json!([])); - codes.as_array_mut().expect("barcode list").push(json!(code)); - - for field in schema.as_array().into_iter().flatten().filter(|field| structured_barcode_field(field)) { - let key = field_key(field).as_str().unwrap(); - let value = if field_kind(field) == "number" { - let mm_factor = |unit: &Value| match unit.as_str() { Some("cm" | "厘米") => 10.0, Some("m" | "米") => 1000.0, _ => 1.0 }; - let ratio = mm_factor(&row["dimensions"]["unit"]) / mm_factor(&field["unit"]); - row["dimensions"][key].as_str().and_then(|text| text.parse::().ok()) - .and_then(|value| serde_json::Number::from_f64(value * ratio)).map_or_else(|| json!(""), Value::Number) - } else { - row.get(key).cloned().unwrap_or_else(|| json!("")) - }; - brief["intake"]["barcodeValues"][&code][key] = value; - } - } - if variants != brief_variants(brief) { set_brief_variants(brief, variants); } - brief["barcodeBindings"] = Value::Object(bindings); - brief["barcodeEntries"] = json!(rows); - update_detail_barcode(brief); - if let Some(row) = rows.iter().find(|row| row["barcode"] == brief["detailBarcode"]).or_else(|| rows.first()) { - brief["dimensions"] = row["dimensions"].clone(); - if let Some(color) = non_empty_str(&row["colorName"]) { - brief["colorName"] = json!(color); - } - } -} - -pub(super) fn wizard_barcode_editor(ui: &mut Ui, id: egui::Id, value: &mut String) -> egui::Response { - stitch_kit::caption(ui, "条码编码"); - let id = creation_editor_id(ui, id); - let reduced = ui.style().animation_time == 0.0; - stitch_ui::halo_field(ui, id.with("halo"), None, reduced, |ui| { - ui.add(stitch_ui::text_input(value, BARCODE_HINT, true).id(id).return_key(None) - .desired_rows(1).font(Type::Body.font_id()).frame(egui::Frame::NONE) - .margin(egui::Margin::ZERO).desired_width(ui.available_width())).accessible_name("条码编码") - }) -} - -fn update_detail_barcode(brief: &mut Value) -> bool { - let selected = brief["detailBarcode"].as_str(); - let next = { - let mut codes = project_barcodes(brief); - let first = codes.next(); - let next = if codes.next().is_none() { - first - } else { - selected.filter(|selected| project_barcodes(brief).any(|code| code == *selected)) - }; - if selected == next { return false; } - next.map(str::to_owned) - }; - if let Some(next) = next { - brief["detailBarcode"] = json!(next); - } else if let Some(fields) = brief.as_object_mut() { - fields.remove("detailBarcode"); - } - true -} - -fn replace_barcode(brief: &mut Value, old: &str, replacement: Option<&str>) { - if brief["detailBarcode"] == old { - if let Some(code) = replacement { - brief["detailBarcode"] = json!(code); - } else if let Some(fields) = brief.as_object_mut() { - fields.remove("detailBarcode"); - } - } - if let Some(images) = brief["images"].as_array_mut() { - if let Some(barcode) = replacement { - for image in images.iter_mut().filter(|image| image["barcode"] == old) { image["barcode"] = json!(barcode); } - } else { - images.retain(|image| image["barcode"] != old); - } - } - if let Some(values) = brief.get_mut("platformFacts").and_then(|facts| facts["barcodes"].as_object_mut()) - && let Some(value) = values.remove(old) && let Some(code) = replacement - { - values.insert(code.to_owned(), value); - } - if let Some(values) = brief.get_mut("intake").and_then(|intake| intake.get_mut("barcodeValues")) - .and_then(Value::as_object_mut) - && let Some(value) = values.remove(old) - && let Some(code) = replacement - { - values.insert(code.to_owned(), value); - } -} - -fn section_heading(ui: &mut Ui, title: &str, description: &str) { - stitch_kit::section_heading(ui, title); - if !description.is_empty() { - ui.add_space(space::XXS); - stitch_kit::caption(ui, description); - } -} - -#[cfg(test)] -fn brief_step(ui: &mut Ui, title: &str, ready: bool, previous_ready: bool) { - let (status, tone) = if ready { ("已就绪", Tone::Success) } - else if previous_ready { ("当前步骤", Tone::Active) } - else { ("待填写", Tone::Quiet) }; - ui.horizontal_wrapped(|ui| { - stitch_kit::section_heading(ui, title); - stitch_kit::label(ui, status, Type::Meta, tone); - }); - ui.add_space(space::SM); -} - -fn section_break(ui: &mut Ui) { - ui.add_space(space::LG); - stitch_ui::divider(ui); - ui.add_space(space::LG); -} -fn brief_section_break(ui: &mut Ui) { - ui.add_space(space::LG); - stitch_ui::divider(ui); - ui.add_space(space::MD); -} -fn form_editable(busy: Option<&str>, unknown: bool) -> bool { - !unknown && (busy.is_none() || matches!(busy, Some("creation-save" | "creation-select" | "creation-plan-edit" | "pi-rules"))) -} -fn bound(w: &Workspace, app: &PhotocraftApp, value: &Value) -> bool { - value["accountId"] == w.account["id"] && value["origin"] == w.origin && value["doc"].as_u64() == app.session.active().map(|s| s.doc.id.0) -} -pub(super) fn allowed(w: &mut Workspace, app: &PhotocraftApp, value: &Value) -> Result { - let run = value["run"].as_str().filter(|s| s.len() == 36).ok_or("生成会话无效")?; - let same = bound(w, app, value) - && value["baseRevision"].as_u64() == Some(w.creation_base_revision) - && w.allow_apply - && !w.unknown - && w.busy.as_deref() == Some("creation-generate") - && app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc && s.revision == w.expected_revision); - if same && w.creation_run.is_none() { - w.creation_run = Some(run.into()); - } - Ok(json!({"allowed":same && w.creation_run.as_deref()==Some(run),"revision":w.expected_revision})) -} -pub(super) fn canvas_received(w: &mut Workspace, app: &mut PhotocraftApp, mut doc: Box, value: Value) { - if !bound(w, app, &value) { - return; - } - let explicit = value["explicit"] == true; - let permitted = w.allow_apply - && app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc && s.revision == w.expected_revision) - && (explicit || (value["baseRevision"].as_u64() == Some(w.creation_base_revision) && value["run"].as_str() == w.creation_run.as_deref())); - if !permitted { - w.creation_pending = Some((doc, value)); - w.creation_progress = "生成结果已保留,点击载入后继续编辑".into(); - return; - } - let Some(id) = app.session.active().map(|s| s.doc.id) else { - return; - }; - doc.id = id; - let label = if explicit { "载入生成结果".into() } else { format!("生成第 {} 屏", value["sequence"].as_u64().unwrap_or(0) + 1) }; - match app.session.edit(&label, move |current, selected| { - *current = *doc; - *selected = None; - Ok(()) - }) { - Ok(()) => { - app.sync_views(); - w.expected_revision = app.session.active().map_or(0, |s| s.revision); - w.creation = value["creation"].clone(); - w.creation_pending = None; - w.creation_open = false; - w.creation_step = 3; - w.library = false; - w.material = false; - w.draft_changed = true; - w.sync_dirty = true; - if explicit { - w.allow_apply = false; - } - } - Err(e) => w.error = e.to_string(), - } -} -pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, value: &Value) { - if bound(w, app, value) { - w.receive_template_snapshot(&value["templateWorkflow"], false); - } - if !bound(w, app, value) { - return; - } - if method == "creation-progress" { - w.creation_progress = value["text"].as_str().unwrap_or("").chars().take(4000).collect(); - return; - } - if method == "creation-product-platform" && value["platformBrief"].is_object() { - w.creation_read_scope(app); - let current = w.brief_with_manual_fields(); - let incoming = &value["platformBrief"]; - let current_spu = non_empty_str(¤t["platformFacts"]["spu"]) - .or_else(|| non_empty_str(¤t["normalizedProduct"]["identity"]["spu"])) - .or_else(|| non_empty_str(¤t[spu_field(¤t)])); - let merge_existing = current_spu.is_none_or(|spu| incoming["identifier"] == spu); - let mut next_brief = incoming.clone(); - let mut preserved = 0; - if merge_existing { - let edited = current["manualFields"].as_array().into_iter().flatten() - .filter_map(Value::as_str).map(str::to_owned).collect(); - (next_brief, preserved) = merge_platform_brief_preserving_manual_edits(¤t, incoming, &edited); - if let Some(markers) = current.get("manualFields") { - next_brief["manualFields"] = markers.clone(); - } - fill_platform_intake(&mut next_brief); - merge_platform_barcode_cards(¤t, &mut next_brief, &edited); - } else { - w.creation_reads.manual_edited_fields.clear(); - fill_platform_intake(&mut next_brief); - } - assign_platform_images(&mut next_brief); - w.creation_brief = next_brief; - w.creation_dirty = true; - w.sync_dirty = true; - w.draft_changed = true; - w.creation_reads.platform_message = value["message"].as_str().unwrap_or("").into(); - w.creation_reads.platform_sync_note = if preserved > 0 { - format!("已重新拉取平台资料,保留了你手动修改的 {preserved} 项字段") - } else { - String::new() - }; - return; - } - if let Some(images) = value["images"].as_array() { - if method == "creation-import" { - w.match_imported_reference_paths(app, images); - } - if value["imageSlot"].is_object() { - match add_slot_images(&mut w.creation_brief, &value["imageSlot"], images) { - Ok(()) => { - w.creation_dirty = true; - w.sync_dirty = true; - } - Err(error) => w.creation_reads.reference_import_error = error, - } - return; - } - let mut current = w.creation_brief["images"].as_array().cloned().unwrap_or_default(); - let references = image_rows(&w.creation_brief); - for image in images { - if !references.iter().any(|(existing, _)| existing["source"] == image["source"]) && !current.iter().any(|v| v["source"] == image["source"]) { - current.push(image.clone()); - } - } - w.creation_brief["images"] = json!(current); - w.creation_dirty = true; - w.sync_dirty = true; - } - if value["creation"].is_object() { - let newer_draft = if matches!(method, "creation-save" | "creation-select" | "creation-plan-edit") { - w.creation_submitted_draft.take().filter(|sent| *sent != w.creation_draft()).map(|_| w.creation_draft()) - } else { None }; - let edited_plan = (w.creation_plan != w.creation["plan"]["screens"]).then(|| w.creation_plan.clone()); - let entries = w.creation_brief.get("barcodeEntries").cloned(); - let same_doc = w.creation_doc == value["doc"].as_u64(); - w.creation = value["creation"].clone(); - if same_doc && w.creation["brief"].is_object() - && w.creation["brief"].get("barcodeEntries").is_none() - && let Some(entries) = entries - { - w.creation["brief"]["barcodeEntries"] = entries; - } - w.creation_doc = value["doc"].as_u64(); - let template_binding = w.template_binding(app.session.active().map(|state| state.doc.id.0)); - w.template_ui.bind_project(&template_binding); - w.creation_read_failed = false; - if !w.creation_dirty || !matches!(method, "creation-read" | "creation-import" | "creation-import-data" | "creation-import-library" | "creation-rules") { - w.creation_brief = w.creation["brief"].clone(); - w.creation_dirty = false; - w.creation_selected = - w.creation["sellingPoints"]["selected"].as_array().map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect()).unwrap_or_default(); - w.creation_direction = w.creation["sellingPoints"]["direction"].as_str().unwrap_or("").into(); - w.creation_plan = w.creation["plan"]["screens"].clone(); - w.creation_width = w.creation["width"].as_u64().unwrap_or_default() as u32; - w.creation_delivery_dir = super::product_production::delivery_dir(&w.creation); - if method == "creation-save" - && let Some(plan) = edited_plan - { - w.creation_plan = plan; - w.creation_dirty = true; - } - } - if let Some(draft) = newer_draft { - w.creation_brief = draft["brief"].clone(); - w.creation_width = draft["width"].as_u64().unwrap_or_default() as u32; - w.creation_delivery_dir = super::product_production::delivery_dir(&draft); - w.creation_plan = draft["screens"].clone(); - w.creation_direction = draft["direction"].as_str().unwrap_or("").into(); - w.creation_selected = draft["selected"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); - w.creation_dirty = true; - } - if method == "creation-read" && w.creation_restore_draft.is_object() { - let draft = std::mem::take(&mut w.creation_restore_draft); - if let Some(brief) = saved_creation_draft_brief(&w.creation, &draft) { - w.creation_brief = brief.clone(); - w.creation_width = draft["width"].as_u64().unwrap_or_default() as u32; - if draft["screens"].is_array() { - w.creation_plan = draft["screens"].clone(); - } - if let Some(direction) = draft["direction"].as_str() { - w.creation_direction = direction.into(); - } - if let Some(selected) = draft["selected"].as_array() { - w.creation_selected = selected.iter().filter_map(Value::as_str).take(20).map(str::to_owned).collect(); - } - w.creation_delivery_dir = super::product_production::delivery_dir(&draft); - w.creation_dirty = w.creation_brief != w.creation["brief"] - || w.creation_plan != w.creation["plan"]["screens"] - || w.creation_direction != w.creation["sellingPoints"]["direction"].as_str().unwrap_or("") - || w.creation_delivery_dir != super::product_production::delivery_dir(&w.creation); - w.restored_creation_signature = w.creation_dirty.then(|| w.creation_draft().to_string()); - } - } - } - if method == "creation-read" && !w.creation_dirty && !w.unknown && w.busy.is_none() && value["pending"] != true - && let Some(revision) = value["resumeMaterialDelivery"].as_u64() - { - w.send("project-sync", json!({"doc":value["doc"],"revision":revision,"status":"completed","resume":true})); - } - if method == "creation-facts" && value["pending"] != true { - w.creation_step = 1; - } - if method == "creation-plan" && value["pending"] != true { - w.creation_step = 2; - } - if value["pending"] == true { - w.unknown = true; - w.creation_progress = "原请求待核查".into(); - } else if method == "creation-recover" { - w.unknown = false; - } - if let Some(message) = value["message"].as_str() { - w.creation_progress = message.into(); - } - if method != "creation-read" { - w.sync_dirty = true; - } - if method == "creation-save" { - let _ = w.tx.send(Request::Action("pi-rules".into(), json!({"doc":value["doc"]}))); - } -} -pub(super) fn sync_received(w: &mut Workspace, app: &PhotocraftApp, value: &Value) { - if !bound(w, app, value) { - return; - } - for key in ["cloudLink", "syncedRevision", "status"] { - if !value[key].is_null() { - w.project_context[key] = value[key].clone(); - } - } - let same = app.session.active().is_some_and(|s| value["revision"].as_u64() == Some(s.revision)); - w.sync_dirty = !(same && value["syncDirty"] != true && w.sync_request_meta == w.sync_signature()); - if let Some(items) = value["projects"].as_array() { - w.merge_project_receipt(app, items); - } - if let Some(id) = value["materialDelivery"]["materialId"].as_str() { - w.project_context["materialDelivery"] = value["materialDelivery"].clone(); - w.note(format!("成品已提交素材库,素材 ID:{id}")); - w.delivery_completion = true; - w.sync_confirm = true; - w.listing_read_at = None; - w.listing_read_error = None; - w.finished_web_error = None; - } - 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) { - if !bound(w, app, value) { - return; - } - w.listing_read_error = value["error"].as_str().map(str::to_owned); - if let Some(receipt) = value["delivery"].as_object() { - if receipt.get("materialId").and_then(Value::as_str).is_none() { - return; - } - let current = &mut w.project_context["materialDelivery"]; - if current["materialId"] != value["delivery"]["materialId"] { - *current = Value::Object(receipt.clone()); - } else if current["state"] != "removed" - && (value["delivery"]["state"] == "removed" - || value["delivery"]["listingStatus"]["sequence"].as_u64() >= current["listingStatus"]["sequence"].as_u64()) - { - current["state"] = value["delivery"]["state"].clone(); - current["listingStatus"] = value["delivery"]["listingStatus"].clone(); - } - } -} - -pub(super) fn finished_web_received(w: &mut Workspace, app: &PhotocraftApp, value: &Value) { - if bound(w, app, value) { - w.finished_web_pending = false; - w.finished_web_error = value["error"].as_str().map(str::to_owned); - } -} - -fn listing_status_text(receipt: &Value) -> (&'static str, stitch_ui::StatusTone) { - use stitch_ui::StatusTone::{Error, Neutral}; - if receipt["state"] == "removed" { - return ("素材已撤回", Neutral); - } - match receipt["listingStatus"]["state"].as_str() { - Some("pending") => ("等待上架", Neutral), - Some("listing") => ("上架中", Neutral), - Some("listed") => ("已上架", Neutral), - Some("failed") => ("上架失败", Error), - _ if receipt["state"] == "completed" => ("暂无上架状态", Neutral), - _ => ("正在查询上架状态", Neutral), - } -} - -// The import worker reports a final receipt rather than intermediate bytes; -// expose activity only and never manufacture an upload percentage. -fn reference_import_activity(busy: Option<&str>) -> Option<&'static str> { - match busy { - Some("creation-import" | "creation-import-data") => Some("正在导入参考图"), - Some("creation-import-library") => Some("正在读取素材库参考图"), - _ => None, - } -} - - impl Workspace { - fn creation_escape(&mut self, app: &PhotocraftApp, ui: &mut Ui) { - let composing_id = egui::Id::unique("creation-ime-composing"); - let ime_events = ui.input(|input| input.events.iter().filter_map(|event| match event { egui::Event::Ime(event) => Some(event.clone()), _ => None }).collect::>()); - let (ime_event, composing) = ui.ctx().data_mut(|data| { - let state = data.get_temp_mut_or_default::(composing_id); - for event in &ime_events { - match event { - egui::ImeEvent::Preedit { text, .. } => *state = !text.is_empty(), - egui::ImeEvent::Commit(_) => *state = false, - _ => {} - } - } - (!ime_events.is_empty(), *state) - }); - let previous_editors = ui.ctx().data_mut(|data| data.remove_temp::>(egui::Id::unique("creation-active-editors"))).unwrap_or_default(); - if !ui.input(|input| input.key_pressed(egui::Key::Escape)) || composing || ime_event || app.file_dialog_open() - || self.sync_confirm || ui.ctx().memory(|memory| memory.top_modal_layer().is_some()) { return; } - if egui::Popup::is_any_open(ui.ctx()) { - if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { - egui::Popup::close_all(ui.ctx()); - // egui clears focused_widget during input preprocessing, even - // when Escape belongs to an overlying popup. Restore the - // underlying editor so this key closes only the popup. - if let Some(id) = previous_editors.iter().copied().find(|id| ui.ctx().memory(|memory| memory.had_focus_last_frame(*id))) { - ui.ctx().memory_mut(|memory| memory.request_focus(id)); - } - } - return; - } - // The workspace settings popup handles Escape before the brief does. - if self.model_settings || self.key_settings { - return; - } - let editor = ui.ctx().memory(|memory| previous_editors.iter().copied().find(|id| memory.has_focus(*id) || memory.had_focus_last_frame(*id))); - if let Some(id) = editor { - if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { - ui.ctx().memory_mut(|memory| memory.surrender_focus(id)); - } - return; - } - if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { - if self.creation_step == 0 && let Some((_, stage)) = self.creation_reads.wizard_stage { - self.handle_wizard_navigation(app, if stage == CreationStage::Source { WizardFooterOutcome::Cancel } else { WizardFooterOutcome::Back }); - return; - } - self.retain_creation_ui_draft(app); - let previous = match self.creation_step { 2 => 1, 1 => 0, _ => 3 }; - self.set_creation_destination(previous); - } - } - fn creation_field_scope(&self, app: &PhotocraftApp) -> egui::Id { - self.creation_field_scope_for(self.creation_doc, app.session.active().map(|s| s.doc.id.0)) - } - fn creation_field_scope_for(&self, creation_doc: Option, active_doc: Option) -> egui::Id { - egui::Id::unique(("creation-fields", &self.origin, self.account["id"].as_str(), creation_doc, active_doc)) - } - pub(super) fn resume_project_brief(&mut self, app: &PhotocraftApp, project: &Value) { - let Some(state) = app.session.active() else { return }; - let Ok(saved_stage) = serde_json::from_value::(project["briefResumeStage"].clone()) else { return }; - if project["briefIncomplete"] != true - || super::canvas_workspace::document_mapping(&state.doc).is_some_and(|mapping| mapping["canvasFirst"] == true) - { - return; - } - let doc = Some(state.doc.id.0); - let dirty_brief = if self.creation_doc == doc && self.creation_dirty { - Some(&self.creation_brief) - } else { - self.current_creation_ui_scope(app).and_then(|scope| self.retained_creation_ui.get(&scope)) - .map(|retained| &retained.draft["brief"]) - }; - let stage = dirty_brief.map_or(saved_stage, |brief| { - incomplete_brief_stage(brief, &Value::Null, |_| true).unwrap_or(CreationStage::Details) - }); - self.creation_reads.staged_new_project = false; - self.creation_reads.staged_prior_draft = None; - self.creation_reads.new_project_doc = None; - self.creation_reads.wizard_stage = Some((self.creation_field_scope_for(doc, doc), stage)); - self.set_creation_destination(0); - } - fn template_binding(&self, doc: Option) -> String { - format!("{}|{}|{:?}", self.account["id"], self.origin, doc) - } - fn brief_with_manual_fields(&self) -> Value { - let mut brief = self.creation_brief.clone(); - if !self.creation_reads.manual_edited_fields.is_empty() { - let mut edited: std::collections::BTreeSet<_> = brief["manualFields"].as_array().into_iter().flatten() - .filter_map(Value::as_str).collect(); - edited.extend(self.creation_reads.manual_edited_fields.iter().map(String::as_str)); - brief["manualFields"] = json!(edited); - } - brief - } - - pub(super) fn creation_draft(&self) -> Value { - if self.creation_reads.staged_new_project - && let Some(draft) = &self.creation_reads.staged_prior_draft - { - return draft.clone(); - } - if self.creation_restore_draft.is_object() { - return self.creation_restore_draft.clone(); - } - let mut draft = json!({"revision":self.creation["revision"],"brief":self.brief_with_manual_fields(),"width":self.creation_draft_width(), - "screens":self.creation_plan,"direction":self.creation_direction,"selected":self.creation_selected}); - if let Some(path) = &self.creation_delivery_dir { - draft["deliveryDir"] = json!(path); - } - draft - } - fn can_save_creation(&self) -> bool { - self.busy.is_none() && (!self.unknown || self.scoped_production_pending()) - } - pub(super) fn creation_autosave(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) { - if self.creation_doc != app.session.active().map(|s| s.doc.id.0) || self.creation_doc.is_none() { - return; - } - let signature = self.creation_draft().to_string(); - if self.restored_creation_signature.as_deref() == Some(signature.as_str()) { - return; - } - if signature != self.creation_edit_signature { - self.creation_edit_signature = signature; - self.creation_touched = Instant::now(); - if self.creation_dirty { - self.draft_changed = true; - self.sync_dirty = true; - } - } - if !self.creation_dirty || !self.can_save_creation() || self.creation_failed_signature == self.creation_edit_signature { - return; - } - if self.creation_touched.elapsed() < Duration::from_millis(900) { - ctx.request_repaint_after(Duration::from_millis(150)); - return; - } - let brief_changed = self.creation_brief != self.creation["brief"] - || self.creation["width"].as_u64() != self.creation_draft_width() - || super::product_production::delivery_dir(&self.creation) != self.creation_delivery_dir; - let plan_changed = self.creation_plan != self.creation["plan"]["screens"]; - let method = if brief_changed { - "creation-save" - } else if plan_changed { - "creation-plan-edit" - } else { - "creation-select" - }; - if method == "creation-save" || !self.unknown { - self.creation_submit(app, method, json!({})); - } - } - pub(super) fn sync_signature(&self) -> String { - 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 self.busy.is_some() || self.saving.is_some() || self.project_operation_pending() { - self.error = "请等待当前操作完成".into(); - return; - } - let Some(st) = app.session.active() else { - self.error = "请先打开项目".into(); - return; - }; - if input["status"] == "completed" && (self.creation_dirty || self.unknown) { - self.error = "请先保存资料与方案,并核查原请求后再完结".into(); - return; - } - input["doc"] = json!(st.doc.id.0); - input["revision"] = json!(st.revision); - if input["status"].is_null() { - input["status"] = json!("draft"); - } - let meta = json!({"composer":self.composer,"messages":self.messages,"project":self.project_context,"syncDirty":self.sync_dirty,"creationDraft":self.creation_draft()}); - self.sync_request_meta = self.sync_signature(); - self.draft_changed = false; - let _ = self.tx.send(Request::Save(st.doc.clone(), st.revision, meta)); - self.saving = Some((st.doc.id.0, st.revision)); - self.send(method, input); - } - 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 delivered = self.project_context["materialDelivery"]["materialId"].is_string() - && self.project_context["status"] == "completed"; - 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.delivery_completion = false; - self.listing_read_at = None; - self.listing_read_error = None; - } - if self.sync_confirm && self.project_context["cloudLink"]["source"] == "desktop" - && let Some(doc) = app.session.active().map(|state| state.doc.id.0) - { - let now = Instant::now(); - if self.listing_read_at.is_none_or(|(last_doc, next)| last_doc != doc || now >= next) { - self.listing_read_at = Some((doc, now + Duration::from_secs(15))); - if self.tx.send(Request::Action("delivery-status".into(), json!({"doc":doc}))).is_err() { - self.listing_read_error = Some("本机服务已停止,请重启后查看".into()); - } - } - ui.ctx().request_repaint_after(Duration::from_secs(15)); - } - let receipt = &self.project_context["materialDelivery"]; - let completion_receipt = self.delivery_completion && receipt["materialId"].is_string(); - let confirming = !delivered && !completion_receipt; - let title = if completion_receipt { - "成品已提交素材库" - } else if delivered { - "上架状态" - } else { - "完结项目" - }; - let mut jump_target: Option = None; - let review_hints = self.collect_delivery_review_hints(ui); - let closed = stitch_ui::dialog(ui, egui::Id::unique("xiaoyi-finish-project"), title, - self.sync_confirm, self.reduce_motion, 380.0, |ui| { - if confirming { - ui.label("将已完成的详情、主图和 SKU 成品提交到素材库?"); - } - if !review_hints.is_empty() { - ui.add_space(space::XS); - stitch_ui::status_label( - ui, - &format!("{} 项人工核对提示(不阻断完结)", review_hints.len()), - stitch_ui::StatusTone::Warning, - ); - egui::CollapsingHeader::new("查看人工核对清单").default_open(true).show(ui, |ui| { - egui::ScrollArea::vertical() - .id_salt("xiaoyi-review-hints-scroll") - .max_height(140.0) - .show(ui, |ui| { - for hint in &review_hints { - ui.horizontal_wrapped(|ui| { - ui.label(&hint.message); - if hint.has_target() - && stitch_ui::action_button(ui, "去核对", stitch_ui::ButtonRole::Quiet, true).clicked() - { - jump_target = Some(hint.clone()); - } - }); - } - }); - }); - } - let receipt = &self.project_context["materialDelivery"]; - if let Some(id) = receipt["materialId"].as_str() { - let (text, tone) = listing_status_text(receipt); - if receipt["state"].is_string() || self.listing_read_error.is_none() { - stitch_ui::status_label(ui, text, tone); - } - if let Some(message) = receipt["listingStatus"]["message"].as_str() - && receipt["listingStatus"]["state"] == "failed" && receipt["state"] != "removed" - { - ui.label(message); - } - ui.label(format!("素材 ID {id}")); - if let Some(listing_id) = receipt["listingStatus"]["listingId"].as_str() - && receipt["listingStatus"]["state"] == "listed" && receipt["state"] != "removed" - { - ui.label(format!("上架编号 {listing_id}")); - } - } - if let Some(error) = &self.listing_read_error { - stitch_ui::status_label(ui, "上架状态刷新失败", stitch_ui::StatusTone::Warning) - .on_hover_text(error); - } - if let Some(error) = &self.finished_web_error - && !confirming - { - stitch_ui::status_label(ui, error, stitch_ui::StatusTone::Error); - } - let target = receipt["materialId"].as_str().filter(|_| !confirming && receipt["state"] != "removed") - .zip(app.session.active().map(|state| state.doc.id.0)) - .map(|(material, doc)| json!({"materialId":material, "doc":doc})); - ui.horizontal_wrapped(|ui| { - if let Some(target) = target { - let label = if self.finished_web_pending { "正在打开…" } else { "打开成品上架工作台" }; - if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Primary, !self.finished_web_pending).clicked() { - self.finished_web_error = None; - match self.tx.send(Request::Action("finished-web-open".into(), target)) { - Ok(()) => self.finished_web_pending = true, - Err(_) => self.finished_web_error = Some("本机服务已停止,请重启后重试".into()), - } - } - } - let dismiss = if confirming { "取消" } else { "关闭" }; - if stitch_ui::action_button(ui, dismiss, stitch_ui::ButtonRole::Secondary, true).clicked() { - self.sync_confirm = false; - } - if confirming && stitch_ui::action_button(ui, "完结并提交", stitch_ui::ButtonRole::Primary, idle).clicked() { - self.sync_confirm = false; - self.sync_action(app, "project-sync", json!({"status":"completed"})); - } - }); - }); - if closed { self.sync_confirm = false; } - if let Some(target) = jump_target { - self.jump_to_review_hint(app, &target); - } - } - - fn collect_delivery_review_hints(&self, ui: &Ui) -> Vec { - let mut hints = Vec::new(); - for source in [ - &self.project_context["materialDelivery"]["reviewHints"], - &self.project_context["delivery"]["reviewHints"], - &self.project_context["reviewHints"], - &self.creation["reviewHints"], - ] { - parse_review_hints(source, &mut hints); - } - if hints.is_empty() { - let manifest_dir = self.project_context["materialDelivery"]["path"] - .as_str() - .or(self.creation_delivery_dir.as_deref()) - .map(str::trim) - .filter(|path| !path.is_empty()); - if let Some(dir) = manifest_dir { - let cache_id = egui::Id::unique(("xiaoyi-delivery-review-hints", dir)); - let cached = ui.ctx().data_mut(|data| data.get_temp::>(cache_id)); - if let Some(cached) = cached { - return cached; - } - let manifest_path = std::path::Path::new(dir).join("交付清单.json"); - if let Ok(raw) = std::fs::read_to_string(&manifest_path) - && let Ok(manifest) = serde_json::from_str::(&raw) - { - parse_review_hints(&manifest["reviewHints"], &mut hints); - } - ui.ctx().data_mut(|data| data.insert_temp(cache_id, hints.clone())); - } - } - hints - } - - fn jump_to_review_hint(&mut self, app: &PhotocraftApp, hint: &ReviewHintItem) { - let output_id = hint - .output_id - .as_deref() - .unwrap_or_else(|| { - if self.canvas_workspace.output.is_empty() { "detail" } else { self.canvas_workspace.output.as_str() } - }) - .to_owned(); - self.template_ui.navigate(&output_id, hint.slot_id.as_deref()); - let mut request = json!({ "outputId": output_id }); - if let Some(variant_id) = hint.variant_id.as_deref() { - request["variantId"] = json!(variant_id); - } - if let Some(slot_id) = hint.slot_id.as_deref() { - request["slotId"] = json!(slot_id); - } - if let Some(layer_id) = hint.layer_id.as_deref() { - request["layerId"] = json!(layer_id); - } - if let Err(error) = self.slot_action(app, "slot-skeleton", request) { - self.product_views.view_error = Some(error.clone()); - self.error = error; - } - self.sync_confirm = false; - self.show_center(super::CenterView::Canvas, true); - self.creation_open = false; - } - pub(super) fn begin_staged_new_project(&mut self, app: &PhotocraftApp) { - self.retain_creation_ui_draft(app); - if !self.creation_reads.staged_new_project { - self.creation_reads.staged_prior_draft = app.session.active().map(|state| { - if self.creation_doc == Some(state.doc.id.0) { self.creation_draft() } else { Value::Null } - }); - } - self.creation_restore_draft = Value::Null; - self.creation_reads.staged_new_project = true; - self.creation_reads.new_project_doc = None; - self.reset_test_presets(); - self.creation_reads.wizard_stage = None; - self.library = false; - self.material = false; - self.creation_open = true; - self.creation_step = 0; - self.creation_doc = None; - self.creation_brief = empty_brief(); - self.creation = json!({"brief": self.creation_brief.clone()}); - self.creation_dirty = false; - self.creation_read_failed = false; - self.creation_width = 0; - self.creation_delivery_dir = preferred_delivery_dir(app); - self.creation_selected.clear(); - self.creation_direction.clear(); - self.creation_plan = json!([]); - self.creation_progress.clear(); - self.creation_reads.inline_errors.clear(); - self.creation_reads.scroll_to_field = None; - self.creation_reads.manual_edited_fields.clear(); - self.creation_reads.visual_asset_filter = 0; - self.creation_reads.expanded_colors.clear(); - self.creation_reads.expanded_skus.clear(); - self.creation_reads.platform_message.clear(); - self.creation_reads.platform_sync_note.clear(); - self.creation_reads.reference_import_error.clear(); - self.creation_reads.resource_set = Value::Null; - self.creation_reads.resource_component.clear(); - self.creation_reads.resource_image = None; - self.template_workflow = Value::Null; - self.error.clear(); - } - - fn ensure_creation_document(&mut self, app: &mut PhotocraftApp) -> Result<(), String> { - if !self.creation_reads.staged_new_project { - return Ok(()); - } - if self.busy.is_some() { - return Err("请等待当前操作完成".into()); - } - let doc_name = non_empty_str(&self.creation_brief["name"]).unwrap_or("未命名详情页").to_owned(); - app.run("file.new", json!({"name": doc_name, "width": 1440, "height": 1800}))?; - let doc_id = app.session.active().map(|state| state.doc.id.0); - self.creation_doc = doc_id; - self.creation_reads.new_project_doc = doc_id; - self.reference_intro_doc = doc_id; - self.creation_reads.staged_new_project = false; - self.creation_reads.staged_prior_draft = None; - if let Some((_, stage)) = self.creation_reads.wizard_stage { - self.creation_reads.wizard_stage = Some((self.creation_field_scope(app), stage)); - } - Ok(()) - } - - pub(super) fn focus_brief_field(&mut self, field_key: &str, message: &str) { - if let Some((scope, stage)) = self.creation_reads.wizard_stage { - let template = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); - let stage = if matches!(field_key, "brand" | "category" | "template") || !template_identity(&template) { - CreationStage::Template - } else if stage != CreationStage::Details { - CreationStage::Details - } else { - stage - }; - self.creation_reads.wizard_stage = Some((scope, stage)); - } - self.creation_reads.inline_errors.insert(field_key.to_owned(), message.to_owned()); - self.creation_reads.scroll_to_field = Some(field_key.to_owned()); - if let Some(rest) = field_key.strip_prefix("intake-barcode:") - && let Some((code, _)) = rest.split_once(':') - { - self.creation_reads.expanded_skus.remove(&format!("!{code}")); - self.creation_reads.expanded_skus.insert(code.to_owned()); - for group in normalized_color_groups(&self.creation_brief) { - if group.skus.iter().any(|sku| sku.barcode == code) { - self.creation_reads.expanded_colors.insert(group.id); - break; - } - } - } - } - - pub(super) fn creation_action(&mut self, app: &mut PhotocraftApp, method: &str, mut input: Value) -> Result { - let mut method = method; - if matches!(method, "creation-catalog" | "creation-thumbnail") { - let expected_doc = self.creation_read_doc(app); - if input["doc"].as_u64().is_some_and(|id| Some(id) != expected_doc) { - return Err("项目已切换".into()); - } - if method == "creation-catalog" { - let kind = input["kind"].as_str().ok_or("目录类型无效")?; - self.request_creation_catalog(app, kind, input["query"].as_str().unwrap_or("").into(), input["refresh"] == true); - } else { - let id = input["id"].as_str().filter(|id| !id.is_empty()).ok_or("材质编号无效")?; - self.queue_creation_thumbnail(app, id); - } - return Ok(json!({"submitted":true,"readOnly":true})); - } - if method == "creation-new" { - if self.busy.is_some() { - return Err("请等待当前操作完成".into()); - } - self.creation_reads.staged_new_project = false; - self.creation_reads.staged_prior_draft = None; - self.creation_reads.wizard_stage = None; - app.run("file.new", json!({"name":"未命名详情页","width":1440,"height":1800}))?; - self.reference_intro_doc = app.session.active().map(|state| state.doc.id.0); - self.creation_open = true; - self.creation_step = 0; - self.library = false; - self.material = false; - return Ok(json!({"created":true})); - } - if method == "creation-view" { - self.show_creation_step(input["step"].as_u64().unwrap_or(0).min(4) as usize, app.session.active().is_some() || self.creation_reads.staged_new_project); - return Ok(Value::Null); - } - if self.busy.is_some() { - return Err("请等待当前操作完成".into()); - } - if method == "creation-product-platform" && !self.account["id"].is_string() { - return Err("请先登录素材库账号".into()); - } - if self.unknown && !matches!(method, "creation-recover" | "creation-read" | "creation-load") - && !(method == "creation-save" && self.scoped_production_pending()) - { - return Err("原请求结果待核查,不会重发".into()); - } - if self.creation_reads.staged_new_project { - if input["doc"].as_u64().is_some() { - return Err("新建资料尚未关联画布".into()); - } - self.ensure_creation_document(app)?; - } - let st = app.session.active().ok_or("请先新建项目")?; - if input["doc"].as_u64().is_some_and(|id| id != st.doc.id.0) { - return Err("项目已切换".into()); - } - input["doc"] = json!(st.doc.id.0); - input["baseRevision"] = json!(st.revision); - if method == "creation-import" { - self.creation_read_scope(app); - } - if method == "creation-import" && app.session.authorize.is_some() { - use base64::Engine as _; - let paths = input["paths"].as_array().filter(|a| !a.is_empty() && a.len() <= 8).ok_or("每次最多8张图片")?; - let paths = paths.iter().map(|path| path.as_str().filter(|path| !path.is_empty()).map(str::to_owned).ok_or("图片路径无效")) - .collect::, _>>()?; - let read = app.services.automation_read_limited.as_mut().ok_or("自动化导入尚未提供有界读取")?; - let mut images = Vec::new(); - let mut total = 0usize; - for path in paths { - let limit = (24usize * 1024 * 1024).saturating_sub(total).min(20 * 1024 * 1024); - if limit == 0 { return Err("本次产品图片总量超过24MiB".into()); } - let (name, bytes) = read(&path, limit)?; - if bytes.is_empty() || bytes.len() > limit { return Err("产品图片为空或超过读取上限".into()); } - total += bytes.len(); - images.push(json!({"name":name,"data":base64::engine::general_purpose::STANDARD.encode(bytes)})); - } - input["images"] = json!(images); - input.as_object_mut().ok_or("导入参数无效")?.remove("paths"); - method = "creation-import-data"; - } - if input["revision"].is_null() { - input["revision"] = self.creation["revision"].clone(); - } - if input["brief"].is_null() { - input["brief"] = self.brief_with_manual_fields(); - } - if input["width"].is_null() { - input["width"] = json!(self.creation_draft_width()); - } - if input["selected"].is_null() { - input["selected"] = json!(self.creation_selected); - } - if input["direction"].is_null() { - input["direction"] = json!(self.creation_direction); - } - if input["screens"].is_null() { - input["screens"] = self.creation_plan.clone(); - } - if method == "creation-save" && input.get("deliveryDir").is_none() { - input["deliveryDir"] = json!(self.creation_delivery_dir); - } - if matches!(method, "creation-save" | "creation-facts") { - update_detail_barcode(&mut input["brief"]); - } - input["model"] = json!(self.model); - input["imageModel"] = json!(self.image_model); - if matches!(method, "creation-generate" | "creation-load") { - self.owner_doc = Some(st.doc.id.0); - self.expected_revision = st.revision; - self.creation_base_revision = st.revision; - self.creation_run = None; - self.allow_apply = true; - self.creation_pending = None; - } - if matches!(method, "creation-save" | "creation-select" | "creation-plan-edit") { - self.creation_submitted_draft = Some(self.creation_draft()); - } - self.send(method, input); - Ok(json!({"submitted":self.busy.as_deref()==Some(method)})) - } - fn creation_submit(&mut self, app: &mut PhotocraftApp, method: &str, input: Value) { - if let Err(e) = self.creation_action(app, method, input) { - self.error = e; - } - } - fn catalog(&mut self, app: &mut PhotocraftApp, kind: &str, query: String) { - self.request_creation_catalog(app, kind, query, false); - } - pub(super) fn control_geometry(&mut self, name: &str, rect: egui::Rect) { - self.creation_view_geometry[name] = rect_value(rect); - self.creation_view_geometry["controls"][name] = rect_value(rect); - } - fn picker_geometry(&mut self, ui: &Ui, name: &str, response: &egui::Response, loading: bool, ready: bool, rows: Vec) { - self.control_geometry(name, response.rect); - let open = egui::Popup::is_id_open(ui.ctx(), response.id.with("popup")); - let rect = open.then(|| ui.ctx().memory(|memory| memory.area_rect(response.id.with("popup")))).flatten(); - self.creation_view_geometry["popups"][name] = json!({"open":open,"loading":loading,"ready":ready,"rect":rect.map(rect_value),"rows":rows}); - } - fn material_preview(&mut self, response: egui::Response, id: &str, _label: &str, image: &egui::TextureHandle) { - if response.hovered() { - let mut tooltip = egui::Tooltip::for_widget(&response); - tooltip.popup = tooltip.popup.frame(egui::Frame::NONE); - tooltip.show(|ui| { - let size = preview_size(image.size_vec2(), vec2(240.0, 240.0)); - let image_response = ui.image((image.id(), size)); - self.creation_view_geometry["hoverPreview"] = json!({"id":id,"ready":true,"rect":rect_value(image_response.rect),"sourceSize":image.size()}); - }); - } - } pub(super) fn creation_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { self.creation_escape(app, ui); self.creation_view_geometry = json!({"controls":{},"popups":{},"materialRows":[],"hoverPreview":null}); @@ -2962,6973 +157,43 @@ impl Workspace { }); } - fn creation_wizard_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, pad_x: i8) { - let scope = self.creation_field_scope(app); - let selected = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); - let has_template = template_identity(&selected); - let mut stage = self.creation_reads.wizard_stage - .filter(|(owner, _)| *owner == scope) - .map(|(_, stage)| stage) - .unwrap_or_else(|| wizard::resolve_initial_stage(self.creation_reads.staged_new_project, has_template)); - if wizard::ensure_default_barcode(&mut self.creation_brief) { - wizard::migrate_legacy_top_dimensions_to_barcode(&mut self.creation_brief); - } - egui::Frame::NONE.inner_margin(egui::Margin::symmetric(pad_x, 12)).show(ui, |ui| { - wizard_column(ui, |ui| { - wizard::wizard_stepper_ui(ui, &mut stage, true, has_template, self.reduce_motion); - stitch_ui::divider(ui); - }); - }); - self.creation_reads.wizard_stage = Some((scope, stage)); - - let pending_id = scope.with("wizard-barcode-pending"); - let barcode_pending = ui.data(|data| data.get_temp::(pending_id)).unwrap_or(false); - let background = Tokens::get(ui.ctx()).agent().dock; - egui::Panel::bottom("creation-sticky-footer") - .resizable(false) - .show_separator_line(true) - .frame(egui::Frame::NONE.fill(background).inner_margin(egui::Margin::symmetric(pad_x, 7))) - .show(ui, |ui| wizard_column(ui, |ui| { - if stage == CreationStage::Details { - self.brief_footer_ui(app, ui, barcode_pending); - } else { - self.reference_drop_warning_ui(ui); - let setup_warning = self.brief_setup_warning(); - let key_saved = self.key_saved; - let mut open_settings = false; - let mut cfg_rect = None; - let action = wizard::wizard_footer_ui_with_status( - ui, - WizardFooterState { - stage, - can_continue: form_editable(self.busy.as_deref(), self.unknown) - && (stage == CreationStage::Source || has_template), - can_enter_canvas: false, - can_start: false, - }, - true, - |ui| { - if let Some((message, _, action)) = setup_warning { - let configure = stitch_ui::action_button(ui, action, stitch_ui::ButtonRole::Quiet, true).on_hover_text(message); - cfg_rect = Some(configure.rect); - if configure.clicked() { - open_settings = true; - } - } - }, - |_, _| {}, - ); - if let Some(rect) = cfg_rect { - self.control_geometry(if key_saved { "select-model" } else { "configure-personal-key" }, rect); - } - if open_settings { - self.open_brief_setup_settings(); - } - self.handle_wizard_navigation(app, action); - } - })); - if !self.editing_product_brief() || self.creation_step != 0 { - return; - } - let (scope, stage) = self.creation_reads.wizard_stage.unwrap_or((scope, stage)); - let opacity = wizard::stage_reveal_opacity(ui.ctx(), scope.with("wizard-reveal"), stage, self.reduce_motion); - ui.spacing_mut().scroll.floating = true; - let scrolled = egui::ScrollArea::vertical().id_salt((scope, stage)).auto_shrink([false, false]).show(ui, |ui| { - egui::Frame::NONE.inner_margin(egui::Margin::symmetric(pad_x, 12)).show(ui, |ui| { - wizard_column(ui, |ui| { - ui.multiply_opacity(opacity); - let title = ui.label(egui::RichText::new(stage.title()).font(Type::TitleLg.semibold()).color(Tokens::get(ui.ctx()).agent().text)); - self.control_geometry("brief-title", title.rect); - ui.add_space(space::SM); - self.creation_notices_ui(app, ui); - let editable = form_editable(self.busy.as_deref(), self.unknown && !self.scoped_production_pending()); - ui.add_enabled_ui(editable, |ui| { - let width = ui.available_width(); - if stage != CreationStage::Template { - self.test_preset_ui(app, ui); - } - match stage { - CreationStage::Source => self.wizard_source_ui(app, ui, scope, width), - CreationStage::Template => { - let np = normalized_product_summary(&self.creation_brief); - self.unmatched_platform_taxonomy_chips_ui(app, ui, &np); - self.template_and_brand_block_ui(app, ui, width); - } - CreationStage::Details => { - let pending = self.wizard_details_ui(app, ui, scope, width, editable); - ui.data_mut(|data| data.insert_temp(pending_id, pending)); - } - } - }); - }); - }); - }); - self.control_geometry("product-form-viewport", scrolled.inner_rect.intersect(ui.clip_rect())); - } - - fn handle_wizard_navigation(&mut self, app: &PhotocraftApp, action: WizardFooterOutcome) { - let Some((scope, stage)) = self.creation_reads.wizard_stage else { return }; - let next = match (stage, action) { - (_, WizardFooterOutcome::Cancel) => { - self.retain_creation_ui_draft(app); - self.creation_reads.new_project_doc = None; - if self.creation_reads.staged_new_project { - self.creation_reads.staged_new_project = false; - self.creation_restore_draft = self.creation_reads.staged_prior_draft.take().unwrap_or(Value::Null); - self.show_center(super::CenterView::Projects, app.session.active().is_some()); - self.creation_open = false; - } else if self.template_workflow["canvasFirst"] != true { - self.show_center(super::CenterView::Projects, app.session.active().is_some()); - } else { - self.set_creation_destination(3); - self.creation_open = false; - } - return; - } - (CreationStage::Source, WizardFooterOutcome::Next) | (CreationStage::Details, WizardFooterOutcome::Back) => CreationStage::Template, - (CreationStage::Template, WizardFooterOutcome::Next) => CreationStage::Details, - (CreationStage::Template, WizardFooterOutcome::Back) => CreationStage::Source, - _ => return, - }; - self.creation_reads.wizard_stage = Some((scope, next)); - } - - fn test_preset_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - if !self.can_use_test_presets(app) { - return; - } - if !self.creation_catalog.contains_key(TEST_PRESETS) - && self.creation_catalog_error(TEST_PRESETS).is_none() - && !self.creation_catalog_loading(TEST_PRESETS) - { - self.request_creation_catalog(app, TEST_PRESETS, String::new(), false); - } - let Some(presets) = self.creation_catalog.get(TEST_PRESETS).filter(|rows| !rows.is_empty()) else { - return; - }; - let importing = self.test_preset_import_pending(); - let label = if importing { "正在填入测试商品…" } else { "一键填入测试商品(超管)" }; - let button = stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Secondary, !importing) - .on_hover_text("选择后替换当前商品资料和参考图"); - let mut chosen = None; - egui::Popup::menu(&button).style(stitch_ui::scoped_popup_style(ui)) - .frame(stitch_ui::command_menu_frame(ui.ctx())).show(|ui| { - for preset in presets { - if stitch_ui::action_button(ui, preset["label"].as_str().unwrap_or(""), stitch_ui::ButtonRole::Quiet, true).clicked() { - chosen = Some(preset.clone()); - ui.close(); - } - } - }); - if let Some(preset) = chosen { - self.select_test_preset(app, ui.ctx(), preset); - } - ui.add_space(space::SM); - } - - fn select_test_preset(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, preset: Value) { - if !self.can_use_test_presets(app) || self.test_preset_import_pending() { - return; - } - let staged = self.creation_reads.staged_new_project; - if self.ensure_creation_document(app).is_err() { - return; - } - if staged { - // Detach the old project before queuing the import. The new native - // document has no saved draft to restore on the next frame. - let doc = self.creation_doc; - let brief = std::mem::take(&mut self.creation_brief); - let dirty = self.creation_dirty; - self.switch_project_projection(app, ctx, None); - self.observed_doc = doc; - self.loaded_draft = doc; - self.creation_doc = doc; - self.creation_ui_scope = self.current_creation_ui_scope(app); - self.project_view_parked = false; - self.creation_brief = brief; - self.creation = json!({"brief":empty_brief()}); - self.creation_dirty = dirty; - } - // Carry the same picker across the staged draft's first image import. - let presets = self.creation_catalog.remove(TEST_PRESETS); - self.creation_read_scope(app); - if let Some(presets) = presets { - self.creation_catalog.insert(TEST_PRESETS.into(), presets); - } - self.request_test_preset_import(app, preset); - } - - pub(super) fn apply_test_preset(&mut self, app: &PhotocraftApp, mut brief: Value) { - let selected = &self.creation_brief["templateSelection"]; - let taxonomy_changed = self.creation_brief["brandId"] != brief["brandId"] - || self.creation_brief["categoryId"] != brief["categoryId"]; - let keep_template = template_identity(selected) - && selected["id"] == brief["intake"]["templateId"] - && !taxonomy_changed; - if keep_template { - brief["templateSelection"] = selected.clone(); - } else if self.creation_reads.wizard_stage.is_some_and(|(_, stage)| stage == CreationStage::Details) { - self.creation_reads.wizard_stage = Some((self.creation_field_scope(app), CreationStage::Template)); - } - if taxonomy_changed { - self.agent_rule = Value::Null; - self.agent_rule_state = Value::Null; - self.creation_catalog.remove("categories"); - self.creation_catalog.remove("templates"); - } - self.creation_brief = brief; - self.creation_reads.manual_edited_fields.clear(); - self.creation_reads.inline_errors.clear(); - self.creation_reads.reference_import_error.clear(); - self.creation_reads.scroll_to_field = None; - self.creation_failed_signature.clear(); - self.creation_dirty = true; - self.sync_dirty = true; - self.draft_changed = true; - } - - fn reference_drop_warning_ui(&mut self, ui: &mut Ui) { - if self.creation_reads.reference_import_error == REFERENCE_DROP_HINT { - let status = stitch_ui::status_label(ui, REFERENCE_DROP_HINT, stitch_ui::StatusTone::Warning); - self.control_geometry("reference-import-error", status.rect); - } - } - - fn wizard_source_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32) { - self.source_picker(ui); - ui.add_space(space::MD); - match self.creation_brief["source"].as_str() { - Some("product_platform") => { - let np = normalized_product_summary(&self.creation_brief); - self.platform_spu_ui(app, ui, scope, width, np.has_platform_data); - if np.has_platform_data { - stitch_kit::label(ui, format!("已同步 {} 张素材", selected_visual_asset_count(&self.creation_brief)), Type::Meta, Tone::Success); - } - if !self.creation_reads.platform_sync_note.is_empty() { - stitch_kit::label(ui, &self.creation_reads.platform_sync_note, Type::Meta, Tone::Quiet); - } - } - Some("library") => { - self.product_search_button(app, ui); - self.product_select_results(app, ui); - } - _ => { - self.poll_imported_reference_previews(app, ui.ctx()); - wizard::section_heading_with_tip(ui, "本机资料", "支持 PNG、JPG、WebP。每次最多 8 张,单张不超过 20 MB。"); - ui.add_space(space::XS); - let rect = self.reference_picker(app, ui, width, scope.with("source-drop"), - Some(("拖入产品图片或文件夹", "拖入图片或文件夹,或点击浏览文件")), Value::Null); - self.control_geometry("reference-add", rect); - if ui.is_enabled() && let Some(target) = self.reference_drop_geometry(app, ui, rect) { - self.creation_view_geometry["referenceDrop"] = target; - } - ui.add_space(space::XS); - let count = self.creation_brief["images"].as_array().map_or(0, Vec::len); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = space::MD; - if stitch_ui::action_button(ui, "选择文件夹", stitch_ui::ButtonRole::Quiet, true).clicked() { - self.open_reference_dialog(app, Value::Null, true); - } - if count > 0 { - stitch_kit::label(ui, format!("已添加 {count} 张图片"), Type::Meta, Tone::Success); - } - }); - if count > 0 { - ui.add_space(space::XS); - let t = Tokens::get(ui.ctx()).agent(); - let images = self.creation_brief["images"].as_array().cloned().unwrap_or_default(); - let mut remove_idx = None; - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(space::SM, space::SM); - for (idx, img) in images.iter().enumerate() { - let src = img["source"].as_str().unwrap_or(""); - let name = img["name"].as_str().unwrap_or("产品图片"); - let key = super::creation_reads::reference_key(src); - ui.vertical(|ui| { - ui.set_width(76.0); - ui.spacing_mut().item_spacing.y = 4.0; - let (thumb_rect, thumb_resp) = ui.allocate_exact_size(vec2(76.0, 76.0), egui::Sense::hover()); - ui.painter().rect_filled(thumb_rect, radius::ROW, t.field); - ui.painter().rect_stroke(thumb_rect, radius::ROW, egui::Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); - if ui.is_rect_visible(thumb_rect) && !src.is_empty() { - self.queue_creation_reference(app, src); - } - if let Some(tex) = self.creation_thumbs.get(&key).cloned() { - let size = preview_size(tex.size_vec2(), thumb_rect.shrink(3.0).size()); - let fit = egui::Align2::CENTER_CENTER.align_size_within_rect(size, thumb_rect); - ui.painter().image(tex.id(), fit, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text); - self.material_preview(thumb_resp, &key, name, &tex); - } else { - crate::icons::paint(ui, thumb_rect, "image", icon::MD, t.text_dim); - } - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - ui.add_sized( - vec2(54.0, 18.0), - egui::Label::new(egui::RichText::new(name).font(Type::Meta.font_id()).color(t.text_dim)).truncate(), - ).on_hover_text(name); - if stitch_ui::icon_button(ui, "trash", 18.0, false, "移除此图片").clicked() { - remove_idx = Some(idx); - } - }); - }); - } - }); - if let Some(idx) = remove_idx - && let Some(list) = self.creation_brief["images"].as_array_mut() - && idx < list.len() - { - list.remove(idx); - self.creation_dirty = true; - } - } - if !self.creation_reads.reference_import_error.is_empty() && self.creation_reads.reference_import_error != REFERENCE_DROP_HINT { - stitch_ui::status_label(ui, &self.creation_reads.reference_import_error, stitch_ui::StatusTone::Error); - } - brief_section_break(ui); - wizard::section_heading_with_tip(ui, "文字简报(选填)", "可填写产品用途、需要呈现的卖点和制作要求。"); - ui.add_space(space::XS); - if edit_named(ui, (scope, "source-note"), &mut self.creation_brief["note"], width, true, - "输入产品说明或制作要求", "文字简报") - { - self.creation_reads.manual_edited_fields.insert("note".into()); - self.creation_dirty = true; - } - } - } - } - - fn wizard_barcode_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32) -> bool { - let seeded = wizard::ensure_default_barcode(&mut self.creation_brief); - if seeded { - wizard::migrate_legacy_top_dimensions_to_barcode(&mut self.creation_brief); - } - let previous = self.creation_brief["barcodeEntries"].as_array().cloned().unwrap_or_default(); - let mut rows = previous.clone(); - let schema = self.creation_brief["intake"]["schema"]["barcodeFields"].clone(); - let fields = schema.as_array().into_iter().flatten() - .filter(|field| field_kind(field) != "image" && !structured_barcode_field(field)) - .collect::>(); - let images = schema.as_array().into_iter().flatten().filter(|field| field_kind(field) == "image").collect::>(); - - self.poll_imported_reference_previews(app, ui.ctx()); - let hint = |key| schema.as_array().into_iter().flatten() - .find(|field| structured_barcode_field(field) && field_key(field) == key).map(intake_hint).unwrap_or(""); - let mut open_image_for_barcode: Option = None; - let action = wizard::barcode_cards_section_ui( - ui, - scope, - &mut rows, - self.reduce_motion, - hint, - |ui, id, slot| match slot { - wizard::BarcodeSlotRender::Image { row, size, editable: editable_slot } => { - let t = Tokens::get(ui.ctx()).agent(); - let code = non_empty_str(&row["barcode"]); - let matched_sources: Vec<(String, String)> = self.creation_brief["images"] - .as_array() - .into_iter() - .flatten() - .filter(|img| code.is_some() && img["barcode"].as_str() == code) - .filter_map(|img| Some((img["source"].as_str()?.to_owned(), img["name"].as_str().unwrap_or("条码图片").to_owned()))) - .collect(); - let sense = if editable_slot && code.is_some() { egui::Sense::click() } else { egui::Sense::hover() }; - let (rect, resp) = ui.allocate_exact_size(vec2(size, size), sense); - ui.painter().rect_filled(rect, radius::ROW, t.field); - let stroke_color = if resp.hovered() && editable_slot && code.is_some() { t.primary_bg } else { t.card_border }; - ui.painter().rect_stroke(rect, radius::ROW, egui::Stroke::new(1.0, stroke_color), egui::StrokeKind::Inside); - if let Some((first_src, first_name)) = matched_sources.first() { - if ui.is_rect_visible(rect) { - self.queue_creation_reference(app, first_src); - } - let key = super::creation_reads::reference_key(first_src); - if let Some(tex) = self.creation_thumbs.get(&key).cloned() { - let fit_sz = preview_size(tex.size_vec2(), rect.shrink(2.0).size()); - let fit = egui::Align2::CENTER_CENTER.align_size_within_rect(fit_sz, rect); - ui.painter().image(tex.id(), fit, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text); - } else { - crate::icons::paint(ui, rect, "image", if size >= 48.0 { icon::MD } else { icon::SM }, t.text_dim); - } - if matched_sources.len() > 1 { - let badge = egui::Rect::from_min_size(egui::pos2(rect.right() - 18.0, rect.bottom() - 15.0), vec2(17.0, 14.0)); - ui.painter().rect_filled(badge, 3.0, egui::Color32::from_rgba_unmultiplied(15, 16, 18, 210)); - ui.painter().text(badge.center(), egui::Align2::CENTER_CENTER, format!("{}", matched_sources.len()), Type::Meta.font_id(), t.text); - } - let tip = if editable_slot { format!("{first_name}(点击继续添加条码图)") } else { first_name.clone() }; - let resp = resp.on_hover_text(tip); - if resp.clicked() && let Some(c) = code { - open_image_for_barcode = Some(c.to_owned()); - } - } else { - crate::icons::paint(ui, rect, if editable_slot { "plus" } else { "image" }, if size >= 48.0 { icon::MD } else { icon::SM }, t.text_dim); - let tip = if !editable_slot { - "暂无条码专属图片" - } else if code.is_some() { - "点击为该条码添加图片" - } else { - "请先填写条码编码,再添加图片" - }; - let resp = resp.on_hover_text(tip); - if resp.clicked() && let Some(c) = code { - open_image_for_barcode = Some(c.to_owned()); - } - } - } - wizard::BarcodeSlotRender::Related { row } => { - let Some(code) = non_empty_str(&row["barcode"]) else { return; }; - if !project_barcodes(&self.creation_brief).any(|existing| existing == code) { return; } - if !fields.is_empty() || !images.is_empty() { - self.barcode_intake_ui(app, ui, id, width, code, &fields, &images); - } - } - }, - ); - if let Some(code) = open_image_for_barcode { - self.open_reference_dialog(app, json!({"scope":"barcode","barcode":code,"purpose":"product","multiple":true}), false); - } - if let Some(index) = action.remove_index { - rows.remove(index); - } - if action.add_barcode || rows.is_empty() { - rows.push(wizard::barcode_row("", &Value::Null, &Value::Null, &Value::Null)); - } - if action.changed { - for row in &rows { - let Some(id) = row["id"].as_str() else { continue; }; - let Some(old) = previous.iter().find(|previous| previous["id"] == id) else { continue; }; - for field in ["material", "boardType", "colorName"] { - if row[field] != old[field] { - self.creation_reads.manual_edited_fields.insert(format!("barcode-card:{id}:{field}")); - } - } - for axis in ["length", "width", "height", "depth", "secondaryHeight", "unit"] { - if row["dimensions"][axis] != old["dimensions"][axis] { - self.creation_reads.manual_edited_fields.insert(format!("barcode-card:{id}:dimensions.{axis}")); - } - } - } - for old in &previous { - let Some(code) = non_empty_str(&old["barcode"]) else { continue; }; - let new = rows.iter().find(|row| row["id"] == old["id"]).and_then(|row| non_empty_str(&row["barcode"])); - if new != Some(code) { - self.creation_reads.manual_edited_fields.insert(format!("removed-barcode:{code}")); - replace_barcode(&mut self.creation_brief, code, new); - if let Some(new) = new - && let Some(assets) = self.creation_brief.get_mut("normalizedProduct").and_then(|value| value.get_mut("assets")).and_then(Value::as_array_mut) - { - for asset in assets.iter_mut().filter(|asset| asset["barcode"] == code) { - asset["barcode"] = json!(new); - } - } - if let Some(variants) = self.creation_brief.get_mut("normalizedProduct").and_then(|value| value.get_mut("variants")).and_then(Value::as_array_mut) { - for variant in variants { - if let Some(barcodes) = variant["barcodes"].as_array_mut() { - if let Some(new) = new { - for row in barcodes.iter_mut().filter(|row| row["barcode"] == code) { - row["barcode"] = json!(new); - } - } else { - barcodes.retain(|row| row["barcode"] != code); - } - } - } - } - } - } - write_legacy_barcode_fields(&mut self.creation_brief, &mut rows, &schema); - self.creation_dirty = true; - } - if self.creation_brief["barcodeEntries"] != Value::Array(rows.clone()) { - self.creation_brief["barcodeEntries"] = Value::Array(rows); - } - let codes: Vec = project_barcodes(&self.creation_brief).map(str::to_owned).collect(); - if codes.len() > 1 { - ui.add_space(space::SM); - self.detail_barcode_selector_ui(ui, width, scope, &codes); - } - action.pending - } - - fn wizard_details_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32, editable: bool) -> bool { - self.core_identity_and_specs_ui(app, ui, scope, width); - brief_section_break(ui); - let pending = self.wizard_barcode_ui(app, ui, scope, width); - brief_section_break(ui); - self.references_ui(app, ui, width); - brief_section_break(ui); - wizard::section_heading_with_tip(ui, "制作设置", "选择要制作的成品和适用的花色。"); - self.output_tags_ui(ui); - stitch_ui::disclosure(ui, scope.with("wizard-output-colors"), "成品花色范围", false, self.reduce_motion, |ui| { - self.material_select(app, ui, width.min(420.0)); - self.sku_colors_bar_ui(ui, width, scope); - }); - self.special_requirements_ui(ui, scope); - if self.template_workflow["canvasFirst"] != true { - let doc = app.session.active().map(|state| state.doc.id.0); - let id = egui::Id::unique(("production-refinement", self.local_identity(""), doc)); - let _ = self.refinement_ui(ui, Some((id, editable))); - } - self.delivery_directory_control(app, ui, editable); - self.advanced_export_settings_ui(app, ui, scope, width, editable); - pending - } - - fn creation_notices_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - if !self.error.is_empty() { - super::operation_error::details(ui, egui::Id::unique("creation-operation-error"), &self.error, self.reduce_motion, None); - ui.add_space(space::SM); - } - if !self.creation_progress.is_empty() { - stitch_ui::disclosure(ui, egui::Id::unique("creation-progress"), if self.busy.is_some() { "处理中…" } else { "最近结果" }, false, self.reduce_motion, |ui| { - ui.label(&self.creation_progress); - }); - ui.add_space(space::SM); - } - if self.unknown { - ui.horizontal_wrapped(|ui| { - stitch_ui::status_chip(ui, "原请求待核查", stitch_ui::StatusTone::Warning); - if ui.add_enabled_ui(self.busy.is_none(), |ui| stitch_ui::button(ui, "核查原结果", false)).inner.clicked() { - self.recover(app); - } - if self.creation["generation"]["screens"].as_object().is_some_and(|m| !m.is_empty()) - && ui.add_enabled_ui(self.busy.is_none(), |ui| stitch_ui::button(ui, "载入已有结果", false)).inner.clicked() - { - self.creation_submit(app, "creation-load", json!({})); - } - }); - ui.add_space(space::SM); - } - } - - fn brief_autosave_status_ui(&self, ui: &mut Ui) { - let (text, tone) = if self.creation_reads.staged_new_project { - ("草稿暂存中", Tone::Quiet) - } else if self.busy.as_deref() == Some("creation-save") { - ("保存中…", Tone::Quiet) - } else if self.creation_dirty { - ("有未保存修改 · 将自动保存", Tone::Warning) - } else { - ("已自动保存", Tone::Success) - }; - stitch_kit::label(ui, text, Type::Meta, tone); - } - - #[cfg(test)] - fn brief_scroll_body_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) -> bool { - let editable = form_editable(self.busy.as_deref(), self.unknown && !self.scoped_production_pending()); - let t = Tokens::get(ui.ctx()).agent(); - let width = ui.available_width(); - let title_text = if self.creation_reads.staged_new_project { "新建项目" } else { "产品资料" }; - if width >= 440.0 { - ui.horizontal(|ui| { - let title = ui.label(egui::RichText::new(title_text).font(Type::Display.semibold()).color(t.text)); - self.control_geometry("brief-title", title.rect); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - self.brief_autosave_status_ui(ui); - }); - }); - } else { - let title = ui.label(egui::RichText::new(title_text).font(Type::Display.semibold()).color(t.text)); - self.control_geometry("brief-title", title.rect); - self.brief_autosave_status_ui(ui); - } - ui.add_space(space::XXS); - stitch_kit::caption(ui, "可先按 SPU 从产品平台或素材库导入,再核对款式、模板与视觉素材。"); - ui.add_space(space::MD); - ui.add_enabled_ui(editable, |ui| self.brief_content_ui(app, ui)).inner - } - - #[cfg(test)] - fn brief_content_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) -> bool { - let field_scope = self.creation_field_scope(app); - let width = ui.available_width(); - let editable = ui.is_enabled(); - - self.source_import_strip_ui(app, ui, field_scope, width); - brief_section_break(ui); - - let template = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); - brief_step(ui, "1. 选择模板", template_identity(&template), true); - self.template_and_brand_block_ui(app, ui, width); - brief_section_break(ui); - - let template = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); - let template_ready = template_identity(&template); - let archive_ready = brief_readiness(&self.creation_brief, &template).iter() - .filter(|item| !matches!(item.field_key.as_str(), "brand" | "category" | "template" | "images")) - .all(|item| item.ready); - brief_step(ui, "2. 商品档案与款式", archive_ready, template_ready); - self.core_identity_and_specs_ui(app, ui, field_scope, width); - let barcode_pending = self.sku_matrix_ui(app, ui, field_scope, width); - - brief_section_break(ui); - let images_ready = has_selected_product_image(&self.creation_brief); - brief_step(ui, "3. 视觉素材", images_ready, template_ready && archive_ready); - self.references_ui(app, ui, width); - brief_section_break(ui); - - brief_step(ui, "4. 确认制作目标", false, template_ready && archive_ready && images_ready); - self.output_tags_ui(ui); - ui.add_space(space::SM); - self.special_requirements_ui(ui, field_scope); - ui.add_space(space::SM); - let new_project = self.template_workflow["canvasFirst"] != true; - let pending = new_project.then(|| { - let doc = app.session.active().map(|state| state.doc.id.0); - (egui::Id::unique(("production-refinement", self.local_identity(""), doc)), editable) - }); - let _ = self.refinement_ui(ui, pending); - ui.add_space(space::SM); - self.delivery_directory_control(app, ui, editable); - ui.add_space(space::SM); - self.advanced_export_settings_ui(app, ui, field_scope, width, editable); - barcode_pending - } - - #[cfg(test)] - fn source_import_strip_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32) { - let t = Tokens::get(ui.ctx()).agent(); - let np = normalized_product_summary(&self.creation_brief); - let frame = egui::Frame::NONE - .fill(t.dock) - .stroke(egui::Stroke::new(1.0, t.card_border)) - .corner_radius(egui::CornerRadius::same(radius::CONTROL as u8)) - .inner_margin(egui::Margin::same(space::MD as i8)); - frame.show(ui, |ui| { - let inner_width = (width - 2.0 * space::MD - 2.0).max(160.0); - ui.set_width(inner_width); - ui.spacing_mut().item_spacing.y = space::SM; - if inner_width >= 600.0 { - ui.horizontal(|ui| { - ui.allocate_ui_with_layout(vec2(380.0, control::STANDARD), egui::Layout::left_to_right(egui::Align::Center), |ui| { - self.source_picker(ui); - }); - if self.creation_brief["source"] == "library" { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - self.product_search_button(app, ui); - }); - } - }); - } else { - self.source_picker(ui); - if self.creation_brief["source"] == "library" { - self.product_search_button(app, ui); - } - } - if self.creation_brief["source"] == "product_platform" { - self.platform_spu_ui(app, ui, field_scope, inner_width, np.has_platform_data); - } else if self.creation_brief["source"] == "library" { - self.product_select_results(app, ui); - } else { - stitch_kit::caption(ui, "直接填写下方商品档案,或随时切换到「产品平台」按 SPU 拉取规格与图片。"); - } - if !self.creation_reads.platform_sync_note.is_empty() { - stitch_kit::inline_notice(ui, "info", Tone::Verified, &self.creation_reads.platform_sync_note, |_| {}); - } - if np.has_platform_data { - let sku_count = project_barcodes(&self.creation_brief).count(); - let asset_count = selected_visual_asset_count(&self.creation_brief); - let mut meta = vec![format!("已同步 {} {}", np.trace_source, if np.spu.is_empty() { "商品资料" } else { np.spu.as_str() })]; - if sku_count > 0 { - meta.push(format!("{sku_count} 个条码")); - } - if asset_count > 0 { - meta.push(format!("{asset_count} 张素材")); - } - if !np.fetched_at.is_empty() { - meta.push(format!("同步时间 {}", np.fetched_at)); - } - ui.horizontal_wrapped(|ui| { - stitch_kit::label(ui, meta.join(" · "), Type::Meta, Tone::Success); - if !np.raw_field_warnings.is_empty() { - stitch_ui::status_chip(ui, &format!("{} 项字段待核对", np.raw_field_warnings.len()), stitch_ui::StatusTone::Warning); - } - }); - self.unmatched_platform_taxonomy_chips_ui(app, ui, &np); - } - }); - } - - fn unmatched_platform_taxonomy_chips_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, np: &NormalizedProductSummary) { - let cur_brand = self.creation_brief["brandName"].as_str().unwrap_or("").trim(); - let cur_cat = self.creation_brief["categoryName"].as_str().unwrap_or("").trim(); - let brand_unmatched = !np.platform_brand.is_empty() && !cur_brand.eq_ignore_ascii_case(&np.platform_brand); - let cat_unmatched = !np.platform_category.is_empty() && !cur_cat.eq_ignore_ascii_case(&np.platform_category); - if !brand_unmatched && !cat_unmatched { - return; - } - ui.horizontal_wrapped(|ui| { - stitch_kit::label(ui, "平台分类参考:", Type::Meta, Tone::Quiet); - if brand_unmatched { - let brands = self.creation_catalog.get("brands").cloned().unwrap_or_default(); - let matched = brands.iter().find(|row| { - row["ready"] == true - && row["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&np.platform_brand) || n.contains(&np.platform_brand)) - }); - let label = if matched.is_some() { - format!("应用品牌:{}", np.platform_brand) - } else { - format!("平台品牌:{}(待选择对应品牌)", np.platform_brand) - }; - let chip = stitch_ui::action_button(ui, &label, stitch_ui::ButtonRole::Quiet, true); - self.control_geometry("platform-brand-hint", chip.rect); - if chip.clicked() { - if let Some(row) = matched { - self.creation_brief["brandId"] = row["id"].clone(); - self.creation_brief["brandName"] = row["name"].clone(); - self.creation_brief["categoryId"] = json!(""); - self.creation_brief["categoryName"] = json!(""); - self.creation_brief["templateSelection"] = Value::Null; - self.creation_catalog.remove("categories"); - self.creation_catalog.remove("templates"); - self.catalog(app, "categories", String::new()); - self.creation_reads.inline_errors.remove("brand"); - self.creation_reads.manual_edited_fields.insert("brand".into()); - self.creation_dirty = true; - } else { - self.focus_brief_field("brand", &format!("请在品牌列表中选择与「{}」对应的品牌", np.platform_brand)); - } - } - } - if cat_unmatched { - let brand_id = self.creation_brief["brandId"].as_str().unwrap_or("").to_owned(); - let categories = self.creation_catalog.get("categories").cloned().unwrap_or_default(); - let matched = categories.iter().find(|row| { - row["brandId"] == brand_id - && row["ready"] == true - && row["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&np.platform_category) || n.contains(&np.platform_category)) - }); - let label = if matched.is_some() { - format!("应用品类:{}", np.platform_category) - } else { - format!("平台品类:{}(待选择对应品类)", np.platform_category) - }; - let chip = stitch_ui::action_button(ui, &label, stitch_ui::ButtonRole::Quiet, true); - self.control_geometry("platform-category-hint", chip.rect); - if chip.clicked() { - if let Some(row) = matched { - self.creation_brief["categoryId"] = row["id"].clone(); - self.creation_brief["categoryName"] = row["name"].clone(); - self.creation_brief["templateSelection"] = Value::Null; - self.creation_catalog.remove("templates"); - self.creation_reads.inline_errors.remove("category"); - self.creation_reads.manual_edited_fields.insert("category".into()); - self.creation_dirty = true; - } else { - self.focus_brief_field("category", &format!("请在品类列表中选择与「{}」对应的品类", np.platform_category)); - } - } - } - }); - } - - fn core_identity_and_specs_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32) { - #[cfg(test)] - let dynamic = self.creation_brief["intake"]["schema"]["version"] == 1; - let platform = self.creation_brief["source"] == "product_platform"; - let gap = space::MD; - let show_spu_here = !platform || self.creation_reads.wizard_stage.is_some(); - - // Row 1: Product Name + SPU (2 columns >= 560px, 1 column narrow) - if show_spu_here && width >= 560.0 { - let spu_w = (width * 0.36).clamp(180.0, 300.0); - let name_w = (width - spu_w - gap).max(160.0); - ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = gap; - self.product_name_field_ui(ui, field_scope, name_w); - self.spu_identifier_field_ui(ui, field_scope, spu_w); - }); - } else { - self.product_name_field_ui(ui, field_scope, width); - if show_spu_here { - ui.add_space(space::SM); - self.spu_identifier_field_ui(ui, field_scope, width); - } - } - - #[cfg(test)] - stitch_ui::morph_surface(ui, field_scope.with("dimensions-reveal"), !dynamic && self.creation_reads.wizard_stage.is_none(), self.reduce_motion, |ui| { - ui.add_space(space::SM); - self.dimensions_row_ui(ui, field_scope, width); - }); - - // Clean Platform Specs & Copy summary (materials, key attributes, selling points) - let np = normalized_product_summary(&self.creation_brief); - if np.has_platform_data && (!np.materials.is_empty() || !np.attributes.is_empty() || !np.summary.is_empty() || !np.selling_points.is_empty()) { - ui.add_space(space::SM); - self.platform_archive_summary_ui(ui, field_scope, width, &np); - } - - // Dynamic template productFields (with inline error + scroll-to-field support) - let product_fields = self.creation_brief["intake"]["schema"]["productFields"].clone(); - self.poll_imported_reference_previews(app, ui.ctx()); - let image_fields = product_fields.as_array().into_iter().flatten() - .filter(|field| field_kind(field) == "image").collect::>(); - let product_fields = product_fields.as_array().into_iter().flatten() - .filter(|field| field_kind(field) != "image" && !is_product_name_field(field)).collect::>(); - reveal_template_intake(ui, field_scope.with("product-intake-reveal"), - !product_fields.is_empty() || !image_fields.is_empty(), self.reduce_motion, |ui| { - ui.add_space(space::MD); - stitch_kit::label(ui, "模板商品字段", Type::Body, Tone::Active); - ui.add_space(space::XS); - let mut values = self.creation_brief["intake"]["productValues"].clone(); - if !values.is_object() { values = json!({}); } - if intake_fields_with_errors( - ui, - field_scope.with("intake-product"), - width, - &product_fields, - IntakeScope::Product, - &mut values, - self.reduce_motion, - None, - &mut self.creation_reads.inline_errors, - &mut self.creation_reads.scroll_to_field, - &mut self.creation_reads.manual_edited_fields, - ) { - self.creation_brief["intake"]["productValues"] = values; - self.creation_dirty = true; - } - for field in image_fields { - ui.add_space(space::SM); - self.image_slot_ui(app, ui, width, field, None); - } - }); - } - - fn product_name_field_ui(&mut self, ui: &mut Ui, field_scope: egui::Id, field_width: f32) { - let error = self.creation_reads.inline_errors.get("name").cloned(); - let scroll = self.creation_reads.scroll_to_field.as_deref() == Some("name"); - if scroll { - self.creation_reads.scroll_to_field = None; - } - let hint = self.creation_brief["intake"]["schema"]["productFields"].as_array().into_iter().flatten() - .find(|field| is_product_name_field(field)).map(intake_hint).filter(|hint| !hint.is_empty()) - .unwrap_or("输入当前商品名称").to_owned(); - field_group(ui, field_width, "产品名称 *", |ui| { - let field = ui.scope(|ui| { - edit_named_with_error( - ui, - (field_scope, "name"), - &mut self.creation_brief["name"], - field_width, - false, - &hint, - "产品名称", - error.as_deref(), - scroll, - ).0 - }); - if field.inner { - self.creation_dirty = true; - self.creation_reads.inline_errors.remove("name"); - self.creation_reads.manual_edited_fields.insert("name".into()); - } - self.control_geometry("name", field.response.rect); - }); - } - - fn spu_identifier_field_ui(&mut self, ui: &mut Ui, field_scope: egui::Id, field_width: f32) { - let error = self.creation_reads.inline_errors.get("identifier").cloned(); - let scroll = self.creation_reads.scroll_to_field.as_deref() == Some("identifier"); - if scroll { - self.creation_reads.scroll_to_field = None; - } - field_group(ui, field_width, "SPU 型号", |ui| { - let field_name = spu_field(&self.creation_brief); - let mut spu = self.creation_brief[field_name].clone(); - let field = ui.scope(|ui| { - edit_named_with_error( - ui, - (field_scope, "identifier"), - &mut spu, - field_width, - false, - "输入 SPU 型号", - "SPU 型号", - error.as_deref(), - scroll, - ).0 - }); - if field.inner { - self.creation_brief[field_name] = spu; - self.creation_dirty = true; - self.creation_reads.inline_errors.remove("identifier"); - } - if field_name == "deliverySpu" - && let Some(legacy) = self.creation_brief["identifier"].as_str().filter(|value| !value.is_empty()) - { - stitch_kit::caption(ui, format!("原项目编号 {legacy}")); - } - self.control_geometry("identifier", field.response.rect); - }); - } - - #[cfg(test)] - fn dimensions_row_ui(&mut self, ui: &mut Ui, field_scope: egui::Id, width: f32) { - let row_width = width.min(580.0); - field_group(ui, row_width, "产品尺寸(长 × 宽 × 高)", |ui| { - let dimensions = ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 6.0; - let text_color = Tokens::get(ui.ctx()).agent().text_dim; - let symbol_width = ui.painter().layout_no_wrap("×".into(), Type::Body.font_id(), text_color).size().x; - let unit_text_width = ["mm", "cm", "m"] - .iter() - .map(|unit| ui.painter().layout_no_wrap((*unit).to_owned(), Type::Meta.font_id(), text_color).size().x) - .fold(0.0_f32, f32::max); - let unit_width = (unit_text_width + 20.0 + 2.0 * ui.spacing().button_padding.x).max(62.0); - let dimension_width = ((row_width - unit_width - 2.0 * symbol_width - 5.0 * ui.spacing().item_spacing.x) / 3.0).max(56.0); - for (position, (key, hint)) in [("length", "长"), ("width", "宽"), ("height", "高")].iter().enumerate() { - if position > 0 { - ui.label(egui::RichText::new("×").font(Type::Body.font_id()).color(text_color)); - } - if edit_hint(ui, (field_scope, "dimensions", *key), &mut self.creation_brief["dimensions"][*key], dimension_width, false, hint) { - self.creation_dirty = true; - self.creation_reads.manual_edited_fields.insert(format!("dimensions:{key}")); - } - } - let unit_label = self.creation_brief["dimensions"]["unit"].as_str().unwrap_or("mm").to_owned(); - let unit = stitch_ui::halo_select(ui, "creation-unit", unit_width, &unit_label, self.reduce_motion, |ui| { - for unit in ["mm", "cm", "m"] { - let option = stitch_ui::select_option(ui, unit, self.creation_brief["dimensions"]["unit"] == unit, true); - self.control_geometry(&format!("unit-option-{unit}"), option.rect); - if option.clicked() { - self.creation_brief["dimensions"]["unit"] = json!(unit); - self.creation_dirty = true; - self.creation_reads.manual_edited_fields.insert("dimensions:unit".into()); - ui.close(); - } - } - }); - self.control_geometry("dimensions-unit", unit.response.rect); - }); - self.control_geometry("dimensions", dimensions.response.rect); - }); - } - - fn platform_archive_summary_ui(&mut self, ui: &mut Ui, field_scope: egui::Id, width: f32, np: &NormalizedProductSummary) { - let t = Tokens::get(ui.ctx()).agent(); - let frame = egui::Frame::NONE - .fill(t.dock) - .stroke(egui::Stroke::new(1.0, t.card_border)) - .corner_radius(egui::CornerRadius::same(radius::CONTROL as u8)) - .inner_margin(egui::Margin::same(space::MD as i8)); - frame.show(ui, |ui| { - let inner_width = (width - 2.0 * space::MD - 2.0).max(160.0); - ui.set_width(inner_width); - ui.spacing_mut().item_spacing.y = space::XS; - ui.horizontal_wrapped(|ui| { - stitch_kit::label(ui, "平台规格与卖点摘要", Type::Meta, Tone::Active); - if !np.series_or_model.is_empty() { - stitch_kit::label(ui, format!("系列:{}", np.series_or_model), Type::Meta, Tone::Quiet); - } - if let Some(dims) = np.dimensions_display.as_deref() { - stitch_kit::label(ui, format!("参考尺寸:{dims}"), Type::Meta, Tone::Quiet); - } - }); - if !np.materials.is_empty() { - ui.horizontal_wrapped(|ui| { - stitch_kit::label(ui, "材质:", Type::Meta, Tone::Quiet); - stitch_kit::label(ui, np.materials.join(" · "), Type::Meta, Tone::Active); - }); - } - if !np.attributes.is_empty() { - let preview_count = 6usize; - let cols = if inner_width >= 520.0 { 2 } else { 1 }; - let col_w = (inner_width - space::MD * (cols - 1) as f32) / cols as f32; - egui::Grid::new(field_scope.with("platform-attrs")) - .num_columns(cols) - .min_col_width(col_w) - .spacing(vec2(space::MD, space::XXS)) - .show(ui, |ui| { - for (idx, (label, value)) in np.attributes.iter().take(preview_count).enumerate() { - ui.horizontal_wrapped(|ui| { - ui.set_max_width(col_w); - stitch_kit::label(ui, format!("{label}:"), Type::Meta, Tone::Quiet); - stitch_kit::label(ui, value, Type::Meta, Tone::Active); - }); - if (idx + 1) % cols == 0 { - ui.end_row(); - } - } - }); - if np.attributes.len() > preview_count { - stitch_ui::disclosure(ui, field_scope.with("platform-attrs-more"), &format!("查看全部 {} 项规格参数", np.attributes.len()), false, self.reduce_motion, |ui| { - for (label, value) in np.attributes.iter().skip(preview_count) { - ui.horizontal_wrapped(|ui| { - stitch_kit::label(ui, format!("{label}:"), Type::Meta, Tone::Quiet); - stitch_kit::label(ui, value, Type::Meta, Tone::Active); - }); - } - }); - } - } - if !np.summary.is_empty() { - ui.add(egui::Label::new(egui::RichText::new(&np.summary).font(Type::Meta.font_id()).color(t.text_dim)).wrap()); - } - if !np.selling_points.is_empty() { - let shown = 3usize; - for point in np.selling_points.iter().take(shown) { - ui.add(egui::Label::new(egui::RichText::new(format!("· {point}")).font(Type::Meta.font_id()).color(t.text)).wrap()); - } - if np.selling_points.len() > shown { - stitch_ui::disclosure(ui, field_scope.with("platform-points-more"), &format!("展开其余 {} 条卖点", np.selling_points.len() - shown), false, self.reduce_motion, |ui| { - for point in np.selling_points.iter().skip(shown) { - ui.add(egui::Label::new(egui::RichText::new(format!("· {point}")).font(Type::Meta.font_id()).color(t.text)).wrap()); - } - }); - } - } - }); - } - - #[cfg(test)] - fn sku_matrix_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32) -> bool { - let dynamic = self.creation_brief["intake"]["schema"]["version"] == 1; - let platform = self.creation_brief["source"] == "product_platform"; - ui.add_space(space::MD); - if !dynamic && !platform { - if width >= 600.0 { - ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = space::MD; - let material_width = (width * 0.44).clamp(320.0, 420.0).min((width - 200.0).max(240.0)); - let heading_width = (width - material_width - space::MD).max(120.0); - let heading = ui.vertical(|ui| { - ui.set_width(heading_width); - stitch_kit::label(ui, "产品花色与款式条码", Type::Body, Tone::Active); - stitch_kit::caption(ui, "从材质库选择或手动添加花色,并录入对应条码。"); - }); - self.control_geometry("material-heading", heading.response.rect); - self.material_select(app, ui, material_width); - }); - } else { - stitch_kit::label(ui, "产品花色与款式条码", Type::Body, Tone::Active); - stitch_kit::caption(ui, "从材质库选择或手动添加花色,并录入对应条码。"); - ui.add_space(space::XS); - self.material_select(app, ui, width.min(420.0)); - } - ui.add_space(space::SM); - self.sku_colors_bar_ui(ui, width, field_scope); - ui.add_space(space::SM); - } else { - stitch_kit::label(ui, "款式与条码矩阵", Type::Body, Tone::Active); - stitch_kit::caption(ui, "按花色分组折叠展示;点选任一行「设为详情主款」或展开编辑单款参数与图片。"); - ui.add_space(space::XS); - } - self.barcode_cards_ui(app, ui, width, field_scope) - } - - fn template_and_brand_block_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { - let gap = space::MD; - if width >= 520.0 { - let column = (width - gap) / 2.0; - ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = gap; - field_group(ui, column, "品牌 *", |ui| self.brand_select(app, ui, column)); - field_group(ui, column, "品类 *", |ui| self.category_select(app, ui, column)); - }); - } else { - field_group(ui, width, "品牌 *", |ui| self.brand_select(app, ui, width)); - ui.add_space(space::SM); - field_group(ui, width, "品类 *", |ui| self.category_select(app, ui, width)); - } - ui.add_space(space::SM); - field_group(ui, width, "模板 *", |ui| self.template_select(app, ui, width)); - } - - fn advanced_export_settings_ui(&mut self, _app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32, _editable: bool) { - let variants = brief_variants(&self.creation_brief); - let has_variant_subsets = variants.len() > 1; - let has_legacy_sku = self.creation_brief.get("barcodeBindings").is_none(); - if !has_variant_subsets && !has_legacy_sku { - return; - } - let disclosure = stitch_ui::disclosure(ui, field_scope.with("advanced-export-settings"), "高级导出设置(选填)", false, self.reduce_motion, |ui| { - ui.spacing_mut().item_spacing.y = space::SM; - if has_variant_subsets { - ui.add_space(space::XS); - stitch_kit::label(ui, "指定出图花色范围", Type::Meta, Tone::Quiet); - let fields = [("detail", "详情图颜色"), ("main_images", "主图颜色")]; - let inner_w = width.min(ui.available_width()).max(120.0); - if inner_w >= 520.0 { - let column = (inner_w - space::MD) / 2.0; - ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = space::MD; - for (key, label) in fields { - field_group(ui, column, label, |ui| self.sku_output_picker(ui, column, key, &variants)); - } - }); - } else { - for (key, label) in fields { - field_group(ui, inner_w, label, |ui| self.sku_output_picker(ui, inner_w, key, &variants)); - } - } - } - if has_legacy_sku { - ui.add_space(space::XS); - stitch_ui::disclosure(ui, field_scope.with("legacy-sku-bindings"), "旧项目商品编号", false, self.reduce_motion, |ui| { - let mut list = variants.clone(); - if list.is_empty() { - list.push(json!({"id":"default","name":"当前花色"})); - } - let inner_w = ui.available_width(); - for variant in list { - let Some(id) = variant["id"].as_str() else { continue }; - let name = variant["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("当前花色"); - let label = format!("{name} · SKU 编号"); - let mut binding = self.creation_brief["skuBindings"][id].clone(); - if field_group(ui, inner_w, &label, |ui| { - edit_named(ui, field_scope.with(("delivery-skus", id)), &mut binding, inner_w, false, "多个 SKU 用逗号分隔", &label) - }).inner { - self.creation_brief["skuBindings"][id] = binding; - self.creation_dirty = true; - } - } - }); - } - }); - self.control_geometry("advanced-export-settings", disclosure.rect); - } - - fn special_requirements_ui(&mut self, ui: &mut Ui, scope: egui::Id) { - let width = ui.available_width(); - let group = field_group(ui, width, "制作要求与重点(选填)", |ui| { - let (edited, resp) = edit_named_with_error( - ui, - (scope, "note"), - &mut self.creation_brief["note"], - width, - true, - "可补充核心卖点侧重、画面风格、禁用元素或场景偏好,无特殊要求可留空。", - "制作要求与重点", - None, - false, - ); - if edited { - self.creation_dirty = true; - self.creation_reads.manual_edited_fields.insert("note".into()); - } - self.control_geometry("special-requirements-input", resp.rect); - }); - self.control_geometry("special-requirements", group.response.rect); - } - - #[cfg(test)] - fn barcode_cards_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, scope: egui::Id) -> bool { - let t = Tokens::get(ui.ctx()).agent(); - let fields = self.creation_brief["intake"]["schema"]["barcodeFields"].clone(); - let images = fields.as_array().into_iter().flatten().filter(|field| field_kind(field) == "image").collect::>(); - let fields = fields.as_array().into_iter().flatten().filter(|field| field_kind(field) != "image").collect::>(); - let has_barcode_schema = !fields.is_empty() || !images.is_empty(); - - // Preserve existing binding groups for adding/removing/renaming barcodes cleanly. - let variants = brief_variants(&self.creation_brief); - let mut binding_groups: Vec<(String, String)> = variants - .iter() - .filter_map(|variant| Some((variant["id"].as_str()?.to_owned(), variant["name"].as_str().unwrap_or("默认花色").to_owned()))) - .collect(); - if binding_groups.is_empty() || binding_barcodes(&self.creation_brief["barcodeBindings"]["default"]).next().is_some() { - binding_groups.insert(0, ("default".into(), "默认花色".into())); - } - - let norm_groups = normalized_color_groups(&self.creation_brief); - let total_barcodes: usize = norm_groups.iter().map(|g| g.skus.len()).sum(); - let default_detail = self.creation_brief["detailBarcode"].as_str().map(str::to_owned); - let mut pending = false; - - // If normalizedProduct or platformFacts grouped multiple colors, render collapsible color matrix. - let use_grouped_matrix = !norm_groups.is_empty() && (self.creation_brief["normalizedProduct"].is_object() || total_barcodes > 4); - - if use_grouped_matrix { - // Active detail-main SKU banner + selector at top of matrix. - update_detail_barcode(&mut self.creation_brief); - let codes: Vec = project_barcodes(&self.creation_brief).map(str::to_owned).collect(); - if codes.len() > 1 { - self.detail_barcode_selector_ui(ui, width, scope, &codes); - ui.add_space(space::SM); - } - let detail_code = self.creation_brief["detailBarcode"].as_str().unwrap_or("").to_owned(); - for (g_idx, group) in norm_groups.iter().enumerate() { - let contains_detail = group.skus.iter().any(|s| s.barcode == detail_code); - let default_open = total_barcodes <= 4 || contains_detail || (detail_code.is_empty() && g_idx == 0); - let is_open = if self.creation_reads.expanded_colors.contains(&group.id) { - true - } else if self.creation_reads.expanded_colors.contains(&format!("!{}", group.id)) { - false - } else { - default_open - }; - let frame = egui::Frame::NONE - .fill(t.dock) - .stroke(egui::Stroke::new(1.0, t.card_border)) - .corner_radius(egui::CornerRadius::same(radius::CONTROL as u8)) - .inner_margin(egui::Margin::symmetric(10, 8)); - frame.show(ui, |ui| { - let inner_w = (width - 22.0).max(140.0); - ui.set_width(inner_w); - let header_label = format!( - "{}({} 个规格){}", - group.color_name, - group.skus.len(), - if contains_detail { " · 含详情主款" } else { "" } - ); - let toggle = ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = space::XS; - ui.add(crate::icons::image(if is_open { "chevron-down" } else { "chevron-right" }, icon::SM, t.text_dim)); - stitch_ui::action_button(ui, &header_label, stitch_ui::ButtonRole::Quiet, true) - }).inner; - self.control_geometry(&format!("color-group-{}", group.id), toggle.rect); - if toggle.clicked() { - if is_open { - self.creation_reads.expanded_colors.remove(&group.id); - self.creation_reads.expanded_colors.insert(format!("!{}", group.id)); - } else { - self.creation_reads.expanded_colors.remove(&format!("!{}", group.id)); - self.creation_reads.expanded_colors.insert(group.id.clone()); - } - } - if is_open { - ui.add_space(space::XS); - for (s_idx, sku) in group.skus.iter().enumerate() { - if s_idx > 0 { - stitch_ui::divider(ui); - } - let code = sku.barcode.as_str(); - let is_detail = self.creation_brief["detailBarcode"] == code; - let closed_key = format!("!{code}"); - let mut sku_open = self.creation_reads.expanded_skus.contains(code) - || (has_barcode_schema && (is_detail || total_barcodes <= 2) - && !self.creation_reads.expanded_skus.contains(&closed_key)); - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing.x = space::SM; - let star_label = if is_detail { "详情主款" } else { "设为主款" }; - let star = stitch_ui::segmented_option_sized(ui, star_label, is_detail, true, vec2(76.0, 26.0)); - self.control_geometry(&format!("sku-main-{code}"), star.rect); - if star.clicked() && !is_detail { - self.creation_brief["detailBarcode"] = json!(code); - self.creation_brief["colorName"] = json!(sku.color_name); - self.creation_reads.inline_errors.remove("detail-barcode"); - self.creation_dirty = true; - } - ui.label(egui::RichText::new(code).font(egui::FontId::monospace(Type::Meta.size())).color(t.text)); - let mut meta_parts = Vec::new(); - if !sku.spec.is_empty() { - meta_parts.push(sku.spec.clone()); - } - if let Some(dims) = sku.dimensions_display.as_deref() - && !sku.spec.contains(dims) - { - meta_parts.push(dims.to_owned()); - } - if !meta_parts.is_empty() { - ui.add( - egui::Label::new(egui::RichText::new(meta_parts.join(" · ")).font(Type::Meta.font_id()).color(t.text_dim)) - .wrap_mode(egui::TextWrapMode::Extend), - ); - } - if sku.image_count > 0 { - ui.add( - egui::Label::new(egui::RichText::new(format!("{} 图", sku.image_count)).font(Type::Meta.font_id()).color(Tone::Verified.color(&t))) - .wrap_mode(egui::TextWrapMode::Extend), - ); - } - let expand_label = if sku_open { "收起参数" } else { "展开参数" }; - let expand_btn = stitch_ui::action_button(ui, expand_label, stitch_ui::ButtonRole::Quiet, true); - self.control_geometry(&format!("sku-expand-{code}"), expand_btn.rect); - if expand_btn.clicked() { - if sku_open { - self.creation_reads.expanded_skus.remove(code); - self.creation_reads.expanded_skus.insert(closed_key); - } else { - self.creation_reads.expanded_skus.remove(&closed_key); - self.creation_reads.expanded_skus.insert(code.to_owned()); - } - sku_open = !sku_open; - } - }); - let card_scope = scope.with(("norm-sku", code)); - stitch_ui::morph_surface(ui, card_scope.with("reveal"), sku_open, self.reduce_motion, |ui| { - ui.add_space(space::XS); - if has_barcode_schema { - self.barcode_intake_ui(app, ui, card_scope, inner_w, code, &fields, &images); - } else { - // Show platform SKU attributes / selling points when present. - if let Some(row) = self.creation_brief["normalizedProduct"]["variants"] - .as_array() - .into_iter() - .flatten() - .flat_map(|v| v["barcodes"].as_array().into_iter().flatten()) - .find(|b| non_empty_str(&b["barcode"]) == Some(code)) - { - let points = dedupe_strings(string_list(&row["sellingPoints"])); - for pt in points.iter().take(4) { - stitch_kit::caption(ui, format!("· {pt}")); - } - if let Some(sku_code) = non_empty_str(&row["skuCode"]) { - stitch_kit::caption(ui, format!("SKU 编码:{sku_code}")); - } - } - } - }); - } - } - }); - ui.add_space(space::XS); - } - // Still allow adding a manual barcode into default binding if user wants. - let mut extra_codes: Vec = binding_barcodes(&self.creation_brief["barcodeBindings"]["default"]).map(str::to_owned).collect(); - let (added, entry_pending) = self.barcode_entry_ui(ui, width, scope.with(("barcodes", "default")), "default", "手动补充条码", &mut extra_codes); - pending |= entry_pending; - if added { - self.creation_brief["barcodeBindings"]["default"] = json!(extra_codes); - self.creation_dirty = true; - } - update_detail_barcode(&mut self.creation_brief); - return pending; - } - - // Standard / Legacy editable barcode list (compact rows with inline main-SKU star + editable barcode). - let mut ordinal = 0; - for (id, label) in binding_groups { - let group_scope = scope.with(("barcodes", id.as_str())); - let mut codes: Vec = binding_barcodes(&self.creation_brief["barcodeBindings"][id.as_str()]).map(str::to_owned).collect(); - let single_before_add = project_barcodes(&self.creation_brief).take(2).count() == 1; - let (added, entry_pending) = self.barcode_entry_ui(ui, width, group_scope, &id, &label, &mut codes); - pending |= entry_pending; - let mut changed = added; - let mut remove = None; - for (index, code) in codes.iter_mut().enumerate() { - ordinal += 1; - let card = egui::Frame::NONE - .fill(t.dock) - .stroke(egui::Stroke::new(1.0, t.card_border)) - .corner_radius(egui::CornerRadius::same(radius::CONTROL as u8)) - .inner_margin(8) - .show(ui, |ui| { - let inner_w = (width - 18.0).max(1.0); - ui.set_width(inner_w); - let card_scope = group_scope.with(code.as_str()); - let draft_id = card_scope.with("edit"); - let mut draft = ui.data(|data| data.get_temp::(draft_id)).unwrap_or_else(|| code.clone()); - let mut commit = false; - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 8.0; - let number = ui.weak(format!("#{ordinal}")); - let delete_size = 24.0; - let edit_width = (ui.available_width() - delete_size - ui.spacing().item_spacing.x).clamp(1.0, 320.0); - let editor = barcode_editor(ui, card_scope, &mut draft, edit_width, "编辑产品条码"); - self.control_geometry(&format!("barcode-edit-{id}-{index}"), editor.rect); - commit = editor.lost_focus() || (editor.has_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter))); - if ui.input(|input| input.key_pressed(egui::Key::Escape)) && (editor.has_focus() || editor.lost_focus()) { - draft.clone_from(code); - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let delete = stitch_ui::icon_button(ui, "trash", delete_size, false, "删除条码"); - self.control_geometry(&format!("barcode-remove-{id}-{index}"), delete.rect); - if delete.clicked() { remove = Some(index); } - }); - self.control_geometry(&format!("barcode-number-{id}-{index}"), number.rect); - }); - if draft.trim() != code.as_str() { - if let Some(issue) = barcode_issue(&self.creation_brief, &draft) { - stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Warning); - } else if commit { - let replacement = draft.trim(); - replace_barcode(&mut self.creation_brief, code, Some(replacement)); - *code = replacement.to_owned(); - changed = true; - } - } - pending |= draft.trim() != code.as_str() && remove != Some(index); - ui.data_mut(|data| { - if draft == *code || commit && draft.trim() == code.as_str() || remove == Some(index) { - data.remove::(draft_id); - } else { - data.insert_temp(draft_id, draft); - } - }); - reveal_template_intake(ui, card_scope.with("reveal"), has_barcode_schema, self.reduce_motion, |ui| { - self.barcode_intake_ui(app, ui, card_scope, inner_w, code, &fields, &images); - }); - if fields.is_empty() { - let facts = &self.creation_brief["platformFacts"]["barcodes"][code.as_str()]; - let mut parts = Vec::new(); - for key in ["colorName", "sizeText", "spec"] { - if let Some(value) = non_empty_str(&facts[key]) - && !parts.iter().any(|existing: &String| existing.eq_ignore_ascii_case(value)) - { - parts.push(value.to_owned()); - } - } - if let Some(dimensions) = dimension_text(&facts["dimensions"]) { - parts.push(dimensions); - } - if !parts.is_empty() { - stitch_kit::caption(ui, parts.join(" · ")); - } - } - }); - self.control_geometry(&format!("barcode-card-{id}-{index}"), card.response.rect); - } - if let Some(index) = remove { - replace_barcode(&mut self.creation_brief, &codes.remove(index), None); - changed = true; - } - if changed { - self.creation_brief["barcodeBindings"][id.as_str()] = json!(codes); - if added && single_before_add && let Some(fields) = self.creation_brief.as_object_mut() { - fields.remove("detailBarcode"); - } - self.creation_dirty = true; - } - } - let _ = default_detail; - update_detail_barcode(&mut self.creation_brief); - let codes: Vec = project_barcodes(&self.creation_brief).map(str::to_owned).collect(); - if codes.len() > 1 { - ui.add_space(space::XS); - self.detail_barcode_selector_ui(ui, width, scope, &codes); - } - pending - } - - fn detail_barcode_selector_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id, codes: &[String]) { - let current = self.creation_brief["detailBarcode"].as_str().unwrap_or("").to_owned(); - let selected_label = if current.is_empty() { - "请选择详情主款".to_owned() - } else { - sku_display_label(&self.creation_brief, ¤t) - }; - let error = self.creation_reads.inline_errors.get("detail-barcode").cloned(); - let scroll = self.creation_reads.scroll_to_field.as_deref() == Some("detail-barcode"); - if scroll { - self.creation_reads.scroll_to_field = None; - } - field_group(ui, width, "详情主款 *", |ui| { - let picker = stitch_ui::halo_select_with_behavior( - ui, - scope.with("detail-barcode"), - width, - &selected_label, - self.reduce_motion, - egui::PopupCloseBehavior::CloseOnClickOutside, - |ui| { - egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { - for (index, code) in codes.iter().enumerate() { - let display = sku_display_label(&self.creation_brief, code); - let option = stitch_ui::select_option_sized(ui, &display, code == ¤t, true, vec2(ui.available_width(), control::STANDARD)); - self.control_geometry(&format!("detail-barcode-option-{index}"), option.rect); - if option.clicked() { - self.creation_brief["detailBarcode"] = json!(code); - self.creation_reads.inline_errors.remove("detail-barcode"); - if let Some(color) = normalized_color_groups(&self.creation_brief) - .into_iter() - .find(|g| g.skus.iter().any(|s| s.barcode == *code)) - .map(|g| g.color_name) - { - self.creation_brief["colorName"] = json!(color); - } else if self.creation_brief["source"] == "product_platform" { - self.creation_brief["colorName"] = json!(self.creation_brief["platformFacts"]["barcodes"][code.as_str()]["colorName"].as_str().unwrap_or("")); - } - self.creation_dirty = true; - ui.close(); - } - } - }); - }, - ); - if scroll { - picker.response.scroll_to_me(Some(egui::Align::Center)); - picker.response.request_focus(); - } - self.control_geometry("detail-barcode", picker.response.rect); - if let Some(err) = error.as_deref() { - stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error); - } - }); - } - - #[cfg(test)] - fn barcode_entry_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id, id: &str, label: &str, codes: &mut Vec) -> (bool, bool) { - let draft_id = scope.with("new-barcode"); - let mut draft = ui.data(|data| data.get_temp::(draft_id)); - let mut opened = false; - ui.horizontal(|ui| { - ui.set_width(width); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let add = stitch_ui::action_button(ui, "+ 添加条码", stitch_ui::ButtonRole::Quiet, true); - self.control_geometry(&format!("barcode-add-{id}"), add.rect); - if add.clicked() { - draft.get_or_insert_with(String::new); - opened = true; - } - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - ui.add(egui::Label::new(egui::RichText::new(label).font(Type::Body.semibold())).truncate()); - }); - }); - }); - let Some(mut text) = draft else { return (false, false) }; - let editor = barcode_editor(ui, draft_id, &mut text, width, "新增产品条码"); - self.control_geometry(&format!("barcode-input-{id}"), editor.rect); - if opened { editor.request_focus(); } - let issue = barcode_issue(&self.creation_brief, &text); - if !text.trim().is_empty() && let Some(issue) = issue { - stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Warning); - } - let mut added = false; - let mut cancelled = false; - ui.horizontal(|ui| { - let confirm = stitch_ui::action_button(ui, "添加", stitch_ui::ButtonRole::Secondary, issue.is_none()); - self.control_geometry(&format!("barcode-confirm-{id}"), confirm.rect); - if issue.is_none() && (confirm.clicked() || ((editor.has_focus() || editor.lost_focus()) && ui.input(|input| input.key_pressed(egui::Key::Enter)))) { - codes.push(text.trim().to_owned()); - added = true; - } - cancelled = stitch_ui::action_button(ui, "取消", stitch_ui::ButtonRole::Quiet, true).clicked(); - }); - let pending = !added && !cancelled && !text.trim().is_empty(); - ui.data_mut(|data| { - if added || cancelled { data.remove::(draft_id); } - else { data.insert_temp(draft_id, text); } - }); - (added, pending) - } - - pub(super) fn output_tags_ui(&mut self, ui: &mut Ui) { - let mut scopes = selected_output_scopes(&self.creation_brief); - let mut changed = false; - ui.horizontal_wrapped(|ui| { - stitch_kit::label(ui, "输出内容", Type::Meta, Tone::Quiet); - for (control_id, scope_key, label) in OUTPUT_SCOPE_OPTIONS { - let selected = scopes.iter().any(|item| item == scope_key); - let enabled = !selected || scopes.len() > 1; - let response = stitch_ui::toggle_option(ui, label, selected, enabled) - .on_disabled_hover_text("至少保留一项输出内容"); - self.control_geometry(control_id, response.rect); - if response.clicked() { - if selected { - scopes.retain(|item| item != scope_key); - } else { - scopes.push(scope_key.to_owned()); - } - changed = true; - } - } - }); - if changed { - self.creation_brief["outputScopes"] = json!(scopes); - self.creation_reads.manual_edited_fields.insert("outputScopes".into()); - self.creation_dirty = true; - } - } - - #[cfg(test)] - fn brief_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - let barcode_pending = self.brief_scroll_body_ui(app, ui); - ui.add_space(space::MD); - stitch_ui::divider(ui); - ui.add_space(space::MD); - self.brief_footer_ui(app, ui, barcode_pending); - } - - pub(super) fn brief_setup_warning(&self) -> Option<(&'static str, &'static str, &'static str)> { - if !self.key_saved { - Some(("尚未连接个人 Key,请先配置个人 Key", "个人 Key 未连接", "配置个人 Key")) - } else if !(self.model_ready && self.image_ready) { - Some(("尚未配置对话或生图模型", "模型未配置", "选择模型")) - } else { - None - } - } - - pub(super) fn open_brief_setup_settings(&mut self) { - self.open_model_settings(); - if !self.key_saved { - self.key_settings = true; - } - } - - fn brief_footer_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, barcode_pending: bool) { - let template = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); - let readiness = brief_readiness(&self.creation_brief, &template); - let missing_items: Vec<&ReadinessItem> = readiness.iter().filter(|item| !item.ready).collect(); - let missing = canvas_entry_missing(&self.creation_brief, &template); - let new_project = self.template_workflow["canvasFirst"] != true; - let chosen_pending = template.is_null() && self.creation_reads.resource_set["id"].is_string(); - let scoped_pending = self.scoped_production_pending(); - let setup_warning = new_project.then(|| self.brief_setup_warning()).flatten(); - - let blocked = if self.unknown { - Some(if scoped_pending { "可继续制作其余图位。" } else { "请先核查原请求,再进入模板画布。" }.to_owned()) - } else if self.busy.is_some() { - Some("请等待当前操作完成。".to_owned()) - } else if barcode_pending { - Some("请确认正在编辑的条码。".to_owned()) - } else if missing == ["模板"] && chosen_pending { - if self.creation_catalog_loading("resource-set") || self.creation_catalog_loading("resource-component") { - Some("正在核对模板资料,请稍候。".to_owned()) - } else if self.creation_reads.resource_component.is_empty() - && self.creation_catalog.get("resource-set").is_some_and(|parts| parts.len() > 1) - { - Some("请选择要使用的模板组件。".to_owned()) - } else { - Some("所选模板暂不可用,请查看模板区的提示。".to_owned()) - } - } else if !missing_items.is_empty() { - let names: Vec<&str> = missing_items.iter().map(|i| i.label.as_str()).collect(); - Some(format!("待补齐:{}", names.join("、"))) - } else { - None - }; - - // Compact single-row footer when in 3-stage wizard mode - let mut clicked_missing: Option<(String, String)> = None; - let actions_ready = self.busy.is_none() && !self.unknown && !barcode_pending; - let canvas_ready = actions_ready && missing_items.is_empty() && missing.is_empty(); - let production_ready = blocked.is_none() && setup_warning.is_none(); - let refinement = if new_project { - let doc = app.session.active().map(|state| state.doc.id.0); - let id = egui::Id::unique(("production-refinement", self.local_identity(""), doc)); - Some(ui.data(|data| data.get_temp::(id)).unwrap_or(false)) - } else { - None - }; - if self.creation_reads.wizard_stage.is_some() { - self.reference_drop_warning_ui(ui); - let resume = self.has_production_stages() || self.has_paused_production(); - let mut open_settings = false; - let mut recorded_geometries: Vec<(String, egui::Rect)> = Vec::new(); - let mut button_geometries: Vec<(WizardFooterOutcome, egui::Rect)> = Vec::new(); - let autosave_info = if self.creation_reads.staged_new_project { - ("草稿暂存中", Tone::Quiet) - } else if self.busy.as_deref() == Some("creation-save") { - ("保存中…", Tone::Quiet) - } else if self.creation_dirty { - ("有未保存修改 · 将自动保存", Tone::Warning) - } else { - ("已自动保存", Tone::Success) - }; - let key_saved = self.key_saved; - let action = wizard::wizard_footer_ui_with_status( - ui, - WizardFooterState { - stage: CreationStage::Details, - can_continue: resume, - can_enter_canvas: canvas_ready, - can_start: if resume { self.can_resume_product() } else { production_ready }, - }, - new_project || resume, - |ui| { - let hint_row = ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = space::XS; - if !missing_items.is_empty() { - stitch_kit::label(ui, "待补齐:", Type::Meta, Tone::Warning); - for item in &missing_items { - let chip = stitch_ui::action_button(ui, &item.label, stitch_ui::ButtonRole::Quiet, true) - .on_hover_text(&item.message); - recorded_geometries.push((format!("readiness-{}", item.field_key), chip.rect)); - if chip.clicked() { - clicked_missing = Some((item.field_key.clone(), item.message.clone())); - } - } - } else if let Some(msg) = blocked.as_deref() { - stitch_ui::status_label(ui, msg, stitch_ui::StatusTone::Warning); - } else { - stitch_kit::label(ui, autosave_info.0, Type::Meta, autosave_info.1); - } - if let Some((message, chip, action)) = setup_warning { - stitch_ui::status_chip(ui, chip, stitch_ui::StatusTone::Warning).on_hover_text(message); - let configure = stitch_ui::action_button(ui, action, stitch_ui::ButtonRole::Quiet, true); - recorded_geometries.push((if key_saved { "select-model" } else { "configure-personal-key" }.to_owned(), configure.rect)); - if configure.clicked() { - open_settings = true; - } - } - }); - recorded_geometries.push(("entry-hint".to_owned(), hint_row.response.rect)); - }, - |action, response| { - button_geometries.push((action, response.rect)); - }, - ); - for (k, rect) in recorded_geometries { - self.control_geometry(&k, rect); - } - for (btn_action, rect) in button_geometries { - match btn_action { - WizardFooterOutcome::EnterCanvas => self.control_geometry("enter-canvas", rect), - WizardFooterOutcome::Start => self.control_geometry(if resume { "resume-product" } else { "start-product" }, rect), - _ => {} - } - } - if open_settings { - self.open_brief_setup_settings(); - } - if let Some((key, msg)) = clicked_missing.take() { - self.focus_brief_field(&key, &msg); - } - match action { - WizardFooterOutcome::Start if resume => self.resume_product_production(app), - WizardFooterOutcome::Start | WizardFooterOutcome::EnterCanvas => { - self.enter_creation_canvas(app, &template, action == WizardFooterOutcome::Start, refinement); - } - _ => self.handle_wizard_navigation(app, action), - } - } - #[cfg(test)] - if self.creation_reads.wizard_stage.is_none() { - let hint_row = ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing.x = space::SM; - if !missing_items.is_empty() { - stitch_kit::label(ui, "待补齐:", Type::Meta, Tone::Warning); - for item in &missing_items { - let chip = stitch_ui::action_button(ui, &item.label, stitch_ui::ButtonRole::Quiet, true) - .on_hover_text(&item.message); - self.control_geometry(&format!("readiness-{}", item.field_key), chip.rect); - if chip.clicked() { - clicked_missing = Some((item.field_key.clone(), item.message.clone())); - } - } - } else if let Some(msg) = blocked.as_deref() { - stitch_ui::status_label(ui, msg, stitch_ui::StatusTone::Warning); - } - if let Some((message, chip, action)) = setup_warning { - stitch_ui::status_chip(ui, chip, stitch_ui::StatusTone::Warning).on_hover_text(message); - let configure = stitch_ui::action_button(ui, action, stitch_ui::ButtonRole::Secondary, true); - self.control_geometry(if self.key_saved { "select-model" } else { "configure-personal-key" }, configure.rect); - if configure.clicked() { - self.open_brief_setup_settings(); - } - } - }); - self.control_geometry("entry-hint", hint_row.response.rect); - if let Some((key, msg)) = clicked_missing { - self.focus_brief_field(&key, &msg); - } - ui.horizontal_wrapped(|ui| { - self.brief_autosave_status_ui(ui); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.spacing_mut().item_spacing.x = space::SM; - if self.has_production_stages() || self.has_paused_production() { - let resume = stitch_ui::action_button(ui, "继续整套制作", stitch_ui::ButtonRole::Primary, self.can_resume_product()); - self.control_geometry("resume-product", resume.rect); - if resume.clicked() { - self.resume_product_production(app); - } - } - self.brief_enter_button(app, ui, &template, production_ready, canvas_ready, refinement); - }); - }); - } - } - - fn sku_colors_bar_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id) { - let mut variants = brief_variants(&self.creation_brief); - let draft_id = scope.with("manual-sku-color"); - let mut draft = ui.data(|data| data.get_temp::(draft_id)).unwrap_or(Value::Null); - let add_width = 76.0; - let gap = space::SM; - let add = ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = gap; - let entry = ui.scope(|ui| { - edit_named(ui, draft_id, &mut draft, (width - add_width - gap).max(120.0), false, "输入花色名称", "新增花色") - }); - self.control_geometry("sku-color-input", entry.response.rect); - let color = draft.as_str().unwrap_or("").trim(); - let duplicate = variants.iter().any(|row| row["colorName"].as_str().is_some_and(|name| name.eq_ignore_ascii_case(color))); - let enabled = !color.is_empty() && color.chars().count() <= 120 && !duplicate && variants.len() < 64; - let button = stitch_ui::action_button(ui, "添加颜色", stitch_ui::ButtonRole::Secondary, enabled) - .on_disabled_hover_text(if duplicate { "此花色已添加" } else { "请输入颜色名称,最多添加 64 个花色" }); - self.control_geometry("sku-color-add", button.rect); - button.clicked() - }).inner; - if add { - let color = draft.as_str().unwrap_or("").trim(); - variants.push(json!({"id":variant_identity(&format!("manual-sku:{color}")),"name":color,"colorName":color,"colorMaterialId":"","images":[]})); - self.save_sku_colors(variants.clone()); - draft = Value::Null; - } - ui.data_mut(|data| data.insert_temp(draft_id, draft)); - - let mut remove = None; - if !variants.is_empty() { - ui.add_space(space::XS); - ui.horizontal_wrapped(|ui| { - for variant in &variants { - let name = variant["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("原项目花色"); - let removable = self.sku_color_removable(variant); - let t = Tokens::get(ui.ctx()).agent(); - egui::Frame::NONE - .fill(t.dock) - .stroke(egui::Stroke::new(1.0, t.card_border)) - .corner_radius(egui::CornerRadius::same(radius::ROW as u8)) - .inner_margin(egui::Margin::symmetric(8, 3)) - .show(ui, |ui| { - ui.horizontal(|ui| { - let font = Type::Meta.font_id(); - let measured = ui.painter().layout_no_wrap(name.into(), font.clone(), t.text).size().x; - ui.add_sized( - vec2(measured.min((width - 42.0).max(20.0)), 22.0), - egui::Label::new(egui::RichText::new(name).font(font)).truncate(), - ) - .on_hover_text(name); - if removable && stitch_ui::icon_button(ui, "x", 20.0, false, &format!("移除 {name}")).clicked() { - remove = variant["id"].as_str().map(str::to_owned); - } - }); - }); - } - }); - } - if let Some(remove) = remove { - variants.retain(|row| row["id"] != remove); - self.save_sku_colors(variants); - } - } - - fn sku_output_picker(&mut self, ui: &mut Ui, width: f32, component: &str, variants: &[Value]) { - let mut selected = self.creation_brief["outputVariantIds"][component].as_array().cloned().unwrap_or_default(); - let summary = match selected.as_slice() { - [] if variants.is_empty() => "请先添加花色".into(), - [] => format!("全部 {} 个花色", variants.len()), - [id] => variants.iter().find(|row| row["id"] == *id).and_then(|row| row["name"].as_str()).unwrap_or("已选 1 个颜色").to_owned(), - ids => format!("已选 {} 个花色", ids.len()), - }; - let picker_id = format!("sku-output-{component}"); - let mut changed = false; - let menu_height = ((variants.len() + 1) as f32 * (PICKER_ROW_HEIGHT + ui.spacing().item_spacing.y)).min(PICKER_HEIGHT); - let result = ui.add_enabled_ui(!variants.is_empty(), |ui| picker_height(ui, &picker_id, width, menu_height, &summary, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| { - if picker_row(ui, selected.is_empty(), "全部 SKU 颜色", true).clicked() { - selected.clear(); - changed = true; - ui.close(); - } - for row in variants { - let name = row["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("原项目花色"); - let index = selected.iter().position(|id| *id == row["id"]); - let response = picker_toggle_row(ui, index.is_some(), name, index.is_none() || selected.len() > 1) - .on_disabled_hover_text("至少保留一个颜色,或选择全部 SKU 颜色"); - self.control_geometry(&format!("{picker_id}-{}", row["id"].as_str().unwrap_or("")), response.rect); - if response.clicked() { - if let Some(index) = index { selected.remove(index); } - else { selected.push(row["id"].clone()); } - changed = true; - } - } - })).inner; - self.control_geometry(&picker_id, result.response.rect); - if changed { - if !self.creation_brief["outputVariantIds"].is_object() { - self.creation_brief["outputVariantIds"] = json!({}); - } - if let Some(outputs) = self.creation_brief["outputVariantIds"].as_object_mut() { - if selected.is_empty() { outputs.remove(component); } - else { outputs.insert(component.to_owned(), json!(selected)); } - } - self.creation_dirty = true; - } - } - - fn save_sku_colors(&mut self, variants: Vec) { - for field in ["skuBindings", "barcodeBindings"] { - if let Some(bindings) = self.creation_brief.get_mut(field).and_then(Value::as_object_mut) { - if field == "barcodeBindings" && variants.len() == 1 { - if let Some(default) = bindings.remove("default") { - if let Some(id) = variants[0]["id"].as_str() { - bindings.entry(id.to_owned()).or_insert(default); - } - } - } - bindings.retain(|id, _| id == "default" || variants.iter().any(|variant| variant["id"] == *id)); - } - } - set_brief_variants(&mut self.creation_brief, variants); - if !self.creation_brief["outputVariantIds"].is_object() { - self.creation_brief["outputVariantIds"] = json!({}); - } - self.creation_dirty = true; - } - - fn sku_color_removable(&self, variant: &Value) -> bool { - variant["images"].as_array().is_none_or(Vec::is_empty) - && !self.template_workflow["variants"].as_array().into_iter().flatten().any(|saved| saved["id"] == variant["id"]) - && !["detail", "main_images"].into_iter().any(|key| { - self.creation_brief["outputVariantIds"][key].as_array().into_iter().flatten().any(|id| *id == variant["id"]) - }) - } - - fn delivery_directory_control(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, editable: bool) { - stitch_kit::label(ui, "成品保存位置", Type::Meta, Tone::Quiet); - let path = self.creation_delivery_dir.as_deref().unwrap_or("未选择(默认仅保存到项目内)"); - ui.add(egui::Label::new(egui::RichText::new(path).font(Type::Meta.font_id())).wrap()).on_hover_text(path); - ui.horizontal_wrapped(|ui| { - let choose = stitch_ui::action_button(ui, "选择文件夹", stitch_ui::ButtonRole::Secondary, editable); - self.control_geometry("choose-delivery-directory", choose.rect); - if choose.clicked() { - let initial_dir = self.creation_delivery_dir.clone(); - let doc = self.creation_doc; - let identity = self.local_identity(""); - if let Err(error) = app.ask_file(crate::FileDialogRequest::Folder { initial_dir }, move |app, answer| { - let path = match answer { - crate::FileDialogAnswer::FolderTo(path) => path, - crate::FileDialogAnswer::Unavailable(error) => return Err(error), - _ => return Ok(Value::Null), - }; - let w = app.jiansun.as_mut().filter(|w| w.creation_doc == doc && w.local_identity("") == identity) - .ok_or("账号或项目已切换,未修改保存目录")?; - if !std::path::Path::new(&path).is_absolute() { - return Err("请选择绝对路径的成品目录".into()); - } - if app.session.active().and_then(|state| state.path.as_deref()) - .map(std::path::Path::new).and_then(std::path::Path::parent) - .is_some_and(|draft| std::path::Path::new(&path).starts_with(draft) && draft.ends_with( - w.open_projects.get(&doc.unwrap_or_default()).and_then(|id| id.rsplit('|').next()).unwrap_or_default())) - { - return Err("请选择项目草稿目录以外的位置".into()); - } - w.creation_delivery_dir = Some(path.clone()); - w.creation_dirty = true; - remember_delivery_dir(app, &path); - Ok(Value::Null) - }) { - self.error = error; - } - } - let clear = stitch_ui::action_button(ui, "清除", stitch_ui::ButtonRole::Quiet, editable && self.creation_delivery_dir.is_some()); - self.control_geometry("clear-delivery-directory", clear.rect); - if clear.clicked() { - self.creation_delivery_dir = None; - self.creation_dirty = true; - } - }); - } - - fn add_reference_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) -> egui::Rect { - self.reference_picker(app, ui, width, egui::Id::unique("creation-reference-drop"), None, Value::Null) - } - - fn reference_picker(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, - id: egui::Id, labels: Option<(&str, &str)>, slot: Value, - ) -> egui::Rect { - let supported = ui.input(|input| { - let files = &input.raw.hovered_files; - !files.is_empty() && files.len() <= 8 && files.iter().all(|file| { - if let Some(path) = &file.path { - reference_image_path(path) || (slot.is_null() && files.len() == 1 && path.is_dir()) - } else { - matches!(file.mime.as_str(), "image/png" | "image/jpeg" | "image/webp") - } - }) - }); - let enabled = ui.is_enabled() && self.busy.is_none() && !self.unknown; - let drop_pointer = if supported && enabled { - let to_local = ui.ctx().layer_transform_from_global(ui.layer_id()).unwrap_or_default(); - app.services.cursor_pos.as_mut().and_then(|cursor| cursor(ui.ctx())) - .map(|point| to_local * point).filter(|point| ui.clip_rect().contains(*point)) - } else { - None - }; - let add_reference = if let Some((label, placeholder)) = labels { - stitch_ui::labeled_file_drop_zone(ui, id, width, drop_pointer, enabled, self.reduce_motion, label, Some(placeholder)) - } else { - stitch_ui::file_drop_zone(ui, id, width, drop_pointer, enabled, self.reduce_motion) - } - .on_hover_text("支持 PNG、JPG、WebP;每次最多 8 张,单张不超过 20 MB"); - if slot.is_null() { self.control_geometry("reference-add", add_reference.rect); } - if enabled && add_reference.clicked() { - self.open_reference_dialog(app, slot, false); - } - add_reference.rect - } - - fn open_reference_dialog(&mut self, app: &mut PhotocraftApp, slot: Value, folder: bool) { - let id = app.session.active().map(|s| s.doc.id.0); - let staged = self.creation_reads.staged_new_project; - let stage = self.creation_reads.wizard_stage; - let account = self.account["id"].clone(); - let origin = self.origin.clone(); - let request = if folder { - crate::FileDialogRequest::Folder { initial_dir: None } - } else { - crate::FileDialogRequest::Open { - multiple: slot["multiple"] != false, - initial_dir: None, - extensions: Some(vec!["png".into(), "jpg".into(), "jpeg".into(), "webp".into()]), - } - }; - let result = app.ask_file(request, move |app, answer| { - if app.session.active().map(|s| s.doc.id.0) != id || app.jiansun.as_ref().is_none_or(|w| { - w.account["id"] != account || w.origin != origin || (w.creation_doc != id && !staged) - || w.creation_reads.staged_new_project != staged || w.creation_reads.wizard_stage != stage - || !w.creation_open || w.creation_step != 0 || w.library || w.material - }) { - return Err("账号或项目已切换,未导入到其他项目".into()); - } - let paths = match answer { - crate::FileDialogAnswer::Paths(paths) => Ok(paths), - crate::FileDialogAnswer::FolderTo(path) => reference_folder_paths(std::path::Path::new(&path)), - _ => Err("请选择本机产品图片".into()), - }; - if let Err(error) = paths.and_then(|paths| app.import_reference_paths(paths, slot)) - && let Some(w) = app.jiansun.as_mut() - { - w.creation_reads.reference_import_error = error; - } - Ok(Value::Null) - }); - if let Err(error) = result { - self.creation_reads.reference_import_error = error; - } - } - - #[cfg(test)] - fn brief_enter_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, template: &Value, production_ready: bool, canvas_ready: bool, refinement: Option) { - let whole_allowed = self.template_workflow["canvasFirst"] != true; - // Right-to-left parent places Primary on the far right, Secondary beside it. - let generate = whole_allowed && { - let button = stitch_ui::action_button(ui, "确认并开始制作", stitch_ui::ButtonRole::Primary, production_ready); - self.control_geometry("generate-product", button.rect); - button.clicked() - }; - let enter = stitch_ui::action_button( - ui, - "进入模板画布", - if whole_allowed { stitch_ui::ButtonRole::Secondary } else { stitch_ui::ButtonRole::Primary }, - canvas_ready, - ); - self.control_geometry("enter-canvas", enter.rect); - if enter.clicked() || generate { - self.enter_creation_canvas(app, template, generate, refinement); - } - } - - fn enter_creation_canvas(&mut self, app: &mut PhotocraftApp, template: &Value, generate: bool, refinement: Option) { - if let Err(error) = self.ensure_creation_document(app) { - self.error = error; - return; - } - let mut brief = self.creation_brief.clone(); - update_detail_barcode(&mut brief); - let variants = brief_variants(&brief); - set_brief_variants(&mut brief, variants); - brief["templateSelection"] = template.clone(); - if let Err(error) = self.slot_action(app, "slot-skeleton", json!({ - "brief": brief, - "template": template, - "outputId": "detail", - "generateProduct": generate, - "deliveryDir": self.creation_delivery_dir, - "refinement": refinement, - })) { - self.error = error; - } else { - self.creation_reads.new_project_doc = None; - self.creation_open = false; - self.creation_step = 3; - self.library = false; - self.material = false; - } - } - - fn platform_spu_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32, has_synced: bool) { - let query_id = scope.with("platform-spu-query"); - let seed = if self.creation_brief["identifierType"] == "spu" { &self.creation_brief["identifier"] } - else { &self.creation_brief["deliverySpu"] }; - let mut query = ui.data(|data| data.get_temp::(query_id)).unwrap_or_else(|| seed.clone()); - let loading = self.busy.as_deref() == Some("creation-product-platform"); - let logged_in = self.account["id"].is_string(); - let error = self.creation_reads.inline_errors.get("identifier").cloned(); - let scroll = self.creation_reads.scroll_to_field.as_deref() == Some("identifier"); - if scroll { - self.creation_reads.scroll_to_field = None; - } - ui.horizontal_wrapped(|ui| { - let btn_reserve = 128.0; - let input_w = if width >= 340.0 { (width - btn_reserve).max(140.0) } else { width }; - let (edited, resp) = edit_named_with_error( - ui, - query_id, - &mut query, - input_w, - false, - "输入 SPU 型号或条码", - "SPU 型号", - error.as_deref(), - scroll, - ); - if edited { - self.creation_reads.inline_errors.remove("identifier"); - } - self.control_geometry("identifier", resp.rect); - let spu = query.as_str().unwrap_or("").trim(); - let btn_label = if loading { "拉取中…" } else if has_synced { "重新拉取" } else { "拉取资料" }; - let fetch = stitch_ui::action_button( - ui, - btn_label, - stitch_ui::ButtonRole::Secondary, - logged_in && form_editable(self.busy.as_deref(), self.unknown) && !spu.is_empty(), - ); - self.control_geometry("platform-fetch", fetch.rect); - if loading { - stitch_ui::ai_loader(ui, scope.with("platform-fetch-loader"), true, self.reduce_motion); - } - if fetch.clicked() { - self.creation_reads.platform_message.clear(); - self.creation_reads.platform_sync_note.clear(); - if let Err(error) = self.creation_action(app, "creation-product-platform", json!({"spu":spu})) { - self.creation_reads.platform_message = error; - } - } - }); - ui.data_mut(|data| data.insert_temp(query_id, query)); - let message = if logged_in { self.creation_reads.platform_message.as_str() } else { "请先登录素材库账号后再拉取产品平台资料" }; - if !message.is_empty() { - stitch_kit::inline_notice(ui, "triangle-alert", Tone::Warning, message, |_| {}); - } - } - - #[allow(clippy::too_many_arguments)] - fn barcode_intake_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32, - code: &str, fields: &[&Value], images: &[&Value], - ) { - let mut values = self.creation_brief["intake"]["barcodeValues"][code].clone(); - if !values.is_object() { values = json!({}); } - if !fields.is_empty() && intake_fields_with_errors( - ui, scope, width, fields, IntakeScope::Barcode, &mut values, self.reduce_motion, Some(code), - &mut self.creation_reads.inline_errors, &mut self.creation_reads.scroll_to_field, - &mut self.creation_reads.manual_edited_fields, - ) { - self.creation_brief["intake"]["barcodeValues"][code] = values; - self.creation_dirty = true; - } - for field in images { - self.image_slot_ui(app, ui, width, field, Some(code)); - } - } - - fn image_slot_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, field: &Value, barcode: Option<&str>) { - let slot = image_slot(&self.creation_brief["intake"]["templateId"], field, barcode); - self.image_slot_control_ui(app, ui, width, &intake_label(field), intake_hint(field), slot); - } - - fn image_slot_control_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, label: &str, placeholder: &str, slot: Value) { - stitch_kit::label(ui, label, Type::Meta, Tone::Quiet); - let key = self.creation_field_scope(app).with(("reference-image-slot", slot.to_string())); - let drop = self.reference_picker(app, ui, width, key, Some((label, placeholder)), slot.clone()); - if ui.is_enabled() && let Some(mut target) = self.reference_drop_geometry(app, ui, drop) { - target["slot"] = slot.clone(); - target["label"] = json!(label); - target["placeholder"] = json!(placeholder); - self.creation_view_geometry["imageSlots"][key.value().to_string()] = target; - } - let rows = self.creation_brief["images"].as_array().cloned().unwrap_or_default(); - let mut remove = None; - for (index, image) in rows.iter().enumerate().filter(|(_, image)| in_image_slot(image, &slot)) { - let Some(source) = image["source"].as_str() else { continue }; - self.queue_creation_reference(app, source); - let preview_key = super::creation_reads::reference_key(source); - ui.horizontal(|ui| { - material_thumbnail(ui, self.creation_thumbs.get(&preview_key), self.creation_thumbnail_loading(&preview_key), - self.creation_thumbnail_error(&preview_key).is_some()); - let response = stitch_ui::icon_button(ui, "trash", 28.0, false, "删除图片"); - if response.clicked() { remove = Some(index); } - let name = image["name"].as_str().unwrap_or("图片"); - ui.add(egui::Label::new(egui::RichText::new(name).font(Type::Meta.font_id())).truncate()).on_hover_text(name); - }); - } - if let Some(index) = remove { - self.creation_brief["images"] = json!(rows.into_iter().enumerate() - .filter_map(|(position, image)| (position != index).then_some(image)).collect::>()); - self.creation_dirty = true; - } - } - - fn source_picker(&mut self, ui: &mut Ui) { - let choices = [("upload", "手工录入"), ("product_platform", "产品平台"), ("library", "素材库产品")]; - let options = choices.map(|(_, label)| (label, true)); - let selected = choices.iter().position(|(value, _)| self.creation_brief["source"] == *value).unwrap_or(0); - let rail = stitch_ui::segmented_control(ui, ui.scope_id().with("creation-source"), &options, selected, self.reduce_motion); - if let Some(index) = rail.selected && index != selected { - self.creation_brief["source"] = json!(choices[index].0); - self.creation_dirty = true; - } - let mut bounds = egui::Rect::NOTHING; - let mut geometry = Vec::new(); - for ((value, label), response) in choices.into_iter().zip(rail.responses) { - bounds = bounds.union(response.rect); - self.control_geometry(&format!("source-{value}"), response.rect); - geometry.push(json!({"id":value,"label":label,"ready":true,"selected":self.creation_brief["source"] == value,"rect":rect_value(response.rect)})); - } - self.control_geometry("source", bounds); - self.creation_view_geometry["sourceChoices"] = json!(geometry); - self.creation_view_geometry["popups"]["source"] = json!({"open":false,"loading":false,"ready":true,"rect":null,"rows":[]}); - } - - fn reference_drop_geometry(&self, app: &PhotocraftApp, ui: &Ui, rect: egui::Rect) -> Option { - let visible = rect.intersect(ui.clip_rect()); - if !visible.is_positive() || !visible.is_finite() { - return None; - } - let layer = ui.layer_id(); - let global = ui.ctx().layer_transform_to_global(layer).unwrap_or_default() * visible; - Some(json!({ - "doc":app.session.active().map(|state| state.doc.id.0), - "accountId":self.account["id"],"origin":self.origin,"rect":rect_value(global), - "viewport":ui.ctx().viewport_id().0.value(),"layer":layer.id.value(), - })) - } - - fn references_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { - let gallery = ui.scope(|ui| self.visual_assets_gallery_ui(app, ui, width)); - if gallery.inner { - if let Some(target) = self.reference_drop_geometry(app, ui, gallery.response.rect) { - self.creation_view_geometry["referenceDrop"] = target; - } - } else { - if self.creation_reads.wizard_stage.is_none() { - stitch_kit::caption(ui, "请在「商品档案与款式」中上传模板所需图片。"); - } else if !self.creation_reads.reference_import_error.is_empty() - && self.creation_reads.reference_import_error != REFERENCE_DROP_HINT - { - stitch_ui::status_label(ui, &self.creation_reads.reference_import_error, stitch_ui::StatusTone::Error); - } - } - } - - fn visual_assets_gallery_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) -> bool { - self.poll_imported_reference_previews(app, ui.ctx()); - let t = Tokens::get(ui.ctx()).agent(); - let variants = brief_variants(&self.creation_brief); - let mut rows = image_rows(&self.creation_brief); - let mut changed = false; - let mut remove = None; - let mut errors = Vec::new(); - let explicit = uses_template_images(&self.creation_brief); - let hidden: Vec<_> = rows.iter().map(|(image, _)| explicit && image["fieldKey"].is_string() - && ["productFields", "barcodeFields"].into_iter().any(|scope| { - let intake = &self.creation_brief["intake"]; - (scope == "barcodeFields") == image["barcode"].is_string() - && intake["schema"][scope].as_array().into_iter().flatten().any(|field| - field_kind(field) == "image" && in_image_slot(image, - &image_slot(&intake["templateId"], field, image["barcode"].as_str()))) - })).collect(); - let has_visible = hidden.iter().any(|&hidden| !hidden); - let has_norm_assets = self.creation_brief["normalizedProduct"]["assets"].as_array().is_some_and(|a| !a.is_empty()); - - let img_scroll = self.creation_reads.scroll_to_field.as_deref() == Some("images"); - if img_scroll { - self.creation_reads.scroll_to_field = None; - } - let img_error = self.creation_reads.inline_errors.get("images").cloned(); - - let show_gallery = !explicit || has_visible || has_norm_assets; - if show_gallery { - ui.set_min_width(width); - let label = if explicit { "其他视觉素材" } else { "视觉素材库 *" }; - let resp = stitch_kit::label(ui, label, Type::Body, Tone::Active); - if img_scroll { - resp.scroll_to_me(Some(egui::Align::Center)); - } - } - - // Role segmentation filter bar when there are assets or references. - if has_norm_assets || has_visible { - ui.add_space(space::XS); - let options = [("全部", true), ("主体图", true), ("主图/场景", true), ("细节图", true)]; - let filter_idx = self.creation_reads.visual_asset_filter.min(options.len() - 1); - let seg = stitch_ui::segmented_control(ui, egui::Id::unique("creation-visual-asset-filter"), &options, filter_idx, self.reduce_motion); - if let Some(next) = seg.selected { - self.creation_reads.visual_asset_filter = next; - } - ui.add_space(space::XS); - } - - if let Some(err) = img_error.as_deref() { - stitch_kit::inline_notice(ui, "triangle-alert", Tone::Failure, err, |_| {}); - ui.add_space(space::XS); - } else if !explicit && (!rows.is_empty() || has_norm_assets) && !has_selected_product_image(&self.creation_brief) { - stitch_kit::inline_notice(ui, "triangle-alert", Tone::Warning, "请将至少一张参考图的用途设为「产品图」,或勾选已拉取的平台白底/主图。", |_| {}); - ui.add_space(space::XS); - } - - // Normalized Platform Assets grid (toggleable selectedForProject, preserving kind) - let active_filter = self.creation_reads.visual_asset_filter; - if has_norm_assets { - let mut assets = self.creation_brief["normalizedProduct"]["assets"].as_array().cloned().unwrap_or_default(); - let mut asset_changed = false; - let filtered_indices: Vec = assets - .iter() - .enumerate() - .filter(|(_, asset)| { - let kind = asset["kind"].as_str().unwrap_or("reference"); - match active_filter { - 1 => matches!(kind, "whiteBackground" | "sku"), - 2 => kind == "main", - 3 => kind == "reference", - _ => true, - } - }) - .map(|(i, _)| i) - .collect(); - if !filtered_indices.is_empty() { - let grid_cols = stitch_kit::GridColumns { min_cell: 200.0, max_cell: 300.0, most: 4 }; - let (_, cell_w) = grid_cols.measure(width.max(1.0), space::SM, filtered_indices.len()); - let cols = stitch_kit::adaptive_grid(ui, egui::Id::unique("creation-norm-assets"), grid_cols, vec2(space::SM, space::SM), filtered_indices.len(), |ui, slot_idx| { - let asset_idx = filtered_indices[slot_idx]; - let asset = &mut assets[asset_idx]; - let selected = asset["selectedForProject"] != false; - let kind = asset["kind"].as_str().unwrap_or("reference"); - let kind_label = match kind { - "whiteBackground" => "白底图", - "main" => "主图", - "sku" => "SKU 图", - _ => "参考图", - }; - let label = non_empty_str(&asset["label"]) - .or_else(|| non_empty_str(&asset["colorName"])) - .or_else(|| non_empty_str(&asset["barcode"])) - .unwrap_or(kind_label) - .to_owned(); - let sub = non_empty_str(&asset["barcode"]).unwrap_or("").to_owned(); - let local_src = non_empty_str(&asset["localSource"]).map(str::to_owned); - let border = if selected { t.primary_bg } else { t.card_border }; - let frame = egui::Frame::NONE - .fill(t.dock) - .stroke(egui::Stroke::new(1.0, border)) - .corner_radius(egui::CornerRadius::same(radius::CONTROL as u8)) - .inner_margin(8); - let resp = frame.show(ui, |ui| { - ui.vertical(|ui| { - let inner_w = (cell_w - 18.0).max(120.0); - ui.set_width(inner_w); - ui.spacing_mut().item_spacing.y = space::XS; - let thumb_h = 92.0; - let (preview_rect, preview) = ui.allocate_exact_size(vec2(inner_w, thumb_h), egui::Sense::hover()); - ui.painter().rect_filled(preview_rect, radius::ROW, t.field); - if let Some(src) = local_src.as_deref() { - if ui.is_rect_visible(preview_rect) { - self.queue_creation_reference(app, src); - } - let key = super::creation_reads::reference_key(src); - if let Some(tex) = self.creation_thumbs.get(&key).cloned() { - let size = preview_size(tex.size_vec2(), preview_rect.size()); - let rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, preview_rect); - ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text); - self.material_preview(preview, &key, &label, &tex); - } else { - crate::icons::paint(ui, preview_rect, "image", icon::LG, t.text_dim); - } - } else { - crate::icons::paint(ui, preview_rect, "image", icon::LG, t.text_dim); - } - ui.add(egui::Label::new(egui::RichText::new(&label).font(Type::Meta.font_id()).color(t.text)).truncate()).on_hover_text(&label); - ui.horizontal(|ui| { - ui.set_width(inner_w); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let toggle = stitch_ui::toggle_option_sized(ui, if selected { "已选用" } else { "选用" }, selected, true, vec2(60.0, 24.0)); - self.control_geometry(&format!("platform-asset-toggle-{asset_idx}"), toggle.rect); - if toggle.clicked() { - asset["selectedForProject"] = json!(!selected); - asset_changed = true; - } - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - let meta = if sub.is_empty() { kind_label.to_owned() } else { format!("{kind_label} · {sub}") }; - ui.add(egui::Label::new(egui::RichText::new(meta).font(Type::Meta.font_id()).color(t.text_dim)).truncate()); - }); - }); - }); - }); - }); - self.control_geometry(&format!("platform-asset-{asset_idx}"), resp.response.rect); - }); - let _ = cols; - ui.add_space(space::SM); - } - if asset_changed { - self.creation_brief["normalizedProduct"]["assets"] = json!(assets); - self.creation_reads.inline_errors.remove("images"); - self.creation_dirty = true; - } - } - - // Local / Uploaded Reference Images grid — filename on full-width top row (never truncated to 4 chars!) - let visible_indices: Vec = rows - .iter() - .enumerate() - .filter(|(idx, (image, _))| { - if hidden.get(*idx) != Some(&false) { - return false; - } - match active_filter { - 1 => image["purpose"] == "product", - 2 => image["purpose"] == "scene", - 3 => image["imageRole"] == "material" || image["imageRole"] == "detail", - _ => true, - } - }) - .map(|(i, _)| i) - .collect(); - - let columns = if width >= 780.0 { 3 } else if width >= 560.0 { 2 } else { 1 }; - let card_width = (width - 12.0 * (columns - 1) as f32) / columns as f32; - egui::Grid::new("creation-references").num_columns(columns).spacing(vec2(12.0, 12.0)).show(ui, |ui| { - for (position, &index) in visible_indices.iter().enumerate() { - let (image, owner) = &mut rows[index]; - let source = image["source"].as_str().unwrap_or("").to_owned(); - let preview_key = super::creation_reads::reference_key(&source); - let frame = stitch_ui::material_frame( - ui, - stitch_ui::surface_frame(ui.ctx(), stitch_ui::SurfaceRole::Input).corner_radius(radius::CONTROL as u8).inner_margin(10), - |ui| { - ui.vertical(|ui| { - let inner_width = (card_width - 22.0).max(120.0); - ui.set_width(inner_width); - ui.spacing_mut().item_spacing.y = space::XS; - // Full-width filename header row so filenames are always readable - let name = image["name"].as_str().unwrap_or("产品图片").to_owned(); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 6.0; - ui.add(crate::icons::image("image", icon::SM, t.text_dim)); - ui.add_sized( - vec2((inner_width - 52.0).max(60.0), 24.0), - egui::Label::new(egui::RichText::new(&name).font(Type::Meta.font_id()).color(t.text)).truncate(), - ) - .on_hover_text(&name); - let response = stitch_ui::icon_button(ui, "trash", 24.0, false, "移除此参考图"); - self.control_geometry(&format!("reference-remove-{index}"), response.rect); - if response.clicked() { - remove = Some(index); - } - }); - // Thumbnail + Role/Color controls side-by-side below header - ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = 10.0; - let thumbnail_width = (inner_width * 0.28).clamp(56.0, 76.0); - let details_width = (inner_width - thumbnail_width - 10.0).max(96.0); - let (preview_rect, preview) = ui.allocate_exact_size(vec2(thumbnail_width, thumbnail_width), egui::Sense::hover()); - if ui.is_rect_visible(preview_rect) { - self.queue_creation_reference(app, &source); - } - let texture = self.creation_thumbs.get(&preview_key).cloned(); - let loading = self.creation_thumbnail_loading(&preview_key); - let error = self.creation_thumbnail_error(&preview_key).map(str::to_owned); - let saved = self.creation_reference_saved(app, &source); - let status = if texture.is_some() { - "ready" - } else if error.is_some() { - "failed" - } else if loading { - "loading" - } else if saved { - "queued" - } else { - "unsaved" - }; - ui.painter().rect_filled(preview_rect, radius::ROW, t.dock); - if let Some(texture) = texture.as_ref() { - let size = preview_size(texture.size_vec2(), preview_rect.size()); - let rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, preview_rect); - ui.painter().image(texture.id(), rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text); - self.material_preview(preview, &preview_key, &name, texture); - } else { - let label = if error.is_some() { - "读取失败" - } else if loading { - "加载中…" - } else { - "" - }; - if label.is_empty() { - crate::icons::paint(ui, preview_rect, "image", icon::MD, t.text_dim); - } else { - ui.painter().text(preview_rect.center(), egui::Align2::CENTER_CENTER, label, Type::Meta.font_id(), t.text_dim); - } - if let Some(error) = error.as_deref() { - let msg = crate::client_brand::user_error(error, "参考图读取失败"); - preview.on_hover_text(msg); - } - } - self.control_geometry(&format!("reference-preview-{index}"), preview_rect); - self.creation_view_geometry["referenceRows"][index.to_string()] = - json!({"source":source,"owner":owner.as_str(),"status":status,"rect":rect_value(preview_rect)}); - ui.vertical(|ui| { - ui.set_width(details_width); - ui.spacing_mut().item_spacing.y = 6.0; - if let Some(error) = error.as_deref() { - let msg = crate::client_brand::user_error(error, "参考图读取失败"); - errors.push(format!("{name} · {msg}")); - if saved && stitch_ui::action_button(ui, "重试", stitch_ui::ButtonRole::Quiet, true).clicked() { - self.retry_creation_reference(app, &source); - } - } - let reference_id = (&source, owner.clone()); - let purpose = stitch_ui::halo_select(ui, ("creation-purpose", &reference_id), details_width, if image["purpose"] == "scene" { "场景参考" } else { "产品图" }, self.reduce_motion, |ui| { - for (purpose, label) in [("product", "产品图"), ("scene", "场景参考")] { - if stitch_ui::select_option(ui, label, image["purpose"] == purpose, true).clicked() { - image["purpose"] = json!(purpose); - changed = true; - } - } - }); - self.control_geometry(&format!("reference-purpose-{index}"), purpose.response.rect); - let selected = variants - .iter() - .find(|variant| variant["id"] == owner.as_str()) - .and_then(|variant| variant["name"].as_str()) - .unwrap_or(if owner.is_empty() { "共用 · 所有花色" } else { "选择花色" }); - let ownership = stitch_ui::halo_select(ui, ("creation-reference-variant", &reference_id), details_width, selected, self.reduce_motion, |ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); - let size = vec2(ui.available_width(), control::STANDARD); - if stitch_ui::select_option_sized(ui, "共用 · 所有花色", owner.is_empty(), true, size).clicked() { - owner.clear(); - changed = true; - } - for variant in &variants { - let Some(id) = variant["id"].as_str() else { continue }; - if stitch_ui::select_option_sized( - ui, variant["name"].as_str().unwrap_or("花色"), owner.as_str() == id, true, size, - ).clicked() { - *owner = id.into(); - changed = true; - } - } - }); - self.control_geometry(&format!("reference-owner-{index}"), ownership.response.rect); - }); - }); - }); - }, - ); - self.control_geometry(&format!("reference-{index}"), frame.response.rect); - if (position + 1) % columns == 0 { - ui.end_row(); - } - } - }); - if !explicit { - ui.add_space(space::XS); - let drop_rect = self.add_reference_button(app, ui, width); - if rows.is_empty() { - self.control_geometry("reference-empty", drop_rect); - } - } - for error in errors { - stitch_ui::status_label(ui, &error, stitch_ui::StatusTone::Error); - } - if !self.creation_reads.reference_import_error.is_empty() && self.creation_reads.reference_import_error != REFERENCE_DROP_HINT { - let status = stitch_ui::status_label(ui, &self.creation_reads.reference_import_error, stitch_ui::StatusTone::Error); - self.control_geometry("reference-import-error", status.rect); - } - if let Some(label) = reference_import_activity(self.busy.as_deref()) { - ui.add_space(space::SM); - let id = egui::Id::unique(("creation-reference-import", &self.origin, self.account["id"].as_str(), self.creation_doc)); - let response = stitch_ui::progress(ui, id, label, None, self.reduce_motion); - self.control_geometry("reference-import-progress", response.rect); - } - if let Some(index) = remove { - rows = rows.into_iter().enumerate().filter_map(|(position, row)| (position != index).then_some(row)).collect(); - changed = true; - } - if changed { - match store_image_rows(&mut self.creation_brief, rows) { - Ok(()) => { - self.creation_reads.inline_errors.remove("images"); - self.creation_dirty = true; - } - Err(error) => self.error = error, - } - } - show_gallery - } - - fn resource_template_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, selected: &Value, brand: &str, category: &str) { - let bound = |row: &Value| row["brandId"] == brand && row["categoryId"] == category; - if !bound(&self.creation_reads.resource_set) { - self.creation_reads.resource_set = Value::Null; - self.creation_reads.resource_component.clear(); - self.creation_catalog.remove("resource-set"); - self.creation_catalog.remove("resource-component"); - } - let rows = self.creation_catalog.get("templates").into_iter().flatten().filter(|row| bound(row)).cloned().collect::>(); - if !brand.is_empty() && !category.is_empty() - && !self.creation_catalog.contains_key("templates") && !self.creation_catalog_loading("templates") && self.creation_catalog_error("templates").is_none() - { - self.catalog(app, "templates", String::new()); - } - let label = self.creation_reads.resource_set["name"].as_str().or(selected["name"].as_str()).unwrap_or("选择模板").to_owned(); - let mut geometry = Vec::new(); - let response = picker_height(ui, "creation-template", width, PICKER_HEIGHT, - &label, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| { - if brand.is_empty() || category.is_empty() { - ui.weak("先选择品牌与品类"); - return; - } - ui.horizontal(|ui| { - let query = ui.add_sized([(ui.available_width() - 68.0).max(80.0), 28.0], - egui::TextEdit::singleline(&mut self.creation_reads.resource_query).hint_text("模板名称或编号").char_limit(120)); - if stitch_ui::button(ui, "搜索", false).clicked() || query.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { - self.creation_catalog.remove("templates"); - self.catalog(app, "templates", self.creation_reads.resource_query.clone()); - } - }); - let error = self.creation_catalog_error("templates").map(str::to_owned); - if picker_notice(ui, self.creation_catalog_loading("templates"), error.as_deref(), rows.is_empty(), "当前筛选没有模板") { - self.catalog(app, "templates", self.creation_reads.resource_query.clone()); - } - for row in &rows { - let active = self.creation_reads.resource_set["id"] == row["id"]; - let text = format!("{} · {}", row["name"].as_str().unwrap_or("模板"), row["key"].as_str().unwrap_or("")); - let ready = !self.creation_catalog_loading("templates"); - let item = template_picker_row(ui, active, &text, ready, None); - geometry.push(json!({"id":row["id"],"key":row["key"],"ready":ready,"rect":rect_value(item.rect)})); - if item.clicked() { - ui.close(); - if active { - continue; - } - set_intake(&mut self.creation_brief, &row["id"], &row["intake"]); - self.creation_reads.resource_set = row.clone(); - self.creation_reads.resource_component.clear(); - self.creation_reads.resource_image = None; - self.creation_brief["templateSelection"] = Value::Null; - self.creation_reads.inline_errors.remove("template"); - self.creation_dirty = true; - self.creation_catalog.remove("resource-set"); - self.creation_catalog.remove("resource-component"); - self.catalog(app, "resource-set", row["id"].as_str().unwrap_or("").into()); - } - } - }).response; - if self.creation_reads.scroll_to_field.as_deref() == Some("template") { - self.creation_reads.scroll_to_field = None; - response.scroll_to_me(Some(egui::Align::Center)); - response.request_focus(); - } - self.picker_geometry(ui, "template", &response, self.creation_catalog_loading("templates"), !rows.is_empty(), geometry); - if let Some(err) = self.creation_reads.inline_errors.get("template") { - stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error); - } - if let Some(error) = self.creation_catalog_error("templates") { - stitch_ui::status_label(ui, error, stitch_ui::StatusTone::Error); - } - if let Some(progress) = self.resource_progress() { - let wait = progress["retryAfterSeconds"].as_u64(); - ui.horizontal_wrapped(|ui| { - if let Some(seconds) = wait { ui.label(format!("知识库访问受限,约 {seconds} 秒后继续")); } - let cancel = stitch_ui::button(ui, "取消读取", false); - if cancel.clicked() { - let _ = self.tx.send(Request::Action("knowledge-cancel".into(), json!({"jobId":progress["jobId"]}))); - } - }); - } - let Some(set) = self.creation_reads.resource_set["id"].as_str().map(str::to_owned) else { return; }; - let parts = self.creation_catalog.get("resource-set").cloned().unwrap_or_default(); - let error = self.creation_catalog_error("resource-set").map(str::to_owned); - if picker_notice(ui, self.creation_catalog_loading("resource-set"), error.as_deref(), parts.is_empty(), "该资源组没有可用的模板组件") { - self.catalog(app, "resource-set", set.clone()); - } - if ui.is_enabled() - && self.creation_reads.resource_component.is_empty() - && !self.creation_catalog_loading("resource-set") - && let Some(part) = default_resource_component(&parts) - { - self.select_resource_component(app, &set, part); - } - if !parts.is_empty() { - ui.add_space(space::XS); - ui.horizontal_wrapped(|ui| { - for part in &parts { - let Some(id) = part["id"].as_str() else { continue; }; - let name = part["name"].as_str().unwrap_or("模板组件"); - let selected = self.creation_reads.resource_component == id; - let loading = self.creation_catalog_loading("resource-component"); - let action = stitch_ui::segmented_option_sized(ui, name, selected, !loading, vec2(0.0, control::DEFAULT)); - self.control_geometry(&format!("resource-component-{id}"), action.rect); - if action.clicked() && (!selected || !template_identity(&self.creation_brief["templateSelection"])) { - self.select_resource_component(app, &set, part); - } - if !selected || loading { - for issue in part["issues"].as_array().into_iter().flatten().filter_map(Value::as_str) { - stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Error); - } - } - } - }); - } - if self.creation_catalog_loading("resource-component") { - stitch_kit::caption(ui, "正在核对模板资料…"); - } - if let Some(error) = self.creation_catalog_error("resource-component") { - stitch_ui::status_label(ui, error, stitch_ui::StatusTone::Error); - } - let result = self.creation_catalog.get_mut("resource-component").and_then(|rows| rows.first_mut()) - .filter(|row| row["id"] == self.creation_reads.resource_component).map(|row| { - let result = row.clone(); - if let Some(image) = row["image"].as_object_mut() { image.remove("rgba"); } - result - }); - if let Some(result) = result { - self.resource_component_result(app, ui, width, &set, &result); - } else { - let selected_part = parts.iter().find(|part| part["id"] == self.creation_reads.resource_component); - let warnings = template_compatibility_warnings(&[ - &self.creation_reads.resource_set, - selected_part.unwrap_or(&Value::Null), - &self.creation_brief["templateSelection"], - ]); - for warning in warnings { - stitch_ui::status_label(ui, &warning, stitch_ui::StatusTone::Warning); - } - } - self.creation_view_geometry["resourceSet"] = self.creation_reads.resource_set.clone(); - self.creation_view_geometry["templateSelection"] = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); - } - - fn select_resource_component(&mut self, app: &mut PhotocraftApp, set: &str, part: &Value) { - let Some(id) = part["id"].as_str() else { return; }; - let preview = part["previews"].as_array().and_then(|images| images.first()).map(|image| &image["id"]); - self.creation_reads.resource_component = id.to_owned(); - self.creation_reads.resource_image = None; - self.creation_catalog.remove("resource-component"); - self.creation_dirty |= !self.creation_brief["templateSelection"].is_null(); - self.creation_brief["templateSelection"] = Value::Null; - self.catalog(app, "resource-component", json!({"resourceSetId":set,"componentId":id,"previewId":preview}).to_string()); - } - - fn resource_component_result(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, set: &str, result: &Value) { - use base64::Engine as _; - let component = result["id"].as_str().unwrap_or(""); - let choice = &result["choice"]; - if ui.is_enabled() && template_identity(choice) && choice["intake"]["version"] == 1 - && choice["id"] == self.creation_brief["templateSelection"]["id"] - && choice["version"] == self.creation_brief["templateSelection"]["version"] - && choice["contentHash"] == self.creation_brief["templateSelection"]["contentHash"] - { - self.creation_dirty |= wizard::refresh_intake_schema_from_catalog(&mut self.creation_brief, choice); - } - if ui.is_enabled() - && self.creation_brief["templateSelection"].is_null() - && template_identity(choice) - && choice["enterprise"]["resourceSetId"] == set - && choice["enterprise"]["componentId"] == component - && choice["brandId"] == self.creation_brief["brandId"] - && choice["categoryId"] == self.creation_brief["categoryId"] - { - let mut choice = choice.clone(); - if let Some(width) = choice["width"].as_u64() { - self.creation_width = width as u32; - } - if let Some(fields) = choice.as_object_mut() { - fields.remove("width"); - if let Some(schema) = fields.remove("intake") { - set_intake(&mut self.creation_brief, &fields["id"], &schema); - } - } - self.creation_brief["templateSelection"] = choice; - self.creation_reads.inline_errors.remove("template"); - self.creation_dirty = true; - } - for issue in result["issues"].as_array().into_iter().flatten().filter_map(Value::as_str) { - stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Error); - } - let selected_part = self.creation_catalog.get("resource-set") - .and_then(|parts| parts.iter().find(|part| part["id"] == component)) - .cloned() - .unwrap_or(Value::Null); - for warning in template_compatibility_warnings(&[ - result, - choice, - &selected_part, - &self.creation_reads.resource_set, - &self.creation_brief["templateSelection"], - ]) { - stitch_ui::status_label(ui, &warning, stitch_ui::StatusTone::Warning); - } - if let Some(error) = result["previewError"].as_str() { - stitch_kit::caption(ui, error); - } - let preview_key = format!("{set}:{component}:{}", result["previewId"]); - if self.creation_reads.resource_image.as_ref().is_none_or(|(key, _)| key != &preview_key) - && let (Some(w), Some(h), Some(rgba)) = (result["image"]["size"][0].as_u64(), result["image"]["size"][1].as_u64(), result["image"]["rgba"].as_str()) - && (1..=320).contains(&w) && (1..=320).contains(&h) - && let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(rgba) - && bytes.len() as u64 == w * h * 4 - { - let image = egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], &bytes); - self.creation_reads.resource_image = Some((preview_key, ui.ctx().load_texture("resource-template-preview", image, egui::TextureOptions::LINEAR))); - } - let tpl_name = self.creation_reads.resource_set["name"].as_str().or(choice["name"].as_str()).unwrap_or("项目模板").to_owned(); - let tpl_width = result["choice"]["width"].as_u64().unwrap_or(self.creation_width as u64) as u32; - let cover_img = self.creation_reads.resource_image.clone().map(|(_, tex)| tex); - let fallback_structure = if cover_img.is_none() { - choice.get("structurePreview").filter(|v| v.is_object()) - } else { - None - }; - if cover_img.is_some() || fallback_structure.is_some() || template_identity(choice) { - ui.add_space(space::SM); - let card = ui.scope(|ui| { - structure_preview_card( - ui, - fallback_structure, - cover_img.as_ref(), - &tpl_name, - "企业知识库", - self.creation_template_screen_count(), - tpl_width, - Some("已就绪"), - ); - }); - self.control_geometry("resource-preview", card.response.rect); - } - if let Some(previews) = result["previews"].as_array().filter(|images| images.len() > 1) { - ui.add_space(space::XS); - let label = result["previewName"].as_str().unwrap_or("切换预览页"); - picker(ui, "resource-preview-select", width.min(320.0), label, |ui| { - for preview in previews { - let Some(id) = preview["id"].as_str() else { continue; }; - if stitch_ui::select_option(ui, preview["name"].as_str().unwrap_or("预览"), result["previewId"] == id, true).clicked() { - self.creation_reads.resource_image = None; - self.catalog(app, "resource-component", json!({"resourceSetId":set,"componentId":component,"previewId":id,"previewOnly":true}).to_string()); - ui.close(); - } - } - }); - } - } - - fn template_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { - let brand = self.creation_brief["brandId"].as_str().unwrap_or("").to_owned(); - let category = self.creation_brief["categoryId"].as_str().unwrap_or("").to_owned(); - let selected = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); - if self.template_workflow["canvasFirst"] == true && template_identity(&selected) && selected["enterprise"]["sourceKind"] == "resource-map" { - let name = selected["name"].as_str().unwrap_or("项目模板"); - let view = ui.label(format!("{name} · 已固定")); - self.control_geometry("template", view.rect); - self.creation_view_geometry["templateSelection"] = selected; - return; - } - if brand.starts_with("ekb:brand:") || brand.is_empty() { - if self.template_workflow["canvasFirst"] == true && template_identity(&selected) { - let name = selected["name"].as_str().unwrap_or("项目模板"); - let view = ui.label(format!("{name} · 已固定")); - self.control_geometry("template", view.rect); - self.creation_view_geometry["templateSelection"] = selected; - } else { - self.resource_template_select(app, ui, width, &selected, &brand, &category); - } - return; - } - let rows = self - .creation_catalog - .get("templates") - .cloned() - .unwrap_or_default() - .into_iter() - .filter(|row| row["brandId"] == brand && row["categoryId"] == category && template_identity(row)) - .collect::>(); - let fixed = self.template_workflow["canvasFirst"] == true && template_identity(&selected); - let selected_row = - rows.iter().find(|row| row["id"] == selected["id"] && row["version"] == selected["version"] && row["contentHash"] == selected["contentHash"]); - let name = selected_row.and_then(|row| row["name"].as_str()).or_else(|| selected["name"].as_str()).unwrap_or("项目模板"); - let version_label = if selected["enterprise"].is_object() { "企业知识库" } else { selected["version"].as_str().unwrap_or("") }; - let label = if template_identity(&selected) { format!("{name} · {version_label}") } else { "选择模板".into() }; - if !brand.is_empty() - && !category.is_empty() - && !self.creation_catalog.contains_key("templates") - && !self.creation_catalog_loading("templates") - && self.creation_catalog_error("templates").is_none() - { - self.catalog(app, "templates", String::new()); - } - let has_preview = selected_row.and_then(|row| verified_structure_preview(row, &selected, &brand, &category)).is_some(); - let side_by_side = width >= 620.0 && has_preview; - let picker_width = if side_by_side { (width - 280.0 - space::MD).max(240.0) } else { width }; - let mut geometry = Vec::new(); - let draw_picker = |this: &mut Workspace, app: &mut PhotocraftApp, ui: &mut Ui, p_width: f32, geometry: &mut Vec| { - let response = picker(ui, "creation-template", p_width, &label, |ui| { - if brand.is_empty() || category.is_empty() { - ui.weak("先选择品牌与品类"); - } else { - let error = this.creation_catalog_error("templates").map(str::to_owned); - if picker_notice(ui, this.creation_catalog_loading("templates"), error.as_deref(), rows.is_empty(), "当前品类暂无可用模板") { - this.catalog(app, "templates", String::new()); - } - } - if rows.iter().any(|row| verified_structure_preview(row, row, &brand, &category).is_some()) { - stitch_kit::caption(ui, "首屏结构示意 · 不含图片"); - } - for row in &rows { - let mut choice = json!({"id":row["id"],"name":row["name"],"version":row["version"],"contentHash":row["contentHash"],"brandId":row["brandId"],"categoryId":row["categoryId"]}); - if row["enterprise"].is_object() { choice["enterprise"] = row["enterprise"].clone(); } - let row_warnings = template_compatibility_warnings(&[row]); - if !row_warnings.is_empty() { - choice["compatibilityWarnings"] = json!(row_warnings); - } - let is_selected = selected["id"] == row["id"] && selected["version"] == row["version"] && selected["contentHash"] == row["contentHash"]; - let text = format!("{} · {}", row["name"].as_str().unwrap_or("模板"), if row["enterprise"].is_object() { "企业知识库" } else { row["version"].as_str().unwrap_or("") }); - let preview = verified_structure_preview(row, row, &brand, &category); - let enabled = !fixed || is_selected; - let item = template_picker_row(ui, is_selected, &text, enabled, preview); - geometry.push( - json!({"id":row["id"],"version":row["version"],"contentHash":row["contentHash"],"ready":enabled,"hasStructurePreview":preview.is_some(),"rect":rect_value(item.rect)}), - ); - if item.clicked() && !fixed { - if !is_selected { - set_intake(&mut this.creation_brief, &row["id"], &row["intake"]); - } else { - wizard::refresh_intake_schema_from_catalog(&mut this.creation_brief, row); - } - this.creation_brief["templateSelection"] = choice; - this.creation_reads.inline_errors.remove("template"); - this.creation_dirty = true; - ui.close(); - } - } - }); - if response.response.clicked() && response.inner.is_some() && !fixed && !brand.is_empty() && !category.is_empty() { - this.catalog(app, "templates", String::new()); - } - if this.creation_reads.scroll_to_field.as_deref() == Some("template") { - this.creation_reads.scroll_to_field = None; - response.response.scroll_to_me(Some(egui::Align::Center)); - response.response.request_focus(); - } - this.picker_geometry(ui, "template", &response.response, this.creation_catalog_loading("templates"), !rows.is_empty(), geometry.clone()); - if let Some(err) = this.creation_reads.inline_errors.get("template") { - stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error); - } - if let Some(error) = this.creation_catalog_error("templates") { - let msg = crate::client_brand::user_error(error, "请检查网络或模板配置后重试"); - let notice = stitch_ui::status_label(ui, &format!("模板读取失败:{msg}。"), stitch_ui::StatusTone::Error); - this.control_geometry("template-error", notice.rect); - } - ui.add_space(space::XS); - ui.horizontal_wrapped(|ui| { - let chosen_now = selected_template(&this.creation_brief, &this.template_workflow, &this.creation["brief"]); - let status = if template_identity(&chosen_now) { - if rows.iter().any(|row| row["id"] == chosen_now["id"] && (row["version"] != chosen_now["version"] || row["contentHash"] != chosen_now["contentHash"])) { - Some("可更新") - } else if fixed { - Some("已固定") - } else if rows.iter().find(|row| row["id"] == chosen_now["id"] && row["version"] == chosen_now["version"] && row["contentHash"] == chosen_now["contentHash"]).is_some_and(|row| row["cached"] == true) { - Some("已缓存") - } else { - None - } - } else { - None - }; - if let Some(status) = status { - let badge = ui.scope(|ui| stitch_ui::status_chip(ui, status, stitch_ui::StatusTone::Neutral)); - this.control_geometry("template-status", badge.response.rect); - } - let refresh = ui - .add_enabled_ui(!brand.is_empty() && !category.is_empty() && !this.creation_catalog_loading("templates"), |ui| { - stitch_ui::action_button(ui, "检查模板更新", stitch_ui::ButtonRole::Quiet, true) - }) - .inner; - this.control_geometry("template-update", refresh.rect); - if refresh.clicked() { - this.request_creation_catalog(app, "templates", String::new(), true); - } - }); - }; - - if side_by_side { - ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = space::MD; - ui.vertical(|ui| { - ui.set_width(picker_width); - draw_picker(self, app, ui, picker_width, &mut geometry); - }); - let chosen = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); - let preview = rows.iter().find_map(|row| verified_structure_preview(row, &chosen, &brand, &category)); - let card_w = (width - picker_width - space::MD).max(220.0); - let card = ui.vertical(|ui| { - ui.set_width(card_w); - structure_preview_card( - ui, - preview, - None, - name, - version_label, - self.creation_template_screen_count(), - self.creation_width, - if fixed { Some("已固定") } else { None }, - ); - }); - self.control_geometry("template-preview-card", card.response.rect); - }); - } else { - draw_picker(self, app, ui, picker_width, &mut geometry); - let chosen = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); - let preview = rows.iter().find_map(|row| verified_structure_preview(row, &chosen, &brand, &category)); - if preview.is_some() || template_identity(&chosen) { - ui.add_space(space::SM); - let card = ui.scope(|ui| { - structure_preview_card( - ui, - preview, - None, - name, - version_label, - self.creation_template_screen_count(), - self.creation_width, - if fixed { Some("已固定") } else { None }, - ); - }); - self.control_geometry("template-preview-card", card.response.rect); - } - } - self.creation_view_geometry["templateSelection"] = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); - let chosen_now = &self.creation_view_geometry["templateSelection"]; - let chosen_row = rows.iter().find(|row| { - row["id"] == chosen_now["id"] && row["version"] == chosen_now["version"] && row["contentHash"] == chosen_now["contentHash"] - }); - for warning in template_compatibility_warnings(&[chosen_row.unwrap_or(&Value::Null), chosen_now]) { - stitch_ui::status_label(ui, &warning, stitch_ui::StatusTone::Warning); - } - } - fn brand_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { - let rows = self.creation_catalog.get("brands").cloned().unwrap_or_default(); - let selected = self.creation_brief["brandName"].as_str().filter(|s| !s.is_empty()).unwrap_or("选择品牌").to_owned(); - let mut geometry = Vec::new(); - let result = picker(ui, "creation-brand", width, &selected, |ui| { - if !self.creation_catalog.contains_key("brands") && !self.creation_catalog_loading("brands") && self.creation_catalog_error("brands").is_none() { - self.catalog(app, "brands", String::new()); - } - let error = self.creation_catalog_error("brands").map(str::to_owned); - if picker_notice(ui, self.creation_catalog_loading("brands"), error.as_deref(), rows.is_empty(), "暂无品牌") { - self.catalog(app, "brands", String::new()); - } - for row in &rows { - let ready = row["ready"] == true; - let suffix = if !ready { " · 待配置" } else if row["templateCount"].as_u64() == Some(0) { " · 暂无可用模板" } else { "" }; - let label = format!("{}{suffix}", row["name"].as_str().unwrap_or("")); - let response = picker_row(ui, self.creation_brief["brandName"] == row["name"], &label, ready); - geometry.push(json!({"id":row["id"],"label":label,"ready":ready,"rect":rect_value(response.rect)})); - if response.clicked() { - if self.creation_brief["brandName"] == row["name"] { - ui.close(); - continue; - } - self.creation_brief["brandId"] = row["id"].clone(); - self.creation_brief["brandName"] = row["name"].clone(); - self.creation_brief["categoryId"] = json!(""); - self.creation_brief["categoryName"] = json!(""); - self.agent_rule = Value::Null; - self.agent_rule_state = Value::Null; - if let Some(fields) = self.creation_brief.as_object_mut() { fields.remove("intake"); } - self.creation_brief["templateSelection"] = Value::Null; - self.creation_catalog.remove("templates"); - self.creation_catalog.remove("categories"); - self.catalog(app, "categories", String::new()); - self.creation_reads.inline_errors.remove("brand"); - self.creation_reads.manual_edited_fields.insert("brand".into()); - self.creation_dirty = true; - ui.close(); - } - } - }); - if result.response.clicked() && result.inner.is_some() { - self.catalog(app, "brands", String::new()); - } - if self.creation_reads.scroll_to_field.as_deref() == Some("brand") { - self.creation_reads.scroll_to_field = None; - result.response.scroll_to_me(Some(egui::Align::Center)); - result.response.request_focus(); - } - let loading = self.creation_catalog_loading("brands"); - self.picker_geometry(ui, "brand", &result.response, loading, !rows.is_empty() && !loading && self.creation_catalog_error("brands").is_none(), geometry); - if let Some(err) = self.creation_reads.inline_errors.get("brand") { - stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error); - } - } - fn category_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { - let brand = self.creation_brief["brandId"].as_str().unwrap_or("").to_owned(); - let rows = self.creation_catalog.get("categories").cloned().unwrap_or_default().into_iter().filter(|row| row["brandId"] == brand).collect::>(); - let selected = self.creation_brief["categoryName"] - .as_str() - .filter(|s| !s.is_empty()) - .unwrap_or(if brand.is_empty() { "先选择品牌" } else { "选择品类" }) - .to_owned(); - let mut geometry = Vec::new(); - let loading = self.creation_catalog_loading("categories"); - let result = picker(ui, "creation-category", width, &selected, |ui| { - if brand.is_empty() { - ui.weak("先选择品牌"); - } else { - if !self.creation_catalog.contains_key("categories") && !loading && self.creation_catalog_error("categories").is_none() { - self.catalog(app, "categories", String::new()); - } - let error = self.creation_catalog_error("categories").map(str::to_owned); - if picker_notice(ui, loading, error.as_deref(), rows.is_empty(), "暂无已登记的产品品类") { - self.catalog(app, "categories", String::new()); - } - } - for row in &rows { - let ready = row["ready"] == true; - let name = row["name"].as_str().unwrap_or(""); - let label = if ready { name.to_owned() } else { format!("{name} · 待配置") }; - let response = picker_row(ui, self.creation_brief["categoryName"] == row["name"], &label, ready).on_hover_text(if ready { - if row["templateCount"].as_u64() == Some(0) { "知识库已有此品类资料,当前暂无可用模板" } else { "使用该品牌与品类的项目模板" } - } else { - "此品牌尚未配置该品类模板" - }); - geometry.push(json!({"id":row["id"],"label":label,"ready":ready,"rect":rect_value(response.rect)})); - if response.clicked() { - if self.creation_brief["categoryName"] == row["name"] { - ui.close(); - continue; - } - self.creation_brief["categoryId"] = row["id"].clone(); - self.creation_brief["categoryName"] = row["name"].clone(); - self.agent_rule = Value::Null; - self.agent_rule_state = Value::Null; - if let Some(fields) = self.creation_brief.as_object_mut() { fields.remove("intake"); } - self.creation_brief["templateSelection"] = Value::Null; - self.creation_catalog.remove("templates"); - self.creation_reads.inline_errors.remove("category"); - self.creation_reads.manual_edited_fields.insert("category".into()); - self.creation_dirty = true; - ui.close(); - } - } - }); - if result.response.clicked() && result.inner.is_some() && !brand.is_empty() { - self.catalog(app, "categories", String::new()); - } - if self.creation_reads.scroll_to_field.as_deref() == Some("category") { - self.creation_reads.scroll_to_field = None; - result.response.scroll_to_me(Some(egui::Align::Center)); - result.response.request_focus(); - } - self.picker_geometry(ui, "category", &result.response, loading, !rows.is_empty() && !loading, geometry); - if let Some(err) = self.creation_reads.inline_errors.get("category") { - stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error); - } - } - fn material_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { - let rows = self.creation_catalog.get("materials").cloned().unwrap_or_default(); - let mut variants = brief_variants(&self.creation_brief); - let selected = match variants.as_slice() { - [] => "从材质库选择,可多选".to_owned(), - [only] => only["name"].as_str().unwrap_or("花色").to_owned(), - rows => format!("已选 {} 个花色", rows.len()), - }; - let mut geometry = Vec::new(); - let mut material_rows = Vec::new(); - let result = picker_height(ui, "creation-material", width, PICKER_HEIGHT, &selected, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| { - if !self.creation_catalog.contains_key("materials") - && !self.creation_catalog_loading("materials") - && self.creation_catalog_error("materials").is_none() - { - self.catalog(app, "materials", String::new()); - } - let search = stitch_ui::search_field(ui, ui.scope_id().with("creation-material-search"), &mut self.creation_material_query, "搜索材质"); - let now = ui.input(|input| input.time); - let enter = search.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter) - && !input.events.iter().any(|event| matches!(event, egui::Event::Ime(_)))); - let state_id = ui.scope_id().with("creation-material-search-pending"); - let (due, pending) = ui.data_mut(|data| { - let state = data.get_temp_mut_or_default::(state_id); - let due = material_search_due(state, &self.creation_material_query, search.changed(), enter, now); - (due, state.pending) - }); - if pending { ui.ctx().request_repaint_after(Duration::from_millis(50)); } - if due { - self.catalog(app, "materials", self.creation_material_query.clone()); - } - let error = self.creation_catalog_error("materials").map(str::to_owned); - if picker_notice(ui, self.creation_catalog_loading("materials"), error.as_deref(), rows.is_empty(), "暂无匹配材质") { - self.catalog(app, "materials", self.creation_material_query.clone()); - } - let removable = variants.iter().all(|variant| self.sku_color_removable(variant)); - if picker_row(ui, variants.is_empty(), "未指定", removable).on_hover_text("已用于详情图、主图或已有画布的颜色会保留").clicked() { - variants.clear(); - self.save_sku_colors(variants.clone()); - ui.close(); - } - for row in &rows { - let Some(id) = row["id"].as_str().filter(|id| !id.is_empty()) else { continue }; - let label = row["name"].as_str().unwrap_or(""); - let image = self.creation_thumbs.get(id).cloned(); - let error = self.creation_thumbnail_error(id).map(str::to_owned); - let loading = self.creation_thumbnail_loading(id); - let mut image_rect = egui::Rect::NOTHING; - let mut visible = false; - let line = ui.horizontal(|ui| { - let thumbnail = material_thumbnail(ui, image.as_ref(), loading, error.is_some()); - image_rect = thumbnail.rect; - visible = ui.is_rect_visible(image_rect); - if visible && image.is_none() && !loading && error.is_none() { - self.queue_creation_thumbnail(app, id); - } - if let Some(error) = error.as_deref() { - let msg = crate::client_brand::user_error(error, "缩略图读取失败"); - if thumbnail.on_hover_text(format!("{msg}\n点击重新读取")).clicked() { - self.retry_creation_thumbnail(app, id); - } - } else if let Some(image) = image.as_ref() { - self.material_preview(thumbnail, id, label, image); - } - let selected = variants.iter().find(|variant| variant["colorMaterialId"] == row["id"]); - let removable = selected.is_none_or(|variant| self.sku_color_removable(variant)); - let selected = selected.is_some(); - let can_select = removable && (selected || variants.len() < 64); - let response = picker_toggle_row(ui, selected, label, can_select); - let response = if !selected && variants.len() >= 64 { - response.on_hover_text("最多选择 64 个花色") - } else if !removable { - response.on_hover_text("已用于出图、画布或专属参考的颜色会保留") - } else { response }; - if response.clicked() { - if selected { - variants.retain(|variant| variant["colorMaterialId"] != row["id"]); - } else { - variants - .push(json!({"id":variant_identity(id),"name":row["name"],"colorMaterialId":row["id"],"colorName":row["name"],"images":[]})); - } - self.save_sku_colors(variants.clone()); - } - if let Some(image) = image.as_ref() { - self.material_preview(response, id, label, image); - } - }); - let status = if image.is_some() { - "ready" - } else if self.creation_thumbnail_error(id).is_some() { - "failed" - } else if self.creation_thumbnail_loading(id) { - "loading" - } else { - "queued" - }; - geometry.push(json!({"id":id,"label":label,"ready":true,"rect":rect_value(line.response.rect)})); - material_rows.push( - json!({"id":id,"label":label,"rect":rect_value(line.response.rect),"imageRect":rect_value(image_rect),"status":status,"visible":visible}), - ); - } - }); - self.creation_view_geometry["materialRows"] = json!(material_rows); - let loading = self.creation_catalog_loading("materials"); - self.picker_geometry( - ui, - "material", - &result.response, - loading, - !rows.is_empty() && !loading && self.creation_catalog_error("materials").is_none(), - geometry, - ); - } - fn product_search_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - let identifier = self.creation_brief["identifier"].as_str().unwrap_or_default(); - let label = if self.creation_brief["identifierType"] == "spu" { "按 SPU 查找" } else { "查找原项目产品" }; - let search = stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Secondary, !identifier.trim().is_empty()); - if search.clicked() { - self.catalog(app, "products", identifier.to_owned()); - } - self.control_geometry("source-search", search.rect); - } - fn product_select_results(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - let rows = self.creation_catalog.get("products").cloned().unwrap_or_default(); - let error = self.creation_catalog_error("products").map(str::to_owned); - if (self.creation_catalog.contains_key("products") || self.creation_catalog_loading("products") || error.is_some()) - && picker_notice(ui, self.creation_catalog_loading("products"), error.as_deref(), rows.is_empty(), "未找到匹配产品,请核对产品编号") - { - self.catalog(app, "products", self.creation_brief["identifier"].as_str().unwrap_or("").into()); - } - for (index, row) in rows.into_iter().enumerate() { - let title = row["productModel"].as_str().or_else(|| row["name"].as_str()).unwrap_or("产品资料"); - let result = stitch_ui::button(ui, title, false); - self.control_geometry(&format!("source-result-{index}"), result.rect); - if result.clicked() { - self.creation_submit(app, "creation-product", json!({"item":row})); - } - } - } - fn points_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - let field_scope = self.creation_field_scope(app); - let t = Tokens::get(ui.ctx()).agent(); - ui.label(egui::RichText::new("产品事实与卖点").font(Type::Display.semibold()).color(t.text)); - ui.add_space(space::MD); - section_heading(ui, "产品事实", "结合产品资料核对,避免生成未确认的产品信息"); - ui.add_space(space::SM); - let facts = self.creation["facts"]["items"].as_array().cloned().unwrap_or_default(); - if facts.is_empty() { - stitch_kit::caption(ui, "还没有分析结果,产品原始资料会继续保留"); - } - for fact in facts { - ui.label(egui::RichText::new(fact["text"].as_str().unwrap_or("")).font(Type::Body.font_id())).on_hover_text(fact["source"].as_str().unwrap_or("")); - } - let missing = self.creation["facts"]["missing"].as_array().cloned().unwrap_or_default(); - if !missing.is_empty() { - ui.add_space(space::SM); - stitch_ui::disclosure(ui, egui::Id::unique("creation-missing"), &format!("待确认 · {}", missing.len()), false, self.reduce_motion, |ui| { - for item in missing { - ui.label(item.as_str().unwrap_or("")); - } - }); - } - section_break(ui); - let batches = self.creation["sellingPoints"]["batches"].as_array().cloned().unwrap_or_default(); - ui.horizontal_wrapped(|ui| { - stitch_kit::label(ui, "选择卖点", Type::Heading, Tone::Active); - stitch_kit::label(ui, format!("已选 {} / 20", self.creation_selected.len()), Type::Meta, Tone::Quiet); - stitch_kit::label(ui, format!("{} / 12 批", batches.len()), Type::Meta, Tone::Quiet); - }); - ui.add_space(space::SM); - if batches.is_empty() { - stitch_kit::caption(ui, "生成一批卖点,再选择适合这款产品的表达"); - } - for (batch_index, batch) in batches.iter().enumerate() { - let id = batch["id"].as_str().unwrap_or(""); - if batches.len() > 1 { - stitch_kit::label(ui, format!("第 {} 批", batch_index + 1), Type::Meta, Tone::Quiet); - } - for (index, item) in batch["items"].as_array().cloned().unwrap_or_default().iter().enumerate() { - let key = format!("{id}:{index}"); - let selected = self.creation_selected.contains(&key); - let label = item.as_str().or_else(|| item["text"].as_str()).unwrap_or(""); - let response = stitch_ui::toggle_option(ui, label, selected, selected || self.creation_selected.len() < 20); - self.control_geometry(&format!("selling-point-{batch_index}-{index}"), response.rect); - if response.clicked() { - if selected { - self.creation_selected.retain(|s| s != &key); - } else { - self.creation_selected.push(key); - } - self.creation_submit(app, "creation-select", json!({})); - } - } - ui.add_space(space::SM); - } - ui.add_space(space::MD); - let direction_width = ui.available_width(); - field_group(ui, direction_width, "下一批表达方向(可选)", |ui| { - let id = field_scope.with("creation-direction"); - ui.data_mut(|data| data.get_temp_mut_or_default::>(egui::Id::unique("creation-active-editors")).push(id.with("editor"))); - let reduced = ui.style().animation_time == 0.0; - if stitch_ui::halo_field(ui, id, None, reduced, |ui| { - ui.add(stitch_ui::text_input(&mut self.creation_direction, "例如:更突出木材质感与空间搭配", false) - .id(id.with("editor")).desired_width(ui.available_width().max(0.0)).frame(egui::Frame::NONE)) - }) - .changed() - { - self.creation_dirty = true; - } - }); - ui.add_space(space::MD); - ui.horizontal_wrapped(|ui| { - let generate = - ui.add_enabled_ui(batches.len() < 12, |ui| stitch_ui::button(ui, if batches.is_empty() { "生成一批卖点" } else { "再生成一批" }, false)).inner; - self.control_geometry("points-generate", generate.rect); - if generate.clicked() { - self.creation_submit(app, "creation-points", json!({})); - } - let plan = ui.add_enabled_ui(!self.creation_selected.is_empty(), |ui| stitch_ui::button(ui, "生成页面方案", true)).inner; - self.control_geometry("points-plan", plan.rect); - if plan.clicked() { - self.creation_submit(app, "creation-plan", json!({})); - } - }); - } - fn plan_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - let field_scope = self.creation_field_scope(app); - let t = Tokens::get(ui.ctx()).agent(); - let status = self.creation["plan"]["status"].as_str().unwrap_or("idle").to_owned(); - let mut screens = self.creation_plan.as_array().cloned().unwrap_or_default(); - ui.label(egui::RichText::new("页面方案").font(Type::Display.semibold()).color(t.text)); - stitch_kit::caption(ui, "调整页面文案与画面要求,修改后保存并重新确认"); - ui.add_space(space::MD); - ui.horizontal_wrapped(|ui| { - if let Some(count) = self.creation_template_screen_count() { - ui.label(format!("{count} 屏")); - } - let generate = stitch_ui::button(ui, if screens.is_empty() { "生成页面方案" } else { "重新生成方案" }, false); - self.control_geometry("plan-generate", generate.rect); - if generate.clicked() { - self.creation_submit(app, "creation-plan", json!({})); - } - let label = match status.as_str() { - "confirmed" => "已确认", - "needs-confirm" => "待确认", - "stale" => "需要重新确认", - _ => "尚未确认", - }; - stitch_kit::label(ui, label, Type::Meta, Tone::Quiet); - }); - if status == "stale" || self.creation_dirty { - ui.add_space(space::SM); - stitch_kit::inline_notice( - ui, - "triangle-alert", - Tone::Warning, - self.creation["plan"]["invalidReason"].as_str().filter(|s| !s.is_empty()).unwrap_or("资料已变更,请重新确认方案"), - |_| {}, - ); - } - section_break(ui); - if screens.is_empty() { - stitch_kit::label(ui, "还没有页面方案,生成后可以逐页调整", Type::Body, Tone::Quiet); - } - let mut changed = false; - let screen_count = screens.len(); - for (i, screen) in screens.iter_mut().enumerate() { - let screen_id = screen["id"].as_str().filter(|id| !id.is_empty()).map(str::to_owned); - let screen_key = (screen_id.as_deref(), screen_id.is_none().then_some(i)); - stitch_ui::disclosure(ui, egui::Id::unique(("creation-plan-screen", screen_key)), &format!("{} · {}", i + 1, screen["name"].as_str().unwrap_or("页面")), i == 0, self.reduce_motion, |ui| { - let width = ui.available_width(); - field_group(ui, width, "标题", |ui| { - changed |= edit(ui, (field_scope, screen_key, "title"), &mut screen["title"], width, false, "标题"); - }); - ui.add_space(space::SM); - field_group(ui, width, "正文", |ui| { - changed |= edit(ui, (field_scope, screen_key, "body"), &mut screen["body"], width, true, "正文"); - }); - ui.add_space(space::SM); - stitch_ui::disclosure(ui, egui::Id::unique(("creation-image-prompt", screen_key)), "画面要求", false, self.reduce_motion, |ui| { - let width = ui.available_width(); - changed |= edit(ui, (field_scope, screen_key, "imagePrompt"), &mut screen["imagePrompt"], width, true, "画面要求"); - }); - }); - ui.add_space(space::SM); - if i + 1 < screen_count { - stitch_ui::divider(ui); - } - } - self.creation_plan = json!(screens); - if changed { - self.creation_dirty = true; - } - section_break(ui); - ui.horizontal_wrapped(|ui| { - if self.creation_dirty { - let save = stitch_ui::button(ui, "保存方案修改", false); - self.control_geometry("plan-save", save.rect); - if save.clicked() { - self.creation_submit(app, "creation-plan-edit", json!({})); - } - } - let confirm = ui.add_enabled_ui(status == "needs-confirm" && !self.creation_dirty, |ui| stitch_ui::button(ui, "确认方案", false)).inner; - self.control_geometry("plan-confirm", confirm.rect); - if confirm.clicked() { - self.creation_submit(app, "creation-confirm", json!({})); - } - let slots = ui.add_enabled_ui(status == "confirmed" && !self.creation_dirty, |ui| stitch_ui::button(ui, "制作图位", true)).inner; - self.control_geometry("plan-slots", slots.rect); - if slots.clicked() { - self.creation_step = 4; - } - if self.creation_pending.is_some() { - let load = stitch_ui::button(ui, "载入生成结果", false); - self.control_geometry("plan-load", load.rect); - if load.clicked() { - self.creation_submit(app, "creation-load", json!({})); - } - } - }); - } } -const OUTPUT_SCOPE_OPTIONS: [(&str, &str, &str); 3] = [ - ("output-tag-detail", "detail", "详情页"), - ("output-tag-main_images", "main_images", "主图"), - ("output-tag-sku_images", "sku_images", "SKU 图"), -]; #[cfg(test)] -#[test] -fn listing_receipt_distinguishes_reported_failure_and_recalled_assets() { - let success = json!({"state":"completed","listingStatus":{"state":"listed"}}); - assert_eq!(listing_status_text(&success).0, "已上架"); - let failed = json!({"state":"completed","listingStatus":{"state":"failed"}}); - assert_eq!(listing_status_text(&failed), ("上架失败", stitch_ui::StatusTone::Error)); - let removed = json!({"state":"removed","listingStatus":{"state":"listed"}}); - assert_eq!(listing_status_text(&removed).0, "素材已撤回"); -} - +use creation_test_exports::*; #[cfg(test)] -mod tests { - use crate::jiansun::test_support::SettleUi; - use super::*; - use photocraft_doc::LayerContent; - use std::sync::{Arc, mpsc}; - - const TEST_PRESET_PICKER_LABEL: &str = "一键填入测试商品(超管)"; - - fn test_preset_wizard( - account: Value, - width: f32, - ) -> (egui_kittest::Harness<'static, (Workspace, PhotocraftApp)>, mpsc::Receiver) { - let (mut w, app, requests) = brief_fixture(); - w.account = account; - w.reduce_motion = true; - w.observed_doc = w.creation_doc; - w.project_context = json!({"localId":"previous-project"}); - w.begin_staged_new_project(&app); - let harness = egui_kittest::Harness::builder() - .with_size(vec2(width, 850.0)) - .with_context_setup(|ctx| { - PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(ctx); - }) - .build_ui_state(|ui, (w, app): &mut (Workspace, PhotocraftApp)| { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| w.creation_ui(app, ui)); - }, (w, app)); - (harness, requests) - } - - fn request_for_test_product_preset(requests: &mpsc::Receiver, kind: &str) -> Option { - requests.try_iter().find_map(|request| match request { - Request::Action(method, input) if method == "creation-catalog" && input["kind"] == kind => Some(input), - _ => None, - }) - } - - #[test] - fn test_product_presets_hide_the_picker_and_skip_the_request_without_super_admin() { - use egui_kittest::kittest::Queryable; - for account in [ - json!({"id":"qa","isSuperAdmin":false}), - json!({"id":"qa","isDepartmentAdmin":true}), - json!({"id":"qa","isSuperAdmin":"true"}), - Value::Null, - ] { - let (mut harness, requests) = test_preset_wizard(account, 460.0); - harness.run_steps(3); - assert!(harness.query_by_label(TEST_PRESET_PICKER_LABEL).is_none()); - assert!(request_for_test_product_preset(&requests, TEST_PRESETS).is_none()); - assert!(harness.query_by_label("选择文件夹").is_some(), "the normal form remains available"); - } - } - - #[test] - fn test_product_presets_fill_and_replace_the_editable_draft_from_picker_selection() { - use egui_kittest::kittest::Queryable; - let (mut harness, requests) = test_preset_wizard(json!({"id":"qa","isSuperAdmin":true}), 460.0); - harness.run_steps(3); - let initial_catalogs = requests.try_iter().filter_map(|request| match request { - Request::Action(method, input) if method == "creation-catalog" => Some(input), - _ => None, - }).collect::>(); - let mut brands = initial_catalogs.iter().find(|input| input["kind"] == "brands").unwrap().clone(); - let mut response = initial_catalogs.into_iter().find(|input| input["kind"] == TEST_PRESETS).unwrap(); - assert_eq!(response["doc"], 0); - assert!(request_for_test_product_preset(&requests, TEST_PRESETS).is_none()); - assert!(harness.query_by_label(TEST_PRESET_PICKER_LABEL).is_none(), "wait for the authorized response"); - { - let (w, app) = harness.state_mut(); - brands["catalog"]["items"] = json!([]); - assert!(w.creation_read_received(app, "creation-catalog", &brands)); - assert!(request_for_test_product_preset(&requests, "materials").is_some()); - } - response["catalog"]["items"] = json!([ - {"id":"oak","label":"橡木换鞋凳"},{"id":"linen","label":"亚麻储物凳"} - ]); - { - let (w, app) = harness.state_mut(); - assert!(w.creation_read_received(app, "creation-catalog", &response)); - } - harness.run_steps(3); - - for (index, (id, name, barcode)) in [("oak", "橡木换鞋凳", "0200000010010"), ("linen", "亚麻储物凳", "0200000020019")].into_iter().enumerate() { - let picker = harness.get_by_label(TEST_PRESET_PICKER_LABEL); - assert!(picker.rect().width() > 0.0 && picker.rect().right() < 460.0); - picker.click(); - harness.run_steps(3); - harness.get_by_label(name).click(); - harness.run_steps(3); - let mut receipt = request_for_test_product_preset(&requests, "test-product-preset-import").unwrap(); - assert_eq!(receipt["id"], id); - assert_ne!(receipt["doc"], 0); - let mut brief = empty_brief(); - brief["name"] = json!(name); - brief["identifier"] = json!("XYQA-ST-001"); - brief["brandId"] = json!("ekb:brand:小壹测试"); - brief["brandName"] = json!("小壹测试"); - brief["categoryId"] = json!("ekb:category:链路验收"); - brief["categoryName"] = json!("链路验收"); - brief["note"] = json!("适用于玄关"); - brief["intake"] = json!({"productValues":{"productBrand":"测试品牌","sellingPoints":"圆角座面","description":"可收纳", - "specifications":"480 × 380 × 420 mm"},"barcodeValues":{barcode:{"length":"480"}}}); - brief["barcodeEntries"] = json!([{"id":barcode,"barcode":barcode}]); - brief["detailBarcode"] = json!(barcode); - brief["images"] = json!([{"source":format!("local:{}", if index == 0 { "a" } else { "b" }.repeat(64)), - "name":format!("{name}.jpg"),"purpose":"product","barcode":barcode}]); - receipt["presetBrief"] = brief.clone(); - let (w, app) = harness.state_mut(); - if index == 0 { - assert!(w.project_context["localId"].is_null()); - } else { - w.project_context["localId"] = json!("new-draft"); - } - let ctx = egui::Context::default(); - assert!(w.tick_context(app, &ctx)); - assert_eq!(w.observed_doc, receipt["doc"].as_u64()); - assert!(w.creation_read_received(app, "creation-catalog", &receipt)); - assert_eq!(w.creation_brief, brief); - assert!(w.creation_dirty && w.sync_dirty); - assert_eq!(app.session.documents().len(), 2, "reselecting keeps the same draft document"); - let template = json!({"id":"QA-FAST-001","version":"1.0","contentHash":"a".repeat(64)}); - assert!(canvas_entry_missing(&w.creation_brief, &template).is_empty()); - w.creation_brief["note"] = json!("手改后仍然可编辑"); - assert_eq!(w.creation_brief["note"], "手改后仍然可编辑"); - harness.run_steps(3); - } - } - - #[test] - fn test_product_presets_hide_failed_responses_without_changing_the_normal_form() { - use egui_kittest::kittest::Queryable; - for error in [json!({"error":"HTTP 403"}), json!({"error":"HTTP 404"}), json!({"catalog":{"items":null}})] { - let (mut harness, requests) = test_preset_wizard(json!({"id":"qa","isSuperAdmin":true}), 900.0); - harness.run_steps(3); - let mut response = request_for_test_product_preset(&requests, TEST_PRESETS).unwrap(); - let (w, app) = harness.state_mut(); - let before = w.creation_brief.clone(); - response.as_object_mut().unwrap().extend(error.as_object().unwrap().clone()); - assert!(w.creation_read_received(app, "creation-catalog", &response)); - assert_eq!(w.creation_brief, before); - assert!(w.error.is_empty()); - harness.run_steps(3); - assert!(harness.query_by_label(TEST_PRESET_PICKER_LABEL).is_none()); - assert!(harness.query_by_label("选择文件夹").is_some()); - assert!(request_for_test_product_preset(&requests, TEST_PRESETS).is_none()); - } - } - - #[test] - fn unhinted_creation_field_has_a_meaningful_accessible_name() { - use egui_kittest::kittest::Queryable; - let mut h = egui_kittest::Harness::builder().with_context_setup(crate::cjk_fonts::install_system_provider_for_tests).with_size(vec2(320.0, 120.0)).build_ui_state( - |ui, value: &mut Value| { edit(ui, "name", value, 280.0, false, "产品名称"); }, json!("桌子")); - h.run_steps(3); - h.check_accessibility(); - h.get_by_role_and_label(egui::accesskit::Role::TextInput, "产品名称"); - } - - #[test] - fn material_search_coalesces_edits_and_clear_without_repeating_requests() { - let mut state = MaterialSearchPending::default(); - assert!(!material_search_due(&mut state, "木", true, false, 0.0)); - assert!(!material_search_due(&mut state, "木纹", true, false, 0.2)); - assert!(!material_search_due(&mut state, "木纹", false, false, 0.49)); - assert!(material_search_due(&mut state, "木纹", false, false, 0.51)); - assert!(!material_search_due(&mut state, "木纹", false, false, 0.8)); - assert!(material_search_due(&mut state, "", true, false, 0.9)); - assert!(!material_search_due(&mut state, "", false, false, 1.3)); - assert!(material_search_due(&mut state, "材质", true, true, 1.4)); - assert!(!material_search_due(&mut state, "材质", false, false, 1.8)); - } - - #[test] - fn creation_halo_field_respects_form_width_and_native_text_focus() { - for width in [180.0, 320.0, 520.0] { - let ctx = egui::Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let mut value = json!(""); - let mut field_rect = egui::Rect::NOTHING; - let run = |value: &mut Value, events, field_rect: &mut egui::Rect| { - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,400.0))), events, ..Default::default() }, |ui| { - ui.set_width(width); - let start = ui.cursor().min; - edit_hint(ui, "test-name", value, width, false, "输入产品名称"); - *field_rect = egui::Rect::from_min_max(start, ui.min_rect().max); - }); - }; - run(&mut value,vec![],&mut field_rect); - assert!(field_rect.width() <= width + 1.0, "width={width}, rect={field_rect:?}"); - let pos = field_rect.center(); - for pressed in [true,false] { - run(&mut value,vec![egui::Event::PointerMoved(pos),egui::Event::PointerButton { pos, button:egui::PointerButton::Primary, pressed, modifiers:egui::Modifiers::NONE }],&mut field_rect); - } - run(&mut value,vec![egui::Event::Text("产品名称".into())],&mut field_rect); - assert_eq!(value, "产品名称", "native editor retains focus and editing at width {width}"); - } - } - - #[test] - fn creation_editor_focus_survives_an_earlier_field_appearing() { - let ctx = egui::Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let mut earlier = json!(""); - let mut name = json!("原名"); - let frame = |earlier: &mut Value, name: &mut Value, show_earlier: bool, events| { - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(400.0,300.0))), events, ..Default::default() }, |ui| { - if show_earlier { edit(ui, "earlier", earlier, 250.0, false, "前一字段"); } - edit(ui, "name", name, 250.0, false, "产品名称"); - }); - }; - frame(&mut earlier,&mut name,false,vec![]); - ctx.memory_mut(|memory| memory.request_focus(egui::Id::unique("creation-field").with("name").with("editor"))); - frame(&mut earlier,&mut name,true,vec![egui::Event::Text("新".into())]); - assert!(name.as_str().unwrap().contains('新')); - assert_eq!(earlier, ""); - } - - #[test] - fn creation_escape_closes_popup_then_editor_then_view_without_losing_draft() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_open = true; - w.library = false; - w.material = false; - w.creation_step = 0; - w.creation_dirty = true; - w.creation_brief["images"] = json!([]); - w.creation_brief["variants"] = json!([]); - let ctx = egui::Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { - let mut leaked = false; - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(1000.0,900.0))),events,..Default::default() }, |ui| { - w.creation_ui(app,ui); - leaked = ui.input(|input| input.key_pressed(egui::Key::Escape)); - }); - leaked - }; - let key = |pressed| egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed, repeat:false, modifiers:egui::Modifiers::NONE }; - frame(&mut w,&mut app,vec![]); - let before = w.creation_brief.clone(); - let editor = egui::Id::unique("creation-field").with((w.creation_field_scope(&app),"name")).with("editor"); - ctx.memory_mut(|memory| memory.request_focus(editor)); - frame(&mut w,&mut app,vec![]); - egui::Popup::open_id(&ctx,egui::Id::unique("creation-test-popup")); - assert!(!frame(&mut w,&mut app,vec![key(true)])); - assert!(!egui::Popup::is_any_open(&ctx)); - assert_eq!(w.creation_step,0); - frame(&mut w,&mut app,vec![key(false)]); - assert!(!frame(&mut w,&mut app,vec![key(true)])); - assert!(!ctx.memory(|memory| memory.has_focus(editor))); - assert_eq!(w.creation_step,0); - frame(&mut w,&mut app,vec![key(false)]); - assert!(!frame(&mut w,&mut app,vec![key(true)])); - assert_eq!(w.creation_reads.wizard_stage.unwrap().1, CreationStage::Template); - frame(&mut w,&mut app,vec![key(false)]); - assert!(!frame(&mut w,&mut app,vec![key(true)])); - assert_eq!(w.creation_reads.wizard_stage.unwrap().1, CreationStage::Source); - frame(&mut w,&mut app,vec![key(false)]); - assert!(!frame(&mut w,&mut app,vec![key(true)])); - assert_eq!(w.creation_step,3); - assert!(w.creation_dirty); - assert_eq!(w.creation_brief,before); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn creation_escape_waits_for_ime_composition_and_preserves_active_task() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_open=true; - w.creation_step=2; - w.busy=Some("pi-agent".into()); - let ctx=egui::Context::default(); - crate::PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(1000.0,900.0))),events,..Default::default() }, |ui| w.creation_ui(app,ui)); - }; - let key=|pressed| egui::Event::Key { key:egui::Key::Escape,physical_key:Some(egui::Key::Escape),pressed,repeat:false,modifiers:egui::Modifiers::NONE }; - frame(&mut w,&mut app,vec![egui::Event::Ime(egui::ImeEvent::Preedit { text:"shuru".into(),active_range_chars:None }),key(true)]); - assert_eq!(w.creation_step,2); - frame(&mut w,&mut app,vec![key(false),egui::Event::Ime(egui::ImeEvent::Commit("输入".into()))]); - frame(&mut w,&mut app,vec![key(true)]); - assert_eq!(w.creation_step,1); - assert_eq!(w.busy.as_deref(),Some("pi-agent")); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn creation_editor_undo_is_isolated_by_account_origin_and_document() { - let (mut w, mut app, requests) = brief_fixture(); - let ctx = egui::Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - w.origin = "local-a".into(); - w.account = json!({"id":"account-a"}); - w.creation_doc = app.session.active().map(|s| s.doc.id.0); - let a = w.creation_field_scope(&app); - w.account = json!({"id":"account-b"}); - let b = w.creation_field_scope(&app); - assert_ne!(a,b); - w.account = json!({"id":"account-a"}); - w.origin = "local-b".into(); - assert_ne!(a,w.creation_field_scope(&app)); - w.origin = "local-a".into(); - app.session.execute("file.new",json!({"width":32,"height":32})).unwrap(); - assert_ne!(a,w.creation_field_scope(&app)); - let frame = |scope:egui::Id, value:&mut Value, time:f64, events| { - let id = egui::Id::unique("creation-field").with((scope,"name")).with("editor"); - ctx.memory_mut(|memory| memory.request_focus(id)); - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(400.0,300.0))), time:Some(time), events, ..Default::default() }, |ui| { - edit(ui,(scope,"name"),value,250.0,false,"产品名称"); - }); - }; - // egui's Windows input adapter sets both ctrl and logical command; - // TextEdit recognizes undo through the platform-independent command. - let undo = || egui::Event::Key { key:egui::Key::Z, physical_key:Some(egui::Key::Z), pressed:true, repeat:false, - modifiers:egui::Modifiers { ctrl:true, command:true, ..Default::default() } }; - let mut av = json!("原始A"); - let mut bv = json!("原始B"); - frame(a,&mut av,0.0,vec![]); - frame(a,&mut av,0.1,vec![egui::Event::Text("输入A".into())]); - frame(a,&mut av,1.4,vec![]); - assert!(av.as_str().unwrap().contains("输入A")); - frame(b,&mut bv,2.0,vec![]); - frame(b,&mut bv,2.1,vec![undo()]); - assert_eq!(bv,"原始B", "another account cannot undo the first account's text"); - frame(b,&mut bv,2.2,vec![egui::Event::Key { key:egui::Key::Z, physical_key:Some(egui::Key::Z), pressed:false, repeat:false, modifiers:egui::Modifiers::NONE }]); - frame(a,&mut av,2.3,vec![undo()]); - assert_eq!(av,"原始A", "returning to the original account retains its own undo history"); - assert!(requests.try_recv().is_err()); - } - - #[test] - #[ignore = "offscreen GPU creation-field acceptance; requires PHOTOCRAFT_AGENT_QA_OUT"] - fn creation_halo_visual_acceptance() { - let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); - for width in [250.0, 520.0] { - let mut h = egui_kittest::Harness::builder().with_size(vec2(width, 300.0)).with_pixels_per_point(1.5).wgpu().build_ui_state( - |ui, value: &mut Value| { - if !stitch_ui::ui_fonts_ready(ui) { return; } - ui.painter().rect_filled(ui.max_rect(), 0.0, Tokens::get(ui.ctx()).agent().dock); - stitch_ui::scope(ui, |ui| { - field_group(ui, ui.available_width(), "产品名称", |ui| { - edit_hint(ui, "test-name", value, ui.available_width(), false, "输入产品名称"); - }); - field_group(ui, ui.available_width(), "产品描述", |ui| { - let mut description = json!("保留木纹与真实材质。"); - edit(ui, "test-description", &mut description, ui.available_width(), true, "产品描述"); - }); - }); - }, json!("长产品名称 · 木纹书桌")); - crate::PhotocraftApp::setup_context(&h.ctx,crate::theme::ThemeKind::ProMedium); - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join(format!("creation-halo-{width}.png"))).unwrap(); - } - } - - fn bounded_import_fixture() -> (Workspace, PhotocraftApp, mpsc::Receiver) { - let (workspace, mut app, requests) = brief_fixture(); - app.session.authorize = Some(|_, _| Ok(())); - (workspace, app, requests) - } - - #[test] - fn creation_import_automation_uses_only_the_bounded_capability_and_retains_the_current_scope() { - use base64::Engine as _; - use std::{cell::RefCell, rc::Rc}; - let (mut workspace, mut app, requests) = bounded_import_fixture(); - let calls = Rc::new(RefCell::new(Vec::new())); - let seen = calls.clone(); - app.services.automation_read = Some(Box::new(|_| panic!("unbounded capability must never be called"))); - app.services.automation_read_limited = Some(Box::new(move |path, limit| { - seen.borrow_mut().push((path.to_owned(), limit)); - Ok((format!("imported-{path}"), path.as_bytes().to_vec())) - })); - let before = workspace.creation_brief.clone(); - let doc = app.session.active().unwrap().doc.id.0; - workspace.creation_action(&mut app, "creation-import", json!({"doc":doc,"paths":["first.png","second.png"]})).unwrap(); - assert_eq!(calls.borrow().as_slice(), &[("first.png".into(), 20 * 1024 * 1024), ("second.png".into(), 20 * 1024 * 1024)]); - let Request::Action(method, payload) = requests.try_recv().unwrap() else { panic!("expected the scoped import") }; - assert_eq!(method, "creation-import-data"); - assert_eq!(payload["doc"], doc); - assert_eq!(payload["baseRevision"].as_u64(), app.session.active().map(|native| native.revision)); - assert_eq!(payload["brief"], before); - assert!(payload.get("paths").is_none(), "backend receives capability-read bytes, never an ambient path"); - for (index, path) in ["first.png", "second.png"].iter().enumerate() { - assert_eq!(payload["images"][index]["name"], format!("imported-{path}")); - assert_eq!(base64::engine::general_purpose::STANDARD.decode(payload["images"][index]["data"].as_str().unwrap()).unwrap(), path.as_bytes()); - } - assert_eq!(workspace.creation_brief, before, "a dispatch does not preempt the backend's verified import receipt"); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn creation_import_automation_passes_the_remaining_batch_budget_before_reading() { - use std::{cell::RefCell, rc::Rc}; - let (mut workspace, mut app, requests) = bounded_import_fixture(); - let limits = Rc::new(RefCell::new(Vec::new())); - let seen = limits.clone(); - app.services.automation_read_limited = Some(Box::new(move |path, limit| { - seen.borrow_mut().push(limit); - let bytes = if path == "first.png" { 20 * 1024 * 1024 } else { 4 * 1024 * 1024 }; - Ok((path.to_owned(), vec![7; bytes])) - })); - workspace.creation_action(&mut app, "creation-import", json!({"paths":["first.png","second.png"]})).unwrap(); - assert_eq!(limits.borrow().as_slice(), &[20 * 1024 * 1024, 4 * 1024 * 1024]); - let Request::Action(method, payload) = requests.try_recv().unwrap() else { panic!("expected one bounded batch") }; - assert_eq!(method, "creation-import-data"); - assert_eq!(payload["images"].as_array().unwrap().len(), 2); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn creation_import_automation_rejects_empty_oversize_or_failed_reads_without_dispatch() { - use std::{cell::RefCell, rc::Rc}; - for scenario in ["empty", "oversize-single", "oversize-remaining", "budget-exhausted", "capability-error"] { - let (mut workspace, mut app, requests) = bounded_import_fixture(); - let before = workspace.creation_brief.clone(); - let calls = Rc::new(RefCell::new(Vec::new())); - let seen = calls.clone(); - app.services.automation_read_limited = Some(Box::new(move |path, limit| { - seen.borrow_mut().push(limit); - match scenario { - "empty" => Ok((path.into(), vec![])), - "oversize-single" => Ok((path.into(), vec![0; limit + 1])), - "capability-error" => Err("directory capability denied this file".into()), - "oversize-remaining" if path == "second.png" => Ok((path.into(), vec![0; limit + 1])), - _ => Ok((path.into(), vec![0; limit])), - } - })); - let paths = match scenario { - "oversize-remaining" => json!(["first.png", "second.png"]), - "budget-exhausted" => json!(["first.png", "second.png", "third.png"]), - _ => json!(["first.png"]), - }; - let error = workspace.creation_action(&mut app, "creation-import", json!({"paths":paths})).unwrap_err(); - assert!(!error.is_empty()); - if matches!(scenario, "oversize-remaining" | "budget-exhausted") { - assert_eq!(calls.borrow().as_slice(), &[20 * 1024 * 1024, 4 * 1024 * 1024], "no third read after the 24MiB budget is exhausted"); - } else { assert_eq!(calls.borrow().as_slice(), &[20 * 1024 * 1024]); } - assert_eq!(workspace.creation_brief, before, "{scenario} must preserve every image owner and draft field"); - assert!(workspace.busy.is_none(), "{scenario} must not leave a phantom import in flight"); - assert!(requests.try_recv().is_err(), "{scenario} must not dispatch a partial batch"); - } - } - - #[test] - fn creation_import_automation_never_falls_back_to_an_unbounded_reader() { - use std::{cell::Cell, rc::Rc}; - let (mut workspace, mut app, requests) = bounded_import_fixture(); - let calls = Rc::new(Cell::new(0)); - let seen = calls.clone(); - app.services.automation_read = Some(Box::new(move |_| { - seen.set(seen.get() + 1); - Ok(("unexpected.png".into(), vec![1])) - })); - let before = workspace.creation_brief.clone(); - let error = workspace.creation_action(&mut app, "creation-import", json!({"paths":["first.png"]})).unwrap_err(); - assert!(error.contains("有界读取")); - assert_eq!(calls.get(), 0); - assert_eq!(workspace.creation_brief, before); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn creation_import_automation_validates_paths_and_live_scope_before_any_read() { - use std::{cell::Cell, rc::Rc}; - for scenario in ["empty-paths", "too-many", "invalid-path", "empty-path", "stale-document", "busy", "unknown"] { - let (mut workspace, mut app, requests) = bounded_import_fixture(); - let calls = Rc::new(Cell::new(0)); - let seen = calls.clone(); - app.services.automation_read_limited = Some(Box::new(move |_, _| { - seen.set(seen.get() + 1); - Ok(("unexpected.png".into(), vec![1])) - })); - let before = workspace.creation_brief.clone(); - let input = match scenario { - "empty-paths" => json!({"paths":[]}), - "too-many" => json!({"paths":["1","2","3","4","5","6","7","8","9"]}), - "invalid-path" => json!({"paths":["first.png",42]}), - "empty-path" => json!({"paths":["first.png",""]}), - "stale-document" => json!({"doc":u64::MAX,"paths":["first.png"]}), - "busy" => { workspace.busy = Some("agent".into()); json!({"paths":["first.png"]}) } - _ => { workspace.unknown = true; json!({"paths":["first.png"]}) } - }; - assert!(workspace.creation_action(&mut app, "creation-import", input).is_err(), "{scenario}"); - assert_eq!(calls.get(), 0, "{scenario}"); - assert_eq!(workspace.creation_brief, before, "{scenario}"); - assert!(requests.try_recv().is_err(), "{scenario}"); - } - } - - #[test] - fn reference_import_progress_is_visible_only_while_import_is_in_flight() { - let (mut w, mut app) = setup(); - w.creation_brief = empty_brief(); - let ctx = egui::Context::default(); - for (busy, shown) in [(Some("creation-import"), true), (Some("creation-import-library"), true), (Some("agent"), false), (None, false)] { - w.busy = busy.map(str::to_owned); - w.creation_view_geometry = json!({"controls":{}}); - let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }, |ui| { - w.references_ui(&mut app, ui, 500.0); - }); - assert_eq!(!w.creation_view_geometry["controls"]["reference-import-progress"].is_null(), shown, "unexpected activity for {busy:?}"); - } - } - - #[test] - fn template_structure_preview_rejects_stale_identity_and_invalid_geometry() { - let hash = "a".repeat(64); - let selected = json!({"id":"template","version":"v1","contentHash":hash,"brandId":"brand","categoryId":"category"}); - let mut row = selected.clone(); - row["structurePreview"] = json!({"contentHash":selected["contentHash"],"outputId":"S01","width":1440,"height":2000, - "background":"#ffffff","slots":[{"kind":"image","frame":{"x":0,"y":0,"width":1440,"height":1500}}, - {"kind":"text","frame":{"x":100,"y":100,"width":500,"height":80}}],"decorations":[]}); - assert!(verified_structure_preview(&row, &selected, "brand", "category").is_some()); - assert!(verified_structure_preview(&row, &selected, "other", "category").is_none()); - assert!(verified_structure_preview(&row, &selected, "brand", "other").is_none()); - let mut other = selected.clone(); - other["version"] = json!("v2"); - assert!(verified_structure_preview(&row, &other, "brand", "category").is_none()); - row["structurePreview"]["contentHash"] = json!("b".repeat(64)); - assert!(verified_structure_preview(&row, &selected, "brand", "category").is_none()); - row["structurePreview"]["contentHash"] = selected["contentHash"].clone(); - row["structurePreview"]["slots"][0]["frame"]["width"] = json!(1441); - assert!(verified_structure_preview(&row, &selected, "brand", "category").is_none()); - row["structurePreview"] = Value::Null; - assert!(verified_structure_preview(&row, &selected, "brand", "category").is_none()); - } - #[test] - fn template_structure_picker_clicks_only_enabled_real_preview_and_fits_narrow_width() { - let preview = json!({"width":1440,"height":2000,"background":"#ffffff", - "slots":[{"kind":"image","frame":{"x":0,"y":0,"width":1440,"height":1500}}],"decorations":[]}); - for enabled in [true, false] { - let ctx = egui::Context::default(); - let draw = |events| { - let mut response = None; - let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(240.0, 200.0))), events, ..Default::default() }, |ui| { - ui.set_width(180.0); - response = Some(template_picker_row(ui, false, "非常长的真实模板名称 · v1", enabled, Some(&preview))); - }); - response.unwrap() - }; - let initial = draw(vec![]); - assert!(initial.rect.width() <= 181.0, "preview must fit the narrow picker"); - let point = initial.rect.left_top() + vec2(10.0, PICKER_ROW_HEIGHT / 2.0); - draw(vec![egui::Event::PointerMoved(point), egui::Event::PointerButton { pos:point, button:egui::PointerButton::Primary, pressed:true, modifiers:Default::default() }]); - let response = draw(vec![egui::Event::PointerButton { pos:point, button:egui::PointerButton::Primary, pressed:false, modifiers:Default::default() }]); - assert_eq!(response.clicked(), enabled, "thumbnail selection must respect the template lock"); - } - } - - #[test] - fn resource_template_defaults_to_detail_or_a_single_component() { - let detail = json!({"id":"detail","kind":"detail"}); - let main = json!({"id":"main_images","kind":"main_images"}); - let sku = json!({"id":"800","kind":"sku_images"}); - assert_eq!(default_resource_component(&[main, detail.clone(), sku.clone()]), Some(&detail)); - assert_eq!(default_resource_component(std::slice::from_ref(&sku)), Some(&sku)); - assert!(default_resource_component(&[sku, json!({"id":"750","kind":"sku_images"})]).is_none()); - assert!(default_resource_component(&[]).is_none()); - } - - #[test] - fn resource_template_result_binds_the_component_without_an_extra_click() { - let (mut w, mut app, _) = brief_fixture(); - w.creation_brief["templateSelection"] = Value::Null; - w.creation_dirty = false; - let result = json!({"id":"detail","choice":{ - "id":"desk","version":"map-version","contentHash":"a".repeat(64), - "brandId":"brand","categoryId":"category","width":750, - "enterprise":{"resourceSetId":"selected-set","componentId":"detail"} - }}); - let ctx = egui::Context::default(); - let mut render = |set, result: &Value| { - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - w.resource_component_result(&mut app, ui, 500.0, set, result); - }); - output.textures_delta.clear(); - (w.creation_brief["templateSelection"].clone(), w.creation_width, w.creation_dirty) - }; - assert!(render("previous-set", &result).0.is_null()); - let (selected, width, dirty) = render("selected-set", &result); - assert_eq!(selected["enterprise"]["componentId"], "detail"); - assert_eq!(width, 750); - assert!(dirty); - let (after_preview, _, _) = render("selected-set", &json!({"id":"detail","previewId":"another"})); - assert_eq!(after_preview, selected); - } - - #[test] - fn canvas_entry_uses_product_and_exact_template_without_ai_stage_confirmation() { - let mut brief = empty_brief(); - brief["name"] = json!("测试桌"); - brief["brandId"] = json!("brand"); - brief["categoryId"] = json!("desk"); - brief["images"] = json!([{"name":"产品实拍","source":"local:unit-test","purpose":"product"}]); - let template = json!({"id":"real-template-identity-contract","version":"2","contentHash":"a".repeat(64),"brandId":"brand","categoryId":"desk"}); - assert!(canvas_entry_missing(&brief, &template).is_empty(), "facts/selling points/AI plan are not prerequisites for opening the structure"); - assert_eq!(selected_template(&brief, &Value::Null, &brief), Value::Null, "a directory's first item cannot silently become the user's selection"); - brief["templateSelection"] = template.clone(); - assert_eq!(selected_template(&brief, &Value::Null, &brief), template); - assert_eq!(canvas_entry_missing(&brief, &json!({"id":"template","version":"2","contentHash":"not-a-hash"})), ["模板"]); - brief["images"][0]["purpose"] = json!("scene"); - assert_eq!(canvas_entry_missing(&brief, &template), ["产品图"]); - brief["name"] = json!(" "); - assert_eq!(canvas_entry_missing(&brief, &Value::Null), ["模板", "产品名称", "产品图"]); - } - #[test] - fn installed_legacy_template_is_pinned_but_not_relabelled_for_a_changed_brand() { - let mut brief = empty_brief(); - brief["brandId"] = json!("original-brand"); - brief["categoryId"] = json!("desk"); - let canonical = brief.clone(); - let workflow = json!({"templateId":"fixed","templateVersion":"1","templateHash":"a".repeat(64)}); - assert_eq!(selected_template(&brief, &workflow, &canonical)["id"], "fixed"); - brief["brandId"] = json!("different-brand"); - assert!(selected_template(&brief, &workflow, &canonical).is_null()); - assert_eq!(workflow["templateVersion"], "1", "reading a selection never upgrades the old project"); - } - #[test] - fn variant_identity_survives_reordering_and_keeps_the_original_product_option() { - let material = "82f3a6b7-6323-4cf5-a741-d990182f382c"; - assert_eq!(variant_identity(material), material); - let fallback = variant_identity("legacy-material-code"); - assert_eq!(fallback, variant_identity("legacy-material-code")); - assert_ne!(fallback, variant_identity("another-material-code")); - assert_eq!(fallback.len(), 36); - assert_eq!(fallback.chars().nth(14), Some('8')); - let mut brief = empty_brief(); - brief["variant"] = json!("单孔 K 型"); - brief["colorMaterialId"] = json!(material); - brief["colorName"] = json!("柚木色"); - let mut variants = brief_variants(&brief); - assert_eq!(variants[0]["id"], material, "legacy single color survives an empty new variants field"); - variants.push(json!({"id":variant_identity("black"),"name":"黑色","colorMaterialId":"black","colorName":"黑色","images":[]})); - variants.reverse(); - set_brief_variants(&mut brief, variants); - assert_eq!(brief["variant"], "单孔 K 型"); - assert_eq!(brief["colorName"], "黑色", "the first selected color keeps old single-color readers compatible"); - assert_eq!(brief["variants"][1]["id"], material); - } - #[test] - fn specific_variant_references_never_remain_common_or_leak_into_another_color() { - let image = json!({"name":"柚木实拍","source":"local:photo","purpose":"product"}); - let mut brief = empty_brief(); - let teak = variant_identity("teak"); - let black = variant_identity("black"); - set_brief_variants( - &mut brief, - vec![ - json!({"id":teak,"name":"柚木色","colorMaterialId":"teak","colorName":"柚木色","images":[]}), - json!({"id":black,"name":"黑色","colorMaterialId":"black","colorName":"黑色","images":[]}), - ], - ); - brief["images"] = json!([image.clone()]); - store_image_rows(&mut brief, vec![(image.clone(), teak.clone())]).unwrap(); - assert!(brief["images"].as_array().unwrap().is_empty()); - assert_eq!(brief["variants"][0]["images"], json!([image.clone()])); - assert!(brief["variants"][1]["images"].as_array().unwrap().is_empty()); - let unchanged = brief.clone(); - assert!(store_image_rows(&mut brief, vec![(image.clone(), "missing-variant".into())]).is_err()); - assert_eq!(brief, unchanged, "an invalid owner cannot silently turn a private reference into shared evidence"); - store_image_rows(&mut brief, vec![(image.clone(), String::new())]).unwrap(); - assert_eq!(brief["images"], json!([image])); - assert!(brief["variants"].as_array().unwrap().iter().all(|variant| variant["images"].as_array().unwrap().is_empty())); - } - #[test] - fn reimporting_a_variant_image_does_not_silently_make_it_common() { - let (mut w, app) = setup(); - let image = json!({"name":"指定花色实拍","source":"local:original-color","purpose":"product"}); - w.creation_brief = empty_brief(); - set_brief_variants( - &mut w.creation_brief, - vec![json!({"id":variant_identity("teak"),"name":"柚木色","colorMaterialId":"teak","colorName":"柚木色","images":[image.clone()]})], - ); - let mut value = reference(&w); - value.as_object_mut().unwrap().remove("creation"); - value["images"] = json!([image]); - received(&mut w, &app, "creation-import", &value); - assert!(w.creation_brief["images"].as_array().unwrap().is_empty()); - assert_eq!(w.creation_brief["variants"][0]["images"].as_array().unwrap().len(), 1); - } - fn picker_frame(ctx: &egui::Context, populated: bool) -> egui::Id { - let mut id = egui::Id::NULL; - let mut output = - ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1000.0, 800.0))), ..Default::default() }, |ui| { - id = picker(ui, "stable-picker", 320.0, "选择品牌", |ui| { - if populated { - for i in 0..16 { - picker_row(ui, false, &format!("品牌 {i} · 很长的目录名称应在固定宽度内截断"), true); - } - } else { - picker_notice(ui, true, None, false, ""); - } - }) - .response - .id; - }); - output.textures_delta.clear(); - id - } - #[test] - fn dynamic_picker_keeps_width_and_fits_loading_or_loaded_content() { - let ctx = egui::Context::default(); - // The shipped native theme adds scroll content margins. Omitting those - // in a default-context test misses a first-frame width expansion. - ctx.all_styles_mut(|style| style.spacing.scroll.content_margin = egui::Margin::same(1)); - let id = picker_frame(&ctx, false); - let popup = id.with("popup"); - egui::Popup::open_id(&ctx, popup); - picker_frame(&ctx, false); - picker_frame(&ctx, false); - let loading = ctx.memory(|memory| memory.area_rect(popup)).unwrap(); - picker_frame(&ctx, true); - picker_frame(&ctx, true); - let populated = ctx.memory(|memory| memory.area_rect(popup)).unwrap(); - egui::Popup::close_id(&ctx, popup); - picker_frame(&ctx, true); - egui::Popup::open_id(&ctx, popup); - picker_frame(&ctx, true); - picker_frame(&ctx, true); - let reopened = ctx.memory(|memory| memory.area_rect(popup)).unwrap(); - assert!(loading.height() < PICKER_HEIGHT / 2.0, "a short loading state should not reserve an empty list: {loading:?}"); - assert!(populated.height() >= PICKER_HEIGHT, "a long list retains its scroll area: {populated:?}"); - for rect in [populated, reopened] { - assert!((rect.width() - loading.width()).abs() <= 1.0, "menu width is independent of loaded labels: {loading:?} {rect:?}"); - } - assert!((reopened.height() - populated.height()).abs() <= 1.0, "the same list keeps its height on reopen"); - } - #[test] - fn material_thumbnail_reserves_identical_space_in_all_read_states() { - let ctx = egui::Context::default(); - let texture = ctx.load_texture("material-test", egui::ColorImage::filled([48, 24], egui::Color32::WHITE), egui::TextureOptions::LINEAR); - let mut sizes = Vec::new(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - for (image, loading, failed) in [(None, false, false), (None, true, false), (None, false, true), (Some(&texture), false, false)] { - sizes.push(material_thumbnail(ui, image, loading, failed).rect.size()); - } - }); - output.textures_delta.clear(); - assert!(sizes.iter().all(|size| *size == vec2(MATERIAL_THUMB_SIDE, MATERIAL_THUMB_SIDE))); - // Scaling uses f32; accept sub-millipixel rounding while checking both - // the maximum size and the preserved aspect ratio. - for (source, expected) in [(vec2(1600.0, 800.0), vec2(240.0, 120.0)), (vec2(400.0, 1600.0), vec2(60.0, 240.0))] { - assert!((preview_size(source, vec2(240.0, 240.0)) - expected).abs().max_elem() < 0.001); - } - assert_eq!(preview_size(vec2(0.0, 10.0), vec2(240.0, 240.0)), egui::Vec2::ZERO); - } - #[test] - fn material_popup_exposes_each_cached_image_and_its_hover_target() { - let (mut w, mut app) = setup(); - let ctx = egui::Context::default(); - w.creation_brief = empty_brief(); - w.creation_view_geometry = json!({"controls":{},"popups":{},"materialRows":[],"hoverPreview":null}); - let rows: Vec<_> = (0..6).map(|i| json!({"id":format!("material-{i}"),"name":format!("材质 {i}")})).collect(); - for row in &rows { - let id = row["id"].as_str().unwrap(); - w.creation_thumbs.insert(id.into(), ctx.load_texture(id, egui::ColorImage::filled([40, 20], egui::Color32::WHITE), egui::TextureOptions::LINEAR)); - } - w.creation_catalog.insert("materials".into(), rows); - let popup = ui_rect_popup_id(&ctx, &w); - egui::Popup::open_id(&ctx, popup); - for _ in 0..2 { - let mut output = ctx - .run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1000.0, 800.0))), ..Default::default() }, |ui| { - w.material_select(&mut app, ui, 320.0) - }); - output.textures_delta.clear(); - } - let visible: Vec<_> = w.creation_view_geometry["materialRows"].as_array().unwrap().iter().filter(|r| r["visible"] == true).collect(); - assert!(visible.len() >= 4, "a full native popup exposes several material thumbnails"); - for row in visible { - assert_eq!(row["status"], "ready"); - assert_eq!(row["imageRect"][2].as_f64(), Some(f64::from(MATERIAL_THUMB_SIDE))); - assert_eq!(row["imageRect"][3].as_f64(), Some(f64::from(MATERIAL_THUMB_SIDE))); - } - } - fn ui_rect_popup_id(ctx: &egui::Context, w: &Workspace) -> egui::Id { - // Obtain the same native id without inventing an automation-only widget path. - let mut id = egui::Id::NULL; - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - id = picker(ui, "creation-material", 320.0, w.creation_brief["colorName"].as_str().unwrap_or("选择材质颜色"), |_| {}).response.id; - }); - output.textures_delta.clear(); - id.with("popup") - } - fn setup() -> (Workspace, PhotocraftApp) { - let (tx, _) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - 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()); - w.account = json!({"id":"qa"}); - w.origin = "http://localhost:3138".into(); - let st = app.session.active().unwrap(); - w.owner_doc = Some(st.doc.id.0); - w.expected_revision = st.revision; - w.creation_base_revision = st.revision; - w.allow_apply = true; - w.busy = Some("creation-generate".into()); - (w, app) - } - fn reference(w: &Workspace) -> Value { - json!({"doc":w.owner_doc,"accountId":w.account["id"],"origin":w.origin,"run":"00000000-0000-4000-8000-000000000001","baseRevision":w.creation_base_revision,"sequence":1,"creation":{}}) - } - - fn brief_fixture() -> (Workspace, PhotocraftApp, mpsc::Receiver) { - let (mut w, app) = setup(); - let (tx, requests) = mpsc::channel(); - w.tx = tx; - w.busy = None; - w.unknown = false; - w.key_saved = true; - w.creation_brief = empty_brief(); - w.creation_brief["name"] = json!("实木多功能产品 · 用于核对窄窗口的完整产品名称"); - w.creation_brief["brandId"] = json!("brand"); - w.creation_brief["brandName"] = json!("长品牌名称 / 原生资料完整保留"); - w.creation_brief["categoryId"] = json!("category"); - w.creation_brief["categoryName"] = json!("玄关与收纳家具 / 多功能衣帽架"); - w.creation_brief["variant"] = json!("原产品规格文字"); - w.creation_brief["images"] = json!([{"source":"common-image","name":"产品白底参考与需要完整保留的很长文件名.png","purpose":"product"}]); - set_brief_variants( - &mut w.creation_brief, - vec![ - json!({"id":"oak","name":"原木色","colorMaterialId":"material-oak","images":[]}), - json!({"id":"walnut","name":"胡桃木色","colorMaterialId":"material-walnut","images":[{"source":"walnut-image","name":"胡桃木色专属参考.png","purpose":"scene"}]}), - ], - ); - let template = - json!({"id":"template","name":"极简详情模板","version":"1.2","contentHash":"a".repeat(64),"brandId":"brand","categoryId":"category","cached":true}); - w.creation_brief["templateSelection"] = template.clone(); - w.creation_catalog.insert("brands".into(), vec![json!({"id":"brand","name":"长品牌名称","ready":true})]); - w.creation_catalog.insert("materials".into(), vec![]); - w.creation_catalog.insert("templates".into(), vec![template]); - w.agent_categories = vec![json!({"id":"category","name":"玄关与收纳家具"})]; - w.agent_rules = vec![json!({"shopId":"brand","categoryId":"category"})]; - w.creation_doc = app.session.active().map(|state| state.doc.id.0); - w.creation = json!({"brief":w.creation_brief.clone()}); - (w, app, requests) - } - - fn brief_frame(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Context, width: f32, events: Vec) -> egui::Rect { - brief_frame_at_size(w, app, ctx, vec2(width, 2600.0), events) - } - - fn brief_frame_at_size(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Context, size: egui::Vec2, events: Vec) -> egui::Rect { - let mut bounds = egui::Rect::NOTHING; - let mut output = ctx.run_ui( - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }, - |ui| { - bounds = ui.available_rect_before_wrap(); - stitch_ui::scope(ui, |ui| w.brief_ui(app, ui)); - }, - ); - output.textures_delta.clear(); - bounds - } - - - fn barcode_fixture() -> (Workspace, PhotocraftApp, mpsc::Receiver) { - let (mut w, app, requests) = brief_fixture(); - set_brief_variants(&mut w.creation_brief, vec![]); - w.creation_brief["images"] = json!([]); - w.creation_brief["barcodeBindings"] = json!({"default":["DNZ030516N717V01","CY001307N35V01"]}); - set_intake(&mut w.creation_brief, &json!("template"), &json!({"version":1, - "productFields":[ - {"id":"summary","label":"固定卖点","type":"text"}, - {"id":"new_kind","label":"扩展字段","type":"future-kind"} - ], - "barcodeFields":[ - {"id":"color","label":"颜色组合","type":"text"}, - {"id":"length","label":"长度","type":"number","unit":"mm"}, - {"id":"width","label":"宽度","type":"number","unit":"mm"}, - {"id":"height","label":"高度","type":"number","unit":"mm"} - ]})); - w.creation_brief["intake"]["barcodeValues"]["DNZ030516N717V01"] = json!({"length":1200,"width":580,"height":750}); - (w, app, requests) - } - - #[test] - fn platform_facts_fill_template_fields_and_keep_missing_fields_empty() { - let (mut w, mut app, requests) = barcode_fixture(); - let mut brief = w.creation_brief.clone(); - brief["source"] = json!("product_platform"); - brief["identifierType"] = json!("spu"); - brief["identifier"] = json!("00-Model"); - brief["barcodeBindings"] = json!({"default":["00-a,01","00-B"]}); - brief["detailBarcode"] = json!("00-a,01"); - brief["platformFacts"] = json!({"spu":"00-Model","shared":{"material":"织物"},"barcodes":{ - "00-a,01":{"colorName":"灰色","dimensions":{"unit":"mm","length":1800,"width":900,"height":700}}, - "00-B":{"colorName":"米色","dimensions":{"unit":"mm","width":880}} - }}); - brief["intake"]["schema"]["productFields"].as_array_mut().unwrap() - .push(json!({"id":"material","label":"材质","type":"text"})); - let doc = app.session.active().unwrap().doc.id.0; - let receipt = json!({"doc":doc,"origin":w.origin,"accountId":w.account["id"],"platformBrief":brief}); - received(&mut w, &app, "creation-product-platform", &receipt); - assert_eq!(w.creation_brief["intake"]["productValues"], json!({"material":"织物"})); - assert_eq!(w.creation_brief["intake"]["barcodeValues"]["00-a,01"], json!({"color":"灰色","length":1800,"width":900,"height":700})); - assert_eq!(w.creation_brief["intake"]["barcodeValues"]["00-B"], json!({"color":"米色","width":880})); - assert_eq!(field_fact(&json!({"id":"length","type":"number","unit":"cm"}), - &w.creation_brief["platformFacts"]["barcodes"]["00-a,01"]), Some(json!(180.0))); - let ctx = egui::Context::default(); - w.account = Value::Null; - let before = w.creation_brief.clone(); - brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); - assert!(!w.creation_view_geometry["controls"]["platform-fetch"].is_null()); - assert!(w.creation_action(&mut app, "creation-product-platform", json!({"spu":"00-Model"})).unwrap_err().contains("登录")); - assert_eq!(w.creation_brief, before); - assert!(!requests.try_iter().any(|request| matches!(request, Request::Action(method, _) if method == "creation-product-platform"))); - } - - #[test] - fn template_image_slots_use_drop_and_picker_with_exact_roles_and_barcode() { - let (mut w, mut app, requests) = barcode_fixture(); - w.creation_open = true; - w.library = false; - let schema = json!({"version":1,"productFields":[ - {"key":"hero","kind":"image","label":"产品图片","imageRole":"product","placeholder":"拖入产品图"}], - "barcodeFields":[{"key":"fabric","kind":"image","label":"材质图片","imageRole":"material","multiple":false,"placeholder":"拖入材质图"}]}); - set_intake(&mut w.creation_brief, &json!("image-template"), &schema); - let (picker, asked) = crate::file_dialog::fake(vec![Some(crate::FileDialogAnswer::Paths(vec!["D:\\photos\\fabric.png".into()]))]); - app.services.file_dialog = Some(picker); - let ctx = egui::Context::default(); - for width in [380.0, 850.0] { - brief_frame(&mut w, &mut app, &ctx, width, vec![]); - let bounds = brief_frame(&mut w, &mut app, &ctx, width, vec![]); - let slots = w.creation_view_geometry["imageSlots"].as_object().unwrap(); - assert_eq!(slots.len(), 3); - assert!(slots.values().all(|target| { - let rect = &target["rect"]; - rect[0].as_f64().unwrap_or_default() >= f64::from(bounds.left()) && - rect[0].as_f64().unwrap_or_default() + rect[2].as_f64().unwrap_or_default() <= f64::from(bounds.right()) - })); - assert!(w.creation_view_geometry["controls"]["reference-add"].is_null()); - } - let slots = w.creation_view_geometry["imageSlots"].as_object().unwrap(); - let product = slots.values().find(|row| row["label"] == "产品图片").unwrap().clone(); - let fabric = slots.values().find(|row| row["label"] == "材质图片" - && row["slot"]["barcode"] == "DNZ030516N717V01").unwrap().clone(); - let center = |rect: &Value| egui::pos2((rect[0].as_f64().unwrap()+rect[2].as_f64().unwrap()/2.0) as f32, - (rect[1].as_f64().unwrap()+rect[3].as_f64().unwrap()/2.0) as f32); - assert_eq!(product["placeholder"], "拖入产品图"); - assert_eq!(fabric["placeholder"], "拖入材质图"); - app.jiansun = Some(w); - app.open_dropped(&ctx, vec![reference_drop("D:\\photos\\product.png")], Some(center(&product["rect"]))); - let Some(Request::Action(_, input)) = requests.try_iter() - .find(|request| matches!(request, Request::Action(method, _) if method == "creation-import")) - else { panic!("expected import"); }; - assert_eq!(input["imageSlot"]["imageRole"], "product"); - let mut w = app.jiansun.take().unwrap(); - w.busy = None; - let pixels = json!([{"source":format!("local:{}", "d".repeat(64)),"purpose":"product","name":"样品"}]); - let draft = w.creation_brief.clone(); - let doc = app.session.active().unwrap().doc.id.0; - let import = |slot: &Value| json!({"doc":doc,"origin":product["origin"],"accountId":product["accountId"],"images":pixels,"imageSlot":slot}); - received(&mut w, &app, "creation-import", &import(&input["imageSlot"])); - brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); - let slot = w.creation_view_geometry["imageSlots"].as_object().unwrap().values() - .find(|row| row["slot"] == fabric["slot"]).unwrap(); - let click = center(&slot["rect"]); - brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(click)); - app.jiansun = Some(w); - app.poll_file_dialog(&ctx, None); - assert!(matches!(asked.borrow().first(), Some(crate::FileDialogRequest::Open { multiple:false, .. }))); - let Some(Request::Action(_, input)) = requests.try_iter() - .find(|request| matches!(request, Request::Action(method, _) if method == "creation-import")) - else { panic!("expected import"); }; - assert_eq!(input["imageSlot"], fabric["slot"]); - let mut w = app.jiansun.take().unwrap(); - received(&mut w, &app, "creation-import", &import(&input["imageSlot"])); - assert_eq!(w.creation_brief["images"][0]["imageRole"], "product"); - assert_eq!(w.creation_brief["images"][1]["imageRole"], "material"); - assert_eq!(w.creation_brief["images"][1]["barcode"], "DNZ030516N717V01"); - assert_eq!(w.creation_brief["intake"], draft["intake"]); - } - - #[test] - fn barcode_bindings_read_legacy_lists_and_deduplicate_the_complete_trimmed_values() { - let legacy = json!(" DNZ030516N717V01,;CY001307N35V01、\r\nDNZ030516N717V01 "); - assert_eq!(binding_barcodes(&legacy).collect::>(), ["DNZ030516N717V01", "CY001307N35V01"]); - let exact = "0007 台面/甲+乙,A;B\n编码\t二🪑"; - let brief = json!({"barcodeBindings":{"default":["DNZ030516N717V01", "CY001307N35V01", exact]}}); - assert_eq!(project_barcodes(&brief).last(), Some(exact)); - assert_eq!(barcode_issue(&brief, &format!(" {exact} ")), Some("此条码已录入当前项目")); - assert_eq!(barcode_issue(&brief, "cy001307n35v01"), None); - assert_eq!(barcode_issue(&brief, "cy001301N35"), None); - assert_eq!(barcode_issue(&brief, "SJ021613N16V01"), None); - assert_eq!(barcode_issue(&brief, &"A".repeat(121)), None); - assert_eq!(barcode_issue(&brief, " \t\n"), Some("请输入产品条码")); - } - - #[test] - fn pasted_barcode_survives_the_form_and_save_payload_without_losing_characters() { - let (mut w, mut app, requests) = barcode_fixture(); - w.creation_brief["barcodeBindings"] = json!({}); - w.reduce_motion = true; - let ctx = egui::Context::default(); - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); } - let add = control_rect(&w, "barcode-add-default").center(); - brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(add)); - let exact = "0007 台面/甲+乙,A;B\r\n编码\t二🪑"; - brief_frame(&mut w, &mut app, &ctx, 760.0, vec![egui::Event::Paste(format!(" \t{exact}\n "))]); - let apply = control_rect(&w, "barcode-confirm-default").center(); - brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(apply)); - assert_eq!(w.creation_brief["barcodeBindings"]["default"], json!([exact])); - assert_eq!(w.creation_brief["detailBarcode"], exact); - w.creation_action(&mut app, "creation-save", json!({})).unwrap(); - assert!(matches!(requests.try_recv(), Ok(Request::Action(method, input)) if method == "creation-save" - && input["brief"]["barcodeBindings"]["default"] == json!([exact]) - && input["brief"]["detailBarcode"] == exact)); - } - - #[test] - fn detail_barcode_defaults_for_one_and_follows_rename_or_removal() { - let (mut w, mut app, requests) = barcode_fixture(); - assert!(!update_detail_barcode(&mut w.creation_brief)); - assert!(canvas_entry_missing(&w.creation_brief, &Value::Null).contains(&"详情页出图条码")); - w.creation_brief["detailBarcode"] = json!("DNZ030516N717V01"); - replace_barcode(&mut w.creation_brief, "DNZ030516N717V01", Some("SG008839N1049V01")); - w.creation_brief["barcodeBindings"]["default"] = json!(["SG008839N1049V01","CY001307N35V01"]); - assert_eq!(w.creation_brief["detailBarcode"], "SG008839N1049V01"); - assert_eq!(w.creation_brief["intake"]["barcodeValues"]["SG008839N1049V01"]["length"], 1200); - w.creation_action(&mut app, "creation-save", json!({})).unwrap(); - assert!(matches!(requests.try_recv(), Ok(Request::Action(method, input)) if - method == "creation-save" && input["brief"]["detailBarcode"] == "SG008839N1049V01")); - replace_barcode(&mut w.creation_brief, "SG008839N1049V01", None); - w.creation_brief["barcodeBindings"]["default"] = json!(["CY001307N35V01"]); - assert!(update_detail_barcode(&mut w.creation_brief)); - assert_eq!(w.creation_brief["detailBarcode"], "CY001307N35V01"); - } - - #[test] - fn dynamic_intake_reads_optional_hints_and_multiline_without_requiring_schema_changes() { - let explicit = json!({"id":"copy","type":"text","placeholder":" 如:收拢深度 35 cm ","help":"旧说明","multiline":true}); - let legacy_long = json!({"id":"notes","type":"text","label":"注意事项","help":"如:远离火源"}); - let legacy_short = json!({"id":"material","type":"text","label":"材质"}); - let a = json!({"id":"length","type":"number","help":"按本款确认资料填写;尺寸注明单位,暂无资料可留空。"}); - let b = json!({"id":"wood","type":"select","help":"请按确认资料填写。"}); - let c = json!({"id":"finish","type":"text","help":" 请按确认资料填写。 "}); - assert_eq!(intake_hint(&explicit), "如:收拢深度 35 cm"); - assert_eq!(intake_hint(&legacy_long), "如:远离火源"); - assert_eq!(intake_hint(&legacy_short), ""); - assert_eq!(intake_hint(&a), "数字"); - assert_eq!(intake_hint(&b), "请按确认资料填写。"); - assert_eq!(intake_hint(&c), "请按确认资料填写。"); - for key in ["hint", "example", "promptHint", "description"] { - assert_eq!(intake_hint(&json!({(key):"如:白蜡木"})), "如:白蜡木"); - } - assert!(intake_multiline(&explicit)); - assert!(intake_multiline(&legacy_long)); - assert!(!intake_multiline(&legacy_short)); - assert!(!intake_multiline(&json!({"type":"text","label":"注意事项","multiline":false}))); - assert!(is_product_name_field(&json!({"id":"name","label":"产品名称","type":"text"}))); - assert!(is_product_name_field(&json!({"id":"title","label":"商品名 * ","type":"text"}))); - assert!(!is_product_name_field(&json!({"id":"english","label":"英文产品名称","type":"text"}))); - } - - #[test] - fn dynamic_product_intake_reflows_short_fields_and_spans_long_text() { - use egui_kittest::{Harness, kittest::Queryable}; - assert_eq!(product_intake_columns(559.0), 1); - assert_eq!(product_intake_columns(560.0), 2); - for width in [420.0, 640.0] { - let mut harness = Harness::builder().with_size(vec2(width + 40.0, 460.0)) - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .build_ui_state(|ui, values: &mut Value| { - let fields = [ - json!({"id":"a","label":"材质","type":"text","placeholder":"如:橡木"}), - json!({"id":"b","label":"产地","type":"text","help":"如:江苏"}), - json!({"id":"c","label":"核心卖点","type":"text","multiline":true}), - ]; - let fields = fields.iter().collect::>(); - intake_fields(ui, egui::Id::unique("product-intake-test"), width, &fields, - IntakeScope::Product, values, true); - }, json!({})); - harness.run_steps(2); - let a = harness.get_by_role_and_label(egui::accesskit::Role::TextInput, "材质").rect(); - let b = harness.get_by_role_and_label(egui::accesskit::Role::TextInput, "产地").rect(); - let c = harness.get_by_role_and_label(egui::accesskit::Role::MultilineTextInput, "核心卖点").rect(); - if width >= 560.0 { - assert!((a.top() - b.top()).abs() < 1.0 && a.right() < b.left()); - assert!(c.width() > a.width() * 1.9); - } else { - assert!(b.top() > a.bottom() && (a.left() - b.left()).abs() < 1.0); - assert!((c.width() - a.width()).abs() < 1.0); - } - assert!(c.top() > b.bottom() && c.height() > a.height()); - harness.get_by_role_and_label(egui::accesskit::Role::TextInput, "材质").click(); - harness.run_steps(2); - harness.event(egui::Event::Text("橡木".to_owned())); - harness.run_steps(2); - assert_eq!(harness.state(), &json!({"a":"橡木"})); - } - } - - #[test] - fn dynamic_barcode_form_keeps_cards_and_controls_within_wide_and_narrow_bounds() { - assert_eq!(intake_columns(178.0), 2); - assert_eq!(intake_columns(460.0), 3); - for width in [248.0, 760.0, 900.0] { - let (mut w, mut app, _) = barcode_fixture(); - let ctx = egui::Context::default(); - w.reduce_motion = true; - brief_frame(&mut w, &mut app, &ctx, width, vec![]); - let bounds = brief_frame(&mut w, &mut app, &ctx, width, vec![]); - let card = control_rect(&w, "barcode-card-default-0"); - let second = control_rect(&w, "barcode-card-default-1"); - let edit = control_rect(&w, "barcode-edit-default-0"); - let delete = control_rect(&w, "barcode-remove-default-0"); - let number = control_rect(&w, "barcode-number-default-0"); - assert!(card.right() <= bounds.right() + 1.0 && second.right() <= bounds.right() + 1.0); - assert!(card.contains_rect(edit) && card.contains_rect(delete)); - assert!(bounds.contains_rect(control_rect(&w, "source-library"))); - assert!(edit.left() < card.left() + 52.0 && edit.right() < delete.left()); - assert!(edit.left() - number.right() >= 7.0); - if width == 900.0 { - assert!(edit.width() >= 280.0); - } - assert!(card.bottom() <= second.top()); - assert!(w.creation_view_geometry["controls"]["dimensions"].is_null()); - assert!(w.creation_view_geometry["controls"]["material"].is_null()); - assert!(w.creation_view_geometry["controls"]["output-width"].is_null()); - assert!(w.creation_view_geometry["controls"]["barcode-input-default"].is_null()); - let add = control_rect(&w, "barcode-add-default").center(); - brief_frame(&mut w, &mut app, &ctx, width, click_events(add)); - assert!(control_rect(&w, "barcode-input-default").is_positive(), "SPU can still be blank"); - } - } - - #[test] - fn detail_barcode_selector_changes_the_brief_used_by_the_form() { - let (mut w, mut app, requests) = barcode_fixture(); - w.creation_brief["identifier"] = json!("QA-DESK-001"); - w.creation_brief["images"] = json!([{"source":"test-reference","name":"产品图.png","purpose":"product"}]); - let ctx = egui::Context::default(); - w.reduce_motion = true; - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); } - let picker = control_rect(&w, "detail-barcode").center(); - brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(picker)); - brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); - let option = control_rect(&w, "detail-barcode-option-1").center(); - brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(option)); - assert_eq!(w.creation_brief["detailBarcode"], "CY001307N35V01"); - assert_eq!(w.creation_draft()["brief"]["detailBarcode"], "CY001307N35V01"); - let enter = control_rect(&w, "enter-canvas").center(); - brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(enter)); - assert!(matches!(requests.try_recv(), Ok(Request::Save(_, _, _)))); - assert_eq!(w.pending_slot_apply.as_ref().unwrap()["brief"]["detailBarcode"], "CY001307N35V01"); - } - - #[test] - fn template_form_shows_unknown_fields_and_keeps_requirements_input_visible() { - let (mut w, mut app, _) = barcode_fixture(); - w.creation_brief["note"] = json!("已保存的特殊制作要求"); - w.reduce_motion = true; - let ctx = egui::Context::default(); - brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); - assert!(control_rect(&w, "special-requirements-input").is_positive()); - assert_eq!(w.creation_brief["note"], "已保存的特殊制作要求"); - - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - let field = json!({"id":"unexpected","label":"扩展字段","type":"future-kind"}); - intake_fields(ui, egui::Id::unique("unknown-field-test"), 360.0, - &[&field], IntakeScope::Product, &mut json!({}), true); - }); - let text = out.shapes.iter().filter_map(|shape| match &shape.shape { - egui::Shape::Text(text) => Some(text.galley.text()), - _ => None, - }).collect::>(); - assert!(text.iter().any(|text| text.contains("暂不支持此字段类型(future-kind)")), "{text:?}"); - out.textures_delta.clear(); - } - - #[test] - #[ignore = "offscreen GPU visual evidence; requires PHOTOCRAFT_AGENT_QA_OUT"] - fn barcode_form_visual_acceptance() { - let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); - for (width, height) in [(248.0, 2100.0), (760.0, 1760.0), (900.0, 1600.0)] { - let (mut w, app, _) = barcode_fixture(); - w.creation_brief["name"] = json!("轻量可调工作台"); - w.creation_brief["intake"]["schema"]["productFields"] = json!([ - {"id":"name","label":"产品名称","type":"text","required":true}, - {"id":"species","label":"主要材质","type":"text","placeholder":"如:白橡木"}, - {"id":"load","label":"承重","type":"number","unit":"kg","help":"如:60"}, - {"id":"finish","label":"表面处理","type":"select","options":["木蜡油","水性漆"],"placeholder":"选择表面处理"}, - {"id":"origin","label":"产地","type":"text","help":"如:江苏"}, - {"id":"copy","label":"核心卖点","type":"text","multiline":true,"placeholder":"如:台面高度可调。折叠后靠墙收纳。"}, - ]); - w.creation_brief["identifier"] = json!("QA-DESK-001"); - w.creation_brief["detailBarcode"] = json!("CY001307N35V01"); - w.reduce_motion = true; - let mut h = egui_kittest::Harness::builder().with_size(vec2(width, height)) - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests).wgpu().build_ui_state( - |ui, state: &mut (Workspace, PhotocraftApp)| { - if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { - stitch_ui::scope(ui, |ui| state.0.brief_ui(&mut state.1, ui)); - } - }, (w, app)); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join(format!("barcode-form-{width}.png"))).unwrap(); - } - } - - #[test] - #[ignore = "offscreen GPU image-slot acceptance; requires PHOTOCRAFT_AGENT_QA_OUT"] - fn template_image_slots_visual_acceptance() { - let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); - for width in [380.0, 850.0] { - let (mut w, app, _) = barcode_fixture(); - w.creation_brief["source"] = json!("product_platform"); - w.creation_brief["identifierType"] = json!("spu"); - w.creation_brief["identifier"] = json!("SPU-001"); - w.creation_brief["name"] = json!("可调工作台"); - set_intake(&mut w.creation_brief, &json!("visual-template"), &json!({"version":1, - "productFields":[ - {"id":"material","type":"text","label":"材质","promptHint":"例如:白蜡木"}, - {"id":"selling-points","type":"text","label":"核心卖点","description":"例如:台面可折叠,收纳后深度为 35 cm。"}, - {"key":"product","kind":"image","label":"产品图片","placeholder":"拖入产品图或点击选择","imageRole":"product"} - ], - "barcodeFields":[{"key":"material","kind":"image","label":"材质图片","placeholder":"拖入材质图或点击选择","imageRole":"material"}]})); - w.reduce_motion = true; - let mut h = egui_kittest::Harness::builder().with_size(vec2(width, 1600.0)) - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests).wgpu().build_ui_state( - |ui, state: &mut (Workspace, PhotocraftApp)| { - if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { - stitch_ui::scope(ui, |ui| state.0.brief_ui(&mut state.1, ui)); - } - }, (w, app)); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join(format!("track-h-form-{width}.png"))).unwrap(); - } - } - - #[test] - fn resumed_project_shows_continue_after_the_originals_settle() { - let (mut w, mut app, _) = brief_fixture(); - w.model_ready = true; - w.image_ready = true; - w.unknown = true; - w.product_checkpoint = json!({"active":true,"phase":"paused"}); - w.template_workflow = json!({"productionStages":[]}); - let ctx = egui::Context::default(); - brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); - assert!(control_rect(&w, "resume-product").is_positive()); - assert!(!w.can_resume_product()); - w.unknown = false; - brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); - assert!(control_rect(&w, "resume-product").is_positive()); - assert!(w.can_resume_product()); - } - - #[test] - fn a_scoped_pending_slot_leaves_the_production_resume_button_usable() { - let (mut w, mut app, requests) = brief_fixture(); - w.unknown = true; - w.model_ready = true; - w.image_ready = true; - w.models = vec![ - json!({"key":"text","id":"text-only","supportsImageInput":false,"productionReady":false}), - json!({"key":"vision","id":"visual-chat","supportsImageInput":true,"productionReady":true}), - ]; - w.model = "text".into(); - w.template_workflow = json!({"scopedProductionPending":true, - "productionStages":[{"outputId":"detail","variantId":"oak"}]}); - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } - let button = control_rect(&w, "resume-product").center(); - brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(button)); - assert!(w.error.contains("text-only 暂无同时开放读图和工具调用的线路")); - assert!(w.pending_slot_apply.is_none() && requests.try_recv().is_err()); - w.model = "vision".into(); - brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(button)); - assert!(matches!(requests.try_recv(), Ok(Request::Save(_, _, _)))); - assert!(requests.try_recv().is_err()); - assert_eq!(w.pending_slot_apply.as_ref().unwrap()["resumeProduct"], true); - assert!(w.unknown); - assert_eq!(w.creation_brief, original); - } - - #[derive(Debug)] - struct ReferenceDrop(std::path::PathBuf); - impl egui::DroppedFile for ReferenceDrop { - fn path(&self) -> &std::path::Path { &self.0 } - fn bytes(&self) -> Result, String> { Err("the native backend reads the selected path".into()) } - } - fn reference_drop(path: &str) -> egui::DroppedFileHandle { Arc::new(ReferenceDrop(path.into())) } - - #[test] - fn reference_drop_feedback_requires_real_file_hover_inside_visible_target() { - fn labels(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| labels(shape,out)), - egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), - _ => {} - } - } - let (mut w, mut app, requests) = brief_fixture(); - let ctx = egui::Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for (path, mime, point, expected) in [ - (None, "", egui::pos2(50.0,20.0), false), - (Some("oak.PNG"), "", egui::pos2(50.0,20.0), true), - (Some("oak.png"), "", egui::pos2(500.0,20.0), false), - (Some("notes.txt"), "text/plain", egui::pos2(50.0,20.0), false), - (None, "image/webp", egui::pos2(50.0,20.0), true), - (None, "text/plain", egui::pos2(50.0,20.0), false), - ] { - app.services.cursor_pos = Some(Box::new(move |_| Some(point))); - let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(400.0,300.0))), - hovered_files:if path.is_some() || !mime.is_empty() { vec![egui::HoveredFile { path:path.map(std::path::PathBuf::from), mime:mime.into() }] } else { vec![] }, ..Default::default() }, |ui| { - stitch_ui::scope(ui, |ui| w.add_reference_button(&mut app,ui,260.0)); - }); - let mut text = Vec::new(); - for shape in output.shapes { labels(&shape.shape,&mut text); } - assert_eq!(text.iter().any(|label| label == "释放以上传图片"), expected); - assert!(requests.try_recv().is_err(), "hover does not import or send a request"); - } - } - - #[test] - fn reference_dropzone_blocks_click_and_file_hover_while_busy_or_unknown() { - for mode in ["busy", "unknown"] { - let (mut w, mut app, requests) = brief_fixture(); - let (dialog, calls) = crate::file_dialog::fake(vec![]); - app.services.file_dialog = Some(dialog); - if mode == "busy" { w.busy = Some("agent".into()); } else { w.unknown = true; } - let point = egui::pos2(50.0, 20.0); - app.services.cursor_pos = Some(Box::new(move |_| Some(point))); - let ctx = egui::Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for pressed in [true,false] { - let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(400.0,300.0))), - hovered_files:vec![egui::HoveredFile { path:Some("D:\\photos\\oak.png".into()), mime:String::new() }], - events:vec![egui::Event::PointerMoved(point),egui::Event::PointerButton { pos:point,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }], ..Default::default() }, |ui| { - stitch_ui::scope(ui, |ui| w.add_reference_button(&mut app,ui,260.0)); - }); - assert!(!output.shapes.iter().any(|shape| matches!(&shape.shape,egui::Shape::Text(text) if text.galley.text()=="释放以上传图片")), "{mode} must not offer release to upload"); - } - assert!(!app.file_dialog_open()); - assert!(calls.borrow().is_empty()); - assert!(requests.try_recv().is_err()); - } - } - - #[test] - fn shared_modal_and_retained_exit_block_reference_drop_without_changing_scope() { - for interactive in [true,false] { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_open = true; - w.library = false; - let ctx = egui::Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for _ in 0..2 { brief_frame(&mut w,&mut app,&ctx,850.0,vec![]); } - let point = control_rect(&w,"reference-add").center(); - let original = w.creation_brief.clone(); - let doc = app.session.active().unwrap().doc.id; - let revision = app.session.active().unwrap().revision; - let account = w.account.clone(); - app.jiansun = Some(w); - for time in [0.1,0.2] { - let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(850.0,2600.0))), time:Some(time), ..Default::default() }, |ui| { - let _ = stitch_ui::modal(ui.ctx(),egui::Id::unique("reference-drop-modal-test"),stitch_ui::OverlayVisual { render:true, interactive, opacity:0.5 },false, |ui| { ui.label("项目弹窗"); }); - }); - } - assert!(ctx.memory(|memory| memory.top_modal_layer().is_some())); - app.open_dropped(&ctx,vec![reference_drop("D:\\photos\\oak.png")],Some(point)); - assert_eq!(app.session.documents().len(),1); - assert_eq!(app.session.active().unwrap().doc.id,doc); - assert_eq!(app.session.active().unwrap().revision,revision); - assert_eq!(app.jiansun.as_ref().unwrap().creation_brief,original); - assert_eq!(app.jiansun.as_ref().unwrap().account,account); - assert!(requests.try_recv().is_err()); - } - } - - #[test] - fn real_reference_drop_uses_the_existing_import_and_preserves_variant_owners() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_open = true; - w.library = false; - let ctx = egui::Context::default(); - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } - let at = control_rect(&w, "reference-0").center(); - let before = w.creation_brief.clone(); - let doc = app.session.active().unwrap().doc.id.0; - app.jiansun = Some(w); - app.open_dropped(&ctx, vec![reference_drop("D:\\photos\\oak.png"), reference_drop("D:\\photos\\detail.JPG")], Some(at)); - let request = requests.try_recv().unwrap(); - let Request::Action(method, payload) = request else { panic!("expected reference import") }; - assert_eq!(method, "creation-import"); - assert_eq!(payload["doc"], doc); - assert_eq!(payload["paths"], json!(["D:\\photos\\oak.png", "D:\\photos\\detail.JPG"])); - assert_eq!(payload["brief"], before, "drop must not reassign any existing references or colors"); - assert_eq!(app.session.documents().len(), 1, "a reference drop is not opened as another native document"); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn reference_drop_accepts_the_empty_product_card() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_open = true; - w.library = false; - w.creation_brief["images"] = json!([]); - w.creation_brief["variants"] = json!([]); - let ctx = egui::Context::default(); - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } - let at = control_rect(&w, "reference-empty").center(); - let before = w.creation_brief.clone(); - let doc = app.session.active().unwrap().doc.id.0; - app.jiansun = Some(w); - - let files = ["D:\\photos\\椅子-左视图.webp", "D:\\photos\\oak.png", "D:\\photos\\detail.jpg"]; - app.open_dropped(&ctx, files.into_iter().map(reference_drop).collect(), Some(at)); - - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected reference import") }; - assert_eq!(method, "creation-import"); - assert_eq!(input["paths"], json!(files)); - assert_eq!(input["brief"], before); - let images = files.iter().enumerate().map(|(i, path)| json!({ - "source":format!("local:{i:064x}"),"purpose":"product","name":path.rsplit('\\').next().unwrap(), - })).collect::>(); - let mut w = app.jiansun.take().unwrap(); - let receipt = json!({ - "doc":doc,"origin":w.origin,"accountId":w.account["id"],"images":images, - }); - received(&mut w, &app, "creation-import", &receipt); - assert_eq!(w.creation_brief["images"].as_array().unwrap().len(), 3); - assert_eq!(w.creation_brief["name"], before["name"]); - assert_eq!(app.session.active().unwrap().doc.id.0, doc); - assert_eq!(app.session.documents().len(), 1); - } - - #[test] - fn product_form_drop_outside_reference_cards_keeps_the_active_draft() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_open = true; - w.library = false; - w.creation_brief["name"] = json!("已填写产品名称"); - w.creation_dirty = true; - let ctx = egui::Context::default(); - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } - let at = control_rect(&w, "name").center(); - let before = w.creation_brief.clone(); - let doc = app.session.active().unwrap().doc.id.0; - app.jiansun = Some(w); - - for point in [Some(at), Some(egui::pos2(0.0, 0.0)), None] { - app.open_dropped(&ctx, vec![reference_drop("D:\\photos\\oak.png")], point); - } - - let workspace = app.jiansun.as_ref().unwrap(); - assert_eq!(app.session.active().unwrap().doc.id.0, doc); - assert_eq!(app.session.documents().len(), 1); - assert_eq!(workspace.creation_brief, before); - assert!(workspace.creation_dirty); - assert_eq!(workspace.creation_reads.reference_import_error, REFERENCE_DROP_HINT); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn existing_assets_receive_drops_with_template_slots_on_the_form_layer() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_open = true; - w.library = false; - set_intake(&mut w.creation_brief, &json!("image-template"), &json!({"version":1,"productFields":[ - {"key":"hero","kind":"image","label":"产品图片","imageRole":"product"}, - ]})); - let ctx = egui::Context::default(); - let layer = egui::LayerId::new(egui::Order::Middle, egui::Id::unique("brief-drop-layer")); - for _ in 0..3 { - let mut output = ctx.run_ui(egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(900.0, 2600.0))), - ..Default::default() - }, |ui| { - egui::Area::new(layer.id).order(layer.order) - .fixed_pos(egui::pos2(20.0, 20.0)).default_size(vec2(850.0, 2500.0)) - .show(ui.ctx(), |ui| { - ui.set_min_size(vec2(850.0, 2500.0)); - w.creation_ui(&mut app, ui); - }); - }); - output.textures_delta.clear(); - } - let at = control_rect(&w, "reference-0").center(); - assert_eq!(ctx.layer_id_at(at), Some(layer), "drop point {at:?} in {:?}", ctx.memory(|m| m.area_rect(layer.id))); - assert!(drop_contains(&w.creation_view_geometry["product-form-viewport"], at)); - assert!(drop_contains(&w.creation_view_geometry["referenceDrop"]["rect"], at)); - let before = w.creation_brief.clone(); - app.jiansun = Some(w); - app.open_dropped(&ctx, vec![reference_drop("D:\\photos\\chair.webp")], Some(at)); - let input = requests.try_iter().find_map(|request| match request { - Request::Action(method, input) if method == "creation-import" => Some(input), - _ => None, - }).unwrap(); - assert_eq!(input["brief"], before); - assert!(input["imageSlot"].is_null()); - assert_eq!(app.session.documents().len(), 1); - } - - #[test] - fn reference_drop_only_intercepts_the_visible_current_project_target() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_open = true; - w.library = false; - let ctx = egui::Context::default(); - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } - let at = control_rect(&w, "reference-add").center(); - app.jiansun = Some(w); - let files = [reference_drop("D:\\photos\\oak.png")]; - assert!(app.creation_reference_drop(&ctx, &files, None)); - assert!(app.creation_reference_drop(&ctx, &files, Some(egui::pos2(1.0, 1.0)))); - app.jiansun.as_mut().unwrap().account = json!({"id":"another"}); - assert!(app.creation_reference_drop(&ctx, &files, Some(at))); - app.jiansun.as_mut().unwrap().account = json!({"id":"qa"}); - app.session.execute("file.new", json!({"width":32,"height":32})).unwrap(); - assert!(app.creation_reference_drop(&ctx, &files, Some(at))); - assert_eq!(app.jiansun.as_ref().unwrap().creation_reads.reference_import_error, REFERENCE_DROP_HINT); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn reference_drop_rejects_busy_unknown_and_unsupported_files_without_opening_them() { - for mode in ["busy", "unknown", "format", "count"] { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_open = true; - w.library = false; - let ctx = egui::Context::default(); - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } - let at = control_rect(&w, "reference-add").center(); - if mode == "busy" { w.busy = Some("agent".into()); } - if mode == "unknown" { w.unknown = true; } - app.jiansun = Some(w); - let files = if mode == "format" { vec![reference_drop("D:\\photos\\file.pdf")] } - else if mode == "count" { (0..9).map(|_| reference_drop("D:\\photos\\oak.png")).collect() } - else { vec![reference_drop("D:\\photos\\oak.png")] }; - app.open_dropped(&ctx, files, Some(at)); - assert!(!app.jiansun.as_ref().unwrap().creation_reads.reference_import_error.is_empty(), "{mode} should explain why the drop was not imported"); - assert_eq!(app.session.documents().len(), 1, "{mode} should not accidentally open a new document"); - assert!(requests.try_recv().is_err(), "{mode} must not dispatch an import"); - } - } - - fn control_rect(w: &Workspace, name: &str) -> egui::Rect { - let rect = w.creation_view_geometry["controls"][name].as_array().unwrap_or_else(|| panic!("missing control {name}")); - egui::Rect::from_min_size( - egui::pos2(rect[0].as_f64().unwrap() as f32, rect[1].as_f64().unwrap() as f32), - vec2(rect[2].as_f64().unwrap() as f32, rect[3].as_f64().unwrap() as f32), - ) - } - - fn click_events(pos: egui::Pos2) -> Vec { - vec![ - egui::Event::PointerMoved(pos), - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }, - ] - } - - #[test] - fn selling_point_toggle_keeps_key_and_request_contract() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation["sellingPoints"] = json!({"batches":[{"id":"batch","items":["实木结构"]}]}); - let ctx = egui::Context::default(); - fn draw(ctx: &egui::Context, w: &mut Workspace, app: &mut PhotocraftApp, events: Vec) { - let _ = ctx.settle_ui( - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(850.0, 1000.0))), events, ..Default::default() }, - |ui| { stitch_ui::scope_with_motion(ui, w.reduce_motion, |ui| w.points_ui(app, ui)); }, - ); - } - draw(&ctx, &mut w, &mut app, vec![]); - let point = control_rect(&w, "selling-point-0-0").center(); - draw(&ctx, &mut w, &mut app, click_events(point)); - assert_eq!(w.creation_selected, vec!["batch:0"]); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected selection request") }; - assert_eq!(method, "creation-select"); - assert_eq!(input["selected"], json!(["batch:0"])); - w.busy = None; - // A pointer click does not promise keyboard focus in egui. Exercise the - // actual Tab focus path in a fresh context instead of assuming it did. - let keyboard_ctx = egui::Context::default(); - draw(&keyboard_ctx, &mut w, &mut app, vec![]); - let point = control_rect(&w, "selling-point-0-0").center(); - let mut reached = false; - for _ in 0..12 { - draw(&keyboard_ctx, &mut w, &mut app, key_events(egui::Key::Tab)); - let focus = keyboard_ctx.memory(|memory| memory.focused()); - if focus.and_then(|id| keyboard_ctx.read_response(id)) - .is_some_and(|response| response.rect.center().distance(point) < 0.5) - { - reached = true; - break; - } - } - assert!(reached, "Tab traversal reaches the selling-point toggle"); - draw(&keyboard_ctx, &mut w, &mut app, key_events(egui::Key::Space)); - assert!(w.creation_selected.is_empty(), "Tab then Space supports keyboard deselection"); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected selection request") }; - assert_eq!(method, "creation-select"); - assert_eq!(input["selected"], json!([])); - } - - fn key_events(key: egui::Key) -> Vec { - [true, false].into_iter().map(|pressed| egui::Event::Key { - key, physical_key: Some(key), pressed, repeat: false, modifiers: egui::Modifiers::NONE, - }).collect() - } - - #[test] - fn brief_autosave_keeps_form_active_and_preserves_newer_edits() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation["revision"] = json!(1); - w.creation_dirty = true; - let delivery = std::env::temp_dir().join("成品"); - w.creation_delivery_dir = Some(delivery.to_string_lossy().into_owned()); - w.creation_action(&mut app, "creation-save", json!({})).unwrap(); - assert!(form_editable(w.busy.as_deref(), false)); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("save request") }; - assert_eq!(method, "creation-save"); - assert_eq!(input["deliveryDir"], json!(delivery)); - w.creation_delivery_dir = None; - w.creation_brief["name"] = json!("保存过程中继续输入的产品名"); - w.creation_brief["categoryName"] = json!("新选品类"); - let draft = w.creation_draft(); - let value = json!({"doc":w.creation_doc,"accountId":w.account["id"],"origin":w.origin, - "creation":{"revision":2,"deliveryDir":input["deliveryDir"],"brief":input["brief"],"width":input["width"],"screenCount":input["screenCount"],"plan":{"screens":input["screens"]}}}); - received(&mut w, &app, "creation-save", &value); - assert_eq!(w.creation_brief, draft["brief"]); - assert!(w.creation_dirty); - assert!(w.creation_delivery_dir.is_none(), "clearing the folder supersedes the in-flight save"); - assert_eq!(w.creation["revision"], 2); - assert!(!form_editable(Some("creation-import"), false)); - assert!(!form_editable(None, true)); - } - - #[test] - fn sku_color_plan_adds_multiple_colors_and_saves_selected_subsets() { - for width in [900.0, 380.0] { - let (mut w, mut app, requests) = brief_fixture(); - w.reduce_motion = true; - let ctx = egui::Context::default(); - let draw = |w: &mut Workspace, app: &mut PhotocraftApp, events| { - brief_frame_at_size(w, app, &ctx, vec2(width, 3200.0), events) - }; - draw(&mut w, &mut app, vec![]); - let bounds = draw(&mut w, &mut app, vec![]); - let field = control_rect(&w, "sku-color-input"); - assert!(bounds.contains_rect(field)); - draw(&mut w, &mut app, click_events(field.center())); - draw(&mut w, &mut app, vec![egui::Event::Text("暖白色".into())]); - let add = control_rect(&w, "sku-color-add"); - draw(&mut w, &mut app, click_events(add.center())); - let white = variant_identity("manual-sku:暖白色"); - assert_eq!(w.creation_brief["variants"][2]["id"], white); - let adv = control_rect(&w, "advanced-export-settings"); - draw(&mut w, &mut app, click_events(adv.center())); - draw(&mut w, &mut app, vec![]); - let select = |w: &mut Workspace, app: &mut PhotocraftApp, output: &str, ids: &[&str]| { - let trigger = control_rect(w, &format!("sku-output-{output}")); - assert!(bounds.contains_rect(trigger), "{output} trigger {trigger:?} outside {bounds:?}"); - draw(w, app, click_events(trigger.center())); - for _ in 0..25 { draw(w, app, vec![]); } - for id in ids { - let option = control_rect(w, &format!("sku-output-{output}-{id}")); - draw(w, app, click_events(option.center())); - } - draw(w, app, key_events(egui::Key::Escape)); - for _ in 0..25 { draw(w, app, vec![]); } - }; - select(&mut w, &mut app, "detail", &["oak", "walnut"]); - select(&mut w, &mut app, "main_images", &[&white]); - let expected = json!({"detail":["oak","walnut"],"main_images":[white]}); - assert_eq!(w.creation_brief["outputVariantIds"], expected); - for row in w.creation_brief["variants"].as_array().unwrap() { - assert!(!w.sku_color_removable(row)); - } - assert!(w.creation_dirty); - w.creation_action(&mut app, "creation-save", json!({})).unwrap(); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("save brief") }; - assert_eq!(method, "creation-save"); - assert_eq!(input["brief"]["outputVariantIds"], expected); - assert_eq!(input["brief"]["variants"][2]["colorName"], "暖白色"); - } - } - - #[test] - #[ignore = "native GPU visual evidence; requires PHOTOCRAFT_AGENT_QA_OUT"] - fn sku_color_plan_form_visual_acceptance() { - let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); - for (width, height) in [(900.0, 1500.0), (420.0, 2200.0)] { - let (mut w, app, _requests) = brief_fixture(); - w.creation_brief["outputVariantIds"] = json!({"detail":["oak","walnut"],"main_images":["oak"]}); - w.creation_dirty = true; - w.unknown = true; - w.template_workflow = json!({"canvasFirst":true,"scopedProductionPending":true}); - let mut h = egui_kittest::Harness::builder().with_size(vec2(width, height)).wgpu().build_ui_state( - |ui, state: &mut (Workspace, PhotocraftApp)| { - if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { - stitch_ui::scope(ui, |ui| state.0.brief_ui(&mut state.1, ui)); - } - }, - (w, app), - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join(format!("sku-colors-{width}.png"))).unwrap(); - } - } - - #[test] - fn stitch_brief_resizes_without_losing_reference_ownership_or_overflowing_controls() { - let (mut w, mut app, requests) = brief_fixture(); - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - for width in [900.0, 720.0, 600.0, 380.0] { - brief_frame(&mut w, &mut app, &ctx, width, vec![]); - let bounds = brief_frame(&mut w, &mut app, &ctx, width, vec![]); - for name in ["brief-title", "name", "brand", "category", "dimensions", "identifier", "material", "template", "reference-0", "reference-1", "enter-canvas"] { - let rect = control_rect(&w, name); - assert!( - rect.left() >= bounds.left() - 1.0 && rect.right() <= bounds.right() + 1.0, - "{name} must remain inside the {width}px form: {rect:?}, bounds {bounds:?}" - ); - } - for index in 0..2 { - let card = control_rect(&w, &format!("reference-{index}")); - let preview = control_rect(&w, &format!("reference-preview-{index}")); - let purpose = control_rect(&w, &format!("reference-purpose-{index}")); - let owner = control_rect(&w, &format!("reference-owner-{index}")); - assert!( - card.contains_rect(preview) && card.contains_rect(purpose) && card.contains_rect(owner), - "reference controls stay in their own card at {width}px" - ); - assert!(preview.right() < purpose.left(), "reference preview and its controls are side by side at {width}px"); - assert!(purpose.bottom() < owner.top(), "reference controls keep a vertical flow inside the grid cell"); - assert!(card.height() <= 190.0, "reference rows stay compact rather than reserving an oversized image card at {width}px"); - } - let name = control_rect(&w, "name"); - let brand = control_rect(&w, "brand"); - let category = control_rect(&w, "category"); - assert!(control_rect(&w, "brief-title").bottom() < name.top(), "page title precedes the editable product fields"); - let template = control_rect(&w, "template"); - assert!(brand.top() <= category.top()); - assert!(category.bottom() < template.top()); - assert!(template.bottom() < name.top(), "template selection precedes product fields"); - assert!(name.bottom() < control_rect(&w, "reference-0").top(), "product fields precede the visual asset gallery"); - for control in ["name", "brand", "category", "dimensions", "identifier", "template"] { - assert!((control_rect(&w, control).height() - 34.0).abs() < 0.8, "{control} has a consistent field height"); - } - assert_eq!(w.creation_brief, original, "resizing never resets product options, colors, sources or purpose"); - } - assert!(requests.try_recv().is_err(), "painting a fully cached form does not execute a read or model action"); - } - - #[test] - fn output_tags_toggle_real_scopes_without_fake_upcoming_pills() { - let (mut w, mut app, requests) = brief_fixture(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - w.creation_dirty = false; - for width in [900.0, 380.0] { - brief_frame(&mut w, &mut app, &ctx, width, vec![]); - let bounds = brief_frame(&mut w, &mut app, &ctx, width, vec![]); - let mut rects: Vec = Vec::new(); - for (id, _, _) in OUTPUT_SCOPE_OPTIONS { - let rect = control_rect(&w, id); - assert!(bounds.contains_rect(rect), "{id} at {width}: {rect:?}"); - assert!(rects.iter().all(|other| !other.intersects(rect)), "{id} overlaps at {width}"); - rects.push(rect); - } - assert!(w.creation_view_geometry["controls"]["output-tag-main_video"].is_null()); - assert!(w.creation_view_geometry["controls"]["output-tag-seeding_video"].is_null()); - } - let pos = control_rect(&w, "output-tag-sku_images").center(); - brief_frame(&mut w, &mut app, &ctx, 380.0, click_events(pos)); - assert!(w.creation_dirty); - assert_eq!(selected_output_scopes(&w.creation_brief), vec!["detail", "main_images"]); - let pos_main = control_rect(&w, "output-tag-main_images").center(); - brief_frame(&mut w, &mut app, &ctx, 380.0, click_events(pos_main)); - assert_eq!(selected_output_scopes(&w.creation_brief), vec!["detail"]); - // Cannot deselect the final remaining scope. - let pos_detail = control_rect(&w, "output-tag-detail").center(); - brief_frame(&mut w, &mut app, &ctx, 380.0, click_events(pos_detail)); - assert_eq!(selected_output_scopes(&w.creation_brief), vec!["detail"]); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn brief_library_search_and_entry_actions_reflow_without_dispatching() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_brief["source"] = json!("library"); - w.creation["productionBudgetMinutes"] = json!(90); - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - for width in [900.0, 380.0] { - brief_frame(&mut w, &mut app, &ctx, width, vec![]); - brief_frame(&mut w, &mut app, &ctx, width, vec![]); - let source = control_rect(&w, "source"); - let search = control_rect(&w, "source-search"); - let hint = control_rect(&w, "entry-hint"); - assert!(w.creation_draft().get("productionBudgetMinutes").is_none()); - let advanced = control_rect(&w, "advanced-export-settings"); - let enter = control_rect(&w, "enter-canvas"); - assert!(advanced.bottom() <= hint.top() && hint.bottom() <= enter.top()); - assert!(advanced.right() <= width + 1.0); - if width >= 900.0 { - assert!(source.right() < search.left() && source.top() < search.bottom() && search.top() < source.bottom(), "wide source and lookup share a row"); - } else { - assert!(source.bottom() < search.top(), "narrow lookup follows its source"); - } - assert_eq!(w.creation_brief, original); - } - assert!(requests.try_recv().is_err(), "rendering must not search or dispatch model actions"); - } - - #[test] - fn brief_grid_boundaries_keep_fields_separate() { - let (mut w, mut app, requests) = brief_fixture(); - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - for width in [380.0, 519.0, 520.0, 779.0, 780.0, 808.0] { - for _ in 0..2 { - let mut output = ctx.run_ui( - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 2600.0))), ..Default::default() }, - |ui| { stitch_ui::scope(ui, |ui| w.brief_content_ui(&mut app, ui)); }, - ); - output.textures_delta.clear(); - } - let fields: Vec<_> = ["name", "brand", "category", "dimensions", "identifier"].iter().map(|name| control_rect(&w, name)).collect(); - for (index, field) in fields.iter().enumerate() { - assert!(field.left() >= -1.0 && field.right() <= width + 1.0, "field {index} overflows at {width}px: {field:?}"); - for other in fields.iter().skip(index + 1) { - assert!(!field.intersects(*other), "fields overlap at {width}px: {field:?} and {other:?}"); - } - } - assert_eq!(w.creation_brief, original); - } - assert!(requests.try_recv().is_err()); - } - - #[test] - fn dimension_row_fits_its_column_and_displays_the_complete_unit() { - fn text_is_visible(shape: &egui::Shape, expected: &str, selector: egui::Rect, clip: egui::Rect) -> bool { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().any(|shape| text_is_visible(shape, expected, selector, clip)), - egui::Shape::Text(text) => { - let painted: String = text.galley.rows.iter().flat_map(|row| row.glyphs.iter().map(|glyph| glyph.chr)).collect(); - let bounds = egui::Rect::from_min_size(text.pos, text.galley.size()); - painted == expected && selector.contains_rect(bounds) && clip.contains_rect(bounds) - } - _ => false, - } - } - for width in [380.0, 519.0, 780.0, 1000.0] { - for unit in ["mm", "cm", "m"] { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_brief["dimensions"]["unit"] = json!(unit); - let ctx = egui::Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let mut output = None; - for _ in 0..2 { - output = Some(ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(width,2600.0))), ..Default::default() }, - |ui| { stitch_ui::scope(ui, |ui| w.brief_content_ui(&mut app,ui)); })); - } - let row = control_rect(&w, "dimensions"); - let selector = control_rect(&w, "dimensions-unit"); - assert!(row.width() <= width + 1.0, "{width}: dimensions {row:?} exceed container"); - assert!(row.width() >= 320.0, "{width}: dimensions row must remain generous and never crush inputs: {row:?}"); - assert!(row.contains_rect(selector), "{width}: unit selector stays inside the row"); - assert!(output.unwrap().shapes.iter().any(|shape| text_is_visible(&shape.shape,unit,selector,shape.clip_rect)), "{width}: complete unit {unit} must be painted within its selector and clip"); - assert!(requests.try_recv().is_err()); - } - } - } - - #[test] - fn dimension_filter_chip_changes_only_the_selected_unit() { - fn find(shape:&egui::Shape, text:&str) -> Option { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().find_map(|shape| find(shape,text)), - egui::Shape::Text(shape) if shape.galley.text() == text => Some(shape.pos + shape.galley.size() * 0.5), - _ => None, - } - } - let (mut w, mut app, requests) = brief_fixture(); - w.reduce_motion = true; - w.creation_brief["dimensions"]["length"] = json!("1200"); - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - crate::PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { - ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(900.0,1200.0))),events,..Default::default() }, - |ui| { stitch_ui::scope(ui,|ui| w.brief_content_ui(app,ui)); }) - }; - frame(&mut w,&mut app,vec![]); - let anchor = control_rect(&w,"dimensions-unit").center(); - for pressed in [true,false] { - frame(&mut w,&mut app,vec![egui::Event::PointerMoved(anchor),egui::Event::PointerButton { pos:anchor,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); - } - let output = frame(&mut w,&mut app,vec![]); - let cm = output.shapes.iter().find_map(|shape| find(&shape.shape,"cm")).expect("unit popup exposes cm filter chip"); - for pressed in [true,false] { - frame(&mut w,&mut app,vec![egui::Event::PointerMoved(cm),egui::Event::PointerButton { pos:cm,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); - } - let mut expected = original; - expected["dimensions"]["unit"] = json!("cm"); - assert_eq!(w.creation_brief,expected); - assert!(w.creation_dirty); - assert!(requests.try_recv().is_err(),"choosing a unit only edits the local draft"); - } - - #[test] - fn full_creation_surface_resets_horizontal_parent_and_centering_row_layouts() { - let (mut w, mut app, requests) = brief_fixture(); - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - w.creation_open = true; - w.library = false; - w.material = false; - for (window_width, dock_width) in [(1535.0, 519.0), (1100.0, 360.0), (850.0, 360.0)] { - for (stage, controls) in [ - (CreationStage::Source, &["source", "reference-add"][..]), - (CreationStage::Template, &["brand", "category", "template"][..]), - (CreationStage::Details, &["name", "identifier", "reference-0", "reference-1", "enter-canvas"][..]), - ] { - w.creation_reads.wizard_stage = Some((w.creation_field_scope(&app), stage)); - let mut central = egui::Rect::NOTHING; - for _ in 0..2 { - let mut output = ctx.run_ui( - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(window_width, 1032.0))), ..Default::default() }, - |ui| { - ui.horizontal(|ui| { - ui.allocate_ui_with_layout( - vec2(window_width - dock_width - ui.spacing().item_spacing.x, 1032.0), - egui::Layout::left_to_right(egui::Align::Min), - |ui| { - central = ui.available_rect_before_wrap(); - w.creation_ui(&mut app, ui); - }, - ); - ui.allocate_exact_size(vec2(dock_width, 1032.0), egui::Sense::hover()); - }); - }, - ); - output.textures_delta.clear(); - } - for name in controls { - let rect = control_rect(&w, name); - assert!( - rect.left() >= central.left() && rect.right() <= central.right(), - "{name} escaped the real horizontal workspace at {window_width}px: {rect:?}, central {central:?}" - ); - } - } - for (key, value) in original.as_object().unwrap() { - assert_eq!(&w.creation_brief[key], value, "{key}"); - } - } - assert!(requests.try_recv().is_err()); - } - - #[test] - fn library_product_can_add_references_without_changing_its_source_or_existing_owners() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_brief["source"] = json!("library"); - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - brief_frame(&mut w, &mut app, &ctx, 540.0, vec![]); - let add = control_rect(&w, "reference-add"); - assert!(add.width() > 0.0 && add.height() >= 34.0, "library references retain the same visible local image picker"); - assert_eq!(w.creation_brief, original); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn empty_reference_picker_fits_narrow_form_without_changing_variants() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_brief["images"] = json!([]); - let mut variants = brief_variants(&w.creation_brief); - for variant in &mut variants { variant["images"] = json!([]); } - set_brief_variants(&mut w.creation_brief, variants); - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); - let bounds = brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); - let add = control_rect(&w, "reference-add"); - assert!(add.width() >= 100.0 && add.height() >= 72.0); - assert!(add.left() >= bounds.left() && add.right() <= bounds.right(), "the image picker remains inside the narrow form"); - assert_eq!(w.creation_brief, original, "rendering the empty picker must preserve all variant identities"); - assert!(requests.try_recv().is_err(), "rendering an empty picker must not initiate an import"); - } - - #[test] - fn brief_source_buttons_switch_without_discarding_the_draft() { - let (mut w, mut app, requests) = brief_fixture(); - let mut expected = w.creation_brief.clone(); - let ctx = egui::Context::default(); - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } - assert_eq!(w.creation_view_geometry["sourceChoices"][0]["selected"], true); - assert_eq!(w.creation_view_geometry["sourceChoices"][1]["selected"], false); - assert_eq!(w.creation_view_geometry["popups"]["source"]["open"], false); - let rail = control_rect(&w, "source"); - for control in ["source-upload", "source-product_platform", "source-library"] { - let segment = control_rect(&w, control); - assert!(rail.contains_rect(segment) && segment.height() >= control::MENU_ROW); - } - let library = control_rect(&w, "source-library").center(); - brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(library)); - expected["source"] = json!("library"); - assert_eq!(w.creation_brief, expected, "switching source must preserve names, images, variants and template identity"); - assert_eq!(w.creation_view_geometry["sourceChoices"][0]["selected"], false); - assert_eq!(w.creation_view_geometry["sourceChoices"][2]["selected"], true); - assert!(w.creation_dirty); - brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); - let upload = control_rect(&w, "source-upload").center(); - brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(upload)); - expected["source"] = json!("upload"); - assert_eq!(w.creation_brief, expected); - assert!(requests.try_recv().is_err(), "switching source is local and must not load or overwrite data"); - } - - #[test] - fn material_toggle_row_remains_full_width_and_respects_disabled_state() { - fn draw(ctx: &egui::Context, selected: &mut bool, enabled: bool, events: Vec) -> egui::Rect { - let mut rect = egui::Rect::NOTHING; - let _ = ctx.settle_ui( - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 200.0))), events, ..Default::default() }, - |ui| { - ui.set_width(240.0); - let response = picker_toggle_row(ui, *selected, "长花色名称", enabled); - rect = response.rect; - if response.clicked() { *selected = !*selected; } - }, - ); - rect - } - let ctx = egui::Context::default(); - let mut selected = false; - let rect = draw(&ctx, &mut selected, true, vec![]); - let at = rect.right_center() - vec2(5.0, 0.0); - assert!(rect.width() >= 240.0 && rect.height() >= PICKER_ROW_HEIGHT, "the entire material row remains an accessible hit target"); - draw(&ctx, &mut selected, true, click_events(at)); - assert!(selected, "clicking the far edge selects the actual material"); - draw(&ctx, &mut selected, false, click_events(at)); - assert!(selected, "a locked material cannot be removed through the shared toggle"); - } - - #[test] - fn brief_source_buttons_are_keyboard_accessible() { - let (mut w, _, requests) = brief_fixture(); - let mut expected = w.creation_brief.clone(); - let ctx = egui::Context::default(); - let frame = |w: &mut Workspace, events| { - ctx.settle_ui(egui::RawInput { events, ..Default::default() }, |ui| { - stitch_ui::scope(ui, |ui| w.source_picker(ui)); - }); - }; - frame(&mut w, vec![]); - frame(&mut w, key_events(egui::Key::Tab)); - frame(&mut w, key_events(egui::Key::Tab)); - frame(&mut w, key_events(egui::Key::Enter)); - expected["source"] = json!("product_platform"); - assert_eq!(w.creation_brief, expected, "keyboard can select the product platform without changing the draft"); - frame(&mut w, key_events(egui::Key::Tab)); - frame(&mut w, key_events(egui::Key::Enter)); - expected["source"] = json!("library"); - assert_eq!(w.creation_brief, expected, "keyboard can select the library without changing the draft"); - assert_eq!(w.creation_view_geometry["sourceChoices"][2]["selected"], true); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn brief_library_segment_search_and_result_keep_request_identity() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_brief["identifier"] = json!("QA-001"); - w.creation_brief["identifierType"] = json!("spu"); - let ctx = egui::Context::default(); - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } - let library = control_rect(&w, "source-library").center(); - brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(library)); - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } - let search = control_rect(&w, "source-search").center(); - brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(search)); - let Request::Action(method, input) = requests.try_recv().expect("the search dispatches a catalog request") else { panic!("expected catalog action") }; - assert_eq!(method, "creation-catalog"); - assert_eq!(input["kind"], "products"); - assert_eq!(input["identifier"], "QA-001"); - assert_eq!(input["identifierType"], "spu"); - let row = json!({"id":"synthetic-product","name":"测试产品"}); - w.creation_catalog.insert("products".into(), vec![row.clone()]); - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } - let result = control_rect(&w, "source-result-0").center(); - brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(result)); - let request = requests.try_iter().find(|request| matches!(request, Request::Action(method, _) if method == "creation-product")); - let Some(Request::Action(_, input)) = request else { panic!("the chosen product must be submitted") }; - assert_eq!(input["item"], row); - assert_eq!(input["brief"]["source"], "library"); - assert_eq!(input["brief"]["identifier"], "QA-001"); - } - - #[test] - fn brief_material_heading_does_not_shrink_the_catalog() { - let (mut w, mut app, _requests) = brief_fixture(); - let ctx = egui::Context::default(); - for width in [600.0, 780.0, 808.0] { - for _ in 0..2 { - let mut output = ctx.run_ui( - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 2600.0))), ..Default::default() }, - |ui| { stitch_ui::scope(ui, |ui| w.brief_content_ui(&mut app, ui)); }, - ); - output.textures_delta.clear(); - } - let heading = control_rect(&w, "material-heading"); - let material = control_rect(&w, "material"); - assert!(heading.right() < material.left(), "material heading overlaps its picker at {width}px"); - assert!((heading.top() - material.top()).abs() <= 1.0, "material heading and picker must share a compact row at {width}px"); - assert!(material.width() >= 320.0, "material picker and popup must retain readable catalog width at {width}px"); - } - } - - #[test] - fn brief_reference_grid_handles_empty_and_multiple_long_named_images() { - for width in [380.0, 650.0, 850.0] { - for count in 0..=4 { - let (mut w, mut app, _requests) = brief_fixture(); - w.creation_brief["images"] = json!((0..count).map(|index| json!({ - "source": format!("reference-{index}"), - "name": format!("需要完整保留的超长中文产品参考图片名称-{index}.png"), - "purpose": if index % 2 == 0 { "product" } else { "scene" }, - })).collect::>()); - w.creation_brief["variants"][1]["images"] = json!([]); - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, width, vec![]); } - let add = control_rect(&w, "reference-add"); - assert!(add.left() >= -1.0 && add.right() <= width + 1.0, "add control overflows at {width}px with {count} images: {add:?}"); - for index in 0..count { - let card = control_rect(&w, &format!("reference-{index}")); - let preview = control_rect(&w, &format!("reference-preview-{index}")); - let purpose = control_rect(&w, &format!("reference-purpose-{index}")); - let owner = control_rect(&w, &format!("reference-owner-{index}")); - assert!(card.contains_rect(preview) && card.contains_rect(purpose) && card.contains_rect(owner), "controls escape card {index} at {width}px"); - assert!(!card.intersects(add), "add control overlaps card {index} at {width}px"); - for other in (index + 1)..count { - assert!(!card.intersects(control_rect(&w, &format!("reference-{other}"))), "reference cards overlap at {width}px"); - } - } - assert_eq!(w.creation_brief, original, "layout must preserve images, purposes, owners and template"); - } - } - } - - #[test] - fn a_pending_image_allows_editing_and_saving_other_variant_references() { - for width in [380.0, 900.0] { - let (mut w, mut app, requests) = brief_fixture(); - w.unknown = true; - w.template_workflow = json!({"canvasFirst":true,"scopedProductionPending":true}); - let original = w.creation_brief["variants"][0].clone(); - let ctx = egui::Context::default(); - brief_frame(&mut w, &mut app, &ctx, width, vec![]); - brief_frame(&mut w, &mut app, &ctx, width, vec![]); - let remove = control_rect(&w, "reference-remove-1").center(); - brief_frame(&mut w, &mut app, &ctx, width, click_events(remove)); - assert!(w.creation_brief["variants"][1]["images"].as_array().unwrap().is_empty()); - assert_eq!(w.creation_brief["variants"][0], original); - assert!(w.unknown); - assert!(w.creation_dirty && w.can_save_creation()); - w.creation_action(&mut app, "creation-save", json!({})).unwrap(); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected local brief save") }; - assert_eq!(method, "creation-save"); - assert_eq!(input["brief"]["variants"][0], original); - assert!(requests.try_recv().is_err()); - } - } - - #[test] - fn product_brief_save_without_template_preserves_color_references_and_stays_in_form() { - for width in [380.0, 900.0] { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_open = true; - w.creation_step = 0; - w.creation_brief["templateSelection"] = Value::Null; - w.creation_catalog.insert("templates".into(), vec![]); - w.creation_dirty = true; - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - brief_frame(&mut w, &mut app, &ctx, width, vec![]); - let bounds = brief_frame(&mut w, &mut app, &ctx, width, vec![]); - let enter = control_rect(&w, "enter-canvas"); - assert!(bounds.contains_rect(enter)); - assert!(w.creation_view_geometry["controls"]["save-brief"].is_null()); - w.creation_action(&mut app, "creation-save", json!({})).unwrap(); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected local brief save") }; - assert_eq!(method, "creation-save"); - assert_eq!(input["brief"], original); - assert!(requests.try_recv().is_err()); - assert!(w.pending_slot_apply.is_none()); - assert!(w.creation_open && w.creation_step == 0); - } - } - - #[test] - fn new_project_shows_one_refinement_switch_and_the_start_carries_its_choice() { - let (mut w, mut app, requests) = brief_fixture(); - w.model_ready = true; - w.image_ready = true; - let ctx = egui::Context::default(); - brief_frame(&mut w, &mut app, &ctx, 900.0, vec![]); - brief_frame(&mut w, &mut app, &ctx, 900.0, vec![]); - let switch = control_rect(&w, "refinement").center(); - brief_frame(&mut w, &mut app, &ctx, 900.0, click_events(switch)); - let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(900.0, 2600.0))), ..Default::default() }; - let output = ctx.run_ui(input, |ui| { stitch_ui::scope(ui, |ui| w.brief_ui(&mut app, ui)); }); - fn walk(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| walk(shape, out)), - _ => {} - } - } - let mut drawn = Vec::new(); - output.shapes.iter().for_each(|clipped| walk(&clipped.shape, &mut drawn)); - output.drop_without_applying_deltas(); - assert_eq!(drawn.iter().filter(|text| *text == "精修").count(), 1, "one refinement switch: {drawn:?}"); - assert!(!drawn.iter().any(|text| text == "不精修"), "no second refinement chooser: {drawn:?}"); - let start = control_rect(&w, "generate-product").center(); - brief_frame(&mut w, &mut app, &ctx, 900.0, click_events(start)); - assert!(requests.try_iter().any(|request| matches!(request, Request::Save(_, _, _))), "the start saves the project first"); - let start = w.pending_slot_apply.as_ref().expect("the start waits for the save"); - assert_eq!((&start["generateProduct"], &start["refinement"]), (&json!(true), &json!(true)), "{start}"); - } - - #[test] - fn product_brief_update_button_requests_fresh_catalog_and_keeps_draft_on_failure() { - let (mut w, mut app, requests) = brief_fixture(); - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); - brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); - let target = control_rect(&w, "template-update").center(); - brief_frame(&mut w, &mut app, &ctx, 380.0, click_events(target)); - let Request::Action(method, mut input) = requests.try_recv().unwrap() else { panic!("expected template read") }; - assert_eq!(method, "creation-catalog"); - assert_eq!(input["kind"], "templates"); - assert_eq!(input["refresh"], true); - input["error"] = json!("资源不存在或无权访问"); - assert!(w.creation_read_received(&app, "creation-catalog", &input)); - let bounds = brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); - assert!(bounds.contains_rect(control_rect(&w, "template-error"))); - assert_eq!(w.creation_brief, original); - assert!(requests.try_recv().is_err(), "a failed explicit check is not automatically replayed"); - } - - #[test] - fn stitch_brief_canvas_action_saves_the_same_exact_template_and_color_references_before_switching() { - let (mut w, mut app, requests) = brief_fixture(); - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); - brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); - let target = control_rect(&w, "enter-canvas").center(); - brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(target)); - assert!(matches!(requests.try_recv(), Ok(Request::Save(_, _, _))), "entering canvas first preserves the native document"); - assert!(requests.try_recv().is_err(), "no model or skeleton is dispatched before save acknowledgement"); - let pending = w.pending_slot_apply.as_ref().expect("a guarded skeleton switch waits for save"); - assert_eq!(pending["brief"], original); - assert_eq!(pending["template"], original["templateSelection"]); - assert_eq!(pending["outputId"], "detail"); - assert_eq!(w.busy.as_deref(), Some("slot-apply-save")); - } - - #[test] - fn stitch_brief_unknown_canvas_action_never_dispatches_or_discards_the_draft() { - let (mut w, mut app, requests) = brief_fixture(); - w.unknown = true; - let original = w.creation_brief.clone(); - let ctx = egui::Context::default(); - brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); - brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); - let target = control_rect(&w, "enter-canvas").center(); - brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(target)); - assert!(requests.try_recv().is_err()); - assert!(w.pending_slot_apply.is_none()); - assert_eq!(w.creation_brief, original); - assert!(w.unknown); - } - - #[test] - fn stitch_plan_unsaved_changes_keep_confirmation_and_slot_creation_disabled() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation_step = 2; - w.creation_dirty = true; - w.creation["plan"] = json!({"status":"confirmed"}); - w.creation_plan = json!([{"name":"首屏","title":"原产品标题","body":"原产品正文","imagePrompt":"保留真实产品"}]); - let original = w.creation_plan.clone(); - let ctx = egui::Context::default(); - let draw = |w: &mut Workspace, app: &mut PhotocraftApp, events: Vec| { - let mut output = ctx.run_ui( - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(700.0, 1800.0))), events, ..Default::default() }, - |ui| { - stitch_ui::scope(ui, |ui| w.plan_ui(app, ui)); - }, - ); - output.textures_delta.clear(); - }; - draw(&mut w, &mut app, vec![]); - draw(&mut w, &mut app, vec![]); - for control in ["plan-confirm", "plan-slots"] { - let target = control_rect(&w, control).center(); - draw(&mut w, &mut app, click_events(target)); - } - assert_eq!(w.creation_step, 2, "an unsaved plan must not enter the slot workflow"); - assert_eq!(w.creation_plan, original); - assert!(w.creation_dirty); - assert!(requests.try_recv().is_err(), "disabled confirmation never publishes a request"); - } - - #[test] - fn read_only_catalog_requests_do_not_take_or_clear_a_model_execution_lease() { - let (mut w, mut app) = setup(); - let (tx, rx) = mpsc::channel(); - w.tx = tx; - w.unknown = true; - let busy = w.busy.clone(); - let result = w.creation_action(&mut app, "creation-catalog", json!({"kind":"brands","query":""})).unwrap(); - assert_eq!(result["readOnly"], true); - assert_eq!(w.busy, busy); - assert!(w.unknown, "a read cannot resolve or replace the original pending model request"); - let Request::Action(method, input) = rx.try_recv().unwrap() else { panic!("expected independent catalog request") }; - assert_eq!(method, "creation-catalog"); - assert_eq!(input["doc"].as_u64(), app.session.active().map(|s| s.doc.id.0)); - assert_eq!(input["accountId"], "qa"); - assert!(w.creation_action(&mut app, "creation-catalog", json!({"kind":"brands","doc":u64::MAX})).is_err()); - } - #[test] - fn creation_generation_requires_current_identity_revision_and_human_permission() { - let (mut w, mut app) = setup(); - let v = reference(&w); - assert_eq!(allowed(&mut w, &app, &v).unwrap()["allowed"], true); - let mut changed = v.clone(); - changed["accountId"] = json!("other"); - assert_eq!(allowed(&mut w, &app, &changed).unwrap()["allowed"], false); - changed = v.clone(); - changed["run"] = json!("00000000-0000-4000-8000-000000000002"); - assert_eq!(allowed(&mut w, &app, &changed).unwrap()["allowed"], false); - app.session.execute("type.create", json!({"text":"用户已编辑","font":"Noto Sans SC","size":32,"box":[20,20,500,90]})).unwrap(); - assert_eq!(allowed(&mut w, &app, &v).unwrap()["allowed"], false); - w.expected_revision = app.session.active().unwrap().revision; - w.handover(); - assert_eq!(allowed(&mut w, &app, &v).unwrap()["allowed"], false); - } - #[test] - fn generated_canvas_uses_native_undo_and_preserves_late_human_edits() { - let (mut w, mut app) = setup(); - let v = reference(&w); - allowed(&mut w, &app, &v).unwrap(); - let original = app.session.active().unwrap().doc.id; - let before = app.session.active().unwrap().doc.clone(); - let mut generated = photocraft_engine::Session::new(); - generated.execute("file.new", json!({"name":"实际生成结果","width":1440,"height":3600})).unwrap(); - generated.execute("type.create", json!({"text":"真实可编辑标题","font":"Noto Sans SC","size":32,"box":[20,20,500,90]})).unwrap(); - let result = (*generated.active().unwrap().doc).clone(); - canvas_received(&mut w, &mut app, Box::new(result.clone()), v.clone()); - assert_eq!(app.session.active().unwrap().doc.id, original); - assert_eq!(app.session.active().unwrap().doc.size.height, 3600); - assert!(app.session.active().unwrap().doc.walk().iter().any(|(_, _, l)| matches!(&l.content, LayerContent::Text(_)))); - app.session.execute("edit.undo", json!({})).unwrap(); - assert_eq!(app.session.active().unwrap().doc.size, before.size); - assert_eq!(app.session.active().unwrap().doc.walk().len(), before.walk().len()); - let revision = app.session.active().unwrap().revision; - canvas_received(&mut w, &mut app, Box::new(result), v); - assert!(w.creation_pending.is_some()); - assert_eq!(app.session.active().unwrap().revision, revision); - assert_eq!(app.session.active().unwrap().doc.size, before.size); - } - #[test] - fn sync_does_not_clear_dirty_when_backend_detects_a_newer_snapshot() { - let (mut w, app) = setup(); - w.sync_request_meta = w.sync_signature(); - let mut value = reference(&w); - value["revision"] = json!(app.session.active().unwrap().revision); - value["syncDirty"] = json!(true); - sync_received(&mut w, &app, &value); - assert!(w.sync_dirty); - value["syncDirty"] = json!(false); - sync_received(&mut w, &app, &value); - assert!(!w.sync_dirty); - } - - #[test] - fn finished_web_feedback_is_bound_to_the_delivery_project() { - let (mut w, app) = setup(); - let mut receipt = reference(&w); - receipt["materialDelivery"] = json!({"materialId":"delivered-detail", "kind":"detail"}); - receipt["status"] = json!("completed"); - sync_received(&mut w, &app, &receipt); - assert!(w.sync_confirm && w.delivery_completion); - assert!(!w.finished_web_pending, "the completion receipt does not open the workbench on its own"); - - w.finished_web_pending = true; - let mut other_project = receipt.clone(); - other_project["doc"] = json!(receipt["doc"].as_u64().unwrap().wrapping_add(1)); - other_project["error"] = json!("其他项目的错误"); - finished_web_received(&mut w, &app, &other_project); - assert!(w.finished_web_pending && w.finished_web_error.is_none()); - - receipt["error"] = json!("成品上架工作台暂时无法连接,请稍后再试"); - finished_web_received(&mut w, &app, &receipt); - assert!(!w.finished_web_pending); - assert_eq!(w.finished_web_error.as_deref(), receipt["error"].as_str()); - } - - #[test] - fn changed_candidate_or_text_requires_sync_even_when_canvas_revision_is_identical() { - let (mut w, app) = setup(); - let canvas_revision = app.session.active().unwrap().revision; - let baseline = json!({"revision":1,"confirmed":true,"slots":[{"id":"image","selectedCandidateId":"a","fields":[{"id":"title","value":"原文"}]}]}); - w.sync_dirty = false; - w.draft_changed = false; - assert!(w.receive_template_snapshot(&baseline, false)); - assert!(!w.sync_dirty, "loading the existing project establishes a baseline"); - for changed in ["candidate", "text"] { - w.sync_dirty = false; - w.draft_changed = false; - w.sync_request_meta = w.sync_signature(); - let original_signature = w.sync_request_meta.clone(); - let mut next = w.template_workflow.clone(); - next["revision"] = json!(next["revision"].as_u64().unwrap() + 1); - if changed == "candidate" { - next["slots"][0]["selectedCandidateId"] = json!("b"); - } else { - next["slots"][0]["fields"][0]["value"] = json!("人工编辑的标题"); - } - assert!(w.receive_template_snapshot(&next, false), "a read may reconcile a newly completed or edited journal"); - assert!(w.sync_dirty && w.draft_changed, "{changed} changes need a fresh backup"); - assert_ne!(w.sync_signature(), original_signature); - assert_eq!(app.session.active().unwrap().revision, canvas_revision); - let mut receipt = reference(&w); - receipt["revision"] = json!(canvas_revision); - receipt["syncDirty"] = json!(false); - sync_received(&mut w, &app, &receipt); - assert!(w.sync_dirty, "the previous same-canvas sync ACK cannot claim the newer {changed} snapshot"); - } - } - - #[test] - fn first_and_identical_template_reads_do_not_create_an_endless_dirty_cycle() { - let (mut w, _) = setup(); - let snapshot = json!({"revision":7,"confirmed":true,"slots":[{"id":"owned","selectedCandidateId":"a"}]}); - w.sync_dirty = false; - w.draft_changed = false; - assert!(w.receive_template_snapshot(&snapshot, false)); - let loaded_signature = w.sync_signature(); - for _ in 0..3 { - assert!(w.receive_template_snapshot(&snapshot, false)); - assert!(!w.sync_dirty && !w.draft_changed); - assert_eq!(w.sync_signature(), loaded_signature); - } - w.template_workflow = Value::Null; - assert!(w.receive_template_snapshot(&json!({"revision":1,"confirmed":true,"slots":[]}), true)); - assert!(w.sync_dirty && w.draft_changed, "an explicit first template install is a mutation, not a passive baseline read"); - } - #[test] - fn delayed_rules_refresh_updates_canonical_revision_without_overwriting_the_users_draft() { - let (mut w, app) = setup(); - w.creation = json!({"revision":2,"brief":empty_brief(),"sellingPoints":{"selected":["old:0"],"direction":"原方向"},"plan":{"status":"confirmed","screens":[{"id":"one","title":"原方案"}]},"width":1440,"screenCount":3,"designSnapshot":{"rules":{"id":"old-rule"}}}); - w.creation_brief = w.creation["brief"].clone(); - w.creation_brief["name"] = json!("刚输入的产品名称"); - w.creation_brief["dimensions"]["length"] = json!("1800"); - w.creation_selected = vec!["new:1".into()]; - w.creation_direction = "刚输入的表达方向".into(); - w.creation_plan = json!([{"id":"one","title":"尚未保存的标题"}]); - w.creation_width = 750; - w.creation_dirty = true; - let draft = w.creation_draft(); - let mut value = reference(&w); - value["creation"] = w.creation.clone(); - value["creation"]["revision"] = json!(3); - value["creation"]["designSnapshot"]["rules"] = json!({"id":"fixed-rule","contentHash":"a".repeat(64)}); - value["creation"]["plan"]["status"] = json!("stale"); - received(&mut w, &app, "creation-rules", &value); - assert_eq!(w.creation_draft()["brief"], draft["brief"]); - for field in ["screens", "direction", "selected", "width", "screenCount"] { - assert_eq!(w.creation_draft()[field], draft[field]); - } - assert!(w.creation_dirty); - assert_eq!(w.creation["revision"], 3); - assert_eq!(w.creation["designSnapshot"]["rules"]["id"], "fixed-rule"); - assert_eq!(w.creation["plan"]["status"], "stale"); - // With no local edits, the normal canonical plan state remains visible. - w.creation_dirty = false; - received(&mut w, &app, "creation-rules", &value); - assert_eq!(w.creation_plan, value["creation"]["plan"]["screens"]); - assert!(!w.creation_dirty); - } - - fn normalized_product_fixture() -> (Workspace, PhotocraftApp, mpsc::Receiver) { - let (mut w, app, requests) = brief_fixture(); - w.creation_brief["source"] = json!("product_platform"); - w.creation_brief["identifierType"] = json!("spu"); - w.creation_brief["identifier"] = json!("SPU-8802"); - w.creation_brief["name"] = json!("北欧实木升降双人餐桌"); - w.creation_brief["dimensions"] = json!({"length":"1600","width":"850","height":"750","unit":"mm"}); - w.creation_brief["detailBarcode"] = json!("BC-ASH-160"); - w.creation_brief["barcodeBindings"] = json!({"default":["BC-ASH-160","BC-ASH-180","BC-WAL-160","BC-WAL-180","BC-GRY-160"]}); - w.creation_brief["normalizedProduct"] = json!({ - "identity": { - "spu": "SPU-8802", - "productName": "北欧实木升降双人餐桌", - "platformBrand": "原木生活家", - "platformCategory": "餐厅家具/实木餐桌", - "seriesOrModel": "云栖 2026" - }, - "specs": { - "dimensions": { "length": 1600, "width": 850, "height": 750, "unit": "mm", "display": "1600 × 850 × 750 mm" }, - "packageDimensions": null, - "materials": ["北美白蜡木", "食品级木蜡油"], - "colors": ["原木白蜡", "暖胡桃", "星夜灰"], - "attributes": [ - {"key":"load","label":"静态承重","value":"120 kg","group":"specs"}, - {"key":"craft","label":"榫卯工艺","value":"全实木直拼","group":"specs"}, - {"key":"origin","label":"产地","value":"江苏南通","group":"specs"}, - {"key":"assembly","label":"安装方式","value":"预约上门安装","group":"service"} - ] - }, - "copy": { - "summary": "整块北美白蜡木直拼桌面,圆角防磕碰,适配中小户型餐厅与书房场景。", - "sellingPoints": [ - "北美 FAS 级白蜡木,自然大纹理不易开裂", - "圆润 R12 倒角设计,呵护儿童与老人", - "隐藏式加强横梁,稳固承重不晃动", - "环保净味木蜡油涂装,即买即用" - ] - }, - "variants": [ - { - "id": "v-ash", - "colorName": "原木白蜡", - "barcodes": [ - {"barcode":"BC-ASH-160","skuCode":"SKU-A16","skuName":"1.6米标准版","spec":"1.6m×0.85m","dimensions":{"length":1600,"width":850,"height":750,"unit":"mm","display":"1600×850×750 mm"},"sellingPoints":["4-6人日常用餐"],"attributes":[],"imageIds":["a1","a2"]}, - {"barcode":"BC-ASH-180","skuCode":"SKU-A18","skuName":"1.8米加长版","spec":"1.8m×0.90m","dimensions":{"length":1800,"width":900,"height":750,"unit":"mm","display":"1800×900×750 mm"},"sellingPoints":["6-8人聚餐"],"attributes":[],"imageIds":["a3"]} - ] - }, - { - "id": "v-walnut", - "colorName": "暖胡桃", - "barcodes": [ - {"barcode":"BC-WAL-160","skuCode":"SKU-W16","skuName":"1.6米标准版","spec":"1.6m×0.85m","dimensions":{"length":1600,"width":850,"height":750,"unit":"mm","display":"1600×850×750 mm"},"sellingPoints":[],"attributes":[],"imageIds":["a4"]}, - {"barcode":"BC-WAL-180","skuCode":"SKU-W18","skuName":"1.8米加长版","spec":"1.8m×0.90m","dimensions":{"length":1800,"width":900,"height":750,"unit":"mm","display":"1800×900×750 mm"},"sellingPoints":[],"attributes":[],"imageIds":[]} - ] - }, - { - "id": "v-grey", - "colorName": "星夜灰", - "barcodes": [ - {"barcode":"BC-GRY-160","skuCode":"SKU-G16","skuName":"1.6米标准版","spec":"1.6m×0.85m","dimensions":{"length":1600,"width":850,"height":750,"unit":"mm","display":"1600×850×750 mm"},"sellingPoints":[],"attributes":[],"imageIds":[]} - ] - } - ], - "assets": [ - {"id":"a1","url":"https://cdn.example/a1.jpg","kind":"whiteBackground","label":"白蜡木正面全貌白底图","barcode":"BC-ASH-160","colorName":"原木白蜡","localSource":null,"selectedForProject":true}, - {"id":"a2","url":"https://cdn.example/a2.jpg","kind":"main","label":"餐厅自然光场景主图","barcode":"BC-ASH-160","colorName":"原木白蜡","localSource":null,"selectedForProject":true}, - {"id":"a3","url":"https://cdn.example/a3.jpg","kind":"sku","label":"1.8m 款式规格图","barcode":"BC-ASH-180","colorName":"原木白蜡","localSource":null,"selectedForProject":true}, - {"id":"a4","url":"https://cdn.example/a4.jpg","kind":"reference","label":"木纹与倒角细节特写","barcode":"BC-WAL-160","colorName":"暖胡桃","localSource":null,"selectedForProject":false} - ], - "trace": { - "source": "产品平台", - "fetchedAt": "2026-12-02 10:15", - "upstreamSpu": "SPU-8802", - "rawFieldWarnings": ["包装尺寸缺失,已忽略空值", "条码 BC-GRY-160 暂无官方白底图"] - } - }); - w.creation_width = 1440; - w.creation["screenCount"] = json!(8); - w.creation["brief"] = w.creation_brief.clone(); - w.model_ready = true; - w.image_ready = true; - (w, app, requests) - } - - #[test] - fn normalized_product_renders_grouped_color_matrix_and_toggles_assets_preserving_kind() { - let (mut w, mut app, requests) = normalized_product_fixture(); - assert_eq!(sku_display_label(&w.creation_brief, "BC-ASH-160"), "原木白蜡 · 1.6m×0.85m (BC-ASH-160)"); - assert_eq!(sku_short_label(&w.creation_brief, "BC-ASH-160"), "原木白蜡 · 1.6m×0.85m"); - let groups = normalized_color_groups(&w.creation_brief); - assert_eq!(groups.len(), 3); - assert_eq!(groups[0].color_name, "原木白蜡"); - assert_eq!(groups[0].skus.len(), 2); - - let ctx = egui::Context::default(); - w.reduce_motion = true; - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 900.0, vec![]); } - assert!(control_rect(&w, "color-group-v-ash").is_positive()); - assert!(control_rect(&w, "color-group-v-walnut").is_positive()); - // Detail SKU color group is default-expanded; other color groups stay collapsed when total > 4. - assert!(control_rect(&w, "sku-main-BC-ASH-160").is_positive()); - assert!(w.creation_view_geometry["controls"]["sku-main-BC-WAL-160"].is_null()); - - // Toggle platform asset selectedForProject while preserving kind. - let toggle = control_rect(&w, "platform-asset-toggle-3").center(); - brief_frame(&mut w, &mut app, &ctx, 900.0, click_events(toggle)); - assert_eq!(w.creation_brief["normalizedProduct"]["assets"][3]["selectedForProject"], true); - assert_eq!(w.creation_brief["normalizedProduct"]["assets"][3]["kind"], "reference"); - assert!(w.creation_dirty); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn platform_refetch_preserves_manually_edited_fields() { - let (mut w, app, _) = normalized_product_fixture(); - w.creation_brief["name"] = json!("手工改过的精准品名"); - w.creation_brief["note"] = json!("必须突出圆角倒角"); - w.creation_brief["dimensions"] = json!({"length":"1650","width":"860","height":"760","unit":"mm"}); - w.creation_reads.manual_edited_fields.insert("name".into()); - w.creation_reads.manual_edited_fields.insert("note".into()); - w.creation_reads.manual_edited_fields.insert("dimensions".into()); - - let mut incoming = w.creation_brief.clone(); - incoming["name"] = json!("上游覆盖品名"); - incoming["note"] = json!(""); - incoming["dimensions"] = json!({"length":"1600","width":"850","height":"750","unit":"mm"}); - let doc = app.session.active().unwrap().doc.id.0; - let receipt = json!({"doc":doc,"origin":w.origin,"accountId":w.account["id"],"platformBrief":incoming,"message":""}); - received(&mut w, &app, "creation-product-platform", &receipt); - assert_eq!(w.creation_brief["name"], "手工改过的精准品名"); - assert_eq!(w.creation_brief["note"], "必须突出圆角倒角"); - assert_eq!(w.creation_brief["dimensions"]["length"], "1650"); - assert!(w.creation_reads.platform_sync_note.contains("保留了你手动修改的 3 项字段")); - } - - #[test] - fn saved_platform_refetch_fills_barcode_fields_and_preserves_intentional_clears() { - let (mut w, app, _) = normalized_product_fixture(); - let mut incoming = w.creation_brief.clone(); - incoming["normalizedProduct"] = Value::Null; - incoming["barcodeBindings"] = json!({"default":["001","002"]}); - incoming["name"] = json!("上游品名"); - incoming["platformFacts"] = json!({"spu":"SPU-8802","shared":{},"barcodes":{ - "001":{"material":"实木","dimensions":{"unit":"mm","length":1600,"width":650,"height":750}}, - "002":{"material":"板材","dimensions":{"unit":"mm","depth":400,"secondaryHeight":120}} - }}); - w.creation_brief["name"] = json!(""); - w.creation_brief["barcodeBindings"] = json!({"default":["001"]}); - w.creation_brief["barcodeEntries"] = json!([{ - "id":"kept","barcode":"001","material":"","dimensions":{"unit":"cm","length":"161","height":""},"images":[] - }]); - w.creation_brief["manualFields"] = json!(["name","barcode-card:kept:material","barcode-card:kept:dimensions.height"]); - let doc = app.session.active().unwrap().doc.id.0; - let receipt = json!({"doc":doc,"origin":w.origin,"accountId":w.account["id"],"platformBrief":incoming}); - received(&mut w, &app, "creation-product-platform", &receipt); - assert_eq!(w.creation_brief["name"], ""); - let rows = w.creation_brief["barcodeEntries"].as_array().unwrap(); - assert_eq!(rows.len(), 2); - assert_eq!(rows[0]["id"], "kept"); - assert_eq!(rows[0]["material"], ""); - assert_eq!(rows[0]["dimensions"], json!({"unit":"cm","length":"161","width":"65","height":""})); - assert_eq!(rows[1]["barcode"], "002"); - assert_eq!(rows[1]["dimensions"]["width"], "400"); - assert_eq!(rows[1]["dimensions"]["secondaryHeight"], "120"); - } - - #[test] - fn readiness_checklist_highlights_required_intake_fields_and_opens_model_picker() { - let (mut w, mut app, _) = barcode_fixture(); - w.creation_brief["name"] = json!(""); - w.creation_brief["intake"]["schema"]["productFields"] = json!([ - {"id":"origin","label":"产地","type":"text","required":true} - ]); - w.model_ready = false; - w.image_ready = false; - let ctx = egui::Context::default(); - w.reduce_motion = true; - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 900.0, vec![]); } - - let req_chip = control_rect(&w, "readiness-intake-product:origin").center(); - brief_frame(&mut w, &mut app, &ctx, 900.0, click_events(req_chip)); - assert!(w.creation_reads.inline_errors.contains_key("intake-product:origin")); - - let model_btn = control_rect(&w, "select-model").center(); - brief_frame(&mut w, &mut app, &ctx, 900.0, click_events(model_btn)); - assert!(w.model_settings); - } - - fn brief_settings_harness(size: egui::Vec2) -> (egui_kittest::Harness<'static, PhotocraftApp>, mpsc::Receiver) { - let (tx, requests) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut w = Workspace::new(tx, rx); - w.account = json!({"id":"qa"}); - w.origin = "http://localhost:3138".into(); - w.busy = None; - w.reduce_motion = true; - w.creation_catalog.insert("brands".into(), vec![]); - w.creation_catalog.insert("materials".into(), vec![]); - w.configure_client_update(json!({"version":"1.0.0"}), true, |_| Ok(())); - w.begin_staged_new_project(&app); - w.key_saved = true; - app.jiansun = Some(w); - let mut h = egui_kittest::Harness::builder() - .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .with_size(size) - .build_ui_state(|ui, app| { - if stitch_ui::ui_fonts_ready(ui) { - crate::panels::right_dock(app, ui); - } - }, app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); - h.run_steps(5); - (h, requests) - } - - #[test] - fn brief_footer_settings_stays_open_after_models_become_ready() { - use egui_kittest::kittest::{NodeT, Queryable}; - - let (mut h, requests) = brief_settings_harness(vec2(1440.0, 900.0)); - let footer = control_rect(h.state().jiansun.as_ref().unwrap(), "select-model"); - h.query_all_by_label("选择模型") - .find(|button| footer.contains(button.rect().center())).unwrap().click(); - h.run_steps(4); - let title = h.get_by_label("小壹设置").accesskit_node().locate(); - assert!(h.query_by_label("对话模型").is_some()); - assert!(h.query_by_label("生图模型").is_some()); - let checks = requests.try_iter().filter(|request| { - matches!(request, Request::Action(method, input) if method == "client-update" && input["op"] == "check") - }).count(); - assert_eq!(checks, 1); - - let w = h.state_mut().jiansun.as_mut().unwrap(); - w.model_ready = true; - w.image_ready = true; - for _ in 0..4 { - h.step(); - assert_eq!(h.get_by_label("小壹设置").accesskit_node().locate(), title); - } - assert!(h.state().jiansun.as_ref().unwrap().creation_view_geometry["controls"]["select-model"].is_null()); - - h.get_by_label("关闭模型设置").click_accesskit(); - h.run_steps(3); - assert!(h.query_by_label("小壹设置").is_none()); - let w = h.state().jiansun.as_ref().unwrap(); - assert!(!w.model_settings); - assert_eq!(w.agent_page(h.state()), "brief"); - } - - #[test] - fn brief_copilot_opens_one_settings_popup() { - use egui_kittest::kittest::Queryable; - - let (mut h, _requests) = brief_settings_harness(vec2(1440.0, 900.0)); - let footer = control_rect(h.state().jiansun.as_ref().unwrap(), "select-model"); - assert!(h.query_by_label("建项协作者").is_some()); - assert_eq!(h.query_all_by_label("选择模型").count(), 2); - h.query_all_by_label("选择模型") - .find(|button| !footer.contains(button.rect().center())).unwrap().click(); - h.run_steps(4); - assert_eq!(h.query_all_by_label("小壹设置").count(), 1); - assert!(h.query_by_label("对话模型").is_some()); - assert!(h.query_by_label("生图模型").is_some()); - assert!(!h.state().jiansun.as_ref().unwrap().key_settings); - } - - #[test] - fn brief_key_warning_opens_the_personal_key_editor_from_both_surfaces() { - use egui_kittest::kittest::Queryable; - - for from_footer in [true, false] { - let (mut h, requests) = brief_settings_harness(vec2(1440.0, 900.0)); - let w = h.state_mut().jiansun.as_mut().unwrap(); - w.key_saved = false; - w.model_ready = true; - w.image_ready = true; - h.run_steps(4); - assert!(h.query_by_label("选择模型").is_none()); - assert_eq!(h.query_all_by_label("配置个人 Key").count(), 2); - let footer = control_rect(h.state().jiansun.as_ref().unwrap(), "configure-personal-key"); - h.query_all_by_label("配置个人 Key") - .find(|button| footer.contains(button.rect().center()) == from_footer).unwrap().click(); - h.run_steps(4); - let w = h.state().jiansun.as_ref().unwrap(); - assert!(w.model_settings && w.key_settings); - assert!(h.query_by_label("小壹设置").is_some()); - assert!(h.query_by_label("模型 API Key").is_some()); - assert!(requests.try_iter().any(|request| { - matches!(request, Request::Action(method, input) if method == "client-update" && input["op"] == "check") - })); - } - } - - #[test] - fn brief_footer_opens_settings_with_the_agent_dock_collapsed_or_switched() { - use egui_kittest::kittest::Queryable; - - for collapsed in [true, false] { - let size = vec2(760.0, 650.0); - let (mut h, _requests) = brief_settings_harness(size); - let app = h.state_mut(); - if collapsed { - app.ui.dock.set_collapsed(crate::dock::Group::Color, true); - } else { - app.ui.dock_tabs.color = 0; - } - h.run_steps(4); - assert!(h.query_by_label("建项协作者").is_none()); - h.get_by_label("选择模型").click(); - h.run_steps(4); - let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, size); - assert!(viewport.contains_rect(h.get_by_label("小壹设置").rect())); - assert!(viewport.contains_rect(h.get_by_label("关闭模型设置").rect())); - assert!(h.query_by_label("对话模型").is_some()); - assert!(h.query_by_label("生图模型").is_some()); - - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert!(h.query_by_label("小壹设置").is_none()); - assert_eq!(h.state().jiansun.as_ref().unwrap().agent_page(h.state()), "brief"); - } - } - - #[test] - fn reopening_saved_incomplete_projects_resumes_the_missing_step_with_the_saved_draft() { - let template = json!({"id":"template","version":"1","contentHash":"a".repeat(64),"brandId":"brand","categoryId":"category"}); - let images = json!([{"source":format!("local:{}", "a".repeat(64)),"purpose":"product","name":"餐桌正面"}]); - for (stage, canvas_first) in [(Some(CreationStage::Source), false), (Some(CreationStage::Template), false), - (Some(CreationStage::Details), false), (None, true)] - { - let ctx = egui::Context::default(); - let (tx, _requests) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - w.account = json!({"id":"owner"}); - w.origin = "http://localhost:3138".into(); - w.busy = Some("open".into()); - w.library = true; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut opened = photocraft_engine::Session::new(); - opened.execute("file.new", json!({"name":"餐桌草稿","width":64,"height":64})).unwrap(); - let doc = opened.active().unwrap().doc.as_ref().clone(); - let id = doc.id.0; - let mut brief = empty_brief(); - brief["note"] = json!("保留用户填写的备注"); - if matches!(stage, Some(CreationStage::Template | CreationStage::Details)) { - brief["images"] = images.clone(); - } - if stage == Some(CreationStage::Details) { - brief["brandId"] = json!("brand"); - brief["categoryId"] = json!("category"); - brief["templateSelection"] = template.clone(); - } - let workflow = json!({"canvasFirst":canvas_first}); - assert_eq!(incomplete_brief_stage(&brief, &workflow, |_| true), stage); - let (revision, draft_revision) = if stage == Some(CreationStage::Template) { - (0, Value::Null) - } else { - (4, json!(4)) - }; - let card = json!({"source":"native","id":"saved-project","briefIncomplete":stage.is_some(),"briefResumeStage":stage}); - let mut meta = card.clone(); - meta["localId"] = json!("saved-project"); - meta["path"] = json!("saved-project.pcraft"); - meta["accountId"] = w.account["id"].clone(); - meta["origin"] = json!(w.origin); - let _ = ctx.settle_ui(egui::RawInput::default(), |ui| { - w.receive_opened(&mut app, ui.ctx(), Box::new(doc.clone()), meta.clone()); - assert_eq!(w.creation_open, stage.is_some()); - w.receive_json_draft(&mut app, ui.ctx(), json!({"doc":id,"localId":"saved-project", - "creationDraft":{"revision":draft_revision,"brief":brief}})); - w.receive_creation_ui(&app, "creation-read", &json!({"doc":id,"accountId":"owner","origin":w.origin, - "creation":{"revision":revision,"brief":empty_brief()},"templateWorkflow":workflow})); - }); - assert_eq!(w.creation_brief, brief); - if let Some(stage) = stage { - assert_eq!(w.creation_step, 0); - assert_eq!(w.creation_reads.wizard_stage, Some((w.creation_field_scope(&app), stage))); - assert_eq!(w.agent_page(&app), "brief"); - w.handle_wizard_navigation(&app, WizardFooterOutcome::Cancel); - assert_eq!(w.agent_page(&app), "projects"); - w.request_project_open(&mut app, card).unwrap(); - assert_eq!(w.creation_reads.wizard_stage, Some((w.creation_field_scope(&app), stage))); - assert_eq!(w.agent_page(&app), "brief"); - } else { - assert_eq!(w.agent_page(&app), "canvas"); - } - } - } - - #[test] - fn staged_import_uses_a_new_document_and_preserves_the_active_draft() { - let (mut w, mut app, requests) = brief_fixture(); - let old_doc = app.session.active().unwrap().doc.id.0; - let old_draft = w.creation_draft(); - w.begin_staged_new_project(&app); - w.creation_brief["note"] = json!("新项目简报"); - assert_eq!(w.creation_draft(), old_draft); - assert_eq!(app.session.documents().len(), 1); - w.creation_action(&mut app, "creation-import", json!({"paths":["D:/references/new.png"]})).unwrap(); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected reference import") }; - assert_eq!(method, "creation-import"); - assert_ne!(input["doc"], old_doc); - assert_eq!(input["brief"]["note"], "新项目简报"); - assert_eq!(app.session.documents().len(), 2); - assert_eq!(app.session.documents()[0].doc.id.0, old_doc); - } - - #[test] - fn structured_barcode_save_sends_entries_and_legacy_template_values() { - let (mut w, mut app, requests) = brief_fixture(); - let schema = json!([{"id":"length","type":"number","unit":"mm"},{"id":"material","type":"text"}]); - w.creation_brief["intake"] = json!({"schema":{"version":1,"barcodeFields":schema},"productValues":{"origin":"佛山"},"barcodeValues":{}}); - let mut rows = vec![wizard::barcode_row("0007", &json!("oak"), &json!("原木色"), &Value::Null)]; - rows[0]["dimensions"] = json!({"length":"180","width":"85","height":"75","unit":"cm"}); - rows[0]["material"] = json!("白蜡木"); - write_legacy_barcode_fields(&mut w.creation_brief, &mut rows, &schema); - w.creation_brief["barcodeEntries"] = json!(rows); - w.creation_action(&mut app, "creation-save", json!({})).unwrap(); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected brief save") }; - let brief = &input["brief"]; - assert_eq!(method, "creation-save"); - assert_eq!(brief["barcodeEntries"][0]["barcode"], "0007"); - assert_eq!(brief["barcodeBindings"]["oak"], json!(["0007"])); - assert_eq!(brief["detailBarcode"], "0007"); - assert_eq!(brief["dimensions"], brief["barcodeEntries"][0]["dimensions"]); - assert_eq!(brief["intake"]["barcodeValues"]["0007"]["length"].as_f64(), Some(1800.0)); - assert_eq!(brief["intake"]["barcodeValues"]["0007"]["material"], "白蜡木"); - assert_eq!(brief["intake"]["productValues"]["origin"], "佛山"); - } - - #[test] - fn staged_new_project_defers_document_creation_until_entering_canvas() { - let (tx, requests) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - w.busy = None; - w.account = json!({"id":"qa"}); - w.origin = "http://localhost:3138".into(); - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - - w.begin_staged_new_project(&app); - assert!(app.session.documents().is_empty(), "starting a new project must not eagerly spawn an empty canvas tab"); - assert!(w.creation_reads.staged_new_project); - assert_eq!(w.agent_page(&app), "brief"); - - w.creation_brief["name"] = json!("延迟建档餐桌"); - w.creation_brief["brandId"] = json!("brand"); - w.creation_brief["brandName"] = json!("品牌A"); - w.creation_brief["categoryId"] = json!("cat"); - w.creation_brief["categoryName"] = json!("餐桌"); - w.creation_brief["images"] = json!([{"source":"local:img","name":"白底.png","purpose":"product"}]); - w.creation_brief["templateSelection"] = json!({ - "id":"tpl","name":"标准模板","version":"1.0","contentHash":"a".repeat(64),"brandId":"brand","categoryId":"cat" - }); - use egui_kittest::kittest::Queryable; - w.reduce_motion = true; - let mut harness = egui_kittest::Harness::builder() - .with_size(vec2(900.0, 900.0)) - .with_context_setup(|ctx| { - PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(ctx); - }) - .build_ui_state(|ui, state: &mut (Workspace, PhotocraftApp)| { - egui::CentralPanel::default().frame(egui::Frame::NONE) - .show(ui, |ui| state.0.creation_ui(&mut state.1, ui)); - }, (w, app)); - harness.run_steps(3); - assert!(harness.state().1.session.documents().is_empty(), "editing staged brief keeps session clean"); - for (button, stage) in [("下一步:选择模板", CreationStage::Template), ("下一步:填写产品资料", CreationStage::Details)] { - harness.get_by_label(button).click(); - harness.run_steps(3); - assert_eq!(harness.state().0.creation_reads.wizard_stage.unwrap().1, stage); - } - harness.get_by_label("进入模板画布").click(); - harness.run(); - let (w, app) = harness.state(); - assert_eq!(app.session.documents().len(), 1, "entering canvas materializes the document"); - assert!(!w.creation_reads.staged_new_project); - assert!(requests.try_iter().any(|r| matches!(r, Request::Save(_, _, _)))); - } - - #[test] - fn merge_platform_brief_skips_intake_when_incoming_lacks_or_changes_template() { - let mut edited = HashSet::new(); - edited.insert("intake-product:origin".to_owned()); - edited.insert("intake-barcode:SKU001:size".to_owned()); - - let current = json!({ - "name": "老款实木餐桌", - "intake": { - "templateId": "tpl-a", - "schema": {"version": 1}, - "productValues": {"origin": "广东佛山"}, - "barcodeValues": {"SKU001": {"size": "1.6米"}} - } - }); - - let incoming_no_intake = json!({"name": "新平台餐桌"}); - let (merged_null, preserved_null) = - merge_platform_brief_preserving_manual_edits(¤t, &incoming_no_intake, &edited); - assert_eq!(preserved_null, 0); - assert!(merged_null.get("intake").is_none()); - - let incoming_other_template = json!({ - "name": "新平台餐桌", - "intake": { - "templateId": "tpl-b", - "schema": {"version": 1}, - "productValues": {"origin": "默认产地"}, - "barcodeValues": {"SKU001": {"size": "1.8米"}} - } - }); - let (merged_other, preserved_other) = - merge_platform_brief_preserving_manual_edits(¤t, &incoming_other_template, &edited); - assert_eq!(preserved_other, 0); - assert_eq!(merged_other["intake"]["productValues"]["origin"], "默认产地"); - assert_eq!(merged_other["intake"]["barcodeValues"]["SKU001"]["size"], "1.8米"); - - let incoming_same_template = json!({ - "name": "新平台餐桌", - "intake": { - "templateId": "tpl-a", - "schema": {"version": 1}, - "productValues": {"origin": "平台产地"}, - "barcodeValues": {"SKU001": {"size": "平台尺寸"}} - } - }); - let (merged_same, preserved_same) = - merge_platform_brief_preserving_manual_edits(¤t, &incoming_same_template, &edited); - assert_eq!(preserved_same, 2); - assert_eq!(merged_same["intake"]["productValues"]["origin"], "广东佛山"); - assert_eq!(merged_same["intake"]["barcodeValues"]["SKU001"]["size"], "1.6米"); - } - - #[test] - fn test_product_presets_and_consecutive_saves_sync_revision_without_conflict() { - let (mut w, mut app, requests) = brief_fixture(); - w.creation["revision"] = json!(1); - w.creation_plan = w.creation["plan"]["screens"].clone(); - w.creation_failed_signature = "old-failed-signature".into(); - let mut preset_brief = empty_brief(); - preset_brief["name"] = json!("超管预置商品"); - preset_brief["brandId"] = json!("brand-a"); - preset_brief["brandName"] = json!("品牌A"); - preset_brief["categoryId"] = json!("cat-a"); - preset_brief["categoryName"] = json!("品类A"); - - w.apply_test_preset(&app, preset_brief.clone()); - assert!(w.creation_failed_signature.is_empty()); - assert!(w.creation_dirty); - - w.creation_action(&mut app, "creation-save", json!({})).unwrap(); - let Ok(Request::Action(method, first_input)) = requests.try_recv() else { panic!("expected first creation-save"); }; - assert_eq!(method, "creation-save"); - assert_eq!(first_input["brief"]["name"], "超管预置商品"); - - let first_doc = first_input["doc"].clone(); - let first_reply = json!({ - "doc": first_doc, - "accountId": w.account["id"], - "origin": w.origin, - "creation": { - "revision": 2, - "deliveryDir": w.creation_delivery_dir, - "brief": first_input["brief"], - "width": first_input["width"], - "screenCount": 3, - "sellingPoints": {"selected": w.creation_selected, "direction": w.creation_direction, "batches": [], "stale": false}, - "plan": {"status": "idle", "screens": w.creation_plan} - } - }); - received(&mut w, &app, "creation-save", &first_reply); - w.busy = None; - assert_eq!(w.creation["revision"], 2); - assert!(!w.creation_dirty); - - w.creation_brief["templateSelection"] = json!({ - "id": "tpl-2", - "name": "老模板", - "version": "1", - "contentHash": "a".repeat(64), - "brandId": "brand-a", - "categoryId": "cat-a" - }); - w.creation_dirty = true; - w.creation_action(&mut app, "creation-save", json!({})).unwrap(); - let mut second_input = None; - while let Ok(req) = requests.try_recv() { - if let Request::Action(m, inp) = req && m == "creation-save" { - second_input = Some(inp); - } - } - let second_input = second_input.expect("expected second creation-save"); - assert_eq!(second_input["revision"], 2); - let second_reply = json!({ - "doc": first_doc, - "accountId": w.account["id"], - "origin": w.origin, - "creation": { - "revision": 3, - "deliveryDir": w.creation_delivery_dir, - "brief": second_input["brief"], - "width": second_input["width"], - "screenCount": 3, - "sellingPoints": {"selected": w.creation_selected, "direction": w.creation_direction, "batches": [], "stale": false}, - "plan": {"status": "idle", "screens": w.creation_plan} - } - }); - received(&mut w, &app, "creation-save", &second_reply); - assert_eq!(w.creation["revision"], 3); - assert_eq!(w.creation_brief["templateSelection"]["id"], "tpl-2"); - } - - #[test] - fn template_compatibility_warnings_render_as_non_blocking_warning_and_allow_next_step() { - use egui_kittest::kittest::Queryable as _; - let (mut w, app, _requests) = brief_fixture(); - w.creation_read_scope(&app); - w.reduce_motion = true; - w.creation_open = true; - w.creation_step = 0; - w.library = false; - w.material = false; - w.creation_brief["brandId"] = json!("ekb:brand:test"); - w.creation_brief["brandName"] = json!("测试品牌"); - w.creation_brief["categoryId"] = json!("ekb:category:test"); - w.creation_brief["categoryName"] = json!("测试品类"); - w.creation_brief["templateSelection"] = Value::Null; - let version = format!("map-{}", "a".repeat(64)); - let set_row = json!({ - "id": "b".repeat(32), - "name": "老版本兼容模板", - "key": "TPL-LEGACY", - "brandId": "ekb:brand:test", - "categoryId": "ekb:category:test" - }); - w.creation_reads.resource_set = set_row.clone(); - w.creation_reads.resource_component = "detail".into(); - w.creation_catalog.insert("templates".into(), vec![set_row]); - w.creation_catalog.insert("resource-set".into(), vec![json!({ - "id": "detail", - "name": "详情页", - "kind": "detail", - "previews": [] - })]); - w.creation_catalog.insert("resource-component".into(), vec![json!({ - "id": "detail", - "choice": { - "id": "tpl-compat", - "name": "老版本兼容模板", - "version": version, - "contentHash": "a".repeat(64), - "brandId": "ekb:brand:test", - "categoryId": "ekb:category:test", - "width": 1440, - "enterprise": { - "adapterVersion": 4, - "sourceKind": "resource-map", - "snapshotVersion": version, - "resourceSetId": "b".repeat(32), - "componentId": "detail" - }, - "compatibilityWarnings": ["模板缺少映射版本信息,已按兼容模式加载"] - } - })]); - w.creation_reads.wizard_stage = Some((w.creation_field_scope(&app), CreationStage::Template)); - - let mut harness = egui_kittest::Harness::builder() - .with_size(vec2(1024.0, 820.0)) - .with_context_setup(|ctx| { - PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(ctx); - }) - .build_ui_state( - |ui, (w, app): &mut (Workspace, PhotocraftApp)| { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| w.creation_ui(app, ui)); - }, - (w, app), - ); - harness.run_steps(4); - assert_eq!( - harness.state().0.creation_brief["templateSelection"]["compatibilityWarnings"], - json!(["模板缺少映射版本信息,已按兼容模式加载"]) - ); - assert!(harness.query_by_label("模板缺少映射版本信息,已按兼容模式加载").is_some()); - let next_btn = harness.get_by_label("下一步:填写产品资料"); - next_btn.click(); - harness.run_steps(2); - let (w, _) = harness.state(); - assert_eq!(w.creation_reads.wizard_stage.unwrap().1, CreationStage::Details); - assert_eq!( - w.creation_brief["templateSelection"]["compatibilityWarnings"], - json!(["模板缺少映射版本信息,已按兼容模式加载"]) - ); - } - - #[test] - #[ignore = "Vulkan wizard visual inspection; requires PHOTOCRAFT_AGENT_QA_OUT"] - fn creation_wizard_visual_acceptance() { - let _gpu = photocraft_testkit::gpu_lock(); - let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory")); - std::fs::create_dir_all(&directory).unwrap(); - for (width, height) in [(1440.0, 900.0), (960.0, 720.0)] { - for (name, stage) in [("source", CreationStage::Source), ("template", CreationStage::Template), ("details", CreationStage::Details)] { - let (mut w, app, requests) = brief_fixture(); - w.reduce_motion = true; - w.creation_open = true; - w.creation_step = 0; - w.library = false; - w.material = false; - w.key_saved = false; - w.creation_brief["dimensions"] = json!({"length":"1800","width":"850","height":"750","unit":"mm"}); - if stage == CreationStage::Source { - w.creation_brief = empty_brief(); - } else if stage == CreationStage::Details { - w.creation_brief["barcodeBindings"]["oak"] = json!(["DNZ030516N717V01"]); - w.creation_brief["identifier"] = json!("DNZ030516"); - } - w.creation_reads.wizard_stage = Some((w.creation_field_scope(&app), stage)); - let mut setup = eframe::egui_wgpu::WgpuSetupCreateNew::without_display_handle(); - setup.instance_descriptor.backends = eframe::wgpu::Backends::VULKAN; - let mut h = egui_kittest::Harness::builder() - .with_size(vec2(width, height)) - .with_context_setup(|ctx| { - PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(ctx); - }) - .wgpu_setup(eframe::egui_wgpu::WgpuSetup::CreateNew(setup)) - .build_ui_state( - |ui, state: &mut Box<(Workspace, PhotocraftApp)>| { - let (w, app) = &mut **state; - egui::Panel::right("qa-brief-copilot").resizable(false).exact_size(330.0) - .frame(egui::Frame::NONE.fill(Tokens::get(ui.ctx()).agent().dock)) - .show(ui, |ui| stitch_ui::scope(ui, |ui| w.brief_copilot_header_ui(app, ui))); - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| w.creation_ui(app, ui)); - }, - Box::new((w, app)), - ); - h.run_steps(4); - let image = h.render().unwrap(); - assert_eq!(image.dimensions(), (width as u32, height as u32)); - image.save(directory.join(format!("wizard-{name}-{width}x{height}.png"))).unwrap(); - drop(requests); - } - } - } - - #[test] - fn review_hints_parse_both_strings_and_structured_targets_and_jump_switches_output() { - let mut hints = Vec::new(); - parse_review_hints( - &json!([ - "详情页:固定图层「旧卖点」保留了模板旧文字,请人工核对。", - { "message": "主图 S01 字体已回退", "outputId": "main_images", "slotId": "S01", "layerId": "L9" }, - "详情页:固定图层「旧卖点」保留了模板旧文字,请人工核对。" - ]), - &mut hints, - ); - assert_eq!(hints.len(), 2); - assert_eq!(hints[0].output_id.as_deref(), Some("detail")); - assert_eq!(hints[1].output_id.as_deref(), Some("main_images")); - assert_eq!(hints[1].slot_id.as_deref(), Some("S01")); - assert_eq!(hints[1].layer_id.as_deref(), Some("L9")); - - let (mut w, app, requests) = brief_fixture(); - let doc_id = app.session.active().unwrap().doc.id.0; - w.library = false; - w.loaded_draft = Some(doc_id); - w.open_projects.insert(doc_id, w.local_identity("proj-1")); - w.sync_confirm = true; - w.creation_open = true; - w.jump_to_review_hint(&app, &hints[1]); - assert!(!w.sync_confirm); - assert!(!w.creation_open); - let dispatched: Vec<_> = requests.try_iter().collect(); - let queued_slot_switch = w.pending_slot_apply.as_ref().is_some_and(|pending| { - pending["outputId"] == "main_images" - && pending["slotId"] == "S01" - && pending["layerId"] == "L9" - }); - let direct_slot_switch = dispatched.iter().any(|req| { - matches!( - req, - Request::Action(method, input) - if method == "slot-skeleton" - && input["outputId"] == "main_images" - && input["slotId"] == "S01" - && input["layerId"] == "L9" - ) - }); - assert!(queued_slot_switch || direct_slot_switch, "expected slot-skeleton jump to main_images/S01/L9, error={}", w.error); - } - - #[test] - fn enter_creation_canvas_switches_to_canvas_immediately_and_recovers_on_early_error() { - let (mut w, mut app, _requests) = brief_fixture(); - w.creation_open = true; - w.creation_step = 0; - w.library = false; - w.material = false; - let template = json!({"id": "tpl-fast", "title": "极速模板"}); - w.enter_creation_canvas(&mut app, &template, true, Some(false)); - assert!(!w.creation_open, "should switch off creation form immediately"); - assert_eq!(w.creation_step, 3, "should switch to canvas step immediately"); - assert!(!w.library && !w.material); - assert!(w.product_start_queued, "should queue product preparation"); - - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - w.receive_json_event(&mut app, &ctx, "slot-skeleton".into(), Err("模板原稿缺失,请检查模板".into())); - assert!(!w.product_start_queued); - assert_eq!(w.error, "模板原稿缺失,请检查模板"); - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct ReviewHintItem { - message: String, - output_id: Option, - variant_id: Option, - slot_id: Option, - layer_id: Option, -} - -impl ReviewHintItem { - fn has_target(&self) -> bool { - self.output_id.is_some() || self.slot_id.is_some() || self.layer_id.is_some() - } -} - -fn infer_review_hint_output_id(message: &str) -> Option { - if message.starts_with("详情页:") { - Some("detail".to_owned()) - } else if message.starts_with("主图:") { - Some("main_images".to_owned()) - } else if message.starts_with("SKU 图:") || message.starts_with("SKU:") { - Some("sku_images".to_owned()) - } else { - None - } -} - -fn parse_review_hints(value: &Value, out: &mut Vec) { - let Some(items) = value.as_array() else { return }; - for entry in items { - let item = if let Some(text) = entry.as_str().map(str::trim).filter(|s| !s.is_empty()) { - ReviewHintItem { - message: text.to_owned(), - output_id: infer_review_hint_output_id(text), - variant_id: None, - slot_id: None, - layer_id: None, - } - } else if let Some(obj) = entry.as_object() { - let Some(message) = obj - .get("message") - .or_else(|| obj.get("text")) - .or_else(|| obj.get("hint")) - .and_then(Value::as_str) - .map(str::trim) - .filter(|s| !s.is_empty()) - else { - continue; - }; - let output_id = obj - .get("outputId") - .and_then(Value::as_str) - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_owned) - .or_else(|| infer_review_hint_output_id(message)); - let slot_id = obj - .get("slotId") - .and_then(Value::as_str) - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_owned); - let layer_id = obj - .get("layerId") - .and_then(Value::as_str) - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_owned); - ReviewHintItem { - message: message.to_owned(), - output_id, - variant_id: obj.get("variantId").and_then(Value::as_str).map(str::to_owned), - slot_id, - layer_id, - } - } else { - continue; - }; - if !out.contains(&item) { - out.push(item); - } - } -} - -const DELIVERY_DIR_PREF_KEY: &str = "jiansun.deliveryDir"; - -fn remembered_delivery_dir(app: &PhotocraftApp) -> Option { - app.session.prefs().dialogs.get(DELIVERY_DIR_PREF_KEY) - .and_then(Value::as_str) - .map(str::trim) - .filter(|path| !path.is_empty()) - .map(str::to_owned) -} - -fn remember_delivery_dir(app: &mut PhotocraftApp, path: &str) { - let trimmed = path.trim(); - if trimmed.is_empty() { - return; - } - app.session.prefs.edit(|prefs| { - prefs.dialogs.insert(DELIVERY_DIR_PREF_KEY.into(), json!(trimmed)); - }); - let _ = crate::prefs_ui::save_preferences(app); -} - -fn default_delivery_dir_for_home(home: &std::path::Path) -> Option { - let desktop = home.join("Desktop"); - let onedrive_desktop = home.join("OneDrive").join("Desktop"); - let documents = home.join("Documents"); - let base = if desktop.is_dir() { - desktop - } else if onedrive_desktop.is_dir() { - onedrive_desktop - } else if documents.is_dir() { - documents - } else { - desktop +mod creation_test_exports { + pub(super) use super::barcode::{ + binding_barcodes, project_barcodes, replace_barcode, update_detail_barcode, + write_legacy_barcode_fields, }; - base.join("小壹成品").to_str().map(str::to_owned) -} - -fn default_delivery_dir() -> Option { - let home = std::env::var_os("USERPROFILE") - .or_else(|| std::env::var_os("HOME")) - .map(std::path::PathBuf::from)?; - default_delivery_dir_for_home(&home) -} - -fn preferred_delivery_dir(app: &PhotocraftApp) -> Option { - remembered_delivery_dir(app).or_else(default_delivery_dir) + pub(super) use super::brief::{ + OUTPUT_SCOPE_OPTIONS, brief_variants, canvas_entry_missing, dedupe_strings, + default_resource_component, has_selected_product_image, + merge_platform_brief_preserving_manual_edits, non_empty_str, normalized_color_groups, + selected_output_scopes, set_brief_variants, sku_short_label, store_image_rows, + string_list, template_identity, variant_identity, + }; + pub(super) use super::form_widgets_ui::{ + IntakeScope, MaterialSearchPending, brief_section_break, edit, edit_named, field_group, + field_kind, intake_columns, intake_fields_with_errors, intake_hint, intake_multiline, + is_product_name_field, material_search_due, material_thumbnail, picker, picker_notice, + picker_row, picker_toggle_row, preview_size, product_intake_columns, + reveal_template_intake, template_picker_row, + }; + pub(super) use super::intake::{BARCODE_HINT, dimension_text, field_fact, set_intake}; + pub(super) use super::project::{default_delivery_dir_for_home, remember_delivery_dir}; + pub(super) use super::reducers::listing_status_text; + pub(super) use super::review_hints::parse_review_hints; + pub(super) use super::structure_preview_ui::{drop_contains, verified_structure_preview}; + pub(super) use super::super::Value; + pub(super) use super::super::creation_reads::{TEST_PRESETS, wizard}; + pub(super) use super::super::creation_reads::wizard::WizardFooterOutcome; + pub(super) use crate::theme::agent_scale::{Type, control, icon, radius}; + pub(super) use egui::vec2; + pub(super) use std::collections::{HashMap, HashSet}; } #[cfg(test)] -mod delivery_dir_tests { - use super::*; - use std::sync::mpsc; - - #[test] - fn default_delivery_dir_prefers_desktop_then_documents() { - let dir = tempfile::tempdir().unwrap(); - let home = dir.path(); - let docs = home.join("Documents"); - std::fs::create_dir_all(&docs).unwrap(); - assert_eq!(default_delivery_dir_for_home(home).as_deref(), docs.join("小壹成品").to_str()); - - let desktop = home.join("Desktop"); - std::fs::create_dir_all(&desktop).unwrap(); - assert_eq!(default_delivery_dir_for_home(home).as_deref(), desktop.join("小壹成品").to_str()); - } - - #[test] - fn begin_staged_new_project_remembers_last_delivery_dir() { - let (tx, _rx) = mpsc::channel(); - let (_, event_rx) = mpsc::channel(); - let mut w = Workspace::new(tx, event_rx); - let session = photocraft_engine::Session::new(); - let mut app = PhotocraftApp::new(session, crate::Services::default()); - - remember_delivery_dir(&mut app, "/tmp/custom-xiaoyi-output"); - w.begin_staged_new_project(&app); - assert_eq!(w.creation_delivery_dir.as_deref(), Some("/tmp/custom-xiaoyi-output")); - } -} +mod tests; diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/barcode.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/barcode.rs new file mode 100644 index 00000000..833d6f9c --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/barcode.rs @@ -0,0 +1,150 @@ +use super::super::{Value, json}; +use super::brief::{brief_variants, non_empty_str, set_brief_variants}; +use super::form_widgets_ui::{field_key, field_kind}; +use super::intake::BARCODE_SEPARATORS; +use std::collections::HashSet; + +pub(in crate::jiansun) fn binding_barcodes(binding: &Value) -> impl Iterator { + let legacy = binding.as_str().into_iter().flat_map(|text| text.split(BARCODE_SEPARATORS)); + let current = binding.as_array().into_iter().flatten().filter_map(Value::as_str); + let mut seen = std::collections::HashSet::new(); + legacy.chain(current).map(str::trim) + .filter(move |barcode| !barcode.is_empty() && seen.insert(*barcode)) +} + +pub(in crate::jiansun) fn project_barcodes(brief: &Value) -> impl Iterator { + let has_cards = brief["barcodeEntries"].is_array(); + let from_cards = brief["barcodeEntries"].as_array().into_iter().flatten() + .filter_map(|row| non_empty_str(&row["barcode"])); + let from_bindings = brief["barcodeBindings"].as_object().into_iter().flat_map(|groups| groups.values()).flat_map(binding_barcodes); + let from_normalized = brief["normalizedProduct"]["variants"] + .as_array() + .into_iter() + .flatten() + .flat_map(|variant| variant["barcodes"].as_array().into_iter().flatten()) + .filter_map(|row| non_empty_str(&row["barcode"])); + let mut seen = HashSet::new(); + from_cards.chain(from_bindings.chain(from_normalized).filter(move |_| !has_cards)) + .filter(move |code| seen.insert(*code)) +} + + +pub(in crate::jiansun) fn structured_barcode_field(field: &Value) -> bool { + match (field_key(field).as_str(), field_kind(field).as_str()) { + (Some("length" | "width" | "height"), Some("number")) => true, + (Some("colorName" | "material" | "boardType"), Some("text")) => true, + _ => false, + } +} + +pub(in crate::jiansun) fn write_legacy_barcode_fields(brief: &mut Value, rows: &mut [Value], schema: &Value) { + let mut variants = brief_variants(brief); + let mut bindings = serde_json::Map::new(); + let mut owners = std::collections::HashMap::new(); + for row in rows.iter() { + if let Some(owner) = non_empty_str(&row["variantId"]) { + *owners.entry(owner.to_owned()).or_insert(0) += 1; + } + } + for row in rows.iter_mut() { + let Some(code) = non_empty_str(&row["barcode"]).map(str::to_owned) else { continue; }; + let color = non_empty_str(&row["colorName"]); + let matching = variants.iter().find(|variant| color.is_some_and(|color| variant["colorName"] == color || variant["name"] == color)); + let current = variants.iter().position(|variant| variant["id"] == row["variantId"]); + row["variantId"] = if let Some(variant) = matching { + variant["id"].clone() + } else if let Some(index) = current + && let Some(color) = color + && non_empty_str(&variants[index]["colorMaterialId"]).is_none() + && row["variantId"].as_str().and_then(|id| owners.get(id)) == Some(&1) + { + variants[index]["name"] = json!(color); + variants[index]["colorName"] = json!(color); + variants[index]["id"].clone() + } else if let Some(color) = color && variants.len() < 64 { + let id = uuid::Uuid::new_v4().to_string(); + variants.push(json!({"id":id,"name":color,"colorName":color,"colorMaterialId":"","images":[]})); + json!(id) + } else { + current.and_then(|index| variants.get(index)).or_else(|| variants.first()) + .map_or(Value::Null, |variant| variant["id"].clone()) + }; + let owner = row["variantId"].as_str().unwrap_or("default"); + let codes = bindings.entry(owner.to_owned()).or_insert_with(|| json!([])); + codes.as_array_mut().expect("barcode list").push(json!(code)); + + for field in schema.as_array().into_iter().flatten().filter(|field| structured_barcode_field(field)) { + let key = field_key(field).as_str().unwrap(); + let value = if field_kind(field) == "number" { + let mm_factor = |unit: &Value| match unit.as_str() { Some("cm" | "厘米") => 10.0, Some("m" | "米") => 1000.0, _ => 1.0 }; + let ratio = mm_factor(&row["dimensions"]["unit"]) / mm_factor(&field["unit"]); + row["dimensions"][key].as_str().and_then(|text| text.parse::().ok()) + .and_then(|value| serde_json::Number::from_f64(value * ratio)).map_or_else(|| json!(""), Value::Number) + } else { + row.get(key).cloned().unwrap_or_else(|| json!("")) + }; + brief["intake"]["barcodeValues"][&code][key] = value; + } + } + if variants != brief_variants(brief) { set_brief_variants(brief, variants); } + brief["barcodeBindings"] = Value::Object(bindings); + brief["barcodeEntries"] = json!(rows); + update_detail_barcode(brief); + if let Some(row) = rows.iter().find(|row| row["barcode"] == brief["detailBarcode"]).or_else(|| rows.first()) { + brief["dimensions"] = row["dimensions"].clone(); + if let Some(color) = non_empty_str(&row["colorName"]) { + brief["colorName"] = json!(color); + } + } +} + +pub(in crate::jiansun) fn update_detail_barcode(brief: &mut Value) -> bool { + let selected = brief["detailBarcode"].as_str(); + let next = { + let mut codes = project_barcodes(brief); + let first = codes.next(); + let next = if codes.next().is_none() { + first + } else { + selected.filter(|selected| project_barcodes(brief).any(|code| code == *selected)) + }; + if selected == next { return false; } + next.map(str::to_owned) + }; + if let Some(next) = next { + brief["detailBarcode"] = json!(next); + } else if let Some(fields) = brief.as_object_mut() { + fields.remove("detailBarcode"); + } + true +} + +pub(in crate::jiansun) fn replace_barcode(brief: &mut Value, old: &str, replacement: Option<&str>) { + if brief["detailBarcode"] == old { + if let Some(code) = replacement { + brief["detailBarcode"] = json!(code); + } else if let Some(fields) = brief.as_object_mut() { + fields.remove("detailBarcode"); + } + } + if let Some(images) = brief["images"].as_array_mut() { + if let Some(barcode) = replacement { + for image in images.iter_mut().filter(|image| image["barcode"] == old) { image["barcode"] = json!(barcode); } + } else { + images.retain(|image| image["barcode"] != old); + } + } + if let Some(values) = brief.get_mut("platformFacts").and_then(|facts| facts["barcodes"].as_object_mut()) + && let Some(value) = values.remove(old) && let Some(code) = replacement + { + values.insert(code.to_owned(), value); + } + if let Some(values) = brief.get_mut("intake").and_then(|intake| intake.get_mut("barcodeValues")) + .and_then(Value::as_object_mut) + && let Some(value) = values.remove(old) + && let Some(code) = replacement + { + values.insert(code.to_owned(), value); + } +} + diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/brief.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/brief.rs new file mode 100644 index 00000000..9d3a8285 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/brief.rs @@ -0,0 +1,779 @@ +use super::super::{Value, json}; +use super::super::creation_reads::wizard::{self, CreationStage}; +use super::barcode::{binding_barcodes, project_barcodes, update_detail_barcode, write_legacy_barcode_fields}; +use super::form_widgets_ui::{field_kind, is_product_name_field, spu_field}; +use super::intake::dimension_text; +use std::collections::HashSet; + +pub(in crate::jiansun) fn empty_brief() -> Value { + json!({"source":"upload","name":"","brandId":"","brandName":"","categoryId":"","categoryName":"","identifierType":"spu","identifier":"","barcodeBindings":{},"variant":"","colorMaterialId":"","colorName":"","variants":[],"templateSelection":null,"dimensions":{"length":"","width":"","height":"","unit":"mm"},"images":[],"note":""}) +} + +pub(in crate::jiansun) fn variant_identity(material: &str) -> String { + if material.len() == 36 + && material.bytes().enumerate().all(|(index, byte)| if [8, 13, 18, 23].contains(&index) { byte == b'-' } else { byte.is_ascii_hexdigit() }) + { + return material.to_ascii_lowercase(); + } + // Application-defined UUIDv8 for non-UUID legacy material identifiers. It + // is persisted with the selected row; no order/index becomes its identity. + let left = egui::Id::unique(("material-variant-a-v1", material)).value(); + let right = egui::Id::unique(("material-variant-b-v1", material)).value(); + format!( + "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}", + left >> 32, + (left >> 16) & 0xffff, + (left & 0x0fff) | 0x8000, + ((right >> 48) & 0x0fff) | 0x8000, + right & 0xffff_ffff_ffff + ) +} + +pub(in crate::jiansun) fn brief_variants(brief: &Value) -> Vec { + if let Some(rows) = brief["variants"].as_array().filter(|rows| !rows.is_empty()) { + return rows.clone(); + } + let Some(material) = brief["colorMaterialId"].as_str().filter(|id| !id.is_empty()) else { return vec![] }; + let name = brief["colorName"].as_str().filter(|name| !name.is_empty()).unwrap_or("花色"); + vec![json!({"id":variant_identity(material),"name":name,"colorMaterialId":material,"colorName":brief["colorName"],"images":[]})] +} + +pub(in crate::jiansun) fn set_brief_variants(brief: &mut Value, rows: Vec) { + brief["colorMaterialId"] = rows.first().map(|row| row["colorMaterialId"].clone()).unwrap_or(json!("")); + brief["colorName"] = rows.first().map(|row| row["colorName"].clone()).unwrap_or(json!("")); + brief["variants"] = json!(rows); + // brief.variant is the original product option text, not the selected color. +} + +pub(in crate::jiansun) fn template_identity(value: &Value) -> bool { + value["id"].as_str().is_some_and(|id| !id.is_empty() && id.chars().count() <= 160) + && value["version"].as_str().is_some_and(|version| !version.is_empty() && version.chars().count() <= 100) + && value["contentHash"].as_str().is_some_and(|hash| hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))) +} + +pub(in crate::jiansun) fn template_compatibility_warnings(sources: &[&Value]) -> Vec { + let mut out = Vec::new(); + for source in sources { + for key in ["compatibilityWarnings", "warnings"] { + for item in source[key].as_array().into_iter().flatten() { + let Some(text) = item.as_str().map(str::trim).filter(|s| !s.is_empty()) else { continue }; + let text = text.chars().take(400).collect::(); + if !out.contains(&text) { + out.push(text); + if out.len() >= 20 { + return out; + } + } + } + } + } + out +} + +pub(in crate::jiansun) fn default_resource_component(parts: &[Value]) -> Option<&Value> { + if let [only] = parts { + return Some(only); + } + let mut detail = parts.iter().filter(|part| part["kind"] == "detail"); + let candidate = detail.next()?; + detail.next().is_none().then_some(candidate) +} + +pub(in crate::jiansun) fn selected_template(brief: &Value, workflow: &Value, canonical_brief: &Value) -> Value { + let selected = &brief["templateSelection"]; + if template_identity(selected) + && selected.get("brandId").is_none_or(|id| *id == brief["brandId"]) + && selected.get("categoryId").is_none_or(|id| *id == brief["categoryId"]) + { + return selected.clone(); + } + if brief["brandId"] != canonical_brief["brandId"] || brief["categoryId"] != canonical_brief["categoryId"] { + return Value::Null; + } + let installed = json!({"id":workflow["templateId"],"version":workflow["templateVersion"],"contentHash":workflow["templateHash"],"name":workflow["templateName"],"brandId":brief["brandId"],"categoryId":brief["categoryId"]}); + if template_identity(&installed) { installed } else { Value::Null } +} + +pub(in crate::jiansun) fn image_rows(brief: &Value) -> Vec<(Value, String)> { + let mut rows = brief["images"].as_array().into_iter().flatten().cloned().map(|image| (image, String::new())).collect::>(); + for variant in brief_variants(brief) { + let owner = variant["id"].as_str().unwrap_or("").to_owned(); + rows.extend(variant["images"].as_array().into_iter().flatten().cloned().map(|image| (image, owner.clone()))); + } + rows +} + +pub(in crate::jiansun) fn store_image_rows(brief: &mut Value, rows: Vec<(Value, String)>) -> Result<(), String> { + if !brief.is_object() { + return Err("产品资料格式无效,未更改图片归属".into()); + } + let mut variants = brief_variants(brief); + if rows.iter().any(|(_, owner)| !owner.is_empty() && !variants.iter().any(|variant| variant["id"] == owner.as_str())) { + return Err("图片所属花色已变化,请重新选择归属".into()); + } + for variant in &mut variants { + variant["images"] = json!([]); + } + let mut common = Vec::new(); + for (image, owner) in rows { + if let Some(variant) = variants.iter_mut().find(|row| row["id"] == owner) { + let Some(images) = variant["images"].as_array_mut() else { return Err("花色图片记录无效,未更改图片归属".into()) }; + images.push(image); + } else { + common.push(image); + } + } + let removed = brief["images"].as_array().into_iter().flatten() + .filter(|old| old["barcode"].is_string() && !common.iter().any(|image| image["source"] == old["source"] + && image["barcode"] == old["barcode"] && image["fieldKey"] == old["fieldKey"])) + .cloned().collect::>(); + for row in brief["barcodeEntries"].as_array_mut().into_iter().flatten() { + if let Some(pictures) = row["images"].as_array_mut() { + pictures.retain(|picture| !removed.iter().any(|old| old["source"] == picture["source"] + && old["barcode"] == picture["barcode"] && old["fieldKey"] == picture["fieldKey"])); + } + } + brief["images"] = json!(common); + if brief.get("variants").is_some() || !variants.is_empty() { + set_brief_variants(brief, variants); + } + Ok(()) +} + +pub(in crate::jiansun) struct ReadinessItem { + pub(in crate::jiansun) field_key: String, + pub(in crate::jiansun) label: String, + pub(in crate::jiansun) message: String, + pub(in crate::jiansun) ready: bool, +} + +#[derive(Clone, Debug, Default)] +pub(in crate::jiansun) struct NormalizedProductSummary { + pub(in crate::jiansun) has_platform_data: bool, + pub(in crate::jiansun) spu: String, + pub(in crate::jiansun) platform_brand: String, + pub(in crate::jiansun) platform_category: String, + pub(in crate::jiansun) series_or_model: String, + pub(in crate::jiansun) dimensions_display: Option, + pub(in crate::jiansun) materials: Vec, + pub(in crate::jiansun) attributes: Vec<(String, String)>, + pub(in crate::jiansun) summary: String, + pub(in crate::jiansun) selling_points: Vec, + pub(in crate::jiansun) trace_source: String, + #[cfg(test)] + pub(in crate::jiansun) fetched_at: String, + pub(in crate::jiansun) raw_field_warnings: Vec, +} + +#[derive(Clone, Debug, Default)] +pub(in crate::jiansun) struct NormalizedSkuRow { + pub(in crate::jiansun) barcode: String, + #[cfg(test)] + pub(in crate::jiansun) color_name: String, + #[cfg(test)] + pub(in crate::jiansun) spec: String, + #[cfg(test)] + pub(in crate::jiansun) dimensions_display: Option, + #[cfg(test)] + pub(in crate::jiansun) image_count: usize, +} + +#[derive(Clone, Debug, Default)] +pub(in crate::jiansun) struct NormalizedColorGroup { + pub(in crate::jiansun) id: String, + pub(in crate::jiansun) color_name: String, + pub(in crate::jiansun) skus: Vec, +} + +pub(in crate::jiansun) fn non_empty_str(value: &Value) -> Option<&str> { + value.as_str().map(str::trim).filter(|s| !s.is_empty()) +} + +pub(in crate::jiansun) fn string_list(value: &Value) -> Vec { + match value { + Value::String(text) => text + .split(['\n', '、', ',', ',', ';', ';']) + .map(str::trim) + .filter(|item| !item.is_empty()) + .map(str::to_owned) + .collect(), + Value::Array(items) => items + .iter() + .filter_map(non_empty_str) + .map(str::to_owned) + .collect(), + _ => Vec::new(), + } +} + +pub(in crate::jiansun) fn dedupe_strings(items: Vec) -> Vec { + let mut seen = HashSet::new(); + items.into_iter().filter(|item| seen.insert(item.to_lowercase())).collect() +} + +pub(in crate::jiansun) fn normalized_product_summary(brief: &Value) -> NormalizedProductSummary { + let np = &brief["normalizedProduct"]; + let pf = &brief["platformFacts"]; + if np.is_object() { + let identity = &np["identity"]; + let specs = &np["specs"]; + let copy = &np["copy"]; + let trace = &np["trace"]; + let dims = if specs["dimensions"].is_object() { + non_empty_str(&specs["dimensions"]["display"]) + .map(str::to_owned) + .or_else(|| dimension_text(&specs["dimensions"])) + } else { + None + }; + let materials = dedupe_strings(string_list(&specs["materials"])); + let mut seen_attr = HashSet::new(); + let mut attributes = Vec::new(); + for attr in specs["attributes"].as_array().into_iter().flatten() { + let label = non_empty_str(&attr["label"]).or_else(|| non_empty_str(&attr["key"])); + let value = non_empty_str(&attr["value"]); + if let (Some(label), Some(value)) = (label, value) { + let lower = label.to_lowercase(); + if matches!(label, "尺寸" | "产品尺寸" | "长" | "宽" | "高" | "品牌" | "品类" | "颜色" | "花色") + && (dims.is_some() || !materials.is_empty()) + { + continue; + } + if seen_attr.insert(format!("{lower}:{value}")) { + attributes.push((label.to_owned(), value.to_owned())); + } + } + } + return NormalizedProductSummary { + has_platform_data: true, + spu: non_empty_str(&identity["spu"]).or_else(|| non_empty_str(&trace["upstreamSpu"])).or_else(|| non_empty_str(&brief["identifier"])).unwrap_or("").to_owned(), + platform_brand: non_empty_str(&identity["platformBrand"]).unwrap_or("").to_owned(), + platform_category: non_empty_str(&identity["platformCategory"]).unwrap_or("").to_owned(), + series_or_model: non_empty_str(&identity["seriesOrModel"]).unwrap_or("").to_owned(), + dimensions_display: dims, + materials, + attributes, + summary: non_empty_str(©["summary"]).unwrap_or("").to_owned(), + selling_points: dedupe_strings(string_list(©["sellingPoints"])), + trace_source: non_empty_str(&trace["source"]).unwrap_or("产品平台").to_owned(), + #[cfg(test)] + fetched_at: non_empty_str(&trace["fetchedAt"]).unwrap_or("").to_owned(), + raw_field_warnings: dedupe_strings(string_list(&trace["rawFieldWarnings"])), + }; + } + if pf.is_object() { + let shared = &pf["shared"]; + let dims = dimension_text(&shared["dimensions"]); + let materials = dedupe_strings(string_list(&shared["material"])); + let mut attributes = Vec::new(); + if let Some(map) = shared["attributes"].as_object() { + for (k, v) in map { + if let Some(text) = non_empty_str(v) + && !matches!(k.as_str(), "尺寸" | "产品尺寸" | "长" | "宽" | "高") + { + attributes.push((k.clone(), text.to_owned())); + } + } + } + return NormalizedProductSummary { + has_platform_data: true, + spu: non_empty_str(&pf["spu"]).or_else(|| non_empty_str(&brief["identifier"])).unwrap_or("").to_owned(), + platform_brand: non_empty_str(&shared["brandName"]).or_else(|| non_empty_str(&pf["brandName"])).unwrap_or("").to_owned(), + platform_category: non_empty_str(&shared["categoryName"]).or_else(|| non_empty_str(&pf["categoryName"])).unwrap_or("").to_owned(), + series_or_model: non_empty_str(&brief["variant"]).unwrap_or("").to_owned(), + dimensions_display: dims, + materials, + attributes, + summary: non_empty_str(&shared["description"]).unwrap_or("").to_owned(), + selling_points: dedupe_strings(string_list(&shared["sellingPoints"])), + trace_source: "产品平台".into(), + #[cfg(test)] + fetched_at: String::new(), + raw_field_warnings: Vec::new(), + }; + } + NormalizedProductSummary::default() +} + +pub(in crate::jiansun) fn sku_display_label(brief: &Value, barcode: &str) -> String { + let mut color = String::new(); + let mut spec = String::new(); + if let Some(variants) = brief["normalizedProduct"]["variants"].as_array() { + 'outer: for variant in variants { + let v_color = non_empty_str(&variant["colorName"]).unwrap_or(""); + for row in variant["barcodes"].as_array().into_iter().flatten() { + if non_empty_str(&row["barcode"]) == Some(barcode) { + color = v_color.to_owned(); + let s = non_empty_str(&row["spec"]) + .or_else(|| non_empty_str(&row["skuName"])) + .map(str::to_owned) + .or_else(|| non_empty_str(&row["dimensions"]["display"]).map(str::to_owned)) + .or_else(|| dimension_text(&row["dimensions"])) + .unwrap_or_default(); + spec = s; + break 'outer; + } + } + } + } + if color.is_empty() && spec.is_empty() { + let pf = &brief["platformFacts"]["barcodes"][barcode]; + if pf.is_object() { + color = non_empty_str(&pf["colorName"]).unwrap_or("").to_owned(); + spec = non_empty_str(&pf["spec"]) + .or_else(|| non_empty_str(&pf["sizeText"])) + .map(str::to_owned) + .or_else(|| dimension_text(&pf["dimensions"])) + .unwrap_or_default(); + } + } + if color.is_empty() { + for variant in brief_variants(brief) { + if let Some(id) = variant["id"].as_str() + && binding_barcodes(&brief["barcodeBindings"][id]).any(|code| code == barcode) + { + color = non_empty_str(&variant["colorName"]) + .or_else(|| non_empty_str(&variant["name"])) + .unwrap_or("") + .to_owned(); + break; + } + } + } + // Deduplicate color prefix if spec already includes the color name. + if !color.is_empty() && !spec.is_empty() && spec.eq_ignore_ascii_case(&color) { + spec.clear(); + } + match (color.is_empty(), spec.is_empty()) { + (false, false) => format!("{color} · {spec} ({barcode})"), + (false, true) => format!("{color} ({barcode})"), + (true, false) => format!("{spec} ({barcode})"), + (true, true) => barcode.to_owned(), + } +} + +pub(in crate::jiansun) fn sku_short_label(brief: &Value, barcode: &str) -> String { + let full = sku_display_label(brief, barcode); + full.strip_suffix(&format!(" ({barcode})")).unwrap_or(&full).to_owned() +} + +pub(in crate::jiansun) fn normalized_color_groups(brief: &Value) -> Vec { + let mut groups: Vec = Vec::new(); + let mut seen_barcodes: HashSet = HashSet::new(); + #[cfg(test)] + let image_count_for = |code: &str, asset_ids: Option<&[Value]>| -> usize { + let explicit_ids = asset_ids.map(|arr| arr.len()).unwrap_or(0); + let brief_imgs = brief["images"] + .as_array() + .into_iter() + .flatten() + .filter(|img| img["barcode"] == code) + .count(); + let norm_imgs = brief["normalizedProduct"]["assets"] + .as_array() + .into_iter() + .flatten() + .filter(|asset| asset["barcode"] == code && asset["selectedForProject"] != false) + .count(); + explicit_ids.max(brief_imgs).max(norm_imgs) + }; + + if let Some(np_variants) = brief["normalizedProduct"]["variants"].as_array().filter(|a| !a.is_empty()) { + for variant in np_variants { + let color_name = non_empty_str(&variant["colorName"]).unwrap_or("默认花色").to_owned(); + let id = non_empty_str(&variant["id"]).unwrap_or(&color_name).to_owned(); + let mut skus = Vec::new(); + for row in variant["barcodes"].as_array().into_iter().flatten() { + let Some(code) = non_empty_str(&row["barcode"]) else { continue }; + if !seen_barcodes.insert(code.to_owned()) { + continue; + } + skus.push(NormalizedSkuRow { + barcode: code.to_owned(), + #[cfg(test)] + color_name: color_name.clone(), + #[cfg(test)] + spec: non_empty_str(&row["spec"]) + .or_else(|| non_empty_str(&row["skuName"])) + .filter(|spec| !spec.eq_ignore_ascii_case(&color_name)) + .unwrap_or("") + .to_owned(), + #[cfg(test)] + dimensions_display: non_empty_str(&row["dimensions"]["display"]) + .map(str::to_owned) + .or_else(|| dimension_text(&row["dimensions"])), + #[cfg(test)] + image_count: image_count_for(code, row["imageIds"].as_array().map(Vec::as_slice)), + }); + } + if !skus.is_empty() { + groups.push(NormalizedColorGroup { id, color_name, skus }); + } + } + } + + // Merge any manual / legacy barcodeBindings not yet covered by normalizedProduct.variants. + let variants = brief_variants(brief); + let mut binding_groups: Vec<(String, String)> = variants + .iter() + .filter_map(|v| Some((v["id"].as_str()?.to_owned(), v["name"].as_str().unwrap_or("默认花色").to_owned()))) + .collect(); + if binding_groups.is_empty() || binding_barcodes(&brief["barcodeBindings"]["default"]).next().is_some() { + binding_groups.insert(0, ("default".into(), "默认花色".into())); + } + for (group_id, group_label) in binding_groups { + let codes: Vec = binding_barcodes(&brief["barcodeBindings"][&group_id]) + .filter(|code| seen_barcodes.insert((*code).to_owned())) + .map(str::to_owned) + .collect(); + for code in codes { + let pf = &brief["platformFacts"]["barcodes"][&code]; + let color_name = non_empty_str(&pf["colorName"]) + .map(str::to_owned) + .unwrap_or_else(|| group_label.clone()); + let row = NormalizedSkuRow { + #[cfg(test)] + color_name: color_name.clone(), + #[cfg(test)] + spec: non_empty_str(&pf["spec"]) + .or_else(|| non_empty_str(&pf["sizeText"])) + .filter(|spec| !spec.eq_ignore_ascii_case(&color_name)) + .unwrap_or("") + .to_owned(), + #[cfg(test)] + dimensions_display: dimension_text(&pf["dimensions"]), + #[cfg(test)] + image_count: image_count_for(&code, None), + barcode: code, + }; + if let Some(existing) = groups.iter_mut().find(|g| g.color_name == color_name) { + existing.skus.push(row); + } else { + groups.push(NormalizedColorGroup { + id: if group_id == "default" { color_name.clone() } else { group_id.clone() }, + color_name, + skus: vec![row], + }); + } + } + } + groups +} + +pub(in crate::jiansun) fn selected_output_scopes(brief: &Value) -> Vec { + if let Some(arr) = brief["outputScopes"].as_array() { + let items: Vec = arr + .iter() + .filter_map(Value::as_str) + .filter(|s| matches!(*s, "detail" | "main_images" | "sku_images")) + .map(str::to_owned) + .collect(); + if !items.is_empty() { + return items; + } + } + vec!["detail".into(), "main_images".into(), "sku_images".into()] +} + +pub(in crate::jiansun) fn selected_visual_asset_count(brief: &Value) -> usize { + let mut sources = HashSet::new(); + let mut count = 0usize; + for (image, _) in image_rows(brief) { + if let Some(src) = non_empty_str(&image["source"]) { + if sources.insert(src.to_owned()) { + count += 1; + } + } else { + count += 1; + } + } + for asset in brief["normalizedProduct"]["assets"].as_array().into_iter().flatten() { + if asset["selectedForProject"] == false { + continue; + } + if let Some(src) = non_empty_str(&asset["localSource"]).or_else(|| non_empty_str(&asset["url"])).or_else(|| non_empty_str(&asset["id"])) { + if sources.insert(src.to_owned()) { + count += 1; + } + } + } + count +} + +pub(in crate::jiansun) fn has_selected_product_image(brief: &Value) -> bool { + selected_product_image(brief, |_| true) +} + +pub(in crate::jiansun) fn selected_product_image(brief: &Value, local_exists: impl Fn(&str) -> bool) -> bool { + let mut platform_assets = brief["normalizedProduct"]["assets"].as_array().into_iter().flatten(); + let local_ok = reference_images(brief).any(|image| { + image["purpose"] == "product" && (image["barcode"].is_null() || image["barcode"] == brief["detailBarcode"]) + && non_empty_str(&image["source"]).is_some_and(&local_exists) + && !(image["platformImage"] == true && platform_assets.clone().any(|asset| { + asset["localSource"] == image["source"] && asset["selectedForProject"] == false + })) + }); + if local_ok || brief["barcodeEntries"].as_array().into_iter().flatten().any(|row| { + (brief["detailBarcode"].is_null() || row["barcode"] == brief["detailBarcode"]) + && row["images"].as_array().into_iter().flatten().any(|image| { + image["purpose"] == "product" && non_empty_str(&image["source"]).is_some_and(&local_exists) + }) + }) { + return true; + } + platform_assets.any(|asset| { + asset["selectedForProject"] != false + && matches!(asset["kind"].as_str(), Some("whiteBackground" | "main")) + && (asset["barcode"].is_null() + || non_empty_str(&asset["barcode"]).is_none() + || asset["barcode"] == brief["detailBarcode"]) + && (non_empty_str(&asset["localSource"]).is_some_and(&local_exists) || non_empty_str(&asset["url"]).is_some()) + }) +} + +pub(in crate::jiansun) fn reference_images(brief: &Value) -> impl Iterator { + brief["images"].as_array().into_iter().flatten().chain( + brief["variants"].as_array().into_iter().flatten() + .flat_map(|variant| variant["images"].as_array().into_iter().flatten()), + ) +} + +/// The canvas may save a form snapshot before the initial creation read returns revision zero. +pub(in crate::jiansun) const OUTPUT_SCOPE_OPTIONS: [(&str, &str, &str); 3] = [ + ("output-tag-detail", "detail", "详情页"), + ("output-tag-main_images", "main_images", "主图"), + ("output-tag-sku_images", "sku_images", "SKU 图"), +]; + +pub fn saved_creation_draft_brief<'a>(record: &Value, draft: &'a Value) -> Option<&'a Value> { + (draft["brief"].is_object() + && (draft["revision"] == record["revision"] || draft["revision"].is_null() && record["revision"] == 0)) + .then_some(&draft["brief"]) +} + +/// Use the same required fields as the wizard when classifying a saved brief. +pub fn incomplete_brief_stage(brief: &Value, workflow: &Value, local_exists: impl Fn(&str) -> bool) -> Option { + if workflow["canvasFirst"] == true { + return None; + } + let template = selected_template(brief, workflow, brief); + let has_template = template_identity(&template); + let has_source = reference_images(brief).any(|image| non_empty_str(&image["source"]).is_some_and(&local_exists)) + || ["normalizedProduct", "platformFacts"].into_iter().any(|key| { + brief[key].as_object().is_some_and(|fields| !fields.is_empty()) + }) + || (brief["source"] == "library" && non_empty_str(&brief["name"]).is_some() + && non_empty_str(&brief["identifier"]).is_some()); + if !has_template && !has_source { + return Some(CreationStage::Source); + } + let readiness = brief_readiness_with_images(brief, &template, selected_product_image(brief, local_exists)); + if readiness.iter().any(|item| !item.ready && matches!(item.field_key.as_str(), "brand" | "category" | "template")) { + Some(CreationStage::Template) + } else { + readiness.iter().any(|item| !item.ready).then_some(CreationStage::Details) + } +} + +pub(in crate::jiansun) fn intake_value_filled(field: &Value, value: &Value) -> bool { + match field["type"].as_str() { + Some("boolean") => value.is_boolean(), + Some("number") => value.is_number() || value.as_str().is_some_and(|s| !s.trim().is_empty()), + _ => value.as_str().is_some_and(|s| !s.trim().is_empty()), + } +} + +pub(in crate::jiansun) fn brief_readiness(brief: &Value, template: &Value) -> Vec { + brief_readiness_with_images(brief, template, has_selected_product_image(brief)) +} + +pub(in crate::jiansun) fn brief_readiness_with_images(brief: &Value, template: &Value, product_image_ready: bool) -> Vec { + let filled = |field: &str| brief[field].as_str().is_some_and(|value| !value.trim().is_empty()); + let mut items = vec![ + ReadinessItem { field_key: "brand".into(), label: "品牌".into(), message: "请选择品牌".into(), ready: filled("brandId") }, + ReadinessItem { field_key: "category".into(), label: "品类".into(), message: "请选择品类".into(), ready: filled("categoryId") }, + ReadinessItem { field_key: "template".into(), label: "模板".into(), message: "请选择项目模板".into(), ready: template_identity(template) }, + ReadinessItem { field_key: "name".into(), label: "产品名称".into(), message: "请输入产品名称".into(), ready: filled("name") }, + ReadinessItem { field_key: "images".into(), label: "产品图".into(), message: "添加或勾选至少一张商品主体图".into(), ready: product_image_ready }, + ]; + if project_barcodes(brief).next().is_some() { + items.push(ReadinessItem { + field_key: "identifier".into(), + label: "SPU 型号".into(), + message: "请填写 SPU 型号".into(), + ready: filled(spu_field(brief)), + }); + } + if project_barcodes(brief).nth(1).is_some() { + let ready = brief["detailBarcode"].as_str().is_some_and(|selected| project_barcodes(brief).any(|code| code == selected)); + items.push(ReadinessItem { + field_key: "detail-barcode".into(), + label: "详情主款".into(), + message: "请选择一个款式条码作为详情主款".into(), + ready, + }); + } + if brief["intake"]["schema"]["version"] == 1 { + let product_values = &brief["intake"]["productValues"]; + for field in brief["intake"]["schema"]["productFields"].as_array().into_iter().flatten() { + if field["required"] == true && field_kind(field) != "image" && !is_product_name_field(field) { + let Some(id) = field["id"].as_str().filter(|id| !id.trim().is_empty()) else { continue }; + let label = field["label"].as_str().unwrap_or(id); + items.push(ReadinessItem { + field_key: format!("intake-product:{id}"), + label: label.to_owned(), + message: format!("请填写必填字段「{label}」"), + ready: intake_value_filled(field, &product_values[id]), + }); + } + } + let active_code = brief["detailBarcode"].as_str().or_else(|| project_barcodes(brief).next()); + if let Some(code) = active_code { + let barcode_values = &brief["intake"]["barcodeValues"][code]; + for field in brief["intake"]["schema"]["barcodeFields"].as_array().into_iter().flatten() { + if field["required"] == true && field_kind(field) != "image" { + let Some(id) = field["id"].as_str().filter(|id| !id.trim().is_empty()) else { continue }; + let label = field["label"].as_str().unwrap_or(id); + items.push(ReadinessItem { + field_key: format!("intake-barcode:{code}:{id}"), + label: label.to_owned(), + message: format!("请填写主款必填字段「{label}」"), + ready: intake_value_filled(field, &barcode_values[id]), + }); + } + } + } + } + items +} + +pub(in crate::jiansun) fn merge_dimensions(current: &Value, incoming: &Value, cleared: impl Fn(&str) -> bool) -> Value { + let mut merged = incoming.clone(); + if !current.is_object() { return merged; } + let axes = ["length", "width", "height", "depth", "secondaryHeight"]; + let keep_unit = cleared("unit") || axes.iter().any(|axis| non_empty_str(¤t[*axis]).is_some() + || current[*axis].is_number()); + let mm = |unit: &Value| match unit.as_str() { + Some("m" | "米") => 1000.0, Some("cm" | "厘米") => 10.0, _ => 1.0, + }; + if keep_unit { + let scale = mm(&incoming["unit"]) / mm(¤t["unit"]); + if scale != 1.0 { + for axis in axes { + if let Some(value) = incoming[axis].as_f64().or_else(|| incoming[axis].as_str()?.parse().ok()) { + merged[axis] = json!(((value * scale * 1000.0).round() / 1000.0).to_string()); + } + } + } + merged["unit"] = current["unit"].clone(); + } + for axis in axes { + let value = ¤t[axis]; + if non_empty_str(value).is_some() || value.is_number() || cleared(axis) { + merged[axis] = value.clone(); + } + } + merged +} + +pub(in crate::jiansun) fn merge_platform_brief_preserving_manual_edits(current: &Value, incoming: &Value, edited: &HashSet) -> (Value, usize) { + let mut merged = incoming.clone(); + let mut preserved = 0; + for (key, fields) in [ + ("name", &["name"][..]), ("note", &["note"][..]), + ("brand", &["brandId", "brandName"][..]), ("category", &["categoryId", "categoryName"][..]), + ("outputScopes", &["outputScopes"][..]), + ] { + if edited.contains(key) || fields.iter().any(|field| non_empty_str(¤t[*field]).is_some()) { + for field in fields { + if let Some(value) = current.get(field) { merged[*field] = value.clone(); } + } + preserved += usize::from(edited.contains(key)); + } + } + if edited.contains("dimensions") { + preserved += 1; + } + if incoming["dimensions"].is_object() { + merged["dimensions"] = merge_dimensions(¤t["dimensions"], &incoming["dimensions"], + |axis| edited.contains("dimensions") || edited.contains(&format!("dimensions:{axis}"))); + } + + if merged["intake"]["schema"]["version"] == 1 && merged["intake"]["templateId"] == current["intake"]["templateId"] { + for (field, value) in current["intake"]["productValues"].as_object().into_iter().flatten() { + merged["intake"]["productValues"][field] = value.clone(); + preserved += usize::from(edited.contains(&format!("intake-product:{field}"))); + } + for (code, row) in current["intake"]["barcodeValues"].as_object().into_iter().flatten() { + for (field, value) in row.as_object().into_iter().flatten() { + merged["intake"]["barcodeValues"][code][field] = value.clone(); + preserved += usize::from(edited.contains(&format!("intake-barcode:{code}:{field}"))); + } + } + } + (merged, preserved) +} + +pub(in crate::jiansun) fn merge_platform_barcode_cards(current: &Value, brief: &mut Value, edited: &HashSet) { + if let Some(fields) = brief.as_object_mut() { fields.remove("barcodeEntries"); } + wizard::ensure_default_barcode(brief); + let mut old = current.clone(); + wizard::ensure_default_barcode(&mut old); + let mut rows = old["barcodeEntries"].as_array().cloned().unwrap_or_default(); + if current["barcodeEntries"].is_null() { rows.retain(|row| non_empty_str(&row["barcode"]).is_some()); } + for incoming in brief["barcodeEntries"].as_array().into_iter().flatten() { + let Some(code) = non_empty_str(&incoming["barcode"]) else { continue; }; + if let Some(row) = rows.iter_mut().find(|row| row["barcode"] == code) { + let id = row["id"].as_str().unwrap_or("").to_owned(); + row["dimensions"] = merge_dimensions(&row["dimensions"], &incoming["dimensions"], + |axis| edited.contains(&format!("barcode-card:{id}:dimensions.{axis}"))); + for field in ["material", "boardType", "colorName", "specId", "specName", "spec", "skuName", "variantName"] { + if non_empty_str(&row[field]).is_none() && !edited.contains(&format!("barcode-card:{id}:{field}")) + && let Some(value) = incoming.get(field) + { + row[field] = value.clone(); + } + } + if row["variantId"].is_null() { row["variantId"] = incoming["variantId"].clone(); } + } else if !edited.contains(&format!("removed-barcode:{code}")) { + rows.push(incoming.clone()); + } + } + if rows.is_empty() && current["barcodeEntries"].is_null() { + return; + } + let mut variants = brief_variants(brief); + for variant in brief_variants(current) { + if let Some(fresh) = variants.iter_mut().find(|row| row["id"] == variant["id"]) { + if variant["images"].as_array().is_some_and(|images| !images.is_empty()) { + fresh["images"] = variant["images"].clone(); + } + } else if rows.iter().any(|row| row["variantId"] == variant["id"]) { + variants.push(variant); + } + } + set_brief_variants(brief, variants); + let dimensions = brief["dimensions"].clone(); + write_legacy_barcode_fields(brief, &mut rows, &Value::Null); + brief["dimensions"] = dimensions; + brief["barcodeEntries"] = json!(rows); + update_detail_barcode(brief); +} + +pub(in crate::jiansun) fn canvas_entry_missing(brief: &Value, template: &Value) -> Vec<&'static str> { + let filled = |field: &str| brief[field].as_str().is_some_and(|value| !value.trim().is_empty()); + [ + (filled("brandId"), "品牌"), + (filled("categoryId"), "品类"), + (template_identity(template), "模板"), + (filled("name"), "产品名称"), + (has_selected_product_image(brief), "产品图"), + (project_barcodes(brief).next().is_none() || filled(spu_field(brief)), "SPU 型号"), + (project_barcodes(brief).nth(1).is_none() || + brief["detailBarcode"].as_str().is_some_and(|selected| project_barcodes(brief).any(|code| code == selected)), "详情页出图条码"), + ] + .into_iter() + .filter_map(|(present, label)| (!present).then_some(label)) + .collect() +} + diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/brief_footer_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/brief_footer_ui.rs new file mode 100644 index 00000000..122a14cc --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/brief_footer_ui.rs @@ -0,0 +1,643 @@ +use super::super::{Duration, Instant, PhotocraftApp, Request, Tokens, Ui, Value, Workspace, json, stitch_kit, stitch_state::Tone, stitch_ui}; +use super::super::agent_panel::rect_value; +use super::super::creation_reads::wizard::{self, CreationStage, WizardFooterOutcome, WizardFooterState}; +use super::{PICKER_HEIGHT, PICKER_ROW_HEIGHT}; +use super::barcode::project_barcodes; +use super::brief::{ReadinessItem, brief_readiness, brief_variants, canvas_entry_missing, normalized_color_groups, selected_template, variant_identity}; +use super::form_widgets_ui::{edit_named, picker_height, picker_row, picker_toggle_row}; +use super::project::remember_delivery_dir; +use super::reducers::listing_status_text; +use super::review_hints::{ReviewHintItem, parse_review_hints}; +use crate::theme::agent_scale::{Type, radius, space}; +use egui::vec2; + +pub(in crate::jiansun) fn format_upload_bytes(bytes: u64) -> String { + const MB: f64 = 1024.0 * 1024.0; + if bytes >= 1024 * 1024 { + format!("{:.1} MB", bytes as f64 / MB) + } else if bytes >= 1024 { + format!("{:.0} KB", bytes as f64 / 1024.0) + } else { + format!("{bytes} B") + } +} + +pub(in crate::jiansun) fn format_eta_seconds(seconds: u64) -> String { + if seconds >= 60 { + let mins = seconds / 60; + let secs = seconds % 60; + format!("预计剩余 {mins} 分 {secs:02} 秒") + } else { + format!("预计剩余 {seconds} 秒") + } +} + +pub(in crate::jiansun) fn upload_progress_summary(progress: &Value) -> (f32, String, String) { + let uploaded = progress["uploadedBytes"].as_u64().unwrap_or(0); + let total = progress["totalBytes"].as_u64().unwrap_or(0); + let completed_chunks = progress["completedChunks"].as_u64().unwrap_or(0); + let total_chunks = progress["totalChunks"].as_u64().unwrap_or(0); + let file_index = progress["fileIndex"].as_u64().unwrap_or(0) + 1; + let total_files = progress["totalFiles"].as_u64().unwrap_or(0); + let file_name = progress["fileName"].as_str().unwrap_or(""); + let stage = match progress["stage"].as_str() { + Some("merging") => "正在合并文件", + Some("submitting") => "正在提交素材库", + _ => "正在上传成品", + }; + let fraction = if total > 0 { + (uploaded as f32 / total as f32).clamp(0.0, 1.0) + } else if total_chunks > 0 { + (completed_chunks as f32 / total_chunks as f32).clamp(0.0, 1.0) + } else { + 0.0 + }; + let percent = (fraction * 100.0).round() as u32; + let eta = progress["etaSeconds"] + .as_u64() + .map(format_eta_seconds) + .unwrap_or_else(|| "正在测算速度".to_owned()); + let headline = if total_files > 0 { + format!("{stage} · {percent}%(第 {file_index}/{total_files} 个 · {eta})") + } else { + format!("{stage} · {percent}%({eta})") + }; + let detail = if total > 0 && total_chunks > 0 { + format!( + "{} / {} · 分片 {completed_chunks}/{total_chunks}{}", + format_upload_bytes(uploaded), + format_upload_bytes(total), + if file_name.is_empty() { String::new() } else { format!(" · {file_name}") } + ) + } else { + file_name.to_owned() + }; + (fraction, headline, detail) +} + +pub(in crate::jiansun) fn paint_upload_progress_bar(ui: &mut Ui, progress: &Value) { + let (fraction, headline, detail) = upload_progress_summary(progress); + let t = Tokens::get(ui.ctx()).agent(); + stitch_ui::status_label(ui, &headline, stitch_ui::StatusTone::Neutral); + let width = ui.available_width().clamp(140.0, 340.0); + let (rect, _) = ui.allocate_exact_size(vec2(width, 6.0), egui::Sense::hover()); + let painter = ui.painter(); + painter.rect_filled(rect, 3.0, t.field_border); + if fraction > 0.0 { + let mut fill = rect; + fill.set_width((rect.width() * fraction).max(6.0).min(rect.width())); + painter.rect_filled(fill, 3.0, t.accent); + } + if !detail.is_empty() { + stitch_kit::caption(ui, &detail); + } +} + +impl Workspace { + pub(in crate::jiansun) 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 delivered = self.project_context["materialDelivery"]["materialId"].is_string() + && self.project_context["status"] == "completed"; + let uploading = self.busy.as_deref() == Some("project-sync"); + let (label, role) = if delivered { + ("上架状态", stitch_ui::ButtonRole::Secondary) + } else if uploading { + ("上传中…", stitch_ui::ButtonRole::Secondary) + } else { + ("完结", stitch_ui::ButtonRole::Primary) + }; + let button = stitch_ui::action_button(ui, label, role, delivered || uploading || (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.delivery_completion = false; + self.listing_read_at = None; + self.listing_read_error = None; + } + if uploading && !self.sync_confirm { + if let Some(progress) = &self.delivery_upload_progress { + paint_upload_progress_bar(ui, progress); + } else { + stitch_ui::status_label(ui, "正在准备上传成品…", stitch_ui::StatusTone::Neutral); + } + } + if self.sync_confirm && self.project_context["cloudLink"]["source"] == "desktop" + && let Some(doc) = app.session.active().map(|state| state.doc.id.0) + { + let now = Instant::now(); + if self.listing_read_at.is_none_or(|(last_doc, next)| last_doc != doc || now >= next) { + self.listing_read_at = Some((doc, now + Duration::from_secs(15))); + if self.tx.send(Request::Action("delivery-status".into(), json!({"doc":doc}))).is_err() { + self.listing_read_error = Some("本机服务已停止,请重启后查看".into()); + } + } + ui.ctx().request_repaint_after(Duration::from_secs(15)); + } + let receipt = &self.project_context["materialDelivery"]; + let completion_receipt = self.delivery_completion && receipt["materialId"].is_string(); + let confirming = !delivered && !completion_receipt; + let title = if completion_receipt { + "成品已提交素材库" + } else if delivered { + "上架状态" + } else { + "完结项目" + }; + let mut jump_target: Option = None; + let review_hints = self.collect_delivery_review_hints(ui); + let closed = stitch_ui::dialog(ui, egui::Id::unique("xiaoyi-finish-project"), title, + self.sync_confirm, self.reduce_motion, 380.0, |ui| { + if uploading { + if let Some(progress) = &self.delivery_upload_progress { + paint_upload_progress_bar(ui, progress); + } else { + stitch_ui::status_label(ui, "正在准备上传成品…", stitch_ui::StatusTone::Neutral); + } + ui.add_space(space::XS); + } else if confirming { + ui.label("将已完成的详情、主图和 SKU 成品提交到素材库?"); + } + let barcodes: Vec<_> = project_barcodes(&self.creation_brief).collect(); + let color_groups = normalized_color_groups(&self.creation_brief); + if !barcodes.is_empty() || !color_groups.is_empty() { + let sku_summary = if !color_groups.is_empty() { + format!( + "SKU 按 <条码>.jpg 命名({} 个花色 · {} 个条码),多分辨率与同条码多图将自动按子目录隔离。", + color_groups.len(), + barcodes.len() + ) + } else { + format!( + "SKU 按 <条码>.jpg 命名({} 个条码),多分辨率与同条码多图将自动按子目录隔离。", + barcodes.len() + ) + }; + stitch_kit::caption(ui, &sku_summary); + } + if !review_hints.is_empty() { + ui.add_space(space::XS); + stitch_ui::status_label( + ui, + &format!("{} 项人工核对提示(不阻断完结)", review_hints.len()), + stitch_ui::StatusTone::Warning, + ); + egui::CollapsingHeader::new("查看人工核对清单").default_open(true).show(ui, |ui| { + egui::ScrollArea::vertical() + .id_salt("xiaoyi-review-hints-scroll") + .max_height(140.0) + .show(ui, |ui| { + for hint in &review_hints { + ui.horizontal_wrapped(|ui| { + ui.label(&hint.message); + if hint.has_target() + && stitch_ui::action_button(ui, "去核对", stitch_ui::ButtonRole::Quiet, true).clicked() + { + jump_target = Some(hint.clone()); + } + }); + } + }); + }); + } + let receipt = &self.project_context["materialDelivery"]; + if let Some(id) = receipt["materialId"].as_str() { + let (text, tone) = listing_status_text(receipt); + if receipt["state"].is_string() || self.listing_read_error.is_none() { + stitch_ui::status_label(ui, text, tone); + } + if let Some(message) = receipt["listingStatus"]["message"].as_str() + && receipt["listingStatus"]["state"] == "failed" && receipt["state"] != "removed" + { + ui.label(message); + } + ui.label(format!("素材 ID {id}")); + if let Some(listing_id) = receipt["listingStatus"]["listingId"].as_str() + && receipt["listingStatus"]["state"] == "listed" && receipt["state"] != "removed" + { + ui.label(format!("上架编号 {listing_id}")); + } + } + if let Some(error) = &self.listing_read_error { + stitch_ui::status_label(ui, "上架状态刷新失败", stitch_ui::StatusTone::Warning) + .on_hover_text(error); + } + if let Some(error) = &self.finished_web_error + && !confirming + { + stitch_ui::status_label(ui, error, stitch_ui::StatusTone::Error); + } + let target = receipt["materialId"].as_str().filter(|_| !confirming && receipt["state"] != "removed") + .zip(app.session.active().map(|state| state.doc.id.0)) + .map(|(material, doc)| json!({"materialId":material, "doc":doc})); + ui.horizontal_wrapped(|ui| { + if let Some(target) = target { + let label = if self.finished_web_pending { "正在打开…" } else { "打开成品上架工作台" }; + if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Primary, !self.finished_web_pending).clicked() { + self.finished_web_error = None; + match self.tx.send(Request::Action("finished-web-open".into(), target)) { + Ok(()) => self.finished_web_pending = true, + Err(_) => self.finished_web_error = Some("本机服务已停止,请重启后重试".into()), + } + } + } + let dismiss = if confirming { "取消" } else { "关闭" }; + if stitch_ui::action_button(ui, dismiss, stitch_ui::ButtonRole::Secondary, true).clicked() { + self.sync_confirm = false; + } + if confirming && stitch_ui::action_button(ui, "完结并提交", stitch_ui::ButtonRole::Primary, idle).clicked() { + self.sync_confirm = false; + self.sync_action(app, "project-sync", json!({"status":"completed"})); + } + }); + }); + if closed { self.sync_confirm = false; } + if let Some(target) = jump_target { + self.jump_to_review_hint(app, &target); + } + } + + pub(in crate::jiansun) fn collect_delivery_review_hints(&self, ui: &Ui) -> Vec { + let mut hints = Vec::new(); + for source in [ + &self.project_context["materialDelivery"]["reviewHints"], + &self.project_context["delivery"]["reviewHints"], + &self.project_context["reviewHints"], + &self.creation["reviewHints"], + ] { + parse_review_hints(source, &mut hints); + } + if hints.is_empty() { + let manifest_dir = self.project_context["materialDelivery"]["path"] + .as_str() + .or(self.creation_delivery_dir.as_deref()) + .map(str::trim) + .filter(|path| !path.is_empty()); + if let Some(dir) = manifest_dir { + let cache_id = egui::Id::unique(("xiaoyi-delivery-review-hints", dir)); + let cached = ui.ctx().data_mut(|data| data.get_temp::>(cache_id)); + if let Some(cached) = cached { + return cached; + } + let manifest_path = std::path::Path::new(dir).join("交付清单.json"); + if let Ok(raw) = std::fs::read_to_string(&manifest_path) + && let Ok(manifest) = serde_json::from_str::(&raw) + { + parse_review_hints(&manifest["reviewHints"], &mut hints); + } + ui.ctx().data_mut(|data| data.insert_temp(cache_id, hints.clone())); + } + } + hints + } + + + pub(in crate::jiansun) fn brief_footer_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, barcode_pending: bool) { + let template = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + let readiness = brief_readiness(&self.creation_brief, &template); + let missing_items: Vec<&ReadinessItem> = readiness.iter().filter(|item| !item.ready).collect(); + let missing = canvas_entry_missing(&self.creation_brief, &template); + let new_project = self.template_workflow["canvasFirst"] != true; + let chosen_pending = template.is_null() && self.creation_reads.resource_set["id"].is_string(); + let scoped_pending = self.scoped_production_pending(); + let setup_warning = new_project.then(|| self.brief_setup_warning()).flatten(); + + let blocked = if self.unknown { + Some(if scoped_pending { "可继续制作其余图位。" } else { "请先核查原请求,再进入模板画布。" }.to_owned()) + } else if self.busy.is_some() { + Some("请等待当前操作完成。".to_owned()) + } else if barcode_pending { + Some("请确认正在编辑的条码。".to_owned()) + } else if missing == ["模板"] && chosen_pending { + if self.creation_catalog_loading("resource-set") || self.creation_catalog_loading("resource-component") { + Some("正在核对模板资料,请稍候。".to_owned()) + } else if self.creation_reads.resource_component.is_empty() + && self.creation_catalog.get("resource-set").is_some_and(|parts| parts.len() > 1) + { + Some("请选择要使用的模板组件。".to_owned()) + } else { + Some("所选模板暂不可用,请查看模板区的提示。".to_owned()) + } + } else if !missing_items.is_empty() { + let names: Vec<&str> = missing_items.iter().map(|i| i.label.as_str()).collect(); + Some(format!("待补齐:{}", names.join("、"))) + } else { + None + }; + + // Compact single-row footer when in 3-stage wizard mode + let mut clicked_missing: Option<(String, String)> = None; + let actions_ready = self.busy.is_none() && !self.unknown && !barcode_pending; + let canvas_ready = actions_ready && missing_items.is_empty() && missing.is_empty(); + let production_ready = blocked.is_none() && setup_warning.is_none(); + let refinement = if new_project { + let doc = app.session.active().map(|state| state.doc.id.0); + let id = egui::Id::unique(("production-refinement", self.local_identity(""), doc)); + Some(ui.data(|data| data.get_temp::(id)).unwrap_or(false)) + } else { + None + }; + if self.creation_reads.wizard_stage.is_some() { + self.reference_drop_warning_ui(ui); + let resume = self.has_production_stages() || self.has_paused_production(); + let mut open_settings = false; + let mut recorded_geometries: Vec<(String, egui::Rect)> = Vec::new(); + let mut button_geometries: Vec<(WizardFooterOutcome, egui::Rect)> = Vec::new(); + let autosave_info = if self.creation_reads.staged_new_project { + ("草稿暂存中", Tone::Quiet) + } else if self.busy.as_deref() == Some("creation-save") { + ("保存中…", Tone::Quiet) + } else if self.creation_dirty { + ("有未保存修改 · 将自动保存", Tone::Warning) + } else { + ("已自动保存", Tone::Success) + }; + let key_saved = self.key_saved; + let action = wizard::wizard_footer_ui_with_status( + ui, + WizardFooterState { + stage: CreationStage::Details, + can_continue: resume, + can_enter_canvas: canvas_ready, + can_start: if resume { self.can_resume_product() } else { production_ready }, + }, + new_project || resume, + |ui| { + let hint_row = ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = space::XS; + if !missing_items.is_empty() { + stitch_kit::label(ui, "待补齐:", Type::Meta, Tone::Warning); + for item in &missing_items { + let chip = stitch_ui::action_button(ui, &item.label, stitch_ui::ButtonRole::Quiet, true) + .on_hover_text(&item.message); + recorded_geometries.push((format!("readiness-{}", item.field_key), chip.rect)); + if chip.clicked() { + clicked_missing = Some((item.field_key.clone(), item.message.clone())); + } + } + } else if let Some(msg) = blocked.as_deref() { + stitch_ui::status_label(ui, msg, stitch_ui::StatusTone::Warning); + } else { + stitch_kit::label(ui, autosave_info.0, Type::Meta, autosave_info.1); + } + if let Some((message, chip, action)) = setup_warning { + stitch_ui::status_chip(ui, chip, stitch_ui::StatusTone::Warning).on_hover_text(message); + let configure = stitch_ui::action_button(ui, action, stitch_ui::ButtonRole::Quiet, true); + recorded_geometries.push((if key_saved { "select-model" } else { "configure-personal-key" }.to_owned(), configure.rect)); + if configure.clicked() { + open_settings = true; + } + } + }); + recorded_geometries.push(("entry-hint".to_owned(), hint_row.response.rect)); + }, + |action, response| { + button_geometries.push((action, response.rect)); + }, + ); + for (k, rect) in recorded_geometries { + self.control_geometry(&k, rect); + } + for (btn_action, rect) in button_geometries { + match btn_action { + WizardFooterOutcome::EnterCanvas => self.control_geometry("enter-canvas", rect), + WizardFooterOutcome::Start => self.control_geometry(if resume { "resume-product" } else { "start-product" }, rect), + _ => {} + } + } + if open_settings { + self.open_brief_setup_settings(); + } + if let Some((key, msg)) = clicked_missing.take() { + self.focus_brief_field(&key, &msg); + } + match action { + WizardFooterOutcome::Start if resume => self.resume_product_production(app), + WizardFooterOutcome::Start | WizardFooterOutcome::EnterCanvas => { + self.enter_creation_canvas(app, &template, action == WizardFooterOutcome::Start, refinement); + } + _ => self.handle_wizard_navigation(app, action), + } + } + #[cfg(test)] + if self.creation_reads.wizard_stage.is_none() { + let hint_row = ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = space::SM; + if !missing_items.is_empty() { + stitch_kit::label(ui, "待补齐:", Type::Meta, Tone::Warning); + for item in &missing_items { + let chip = stitch_ui::action_button(ui, &item.label, stitch_ui::ButtonRole::Quiet, true) + .on_hover_text(&item.message); + self.control_geometry(&format!("readiness-{}", item.field_key), chip.rect); + if chip.clicked() { + clicked_missing = Some((item.field_key.clone(), item.message.clone())); + } + } + } else if let Some(msg) = blocked.as_deref() { + stitch_ui::status_label(ui, msg, stitch_ui::StatusTone::Warning); + } + if let Some((message, chip, action)) = setup_warning { + stitch_ui::status_chip(ui, chip, stitch_ui::StatusTone::Warning).on_hover_text(message); + let configure = stitch_ui::action_button(ui, action, stitch_ui::ButtonRole::Secondary, true); + self.control_geometry(if self.key_saved { "select-model" } else { "configure-personal-key" }, configure.rect); + if configure.clicked() { + self.open_brief_setup_settings(); + } + } + }); + self.control_geometry("entry-hint", hint_row.response.rect); + if let Some((key, msg)) = clicked_missing { + self.focus_brief_field(&key, &msg); + } + ui.horizontal_wrapped(|ui| { + self.brief_autosave_status_ui(ui); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = space::SM; + if self.has_production_stages() || self.has_paused_production() { + let resume = stitch_ui::action_button(ui, "继续整套制作", stitch_ui::ButtonRole::Primary, self.can_resume_product()); + self.control_geometry("resume-product", resume.rect); + if resume.clicked() { + self.resume_product_production(app); + } + } + self.brief_enter_button(app, ui, &template, production_ready, canvas_ready, refinement); + }); + }); + } + } + + pub(in crate::jiansun) fn brief_enter_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, template: &Value, production_ready: bool, canvas_ready: bool, refinement: Option) { + let whole_allowed = self.template_workflow["canvasFirst"] != true; + // Right-to-left parent places Primary on the far right, Secondary beside it. + let generate = whole_allowed && { + let button = stitch_ui::action_button(ui, "确认并开始制作", stitch_ui::ButtonRole::Primary, production_ready); + self.control_geometry("generate-product", button.rect); + button.clicked() + }; + let enter = stitch_ui::action_button( + ui, + "进入模板画布", + if whole_allowed { stitch_ui::ButtonRole::Secondary } else { stitch_ui::ButtonRole::Primary }, + canvas_ready, + ); + self.control_geometry("enter-canvas", enter.rect); + if enter.clicked() || generate { + self.enter_creation_canvas(app, template, generate, refinement); + } + } + + pub(in crate::jiansun) fn sku_colors_bar_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id) { + let mut variants = brief_variants(&self.creation_brief); + let draft_id = scope.with("manual-sku-color"); + let mut draft = ui.data(|data| data.get_temp::(draft_id)).unwrap_or(Value::Null); + let add_width = 76.0; + let gap = space::SM; + let add = ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = gap; + let entry = ui.scope(|ui| { + edit_named(ui, draft_id, &mut draft, (width - add_width - gap).max(120.0), false, "输入花色名称", "新增花色") + }); + self.control_geometry("sku-color-input", entry.response.rect); + let color = draft.as_str().unwrap_or("").trim(); + let duplicate = variants.iter().any(|row| row["colorName"].as_str().is_some_and(|name| name.eq_ignore_ascii_case(color))); + let enabled = !color.is_empty() && color.chars().count() <= 120 && !duplicate && variants.len() < 64; + let button = stitch_ui::action_button(ui, "添加颜色", stitch_ui::ButtonRole::Secondary, enabled) + .on_disabled_hover_text(if duplicate { "此花色已添加" } else { "请输入颜色名称,最多添加 64 个花色" }); + self.control_geometry("sku-color-add", button.rect); + button.clicked() + }).inner; + if add { + let color = draft.as_str().unwrap_or("").trim(); + variants.push(json!({"id":variant_identity(&format!("manual-sku:{color}")),"name":color,"colorName":color,"colorMaterialId":"","images":[]})); + self.save_sku_colors(variants.clone()); + draft = Value::Null; + } + ui.data_mut(|data| data.insert_temp(draft_id, draft)); + + let mut remove = None; + if !variants.is_empty() { + ui.add_space(space::XS); + ui.horizontal_wrapped(|ui| { + for variant in &variants { + let name = variant["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("原项目花色"); + let removable = self.sku_color_removable(variant); + let t = Tokens::get(ui.ctx()).agent(); + egui::Frame::NONE + .fill(t.dock) + .stroke(egui::Stroke::new(1.0, t.card_border)) + .corner_radius(egui::CornerRadius::same(radius::ROW as u8)) + .inner_margin(egui::Margin::symmetric(8, 3)) + .show(ui, |ui| { + ui.horizontal(|ui| { + let font = Type::Meta.font_id(); + let measured = ui.painter().layout_no_wrap(name.into(), font.clone(), t.text).size().x; + ui.add_sized( + vec2(measured.min((width - 42.0).max(20.0)), 22.0), + egui::Label::new(egui::RichText::new(name).font(font)).truncate(), + ) + .on_hover_text(name); + if removable && stitch_ui::icon_button(ui, "x", 20.0, false, &format!("移除 {name}")).clicked() { + remove = variant["id"].as_str().map(str::to_owned); + } + }); + }); + } + }); + } + if let Some(remove) = remove { + variants.retain(|row| row["id"] != remove); + self.save_sku_colors(variants); + } + } + + pub(in crate::jiansun) fn sku_output_picker(&mut self, ui: &mut Ui, width: f32, component: &str, variants: &[Value]) { + let mut selected = self.creation_brief["outputVariantIds"][component].as_array().cloned().unwrap_or_default(); + let summary = match selected.as_slice() { + [] if variants.is_empty() => "请先添加花色".into(), + [] => format!("全部 {} 个花色", variants.len()), + [id] => variants.iter().find(|row| row["id"] == *id).and_then(|row| row["name"].as_str()).unwrap_or("已选 1 个颜色").to_owned(), + ids => format!("已选 {} 个花色", ids.len()), + }; + let picker_id = format!("sku-output-{component}"); + let mut changed = false; + let menu_height = ((variants.len() + 1) as f32 * (PICKER_ROW_HEIGHT + ui.spacing().item_spacing.y)).min(PICKER_HEIGHT); + let result = ui.add_enabled_ui(!variants.is_empty(), |ui| picker_height(ui, &picker_id, width, menu_height, &summary, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| { + if picker_row(ui, selected.is_empty(), "全部 SKU 颜色", true).clicked() { + selected.clear(); + changed = true; + ui.close(); + } + for row in variants { + let name = row["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("原项目花色"); + let index = selected.iter().position(|id| *id == row["id"]); + let response = picker_toggle_row(ui, index.is_some(), name, index.is_none() || selected.len() > 1) + .on_disabled_hover_text("至少保留一个颜色,或选择全部 SKU 颜色"); + self.control_geometry(&format!("{picker_id}-{}", row["id"].as_str().unwrap_or("")), response.rect); + if response.clicked() { + if let Some(index) = index { selected.remove(index); } + else { selected.push(row["id"].clone()); } + changed = true; + } + } + })).inner; + self.control_geometry(&picker_id, result.response.rect); + if changed { + if !self.creation_brief["outputVariantIds"].is_object() { + self.creation_brief["outputVariantIds"] = json!({}); + } + if let Some(outputs) = self.creation_brief["outputVariantIds"].as_object_mut() { + if selected.is_empty() { outputs.remove(component); } + else { outputs.insert(component.to_owned(), json!(selected)); } + } + self.creation_dirty = true; + } + } + + + pub(in crate::jiansun) fn delivery_directory_control(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, editable: bool) { + stitch_kit::label(ui, "成品保存位置", Type::Meta, Tone::Quiet); + let path = self.creation_delivery_dir.as_deref().unwrap_or("未选择(默认仅保存到项目内)"); + ui.add(egui::Label::new(egui::RichText::new(path).font(Type::Meta.font_id())).wrap()).on_hover_text(path); + ui.horizontal_wrapped(|ui| { + let choose = stitch_ui::action_button(ui, "选择文件夹", stitch_ui::ButtonRole::Secondary, editable); + self.control_geometry("choose-delivery-directory", choose.rect); + if choose.clicked() { + let initial_dir = self.creation_delivery_dir.clone(); + let doc = self.creation_doc; + let identity = self.local_identity(""); + if let Err(error) = app.ask_file(crate::FileDialogRequest::Folder { initial_dir }, move |app, answer| { + let path = match answer { + crate::FileDialogAnswer::FolderTo(path) => path, + crate::FileDialogAnswer::Unavailable(error) => return Err(error), + _ => return Ok(Value::Null), + }; + let w = app.jiansun.as_mut().filter(|w| w.creation_doc == doc && w.local_identity("") == identity) + .ok_or("账号或项目已切换,未修改保存目录")?; + if !std::path::Path::new(&path).is_absolute() { + return Err("请选择绝对路径的成品目录".into()); + } + if app.session.active().and_then(|state| state.path.as_deref()) + .map(std::path::Path::new).and_then(std::path::Path::parent) + .is_some_and(|draft| std::path::Path::new(&path).starts_with(draft) && draft.ends_with( + w.open_projects.get(&doc.unwrap_or_default()).and_then(|id| id.rsplit('|').next()).unwrap_or_default())) + { + return Err("请选择项目草稿目录以外的位置".into()); + } + w.creation_delivery_dir = Some(path.clone()); + w.creation_dirty = true; + remember_delivery_dir(app, &path); + Ok(Value::Null) + }) { + self.error = error; + } + } + let clear = stitch_ui::action_button(ui, "清除", stitch_ui::ButtonRole::Quiet, editable && self.creation_delivery_dir.is_some()); + self.control_geometry("clear-delivery-directory", clear.rect); + if clear.clicked() { + self.creation_delivery_dir = None; + self.creation_dirty = true; + } + }); + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/form_barcode_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/form_barcode_ui.rs new file mode 100644 index 00000000..f7899a35 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/form_barcode_ui.rs @@ -0,0 +1,93 @@ +use super::super::{Ui, Workspace, json, stitch_kit, stitch_state::Tone, stitch_ui}; +use super::brief::{OUTPUT_SCOPE_OPTIONS, normalized_color_groups, selected_output_scopes, sku_display_label}; +use super::form_widgets_ui::field_group; +use crate::theme::agent_scale::{Type, control}; +use egui::vec2; + +impl Workspace { + pub(in crate::jiansun) fn detail_barcode_selector_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id, codes: &[String]) { + let current = self.creation_brief["detailBarcode"].as_str().unwrap_or("").to_owned(); + let selected_label = if current.is_empty() { + "请选择详情主款".to_owned() + } else { + sku_display_label(&self.creation_brief, ¤t) + }; + let error = self.creation_reads.inline_errors.get("detail-barcode").cloned(); + let scroll = self.creation_reads.scroll_to_field.as_deref() == Some("detail-barcode"); + if scroll { + self.creation_reads.scroll_to_field = None; + } + field_group(ui, width, "详情主款 *", |ui| { + let picker = stitch_ui::halo_select_with_behavior( + ui, + scope.with("detail-barcode"), + width, + &selected_label, + self.reduce_motion, + egui::PopupCloseBehavior::CloseOnClickOutside, + |ui| { + egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { + for (index, code) in codes.iter().enumerate() { + let display = sku_display_label(&self.creation_brief, code); + let option = stitch_ui::select_option_sized(ui, &display, code == ¤t, true, vec2(ui.available_width(), control::STANDARD)); + self.control_geometry(&format!("detail-barcode-option-{index}"), option.rect); + if option.clicked() { + self.creation_brief["detailBarcode"] = json!(code); + self.creation_reads.inline_errors.remove("detail-barcode"); + if let Some(color) = normalized_color_groups(&self.creation_brief) + .into_iter() + .find(|g| g.skus.iter().any(|s| s.barcode == *code)) + .map(|g| g.color_name) + { + self.creation_brief["colorName"] = json!(color); + } else if self.creation_brief["source"] == "product_platform" { + self.creation_brief["colorName"] = json!(self.creation_brief["platformFacts"]["barcodes"][code.as_str()]["colorName"].as_str().unwrap_or("")); + } + self.creation_dirty = true; + ui.close(); + } + } + }); + }, + ); + if scroll { + picker.response.scroll_to_me(Some(egui::Align::Center)); + picker.response.request_focus(); + } + self.control_geometry("detail-barcode", picker.response.rect); + if let Some(err) = error.as_deref() { + stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error); + } + }); + } + + + pub(in crate::jiansun) fn output_tags_ui(&mut self, ui: &mut Ui) { + let mut scopes = selected_output_scopes(&self.creation_brief); + let mut changed = false; + ui.horizontal_wrapped(|ui| { + stitch_kit::label(ui, "输出内容", Type::Meta, Tone::Quiet); + for (control_id, scope_key, label) in OUTPUT_SCOPE_OPTIONS { + let selected = scopes.iter().any(|item| item == scope_key); + let enabled = !selected || scopes.len() > 1; + let response = stitch_ui::toggle_option(ui, label, selected, enabled) + .on_disabled_hover_text("至少保留一项输出内容"); + self.control_geometry(control_id, response.rect); + if response.clicked() { + if selected { + scopes.retain(|item| item != scope_key); + } else { + scopes.push(scope_key.to_owned()); + } + changed = true; + } + } + }); + if changed { + self.creation_brief["outputScopes"] = json!(scopes); + self.creation_reads.manual_edited_fields.insert("outputScopes".into()); + self.creation_dirty = true; + } + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/form_identity_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/form_identity_ui.rs new file mode 100644 index 00000000..435fb213 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/form_identity_ui.rs @@ -0,0 +1,437 @@ +use super::super::{PhotocraftApp, Tokens, Ui, Value, Workspace, json, stitch_kit, stitch_state::Tone, stitch_ui}; +use super::brief::{NormalizedProductSummary, brief_variants, normalized_product_summary}; +use super::form_widgets_ui::{IntakeScope, edit_named, edit_named_with_error, field_group, field_kind, intake_fields_with_errors, intake_hint, is_product_name_field, reveal_template_intake, spu_field}; +use crate::theme::agent_scale::{Type, radius, space}; +use egui::vec2; + +impl Workspace { + pub(in crate::jiansun) fn creation_notices_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + if !self.error.is_empty() { + super::operation_error::details(ui, egui::Id::unique("creation-operation-error"), &self.error, self.reduce_motion, None); + ui.add_space(space::SM); + } + if !self.creation_progress.is_empty() { + stitch_ui::disclosure(ui, egui::Id::unique("creation-progress"), if self.busy.is_some() { "处理中…" } else { "最近结果" }, false, self.reduce_motion, |ui| { + ui.label(&self.creation_progress); + }); + ui.add_space(space::SM); + } + if self.unknown { + ui.horizontal_wrapped(|ui| { + stitch_ui::status_chip(ui, "原请求待核查", stitch_ui::StatusTone::Warning); + if ui.add_enabled_ui(self.busy.is_none(), |ui| stitch_ui::button(ui, "核查原结果", false)).inner.clicked() { + self.recover(app); + } + if self.creation["generation"]["screens"].as_object().is_some_and(|m| !m.is_empty()) + && ui.add_enabled_ui(self.busy.is_none(), |ui| stitch_ui::button(ui, "载入已有结果", false)).inner.clicked() + { + self.creation_submit(app, "creation-load", json!({})); + } + }); + ui.add_space(space::SM); + } + } + + pub(in crate::jiansun) fn brief_autosave_status_ui(&self, ui: &mut Ui) { + let (text, tone) = if self.creation_reads.staged_new_project { + ("草稿暂存中", Tone::Quiet) + } else if self.busy.as_deref() == Some("creation-save") { + ("保存中…", Tone::Quiet) + } else if self.creation_dirty { + ("有未保存修改 · 将自动保存", Tone::Warning) + } else { + ("已自动保存", Tone::Success) + }; + stitch_kit::label(ui, text, Type::Meta, tone); + } + + + pub(in crate::jiansun) fn unmatched_platform_taxonomy_chips_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, np: &NormalizedProductSummary) { + let cur_brand = self.creation_brief["brandName"].as_str().unwrap_or("").trim(); + let cur_cat = self.creation_brief["categoryName"].as_str().unwrap_or("").trim(); + let brand_unmatched = !np.platform_brand.is_empty() && !cur_brand.eq_ignore_ascii_case(&np.platform_brand); + let cat_unmatched = !np.platform_category.is_empty() && !cur_cat.eq_ignore_ascii_case(&np.platform_category); + if !brand_unmatched && !cat_unmatched { + return; + } + ui.horizontal_wrapped(|ui| { + stitch_kit::label(ui, "平台分类参考:", Type::Meta, Tone::Quiet); + if brand_unmatched { + let brands = self.creation_catalog.get("brands").cloned().unwrap_or_default(); + let matched = brands.iter().find(|row| { + row["ready"] == true + && row["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&np.platform_brand) || n.contains(&np.platform_brand)) + }); + let label = if matched.is_some() { + format!("应用品牌:{}", np.platform_brand) + } else { + format!("平台品牌:{}(待选择对应品牌)", np.platform_brand) + }; + let chip = stitch_ui::action_button(ui, &label, stitch_ui::ButtonRole::Quiet, true); + self.control_geometry("platform-brand-hint", chip.rect); + if chip.clicked() { + if let Some(row) = matched { + self.creation_brief["brandId"] = row["id"].clone(); + self.creation_brief["brandName"] = row["name"].clone(); + self.creation_brief["categoryId"] = json!(""); + self.creation_brief["categoryName"] = json!(""); + self.creation_brief["templateSelection"] = Value::Null; + self.creation_catalog.remove("categories"); + self.creation_catalog.remove("templates"); + self.catalog(app, "categories", String::new()); + self.creation_reads.inline_errors.remove("brand"); + self.creation_reads.manual_edited_fields.insert("brand".into()); + self.creation_dirty = true; + } else { + self.focus_brief_field("brand", &format!("请在品牌列表中选择与「{}」对应的品牌", np.platform_brand)); + } + } + } + if cat_unmatched { + let brand_id = self.creation_brief["brandId"].as_str().unwrap_or("").to_owned(); + let categories = self.creation_catalog.get("categories").cloned().unwrap_or_default(); + let matched = categories.iter().find(|row| { + row["brandId"] == brand_id + && row["ready"] == true + && row["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&np.platform_category) || n.contains(&np.platform_category)) + }); + let label = if matched.is_some() { + format!("应用品类:{}", np.platform_category) + } else { + format!("平台品类:{}(待选择对应品类)", np.platform_category) + }; + let chip = stitch_ui::action_button(ui, &label, stitch_ui::ButtonRole::Quiet, true); + self.control_geometry("platform-category-hint", chip.rect); + if chip.clicked() { + if let Some(row) = matched { + self.creation_brief["categoryId"] = row["id"].clone(); + self.creation_brief["categoryName"] = row["name"].clone(); + self.creation_brief["templateSelection"] = Value::Null; + self.creation_catalog.remove("templates"); + self.creation_reads.inline_errors.remove("category"); + self.creation_reads.manual_edited_fields.insert("category".into()); + self.creation_dirty = true; + } else { + self.focus_brief_field("category", &format!("请在品类列表中选择与「{}」对应的品类", np.platform_category)); + } + } + } + }); + } + + pub(in crate::jiansun) fn core_identity_and_specs_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32) { + #[cfg(test)] + let dynamic = self.creation_brief["intake"]["schema"]["version"] == 1; + let platform = self.creation_brief["source"] == "product_platform"; + let gap = space::MD; + let show_spu_here = !platform || self.creation_reads.wizard_stage.is_some(); + + // Row 1: Product Name + SPU (2 columns >= 560px, 1 column narrow) + if show_spu_here && width >= 560.0 { + let spu_w = (width * 0.36).clamp(180.0, 300.0); + let name_w = (width - spu_w - gap).max(160.0); + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = gap; + self.product_name_field_ui(ui, field_scope, name_w); + self.spu_identifier_field_ui(ui, field_scope, spu_w); + }); + } else { + self.product_name_field_ui(ui, field_scope, width); + if show_spu_here { + ui.add_space(space::SM); + self.spu_identifier_field_ui(ui, field_scope, width); + } + } + + #[cfg(test)] + stitch_ui::morph_surface(ui, field_scope.with("dimensions-reveal"), !dynamic && self.creation_reads.wizard_stage.is_none(), self.reduce_motion, |ui| { + ui.add_space(space::SM); + self.dimensions_row_ui(ui, field_scope, width); + }); + + // Clean Platform Specs & Copy summary (materials, key attributes, selling points) + let np = normalized_product_summary(&self.creation_brief); + if np.has_platform_data && (!np.materials.is_empty() || !np.attributes.is_empty() || !np.summary.is_empty() || !np.selling_points.is_empty()) { + ui.add_space(space::SM); + self.platform_archive_summary_ui(ui, field_scope, width, &np); + } + + // Dynamic template productFields (with inline error + scroll-to-field support) + let product_fields = self.creation_brief["intake"]["schema"]["productFields"].clone(); + self.poll_imported_reference_previews(app, ui.ctx()); + let image_fields = product_fields.as_array().into_iter().flatten() + .filter(|field| field_kind(field) == "image").collect::>(); + let product_fields = product_fields.as_array().into_iter().flatten() + .filter(|field| field_kind(field) != "image" && !is_product_name_field(field)).collect::>(); + reveal_template_intake(ui, field_scope.with("product-intake-reveal"), + !product_fields.is_empty() || !image_fields.is_empty(), self.reduce_motion, |ui| { + ui.add_space(space::MD); + stitch_kit::label(ui, "模板商品字段", Type::Body, Tone::Active); + ui.add_space(space::XS); + let mut values = self.creation_brief["intake"]["productValues"].clone(); + if !values.is_object() { values = json!({}); } + if intake_fields_with_errors( + ui, + field_scope.with("intake-product"), + width, + &product_fields, + IntakeScope::Product, + &mut values, + self.reduce_motion, + None, + &mut self.creation_reads.inline_errors, + &mut self.creation_reads.scroll_to_field, + &mut self.creation_reads.manual_edited_fields, + ) { + self.creation_brief["intake"]["productValues"] = values; + self.creation_dirty = true; + } + for field in image_fields { + ui.add_space(space::SM); + self.image_slot_ui(app, ui, width, field, None); + } + }); + } + + pub(in crate::jiansun) fn product_name_field_ui(&mut self, ui: &mut Ui, field_scope: egui::Id, field_width: f32) { + let error = self.creation_reads.inline_errors.get("name").cloned(); + let scroll = self.creation_reads.scroll_to_field.as_deref() == Some("name"); + if scroll { + self.creation_reads.scroll_to_field = None; + } + let hint = self.creation_brief["intake"]["schema"]["productFields"].as_array().into_iter().flatten() + .find(|field| is_product_name_field(field)).map(intake_hint).filter(|hint| !hint.is_empty()) + .unwrap_or("输入当前商品名称").to_owned(); + field_group(ui, field_width, "产品名称 *", |ui| { + let field = ui.scope(|ui| { + edit_named_with_error( + ui, + (field_scope, "name"), + &mut self.creation_brief["name"], + field_width, + false, + &hint, + "产品名称", + error.as_deref(), + scroll, + ).0 + }); + if field.inner { + self.creation_dirty = true; + self.creation_reads.inline_errors.remove("name"); + self.creation_reads.manual_edited_fields.insert("name".into()); + } + self.control_geometry("name", field.response.rect); + }); + } + + pub(in crate::jiansun) fn spu_identifier_field_ui(&mut self, ui: &mut Ui, field_scope: egui::Id, field_width: f32) { + let error = self.creation_reads.inline_errors.get("identifier").cloned(); + let scroll = self.creation_reads.scroll_to_field.as_deref() == Some("identifier"); + if scroll { + self.creation_reads.scroll_to_field = None; + } + field_group(ui, field_width, "SPU 型号", |ui| { + let field_name = spu_field(&self.creation_brief); + let mut spu = self.creation_brief[field_name].clone(); + let field = ui.scope(|ui| { + edit_named_with_error( + ui, + (field_scope, "identifier"), + &mut spu, + field_width, + false, + "输入 SPU 型号", + "SPU 型号", + error.as_deref(), + scroll, + ).0 + }); + if field.inner { + self.creation_brief[field_name] = spu; + self.creation_dirty = true; + self.creation_reads.inline_errors.remove("identifier"); + } + if field_name == "deliverySpu" + && let Some(legacy) = self.creation_brief["identifier"].as_str().filter(|value| !value.is_empty()) + { + stitch_kit::caption(ui, format!("原项目编号 {legacy}")); + } + self.control_geometry("identifier", field.response.rect); + }); + } + + + pub(in crate::jiansun) fn platform_archive_summary_ui(&mut self, ui: &mut Ui, field_scope: egui::Id, width: f32, np: &NormalizedProductSummary) { + let t = Tokens::get(ui.ctx()).agent(); + let frame = egui::Frame::NONE + .fill(t.dock) + .stroke(egui::Stroke::new(1.0, t.card_border)) + .corner_radius(egui::CornerRadius::same(radius::CONTROL as u8)) + .inner_margin(egui::Margin::same(space::MD as i8)); + frame.show(ui, |ui| { + let inner_width = (width - 2.0 * space::MD - 2.0).max(160.0); + ui.set_width(inner_width); + ui.spacing_mut().item_spacing.y = space::XS; + ui.horizontal_wrapped(|ui| { + stitch_kit::label(ui, "平台规格与卖点摘要", Type::Meta, Tone::Active); + if !np.series_or_model.is_empty() { + stitch_kit::label(ui, format!("系列:{}", np.series_or_model), Type::Meta, Tone::Quiet); + } + if let Some(dims) = np.dimensions_display.as_deref() { + stitch_kit::label(ui, format!("参考尺寸:{dims}"), Type::Meta, Tone::Quiet); + } + }); + if !np.materials.is_empty() { + ui.horizontal_wrapped(|ui| { + stitch_kit::label(ui, "材质:", Type::Meta, Tone::Quiet); + stitch_kit::label(ui, np.materials.join(" · "), Type::Meta, Tone::Active); + }); + } + if !np.attributes.is_empty() { + let preview_count = 6usize; + let cols = if inner_width >= 520.0 { 2 } else { 1 }; + let col_w = (inner_width - space::MD * (cols - 1) as f32) / cols as f32; + egui::Grid::new(field_scope.with("platform-attrs")) + .num_columns(cols) + .min_col_width(col_w) + .spacing(vec2(space::MD, space::XXS)) + .show(ui, |ui| { + for (idx, (label, value)) in np.attributes.iter().take(preview_count).enumerate() { + ui.horizontal_wrapped(|ui| { + ui.set_max_width(col_w); + stitch_kit::label(ui, format!("{label}:"), Type::Meta, Tone::Quiet); + stitch_kit::label(ui, value, Type::Meta, Tone::Active); + }); + if (idx + 1) % cols == 0 { + ui.end_row(); + } + } + }); + if np.attributes.len() > preview_count { + stitch_ui::disclosure(ui, field_scope.with("platform-attrs-more"), &format!("查看全部 {} 项规格参数", np.attributes.len()), false, self.reduce_motion, |ui| { + for (label, value) in np.attributes.iter().skip(preview_count) { + ui.horizontal_wrapped(|ui| { + stitch_kit::label(ui, format!("{label}:"), Type::Meta, Tone::Quiet); + stitch_kit::label(ui, value, Type::Meta, Tone::Active); + }); + } + }); + } + } + if !np.summary.is_empty() { + ui.add(egui::Label::new(egui::RichText::new(&np.summary).font(Type::Meta.font_id()).color(t.text_dim)).wrap()); + } + if !np.selling_points.is_empty() { + let shown = 3usize; + for point in np.selling_points.iter().take(shown) { + ui.add(egui::Label::new(egui::RichText::new(format!("· {point}")).font(Type::Meta.font_id()).color(t.text)).wrap()); + } + if np.selling_points.len() > shown { + stitch_ui::disclosure(ui, field_scope.with("platform-points-more"), &format!("展开其余 {} 条卖点", np.selling_points.len() - shown), false, self.reduce_motion, |ui| { + for point in np.selling_points.iter().skip(shown) { + ui.add(egui::Label::new(egui::RichText::new(format!("· {point}")).font(Type::Meta.font_id()).color(t.text)).wrap()); + } + }); + } + } + }); + } + + + pub(in crate::jiansun) fn template_and_brand_block_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { + let gap = space::MD; + if width >= 520.0 { + let column = (width - gap) / 2.0; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = gap; + field_group(ui, column, "品牌 *", |ui| self.brand_select(app, ui, column)); + field_group(ui, column, "品类 *", |ui| self.category_select(app, ui, column)); + }); + } else { + field_group(ui, width, "品牌 *", |ui| self.brand_select(app, ui, width)); + ui.add_space(space::SM); + field_group(ui, width, "品类 *", |ui| self.category_select(app, ui, width)); + } + ui.add_space(space::SM); + field_group(ui, width, "模板 *", |ui| self.template_select(app, ui, width)); + } + + pub(in crate::jiansun) fn advanced_export_settings_ui(&mut self, _app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32, _editable: bool) { + let variants = brief_variants(&self.creation_brief); + let has_variant_subsets = variants.len() > 1; + let has_legacy_sku = self.creation_brief.get("barcodeBindings").is_none(); + if !has_variant_subsets && !has_legacy_sku { + return; + } + let disclosure = stitch_ui::disclosure(ui, field_scope.with("advanced-export-settings"), "高级导出设置(选填)", false, self.reduce_motion, |ui| { + ui.spacing_mut().item_spacing.y = space::SM; + if has_variant_subsets { + ui.add_space(space::XS); + stitch_kit::label(ui, "指定出图花色范围", Type::Meta, Tone::Quiet); + let fields = [("detail", "详情图颜色"), ("main_images", "主图颜色")]; + let inner_w = width.min(ui.available_width()).max(120.0); + if inner_w >= 520.0 { + let column = (inner_w - space::MD) / 2.0; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = space::MD; + for (key, label) in fields { + field_group(ui, column, label, |ui| self.sku_output_picker(ui, column, key, &variants)); + } + }); + } else { + for (key, label) in fields { + field_group(ui, inner_w, label, |ui| self.sku_output_picker(ui, inner_w, key, &variants)); + } + } + } + if has_legacy_sku { + ui.add_space(space::XS); + stitch_ui::disclosure(ui, field_scope.with("legacy-sku-bindings"), "旧项目商品编号", false, self.reduce_motion, |ui| { + let mut list = variants.clone(); + if list.is_empty() { + list.push(json!({"id":"default","name":"当前花色"})); + } + let inner_w = ui.available_width(); + for variant in list { + let Some(id) = variant["id"].as_str() else { continue }; + let name = variant["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("当前花色"); + let label = format!("{name} · SKU 编号"); + let mut binding = self.creation_brief["skuBindings"][id].clone(); + if field_group(ui, inner_w, &label, |ui| { + edit_named(ui, field_scope.with(("delivery-skus", id)), &mut binding, inner_w, false, "多个 SKU 用逗号分隔", &label) + }).inner { + self.creation_brief["skuBindings"][id] = binding; + self.creation_dirty = true; + } + } + }); + } + }); + self.control_geometry("advanced-export-settings", disclosure.rect); + } + + pub(in crate::jiansun) fn special_requirements_ui(&mut self, ui: &mut Ui, scope: egui::Id) { + let width = ui.available_width(); + let group = field_group(ui, width, "制作要求与重点(选填)", |ui| { + let (edited, resp) = edit_named_with_error( + ui, + (scope, "note"), + &mut self.creation_brief["note"], + width, + true, + "可补充核心卖点侧重、画面风格、禁用元素或场景偏好,无特殊要求可留空。", + "制作要求与重点", + None, + false, + ); + if edited { + self.creation_dirty = true; + self.creation_reads.manual_edited_fields.insert("note".into()); + } + self.control_geometry("special-requirements-input", resp.rect); + }); + self.control_geometry("special-requirements", group.response.rect); + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/form_widgets_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/form_widgets_ui.rs new file mode 100644 index 00000000..86f5864e --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/form_widgets_ui.rs @@ -0,0 +1,584 @@ +use super::super::{PhotocraftApp, Tokens, Ui, Value, Workspace, agent_panel::rect_value, json, stitch_kit, stitch_ui}; +use super::super::creation_reads::wizard::{CreationStage, WizardFooterOutcome}; +use super::{MATERIAL_THUMB_SIDE, PICKER_HEIGHT, PICKER_ROW_HEIGHT}; +use super::barcode::project_barcodes; +use super::brief::non_empty_str; +use super::intake::BARCODE_HINT; +use super::structure_preview_ui::paint_template_structure; +use crate::theme::agent_scale::{Type, control, space}; +use egui::vec2; +use std::collections::{HashMap, HashSet}; + +pub(crate) fn creation_escape_active(app: &PhotocraftApp) -> bool { + app.jiansun.as_ref().is_some_and(|workspace| + workspace.creation_open && workspace.creation_step != 3 && !workspace.library && !workspace.material) +} + +/// Constrain the native ComboBox before its first measuring pass. Its default +/// popup extends labels and shrinks loading content to one row, producing a +/// different menu on first open and after the asynchronous catalogue arrives. +pub(in crate::jiansun) fn picker(ui: &mut Ui, id: &str, width: f32, selected: &str, contents: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse> { + picker_height(ui, id, width, PICKER_HEIGHT, selected, egui::PopupCloseBehavior::CloseOnClick, contents) +} + +pub(in crate::jiansun) fn picker_height(ui: &mut Ui, id: &str, width: f32, height: f32, selected: &str, close_behavior: egui::PopupCloseBehavior, contents: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse> { + ui.scope(|ui| { + ui.set_width(width); + let t = Tokens::get(ui.ctx()).agent(); + ui.spacing_mut().interact_size.y = 34.0; + ui.spacing_mut().button_padding = vec2(10.0, 7.0); + let visuals = ui.visuals_mut(); + visuals.widgets.inactive.corner_radius = egui::CornerRadius::same(9); + visuals.widgets.hovered.corner_radius = egui::CornerRadius::same(9); + visuals.widgets.inactive.weak_bg_fill = t.field; + visuals.widgets.inactive.bg_stroke = egui::Stroke::new(1.0, t.field_border); + stitch_ui::halo_select_with_behavior(ui, id, width, selected, ui.style().animation_time == 0.0, close_behavior, |ui| { + // Reserve the same scrollbar gutter before and after data arrives. + ui.set_width( + (width - ui.spacing().menu_margin.sum().x - ui.spacing().scroll.allocated_width() - ui.spacing().scroll.content_margin.sum().x).max(120.0), + ); + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + egui::ScrollArea::vertical().max_height(height).min_scrolled_height(height) + .auto_shrink([false, true]).show(ui, contents).inner + }, + ) + }) + .inner +} + +pub(in crate::jiansun) fn picker_row(ui: &mut Ui, selected: bool, label: &str, enabled: bool) -> egui::Response { + // add_sized centers its child and reports the text's intrinsic width on the + // first sizing pass. An explicit native minimum keeps the whole left-aligned + // row the same size before and after the popup's layout cache is populated. + let size = vec2(ui.available_width(), PICKER_ROW_HEIGHT); + ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { + // The shared option inherits wrap mode; clamp long template names to + // the space left after the preview instead of widening the popup. + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + stitch_ui::select_option_sized(ui, label, selected, enabled, size) + }) + .inner +} + +pub(in crate::jiansun) fn template_picker_row(ui: &mut Ui, selected: bool, label: &str, enabled: bool, preview: Option<&Value>) -> egui::Response { + if let Some(preview) = preview { + ui.horizontal(|ui| { + let (area, thumbnail) = ui.allocate_exact_size(vec2(26.0, PICKER_ROW_HEIGHT), if enabled { egui::Sense::click() } else { egui::Sense::hover() }); + paint_template_structure(ui, preview, area.shrink(2.0)); + let thumbnail = thumbnail.on_hover_text("首屏结构示意,不含图片"); + picker_row(ui, selected, label, enabled).union(thumbnail) + }).inner + } else { + picker_row(ui, selected, label, enabled) + } +} + +pub(in crate::jiansun) fn picker_toggle_row(ui: &mut Ui, selected: bool, label: &str, enabled: bool) -> egui::Response { + let size = vec2(ui.available_width(), PICKER_ROW_HEIGHT); + ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { + stitch_ui::menu_toggle_sized(ui, label, selected, enabled, size) + }).inner +} + +pub(in crate::jiansun) fn picker_notice(ui: &mut Ui, loading: bool, error: Option<&str>, empty: bool, empty_label: &str) -> bool { + let mut retry = false; + if loading { + ui.horizontal(|ui| { + let reduced = ui.style().animation_time == 0.0; + stitch_ui::ai_loader(ui, egui::Id::unique("creation-catalog-loader"), true, reduced); + ui.label("正在读取…"); + }); + } else if let Some(error) = error { + stitch_ui::status_label(ui, "读取失败", stitch_ui::StatusTone::Error).on_hover_text(error); + retry = stitch_ui::action_button(ui, "重新读取", stitch_ui::ButtonRole::Secondary, true).clicked(); + } else if empty { + stitch_ui::status_label(ui, empty_label, stitch_ui::StatusTone::Neutral); + retry = stitch_ui::action_button(ui, "重新读取", stitch_ui::ButtonRole::Secondary, true).clicked(); + } + retry +} + +pub(in crate::jiansun) fn preview_size(size: egui::Vec2, max: egui::Vec2) -> egui::Vec2 { + if !size.is_finite() || size.x <= 0.0 || size.y <= 0.0 { + return egui::Vec2::ZERO; + } + size * (max.x / size.x).min(max.y / size.y) +} + +pub(in crate::jiansun) fn material_thumbnail(ui: &mut Ui, texture: Option<&egui::TextureHandle>, loading: bool, failed: bool) -> egui::Response { + let (rect, response) = + ui.allocate_exact_size(vec2(MATERIAL_THUMB_SIDE, MATERIAL_THUMB_SIDE), if failed { egui::Sense::click() } else { egui::Sense::hover() }); + let t = Tokens::get(ui.ctx()).agent(); + ui.painter().rect_filled(rect, t.radius_sm, t.field); + ui.painter().rect_stroke(rect, t.radius_sm, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); + if let Some(texture) = texture { + let size = preview_size(texture.size_vec2(), rect.size()); + let image_rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, rect); + ui.painter().image(texture.id(), image_rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + } else if loading { + let mut child = ui.new_child(egui::UiBuilder::new().id_salt(response.id.with("loader")).max_rect(rect.shrink(3.0))); + child.set_clip_rect(rect.intersect(ui.clip_rect())); + let reduced = ui.style().animation_time == 0.0; + stitch_ui::ai_loader(&mut child, response.id.with("loader"), true, reduced); + } else if failed { + crate::icons::paint(ui, rect.shrink(8.0), "triangle-alert", 14.0, t.text_dim); + } + response +} + + +pub(in crate::jiansun) fn edit(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &mut Value, width: f32, multiline: bool, name: &str) -> bool { + edit_named(ui, id, value, width, multiline, "", name) +} + +#[derive(Clone, Default)] +pub(in crate::jiansun) struct MaterialSearchPending { query: String, changed_at: f64, pub(in crate::jiansun) pending: bool } + +pub(in crate::jiansun) fn material_search_due(state: &mut MaterialSearchPending, query: &str, changed: bool, enter: bool, now: f64) -> bool { + if changed { + state.query = query.to_owned(); + state.changed_at = now; + state.pending = true; + } + if enter || (state.pending && (query.is_empty() || now - state.changed_at >= 0.3)) { + state.pending = false; + return true; + } + false +} + + +pub(in crate::jiansun) fn edit_named(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &mut Value, width: f32, multiline: bool, hint: &str, name: &str) -> bool { + edit_named_with_error(ui, id, value, width, multiline, hint, name, None, false).0 +} + +pub(in crate::jiansun) fn edit_named_with_error( + ui: &mut Ui, + id: impl std::hash::Hash + std::fmt::Debug, + value: &mut Value, + width: f32, + multiline: bool, + hint: &str, + name: &str, + error: Option<&str>, + focus_and_scroll: bool, +) -> (bool, egui::Response) { + let mut text = match value { + Value::String(text) => text.clone(), + Value::Number(number) => number.to_string(), + _ => String::new(), + }; + let hint = egui::RichText::new(hint).color(Tokens::get(ui.ctx()).agent().text_dim); + let mut field = stitch_ui::text_input(&mut text, "", multiline).hint_text(hint); + if multiline { + field = field.desired_rows(3); + } + let response = form_editor_with_error(ui, id, field, width, name, error); + if focus_and_scroll { + response.scroll_to_me(Some(egui::Align::Center)); + response.request_focus(); + } + let changed = response.changed(); + if changed { *value = json!(text); } + (changed, response) +} + +pub(in crate::jiansun) fn form_editor_with_error( + ui: &mut Ui, + id: impl std::hash::Hash + std::fmt::Debug, + field: egui::TextEdit<'_>, + width: f32, + name: &str, + error: Option<&str>, +) -> egui::Response { + // Halo Field consumes 10pt inner margin plus its 1pt stroke on each side. + let content_width = (width - 22.0).max(0.0); + let editor = creation_editor_id(ui, id); + let field = field.desired_width(content_width).id(editor).frame(egui::Frame::NONE); + let reduced = ui.style().animation_time == 0.0; + stitch_ui::halo_field(ui, editor.with("halo"), error, reduced, |ui| ui.add(field).accessible_name(name)) +} + +pub(in crate::jiansun) fn creation_editor_id(ui: &Ui, id: impl std::hash::Hash + std::fmt::Debug) -> egui::Id { + let editor = egui::Id::unique("creation-field").with(id).with("editor"); + ui.data_mut(|data| data.get_temp_mut_or_default::>(egui::Id::unique("creation-active-editors")).push(editor)); + editor +} + +pub(in crate::jiansun) fn wizard_barcode_editor(ui: &mut Ui, id: egui::Id, value: &mut String) -> egui::Response { + stitch_kit::caption(ui, "条码编码"); + let id = creation_editor_id(ui, id); + let reduced = ui.style().animation_time == 0.0; + stitch_ui::halo_field(ui, id.with("halo"), None, reduced, |ui| { + ui.add(stitch_ui::text_input(value, BARCODE_HINT, true).id(id).return_key(None) + .desired_rows(1).font(Type::Body.font_id()).frame(egui::Frame::NONE) + .margin(egui::Margin::ZERO).desired_width(ui.available_width())).accessible_name("条码编码") + }) +} + +pub(in crate::jiansun) fn field_group(ui: &mut Ui, width: f32, label: &str, contents: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse { + ui.vertical(|ui| { + ui.set_width(width); + ui.spacing_mut().item_spacing.y = space::XS + space::XXS; + ui.label(egui::RichText::new(label).font(Type::Meta.font_id()).color(Tokens::get(ui.ctx()).agent().text_dim)); + contents(ui) + }) +} + +pub(in crate::jiansun) fn intake_columns(width: f32) -> usize { + if width >= 420.0 { 3 } else if width >= 152.0 { 2 } else { 1 } +} + +pub(in crate::jiansun) fn product_intake_columns(width: f32) -> usize { + if width >= 560.0 { 2 } else { 1 } +} + +pub(in crate::jiansun) fn is_product_name_field(field: &Value) -> bool { + field["type"] == "text" + && field["label"].as_str().is_some_and(|label| { + matches!(label.trim().trim_end_matches(['*', '*']).trim(), "产品名称" | "产品名" | "商品名称" | "商品名") + }) +} + +pub(in crate::jiansun) fn intake_multiline(field: &Value) -> bool { + field["type"] == "text" && field["multiline"].as_bool().unwrap_or_else(|| { + matches!(field["label"].as_str().map(str::trim), + Some("核心卖点" | "产品卖点" | "卖点描述" | "注意事项" | "产品描述" | "产品介绍" | "使用说明")) + }) +} + +pub(in crate::jiansun) fn intake_hint(field: &Value) -> &str { + ["placeholder", "hint", "example", "promptHint", "description", "help"].into_iter() + .filter_map(|key| non_empty_str(&field[key])) + .find(|hint| *hint != "按本款确认资料填写;尺寸注明单位,暂无资料可留空。") + .unwrap_or(match field_kind(field).as_str() { + Some("number") => "数字", + Some("select") => "请选择", + Some("image") => "拖放图片或点击选择", + _ => "", + }) +} + +pub(in crate::jiansun) fn reveal_template_intake(ui: &mut Ui, id: egui::Id, open: bool, reduced: bool, contents: impl FnOnce(&mut Ui)) { + let height_id = id.with("intake-height"); + stitch_ui::morph_surface(ui, id, open, reduced, |ui| { + if open { + contents(ui); + let height = ui.min_rect().height(); + ui.data_mut(|data| data.insert_temp(height_id, height)); + } else if let Some(height) = ui.data(|data| data.get_temp::(height_id)) { + // Field definitions can disappear when a template is cleared. Keep + // the measured space while it collapses without mounting stale fields. + ui.add_space(height); + } + }); +} + +#[derive(Clone, Copy)] +pub(in crate::jiansun) enum IntakeScope { + Product, + Barcode, +} + + +#[allow(clippy::too_many_arguments)] +pub(in crate::jiansun) fn intake_fields_with_errors( + ui: &mut Ui, + scope: egui::Id, + width: f32, + fields: &[&Value], + kind: IntakeScope, + values: &mut Value, + reduced: bool, + barcode: Option<&str>, + inline_errors: &mut HashMap, + scroll_to_field: &mut Option, + manual_edited: &mut HashSet, +) -> bool { + let (columns, gap) = match kind { + IntakeScope::Product => (product_intake_columns(width), space::MD), + IntakeScope::Barcode => (intake_columns(width), space::SM), + }; + let spans_row = |field: &Value| match kind { + IntakeScope::Product => intake_multiline(field), + IntakeScope::Barcode => !matches!(field["type"].as_str(), Some("number" | "select" | "boolean")), + }; + let column_width = (width - gap * (columns - 1) as f32) / columns as f32; + let mut changed = false; + ui.scope(|ui| { + ui.spacing_mut().item_spacing.y = space::MD; + let mut remaining = fields; + while let Some((first, _)) = remaining.split_first() { + let full_width = spans_row(first); + let count = if full_width { 1 } else { + remaining.iter().take(columns).take_while(|field| !spans_row(field)).count() + }; + let (row, rest) = remaining.split_at(count); + let field_width = if full_width { width } else { column_width }; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = gap; + let label_height = row.iter().map(|field| ui.painter().layout( + intake_label(field), Type::Meta.font_id(), Tokens::get(ui.ctx()).agent().text_dim, field_width, + ).size().y).fold(0.0_f32, f32::max); + for field in row { + let raw_hint = intake_hint(field); + let fallback; + let effective_hint = if !raw_hint.is_empty() { + raw_hint + } else { + let clean_label = field["label"].as_str().unwrap_or("").trim().trim_end_matches(['*', '*']).trim(); + fallback = match clean_label { + "" => String::new(), + "核心卖点" => "输入核心卖点、材质亮点或使用场景优势".to_owned(), + "注意事项" => "输入安装、保养或画面避坑注意事项(选填)".to_owned(), + other if field["required"] == true => format!("输入{other}"), + other => format!("输入{other}(选填)"), + }; + fallback.as_str() + }; + changed |= intake_field( + ui, scope, field_width, label_height, field, effective_hint, + values, reduced, barcode, inline_errors, scroll_to_field, manual_edited, + ); + } + }); + remaining = rest; + } + }); + changed +} + +pub(in crate::jiansun) fn intake_label(field: &Value) -> String { + let name = field["label"].as_str().or(field["id"].as_str()).unwrap_or("未命名字段"); + format!("{}{}{}", name, + field["unit"].as_str().map(|unit| format!(" ({unit})")).unwrap_or_default(), + if field["required"] == true { " *" } else { "" }) +} + +#[allow(clippy::too_many_arguments)] +pub(in crate::jiansun) fn intake_field( + ui: &mut Ui, + scope: egui::Id, + width: f32, + label_height: f32, + field: &Value, + hint: &str, + values: &mut Value, + reduced: bool, + barcode: Option<&str>, + inline_errors: &mut HashMap, + scroll_to_field: &mut Option, + manual_edited: &mut HashSet, +) -> bool { + let label = intake_label(field); + let Some(id) = field["id"].as_str().filter(|id| !id.trim().is_empty()) else { + stitch_ui::status_label(ui, &format!("{label}缺少字段编号"), stitch_ui::StatusTone::Warning); + return false; + }; + let error_key = match barcode { + Some(code) => format!("intake-barcode:{code}:{id}"), + None => format!("intake-product:{id}"), + }; + let field_error = inline_errors.get(&error_key).cloned(); + let should_scroll = scroll_to_field.as_deref() == Some(error_key.as_str()); + if should_scroll { + *scroll_to_field = None; + } + let mut changed = false; + ui.vertical(|ui| { + ui.set_width(width); + ui.spacing_mut().item_spacing.y = space::XS + space::XXS; + let text_dim = Tokens::get(ui.ctx()).agent().text_dim; + ui.allocate_ui(vec2(width, label_height), |ui| { + ui.set_min_height(label_height); + ui.add(egui::Label::new(egui::RichText::new(&label).font(Type::Meta.font_id()).color(text_dim)).wrap()); + }); + match field["type"].as_str() { + Some("text" | "number") => { + let mut value = values[id].clone(); + let (edited, _) = edit_named_with_error( + ui, scope.with(id), &mut value, width, intake_multiline(field), hint, &label, + field_error.as_deref(), should_scroll, + ); + if edited { + values[id] = value; + changed = true; + } + } + Some("select") => { + let selected = values[id].as_str().filter(|value| !value.is_empty()).map(str::to_owned); + let response = stitch_ui::halo_select_hint(ui, scope.with(id), width, selected.as_deref(), hint, reduced, |ui| { + for option in field["options"].as_array().into_iter().flatten().filter_map(Value::as_str) { + if stitch_ui::select_option_sized(ui, option, values[id] == option, true, vec2(ui.available_width(), control::STANDARD)).clicked() { + values[id] = json!(option); + changed = true; + ui.close(); + } + } + }); + let resp = response.response.accessible_name(&label); + if should_scroll { + resp.scroll_to_me(Some(egui::Align::Center)); + resp.request_focus(); + } + if let Some(err) = field_error.as_deref() { + stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error); + } + } + Some("boolean") => { + let value = values[id] == true; + let resp = stitch_ui::toggle_option_sized(ui, "是", value, true, vec2(width, control::STANDARD)).accessible_name(&label); + if should_scroll { + resp.scroll_to_me(Some(egui::Align::Center)); + resp.request_focus(); + } + if resp.clicked() { + values[id] = json!(!value); + changed = true; + } + } + _ => { + let kind = field["type"].as_str().unwrap_or("未指定"); + stitch_ui::status_label(ui, &format!("暂不支持此字段类型({kind})"), stitch_ui::StatusTone::Warning); + } + } + }); + if changed { + inline_errors.remove(&error_key); + manual_edited.insert(error_key); + } + changed +} + +pub(in crate::jiansun) fn spu_field(brief: &Value) -> &'static str { + if brief["identifierType"] == "spu" { "identifier" } else { "deliverySpu" } +} + +pub(in crate::jiansun) fn field_kind(field: &Value) -> &Value { field.get("type").unwrap_or(&field["kind"]) } + +pub(in crate::jiansun) fn field_key(field: &Value) -> &Value { field.get("id").unwrap_or(&field["key"]) } + +pub(in crate::jiansun) fn image_slot(template: &Value, field: &Value, barcode: Option<&str>) -> Value { + json!({"templateId":template,"fieldKey":field_key(field),"barcode":barcode, + "imageRole":field["imageRole"].as_str().or_else(|| field_key(field).as_str()), + "multiple":field["multiple"] != false, + "purpose":if field["imageRole"].as_str().is_none_or(|role| matches!(role, "product" | "detail")) { "product" } else { "scene" }}) +} + +pub(in crate::jiansun) fn current_image_slot(brief: &Value, slot: &Value) -> bool { + let intake = &brief["intake"]; + let barcode = slot["barcode"].as_str(); + if slot["scope"] == "barcode" { + return barcode.is_some_and(|barcode| project_barcodes(brief).any(|code| code == barcode)); + } + let scope = if barcode.is_some() { "barcodeFields" } else { "productFields" }; + barcode.is_none_or(|barcode| project_barcodes(brief).any(|code| code == barcode)) + && intake["schema"][scope].as_array().into_iter().flatten().any(|field| + field_kind(field) == "image" && image_slot(&intake["templateId"], field, barcode) == *slot) +} + +pub(in crate::jiansun) fn in_image_slot(image: &Value, slot: &Value) -> bool { + image["barcode"] == slot["barcode"] + && (slot["scope"] == "barcode" || (image["fieldKey"] == slot["fieldKey"] && image["templateId"] == slot["templateId"])) +} + +pub(in crate::jiansun) fn uses_template_images(brief: &Value) -> bool { + ["productFields", "barcodeFields"].into_iter().any(|scope| + brief["intake"]["schema"][scope].as_array().into_iter().flatten().any(|field| field_kind(field) == "image")) +} + + +pub(in crate::jiansun) fn section_heading(ui: &mut Ui, title: &str, description: &str) { + stitch_kit::section_heading(ui, title); + if !description.is_empty() { + ui.add_space(space::XXS); + stitch_kit::caption(ui, description); + } +} + + +pub(in crate::jiansun) fn section_break(ui: &mut Ui) { + ui.add_space(space::LG); + stitch_ui::divider(ui); + ui.add_space(space::LG); +} +pub(in crate::jiansun) fn brief_section_break(ui: &mut Ui) { + ui.add_space(space::LG); + stitch_ui::divider(ui); + ui.add_space(space::MD); +} + +impl Workspace { + pub(in crate::jiansun) fn creation_escape(&mut self, app: &PhotocraftApp, ui: &mut Ui) { + let composing_id = egui::Id::unique("creation-ime-composing"); + let ime_events = ui.input(|input| input.events.iter().filter_map(|event| match event { egui::Event::Ime(event) => Some(event.clone()), _ => None }).collect::>()); + let (ime_event, composing) = ui.ctx().data_mut(|data| { + let state = data.get_temp_mut_or_default::(composing_id); + for event in &ime_events { + match event { + egui::ImeEvent::Preedit { text, .. } => *state = !text.is_empty(), + egui::ImeEvent::Commit(_) => *state = false, + _ => {} + } + } + (!ime_events.is_empty(), *state) + }); + let previous_editors = ui.ctx().data_mut(|data| data.remove_temp::>(egui::Id::unique("creation-active-editors"))).unwrap_or_default(); + if !ui.input(|input| input.key_pressed(egui::Key::Escape)) || composing || ime_event || app.file_dialog_open() + || self.sync_confirm || ui.ctx().memory(|memory| memory.top_modal_layer().is_some()) { return; } + if egui::Popup::is_any_open(ui.ctx()) { + if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + egui::Popup::close_all(ui.ctx()); + // egui clears focused_widget during input preprocessing, even + // when Escape belongs to an overlying popup. Restore the + // underlying editor so this key closes only the popup. + if let Some(id) = previous_editors.iter().copied().find(|id| ui.ctx().memory(|memory| memory.had_focus_last_frame(*id))) { + ui.ctx().memory_mut(|memory| memory.request_focus(id)); + } + } + return; + } + // The workspace settings popup handles Escape before the brief does. + if self.model_settings || self.key_settings { + return; + } + let editor = ui.ctx().memory(|memory| previous_editors.iter().copied().find(|id| memory.has_focus(*id) || memory.had_focus_last_frame(*id))); + if let Some(id) = editor { + if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + ui.ctx().memory_mut(|memory| memory.surrender_focus(id)); + } + return; + } + if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + if self.creation_step == 0 && let Some((_, stage)) = self.creation_reads.wizard_stage { + self.handle_wizard_navigation(app, if stage == CreationStage::Source { WizardFooterOutcome::Cancel } else { WizardFooterOutcome::Back }); + return; + } + self.retain_creation_ui_draft(app); + let previous = match self.creation_step { 2 => 1, 1 => 0, _ => 3 }; + self.set_creation_destination(previous); + } + } + + pub(in crate::jiansun) fn control_geometry(&mut self, name: &str, rect: egui::Rect) { + self.creation_view_geometry[name] = rect_value(rect); + self.creation_view_geometry["controls"][name] = rect_value(rect); + } + pub(in crate::jiansun) fn picker_geometry(&mut self, ui: &Ui, name: &str, response: &egui::Response, loading: bool, ready: bool, rows: Vec) { + self.control_geometry(name, response.rect); + let open = egui::Popup::is_id_open(ui.ctx(), response.id.with("popup")); + let rect = open.then(|| ui.ctx().memory(|memory| memory.area_rect(response.id.with("popup")))).flatten(); + self.creation_view_geometry["popups"][name] = json!({"open":open,"loading":loading,"ready":ready,"rect":rect.map(rect_value),"rows":rows}); + } + pub(in crate::jiansun) fn material_preview(&mut self, response: egui::Response, id: &str, _label: &str, image: &egui::TextureHandle) { + if response.hovered() { + let mut tooltip = egui::Tooltip::for_widget(&response); + tooltip.popup = tooltip.popup.frame(egui::Frame::NONE); + tooltip.show(|ui| { + let size = preview_size(image.size_vec2(), vec2(240.0, 240.0)); + let image_response = ui.image((image.id(), size)); + self.creation_view_geometry["hoverPreview"] = json!({"id":id,"ready":true,"rect":rect_value(image_response.rect),"sourceSize":image.size()}); + }); + } + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/gallery_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/gallery_ui.rs new file mode 100644 index 00000000..07d8f0d8 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/gallery_ui.rs @@ -0,0 +1,356 @@ +use super::super::{PhotocraftApp, Tokens, Ui, Workspace, agent_panel::rect_value, json, stitch_kit, stitch_state::Tone, stitch_ui}; +use super::REFERENCE_DROP_HINT; +use super::brief::{brief_variants, has_selected_product_image, image_rows, non_empty_str, store_image_rows}; +use super::form_widgets_ui::{field_kind, image_slot, in_image_slot, preview_size, uses_template_images}; +use super::reducers::reference_import_activity; +use crate::theme::{AGENT_SEMANTIC, agent_scale::{Type, control, icon, radius, space}}; +use egui::vec2; + +impl Workspace { + pub(in crate::jiansun) fn visual_assets_gallery_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) -> bool { + self.poll_imported_reference_previews(app, ui.ctx()); + let t = Tokens::get(ui.ctx()).agent(); + let variants = brief_variants(&self.creation_brief); + let mut rows = image_rows(&self.creation_brief); + let mut changed = false; + let mut remove = None; + let mut errors = Vec::new(); + let explicit = uses_template_images(&self.creation_brief); + let hidden: Vec<_> = rows.iter().map(|(image, _)| explicit && image["fieldKey"].is_string() + && ["productFields", "barcodeFields"].into_iter().any(|scope| { + let intake = &self.creation_brief["intake"]; + (scope == "barcodeFields") == image["barcode"].is_string() + && intake["schema"][scope].as_array().into_iter().flatten().any(|field| + field_kind(field) == "image" && in_image_slot(image, + &image_slot(&intake["templateId"], field, image["barcode"].as_str()))) + })).collect(); + let has_visible = hidden.iter().any(|&hidden| !hidden); + let has_norm_assets = self.creation_brief["normalizedProduct"]["assets"].as_array().is_some_and(|a| !a.is_empty()); + + let img_scroll = self.creation_reads.scroll_to_field.as_deref() == Some("images"); + if img_scroll { + self.creation_reads.scroll_to_field = None; + } + let img_error = self.creation_reads.inline_errors.get("images").cloned(); + + let show_gallery = !explicit || has_visible || has_norm_assets; + if show_gallery { + ui.set_min_width(width); + let label = if explicit { "其他视觉素材" } else { "视觉素材库 *" }; + let resp = stitch_kit::label(ui, label, Type::Body, Tone::Active); + if img_scroll { + resp.scroll_to_me(Some(egui::Align::Center)); + } + } + + // Role segmentation filter bar when there are assets or references. + if has_norm_assets || has_visible { + ui.add_space(space::XS); + let options = [("全部", true), ("主体图", true), ("主图/场景", true), ("细节图", true)]; + let filter_idx = self.creation_reads.visual_asset_filter.min(options.len() - 1); + let seg = stitch_ui::segmented_control(ui, egui::Id::unique("creation-visual-asset-filter"), &options, filter_idx, self.reduce_motion); + if let Some(next) = seg.selected { + self.creation_reads.visual_asset_filter = next; + } + ui.add_space(space::XS); + } + + if let Some(err) = img_error.as_deref() { + stitch_kit::inline_notice(ui, "triangle-alert", Tone::Failure, err, |_| {}); + ui.add_space(space::XS); + } else if !explicit && (!rows.is_empty() || has_norm_assets) && !has_selected_product_image(&self.creation_brief) { + stitch_kit::inline_notice(ui, "triangle-alert", Tone::Warning, "请将至少一张参考图的用途设为「产品图」,或勾选已拉取的平台白底/主图。", |_| {}); + ui.add_space(space::XS); + } + + // Normalized Platform Assets grid (toggleable selectedForProject, preserving kind) + let active_filter = self.creation_reads.visual_asset_filter; + if has_norm_assets { + let mut assets = self.creation_brief["normalizedProduct"]["assets"].as_array().cloned().unwrap_or_default(); + let mut asset_changed = false; + let filtered_indices: Vec = assets + .iter() + .enumerate() + .filter(|(_, asset)| { + let kind = asset["kind"].as_str().unwrap_or("reference"); + match active_filter { + 1 => matches!(kind, "whiteBackground" | "sku"), + 2 => kind == "main", + 3 => kind == "reference", + _ => true, + } + }) + .map(|(i, _)| i) + .collect(); + if !filtered_indices.is_empty() { + let grid_cols = stitch_kit::GridColumns { min_cell: 200.0, max_cell: 300.0, most: 4 }; + let (_, cell_w) = grid_cols.measure(width.max(1.0), space::SM, filtered_indices.len()); + let cols = stitch_kit::adaptive_grid(ui, egui::Id::unique("creation-norm-assets"), grid_cols, vec2(space::SM, space::SM), filtered_indices.len(), |ui, slot_idx| { + let asset_idx = filtered_indices[slot_idx]; + let asset = &mut assets[asset_idx]; + let selected = asset["selectedForProject"] != false; + let kind = asset["kind"].as_str().unwrap_or("reference"); + let kind_label = match kind { + "whiteBackground" => "白底图", + "main" => "主图", + "sku" => "SKU 图", + _ => "参考图", + }; + let label = non_empty_str(&asset["label"]) + .or_else(|| non_empty_str(&asset["colorName"])) + .or_else(|| non_empty_str(&asset["barcode"])) + .unwrap_or(kind_label) + .to_owned(); + let sub = non_empty_str(&asset["barcode"]).unwrap_or("").to_owned(); + let local_src = non_empty_str(&asset["localSource"]).map(str::to_owned); + let border = if selected { t.primary_bg } else { t.card_border }; + let frame = egui::Frame::NONE + .fill(t.dock) + .stroke(egui::Stroke::new(1.0, border)) + .corner_radius(egui::CornerRadius::same(radius::CONTROL as u8)) + .inner_margin(8); + let resp = frame.show(ui, |ui| { + ui.vertical(|ui| { + let inner_w = (cell_w - 18.0).max(120.0); + ui.set_width(inner_w); + ui.spacing_mut().item_spacing.y = space::XS; + let thumb_h = 92.0; + let (preview_rect, preview) = ui.allocate_exact_size(vec2(inner_w, thumb_h), egui::Sense::hover()); + ui.painter().rect_filled(preview_rect, radius::ROW, t.field); + if let Some(src) = local_src.as_deref() { + if ui.is_rect_visible(preview_rect) { + self.queue_creation_reference(app, src); + } + let key = super::creation_reads::reference_key(src); + if let Some(tex) = self.creation_thumbs.get(&key).cloned() { + let size = preview_size(tex.size_vec2(), preview_rect.size()); + let rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, preview_rect); + ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text); + self.material_preview(preview, &key, &label, &tex); + } else { + crate::icons::paint(ui, preview_rect, "image", icon::LG, t.text_dim); + } + } else { + crate::icons::paint(ui, preview_rect, "image", icon::LG, t.text_dim); + } + ui.add(egui::Label::new(egui::RichText::new(&label).font(Type::Meta.font_id()).color(t.text)).truncate()).on_hover_text(&label); + ui.horizontal(|ui| { + ui.set_width(inner_w); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let toggle = stitch_ui::toggle_option_sized(ui, if selected { "已选用" } else { "选用" }, selected, true, vec2(60.0, 24.0)); + self.control_geometry(&format!("platform-asset-toggle-{asset_idx}"), toggle.rect); + if toggle.clicked() { + asset["selectedForProject"] = json!(!selected); + asset_changed = true; + } + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + let meta = if sub.is_empty() { kind_label.to_owned() } else { format!("{kind_label} · {sub}") }; + ui.add(egui::Label::new(egui::RichText::new(meta).font(Type::Meta.font_id()).color(t.text_dim)).truncate()); + }); + }); + }); + }); + }); + self.control_geometry(&format!("platform-asset-{asset_idx}"), resp.response.rect); + }); + let _ = cols; + ui.add_space(space::SM); + } + if asset_changed { + self.creation_brief["normalizedProduct"]["assets"] = json!(assets); + self.creation_reads.inline_errors.remove("images"); + self.creation_dirty = true; + } + } + + // Local / Uploaded Reference Images grid — filename on full-width top row (never truncated to 4 chars!) + let visible_indices: Vec = rows + .iter() + .enumerate() + .filter(|(idx, (image, _))| { + if hidden.get(*idx) != Some(&false) { + return false; + } + match active_filter { + 1 => image["purpose"] == "product", + 2 => image["purpose"] == "scene", + 3 => image["imageRole"] == "material" || image["imageRole"] == "detail", + _ => true, + } + }) + .map(|(i, _)| i) + .collect(); + + let columns = if width >= 780.0 { 3 } else if width >= 560.0 { 2 } else { 1 }; + let card_width = (width - 12.0 * (columns - 1) as f32) / columns as f32; + egui::Grid::new("creation-references").num_columns(columns).spacing(vec2(12.0, 12.0)).show(ui, |ui| { + for (position, &index) in visible_indices.iter().enumerate() { + let (image, owner) = &mut rows[index]; + let source = image["source"].as_str().unwrap_or("").to_owned(); + let preview_key = super::creation_reads::reference_key(&source); + let frame = stitch_ui::material_frame( + ui, + stitch_ui::surface_frame(ui.ctx(), stitch_ui::SurfaceRole::Input).corner_radius(radius::CONTROL as u8).inner_margin(10), + |ui| { + ui.vertical(|ui| { + let inner_width = (card_width - 22.0).max(120.0); + ui.set_width(inner_width); + ui.spacing_mut().item_spacing.y = space::XS; + // Full-width filename header row so filenames are always readable + let name = image["name"].as_str().unwrap_or("产品图片").to_owned(); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + ui.add(crate::icons::image("image", icon::SM, t.text_dim)); + ui.add_sized( + vec2((inner_width - 52.0).max(60.0), 24.0), + egui::Label::new(egui::RichText::new(&name).font(Type::Meta.font_id()).color(t.text)).truncate(), + ) + .on_hover_text(&name); + let response = stitch_ui::icon_button(ui, "trash", 24.0, false, "移除此参考图"); + self.control_geometry(&format!("reference-remove-{index}"), response.rect); + if response.clicked() { + remove = Some(index); + } + }); + // Thumbnail + Role/Color controls side-by-side below header + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 10.0; + let thumbnail_width = (inner_width * 0.28).clamp(56.0, 76.0); + let details_width = (inner_width - thumbnail_width - 10.0).max(96.0); + let (preview_rect, preview) = ui.allocate_exact_size(vec2(thumbnail_width, thumbnail_width), egui::Sense::hover()); + if ui.is_rect_visible(preview_rect) { + self.queue_creation_reference(app, &source); + } + let texture = self.creation_thumbs.get(&preview_key).cloned(); + let loading = self.creation_thumbnail_loading(&preview_key); + let error = self.creation_thumbnail_error(&preview_key).map(str::to_owned); + let saved = self.creation_reference_saved(app, &source); + let status = if texture.is_some() { + "ready" + } else if error.is_some() { + "failed" + } else if loading { + "loading" + } else if saved { + "queued" + } else { + "unsaved" + }; + ui.painter().rect_filled(preview_rect, radius::ROW, t.dock); + if let Some(texture) = texture.as_ref() { + let size = preview_size(texture.size_vec2(), preview_rect.size()); + let rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, preview_rect); + ui.painter().image(texture.id(), rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text); + self.material_preview(preview, &preview_key, &name, texture); + } else { + let label = if error.is_some() { + "读取失败" + } else if loading { + "加载中…" + } else { + "" + }; + if label.is_empty() { + crate::icons::paint(ui, preview_rect, "image", icon::MD, t.text_dim); + } else { + ui.painter().text(preview_rect.center(), egui::Align2::CENTER_CENTER, label, Type::Meta.font_id(), t.text_dim); + } + if let Some(error) = error.as_deref() { + let msg = crate::client_brand::user_error(error, "参考图读取失败"); + preview.on_hover_text(msg); + } + } + self.control_geometry(&format!("reference-preview-{index}"), preview_rect); + self.creation_view_geometry["referenceRows"][index.to_string()] = + json!({"source":source,"owner":owner.as_str(),"status":status,"rect":rect_value(preview_rect)}); + ui.vertical(|ui| { + ui.set_width(details_width); + ui.spacing_mut().item_spacing.y = 6.0; + if let Some(error) = error.as_deref() { + let msg = crate::client_brand::user_error(error, "参考图读取失败"); + errors.push(format!("{name} · {msg}")); + if saved && stitch_ui::action_button(ui, "重试", stitch_ui::ButtonRole::Quiet, true).clicked() { + self.retry_creation_reference(app, &source); + } + } + let reference_id = (&source, owner.clone()); + let purpose = stitch_ui::halo_select(ui, ("creation-purpose", &reference_id), details_width, if image["purpose"] == "scene" { "场景参考" } else { "产品图" }, self.reduce_motion, |ui| { + for (purpose, label) in [("product", "产品图"), ("scene", "场景参考")] { + if stitch_ui::select_option(ui, label, image["purpose"] == purpose, true).clicked() { + image["purpose"] = json!(purpose); + changed = true; + } + } + }); + self.control_geometry(&format!("reference-purpose-{index}"), purpose.response.rect); + let selected = variants + .iter() + .find(|variant| variant["id"] == owner.as_str()) + .and_then(|variant| variant["name"].as_str()) + .unwrap_or(if owner.is_empty() { "共用 · 所有花色" } else { "选择花色" }); + let ownership = stitch_ui::halo_select(ui, ("creation-reference-variant", &reference_id), details_width, selected, self.reduce_motion, |ui| { + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + let size = vec2(ui.available_width(), control::STANDARD); + if stitch_ui::select_option_sized(ui, "共用 · 所有花色", owner.is_empty(), true, size).clicked() { + owner.clear(); + changed = true; + } + for variant in &variants { + let Some(id) = variant["id"].as_str() else { continue }; + if stitch_ui::select_option_sized( + ui, variant["name"].as_str().unwrap_or("花色"), owner.as_str() == id, true, size, + ).clicked() { + *owner = id.into(); + changed = true; + } + } + }); + self.control_geometry(&format!("reference-owner-{index}"), ownership.response.rect); + }); + }); + }); + }, + ); + self.control_geometry(&format!("reference-{index}"), frame.response.rect); + if (position + 1) % columns == 0 { + ui.end_row(); + } + } + }); + if !explicit { + ui.add_space(space::XS); + let drop_rect = self.add_reference_button(app, ui, width); + if rows.is_empty() { + self.control_geometry("reference-empty", drop_rect); + } + } + for error in errors { + stitch_ui::status_label(ui, &error, stitch_ui::StatusTone::Error); + } + if !self.creation_reads.reference_import_error.is_empty() && self.creation_reads.reference_import_error != REFERENCE_DROP_HINT { + let status = stitch_ui::status_label(ui, &self.creation_reads.reference_import_error, stitch_ui::StatusTone::Error); + self.control_geometry("reference-import-error", status.rect); + } + if let Some(label) = reference_import_activity(self.busy.as_deref()) { + ui.add_space(space::SM); + let id = egui::Id::unique(("creation-reference-import", &self.origin, self.account["id"].as_str(), self.creation_doc)); + let response = stitch_ui::progress(ui, id, label, None, self.reduce_motion); + self.control_geometry("reference-import-progress", response.rect); + } + if let Some(index) = remove { + rows = rows.into_iter().enumerate().filter_map(|(position, row)| (position != index).then_some(row)).collect(); + changed = true; + } + if changed { + match store_image_rows(&mut self.creation_brief, rows) { + Ok(()) => { + self.creation_reads.inline_errors.remove("images"); + self.creation_dirty = true; + } + Err(error) => self.error = error, + } + } + show_gallery + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/intake.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/intake.rs new file mode 100644 index 00000000..524e851a --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/intake.rs @@ -0,0 +1,202 @@ +use super::super::{Value, json}; +use super::super::creation_reads::wizard; +use super::brief::{dedupe_strings, non_empty_str, string_list}; +use super::form_widgets_ui::{current_image_slot, field_key, field_kind, in_image_slot}; + +pub(in crate::jiansun) fn assign_platform_images(brief: &mut Value) { + let intake = brief["intake"].clone(); + if let Some(images) = brief["images"].as_array_mut() { + for image in images.iter_mut().filter(|image| image["platformImage"] == true) { + let scope = if image["barcode"].is_string() { "barcodeFields" } else { "productFields" }; + if let Some(field) = intake["schema"][scope].as_array().into_iter().flatten().find(|field| + field_kind(field) == "image" && field["imageRole"] == "product" && field["multiple"] != false) { + image["fieldKey"] = field_key(field).clone(); + image["templateId"] = intake["templateId"].clone(); + } else if let Some(row) = image.as_object_mut() { + row.remove("fieldKey"); + row.remove("templateId"); + } + } + } +} + +pub(in crate::jiansun) fn add_slot_images(brief: &mut Value, slot: &Value, images: &[Value]) -> Result<(), String> { + if !current_image_slot(brief, slot) { + return Err("图片框已变化,请重新选择".into()); + } + let mut current = brief["images"].as_array().cloned().unwrap_or_default(); + if slot["multiple"] == false { + current.retain(|image| !in_image_slot(image, slot)); + } + for mut image in images.iter().take(if slot["multiple"] == false { 1 } else { 8 }).cloned() { + if current.iter().any(|row| in_image_slot(row, slot) && row["source"] == image["source"]) { continue; } + for key in ["fieldKey","templateId","imageRole","barcode"] { + if !slot[key].is_null() { image[key] = slot[key].clone(); } + } + image["purpose"] = slot["purpose"].clone(); + current.push(image); + } + if current.len() > 8 { return Err("共用及条码图片最多 8 张,请先删除不用的图片".into()); } + brief["images"] = json!(current); + if let Some(code) = slot["barcode"].as_str() + && let Some(row) = brief["barcodeEntries"].as_array_mut().into_iter().flatten() + .find(|row| row["barcode"] == code) + { + let mut pictures = row["images"].as_array().cloned().unwrap_or_default(); + if slot["multiple"] == false { pictures.retain(|image| !in_image_slot(image, slot)); } + for image in current.into_iter().filter(|image| in_image_slot(image, slot)) { + if !pictures.contains(&image) { pictures.push(image); } + } + row["images"] = json!(pictures); + } + Ok(()) +} + +pub(in crate::jiansun) fn field_fact(field: &Value, facts: &Value) -> Option { + let lookup = |name: &str| -> Option { + let alias = match name { + "颜色" | "花色" | "color" => "colorName", + "商品名" | "产品名称" | "name" => "productName", + "条码" | "商品条码" => "barcode", + "SKU 编号" | "SKU编码" => "skuCode", + "规格" | "规格型号" => "spec", + "尺寸" | "产品尺寸" | "size" => "sizeText", + "材质" | "主要材质" => "material", + "说明" | "产品说明" | "产品描述" | "描述" => "description", + "卖点" | "产品卖点" => "sellingPoints", + "长" | "长度" => "length", + "宽" | "宽度" => "width", + "高" | "高度" => "height", + "深" | "进深" => "depth", + _ => name, + }; + if matches!(alias, "length" | "width" | "height" | "depth" | "secondaryHeight") { + let dimension = &facts["dimensions"]; + let value = dimension.get(alias).or_else(|| (alias == "width").then(|| dimension.get("depth")).flatten()) + .or_else(|| facts.get(alias))?; + let numeric = value.as_f64().or_else(|| value.as_str()?.parse::().ok())?; + if !field["unit"].is_string() || dimension["unit"] == field["unit"] { + return Some(value.clone()); + } + let millimetres = |unit: &Value| match unit.as_str()? { + "mm" => Some(1.0), "cm" => Some(10.0), "m" => Some(1000.0), _ => None, + }; + let converted = numeric * millimetres(&dimension["unit"])? / millimetres(&field["unit"])?; + return converted.is_finite().then(|| json!(converted)); + } + facts.get(alias).or_else(|| facts["attributes"].get(name)) + .or_else(|| match alias { + "sizeText" => facts.get("spec").or_else(|| facts.get("dimensions")), + "spec" => facts.get("sizeText"), + _ => None, + }).filter(|value| !value.is_null()).cloned() + }; + let key = field_key(field).as_str()?; + let label = field["label"].as_str().unwrap_or(key); + let value = lookup(key).or_else(|| lookup(label))?; + match field_kind(field).as_str()? { + "text" if value.is_number() => Some(json!(value.to_string())), + "text" if value.is_string() => Some(value), + "text" if value.is_array() => Some(json!(value.as_array()?.iter().filter_map(Value::as_str).collect::>().join("\n"))), + "text" if value.is_object() => dimension_text(&value).map(Value::String), + "number" if value.is_number() || value.as_str().is_some_and(|s| s.parse::().is_ok_and(f64::is_finite)) => Some(value), + "select" if field["options"].as_array().is_some_and(|options| options.contains(&value)) => Some(value), + "boolean" if value.is_boolean() => Some(value), + _ => None, + } +} + +pub(in crate::jiansun) fn dimension_text(dimensions: &Value) -> Option { + let axes = [("length", "长"), ("width", "宽"), ("height", "高")].into_iter() + .filter_map(|(axis, label)| dimensions[axis].as_number().map(|value| format!("{label} {value}"))) + .collect::>(); + (!axes.is_empty()).then(|| match dimensions["unit"].as_str() { + Some(unit) => format!("{} {unit}", axes.join(" × ")), + None => axes.join(" × "), + }) +} + +pub(in crate::jiansun) fn fill_platform_intake(brief: &mut Value) { + if brief["intake"]["schema"]["version"] != 1 { return; } + let fill = |fields: &Value, facts: &Value| -> serde_json::Map { + fields.as_array().into_iter().flatten().filter_map(|field| + Some((field_key(field).as_str()?.to_owned(), field_fact(field, facts)?))).collect() + }; + let fill_missing = |answers: &mut Value, values: serde_json::Map| { + for (key, value) in values { + if answers.get(&key).is_none() { answers[&key] = value; } + } + }; + if brief["normalizedProduct"].is_object() { + let np = &brief["normalizedProduct"]; + let mut shared = json!({ + "productName": brief["name"].clone(), + "dimensions": np["specs"]["dimensions"].clone(), + "description": np["copy"]["summary"].clone(), + "sellingPoints": np["copy"]["sellingPoints"].clone(), + }); + let mats = dedupe_strings(string_list(&np["specs"]["materials"])); + if !mats.is_empty() { + shared["material"] = json!(mats.join("、")); + } + let mut attr_map = serde_json::Map::new(); + for attr in np["specs"]["attributes"].as_array().into_iter().flatten() { + if let (Some(k), Some(v)) = (non_empty_str(&attr["label"]).or_else(|| non_empty_str(&attr["key"])), non_empty_str(&attr["value"])) { + attr_map.insert(k.to_owned(), json!(v)); + } + } + shared["attributes"] = Value::Object(attr_map); + let mut barcodes = std::collections::BTreeMap::new(); + for variant in np["variants"].as_array().into_iter().flatten() { + let color = variant["colorName"].clone(); + for row in variant["barcodes"].as_array().into_iter().flatten() { + let Some(code) = non_empty_str(&row["barcode"]) else { continue }; + let mut facts = row.clone(); + facts["barcode"] = json!(code); + facts["colorName"] = color.clone(); + barcodes.insert(code.to_owned(), fill(&brief["intake"]["schema"]["barcodeFields"], &facts)); + } + } + let shared_values = fill(&brief["intake"]["schema"]["productFields"], &shared); + fill_missing(&mut brief["intake"]["productValues"], shared_values); + for (code, values) in barcodes { + fill_missing(&mut brief["intake"]["barcodeValues"][code], values); + } + return; + } + if brief["platformFacts"]["spu"] != brief["identifier"] { return; } + let mut shared = brief["platformFacts"]["shared"].clone(); + if !shared.is_object() { return; } + shared["productName"] = brief["name"].clone(); + let mut barcodes = std::collections::BTreeMap::new(); + if let Some(rows) = brief["platformFacts"]["barcodes"].as_object() { + for (code, row) in rows { + let mut facts = row.clone(); + facts["barcode"] = json!(code); + barcodes.insert(code.clone(), fill(&brief["intake"]["schema"]["barcodeFields"], &facts)); + } + } + let shared_values = fill(&brief["intake"]["schema"]["productFields"], &shared); + fill_missing(&mut brief["intake"]["productValues"], shared_values); + for (code, values) in barcodes { + fill_missing(&mut brief["intake"]["barcodeValues"][code], values); + } +} + +pub(in crate::jiansun) fn set_intake(brief: &mut Value, template_id: &Value, schema: &Value) { + if schema["version"] != 1 { + if let Some(fields) = brief.as_object_mut() { + fields.remove("intake"); + } + } else if brief["intake"]["templateId"] != *template_id || brief["intake"]["schema"]["version"] != 1 { + brief["intake"] = json!({"templateId":template_id,"schema":schema,"productValues":{},"barcodeValues":{}}); + fill_platform_intake(brief); + assign_platform_images(brief); + } else { + wizard::refresh_intake_schema_from_catalog(brief, &json!({"id": template_id, "intake": schema})); + } +} + +pub(in crate::jiansun) const BARCODE_HINT: &str = "如 DNZ030516N717V01"; +pub(in crate::jiansun) const BARCODE_SEPARATORS: [char; 7] = ['\r', '\n', ',', ',', '、', ';', ';']; + diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/plan_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/plan_ui.rs new file mode 100644 index 00000000..0c979433 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/plan_ui.rs @@ -0,0 +1,188 @@ +use super::super::{PhotocraftApp, Tokens, Ui, Workspace, json, stitch_kit, stitch_state::Tone, stitch_ui}; +use super::form_widgets_ui::{edit, field_group, section_break, section_heading}; +use crate::theme::agent_scale::{Type, space}; + +impl Workspace { + pub(in crate::jiansun) fn points_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + let field_scope = self.creation_field_scope(app); + let t = Tokens::get(ui.ctx()).agent(); + ui.label(egui::RichText::new("产品事实与卖点").font(Type::Display.semibold()).color(t.text)); + ui.add_space(space::MD); + section_heading(ui, "产品事实", "结合产品资料核对,避免生成未确认的产品信息"); + ui.add_space(space::SM); + let facts = self.creation["facts"]["items"].as_array().cloned().unwrap_or_default(); + if facts.is_empty() { + stitch_kit::caption(ui, "还没有分析结果,产品原始资料会继续保留"); + } + for fact in facts { + ui.label(egui::RichText::new(fact["text"].as_str().unwrap_or("")).font(Type::Body.font_id())).on_hover_text(fact["source"].as_str().unwrap_or("")); + } + let missing = self.creation["facts"]["missing"].as_array().cloned().unwrap_or_default(); + if !missing.is_empty() { + ui.add_space(space::SM); + stitch_ui::disclosure(ui, egui::Id::unique("creation-missing"), &format!("待确认 · {}", missing.len()), false, self.reduce_motion, |ui| { + for item in missing { + ui.label(item.as_str().unwrap_or("")); + } + }); + } + section_break(ui); + let batches = self.creation["sellingPoints"]["batches"].as_array().cloned().unwrap_or_default(); + ui.horizontal_wrapped(|ui| { + stitch_kit::label(ui, "选择卖点", Type::Heading, Tone::Active); + stitch_kit::label(ui, format!("已选 {} / 20", self.creation_selected.len()), Type::Meta, Tone::Quiet); + stitch_kit::label(ui, format!("{} / 12 批", batches.len()), Type::Meta, Tone::Quiet); + }); + ui.add_space(space::SM); + if batches.is_empty() { + stitch_kit::caption(ui, "生成一批卖点,再选择适合这款产品的表达"); + } + for (batch_index, batch) in batches.iter().enumerate() { + let id = batch["id"].as_str().unwrap_or(""); + if batches.len() > 1 { + stitch_kit::label(ui, format!("第 {} 批", batch_index + 1), Type::Meta, Tone::Quiet); + } + for (index, item) in batch["items"].as_array().cloned().unwrap_or_default().iter().enumerate() { + let key = format!("{id}:{index}"); + let selected = self.creation_selected.contains(&key); + let label = item.as_str().or_else(|| item["text"].as_str()).unwrap_or(""); + let response = stitch_ui::toggle_option(ui, label, selected, selected || self.creation_selected.len() < 20); + self.control_geometry(&format!("selling-point-{batch_index}-{index}"), response.rect); + if response.clicked() { + if selected { + self.creation_selected.retain(|s| s != &key); + } else { + self.creation_selected.push(key); + } + self.creation_submit(app, "creation-select", json!({})); + } + } + ui.add_space(space::SM); + } + ui.add_space(space::MD); + let direction_width = ui.available_width(); + field_group(ui, direction_width, "下一批表达方向(可选)", |ui| { + let id = field_scope.with("creation-direction"); + ui.data_mut(|data| data.get_temp_mut_or_default::>(egui::Id::unique("creation-active-editors")).push(id.with("editor"))); + let reduced = ui.style().animation_time == 0.0; + if stitch_ui::halo_field(ui, id, None, reduced, |ui| { + ui.add(stitch_ui::text_input(&mut self.creation_direction, "例如:更突出木材质感与空间搭配", false) + .id(id.with("editor")).desired_width(ui.available_width().max(0.0)).frame(egui::Frame::NONE)) + }) + .changed() + { + self.creation_dirty = true; + } + }); + ui.add_space(space::MD); + ui.horizontal_wrapped(|ui| { + let generate = + ui.add_enabled_ui(batches.len() < 12, |ui| stitch_ui::button(ui, if batches.is_empty() { "生成一批卖点" } else { "再生成一批" }, false)).inner; + self.control_geometry("points-generate", generate.rect); + if generate.clicked() { + self.creation_submit(app, "creation-points", json!({})); + } + let plan = ui.add_enabled_ui(!self.creation_selected.is_empty(), |ui| stitch_ui::button(ui, "生成页面方案", true)).inner; + self.control_geometry("points-plan", plan.rect); + if plan.clicked() { + self.creation_submit(app, "creation-plan", json!({})); + } + }); + } + pub(in crate::jiansun) fn plan_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + let field_scope = self.creation_field_scope(app); + let t = Tokens::get(ui.ctx()).agent(); + let status = self.creation["plan"]["status"].as_str().unwrap_or("idle").to_owned(); + let mut screens = self.creation_plan.as_array().cloned().unwrap_or_default(); + ui.label(egui::RichText::new("页面方案").font(Type::Display.semibold()).color(t.text)); + stitch_kit::caption(ui, "调整页面文案与画面要求,修改后保存并重新确认"); + ui.add_space(space::MD); + ui.horizontal_wrapped(|ui| { + if let Some(count) = self.creation_template_screen_count() { + ui.label(format!("{count} 屏")); + } + let generate = stitch_ui::button(ui, if screens.is_empty() { "生成页面方案" } else { "重新生成方案" }, false); + self.control_geometry("plan-generate", generate.rect); + if generate.clicked() { + self.creation_submit(app, "creation-plan", json!({})); + } + let label = match status.as_str() { + "confirmed" => "已确认", + "needs-confirm" => "待确认", + "stale" => "需要重新确认", + _ => "尚未确认", + }; + stitch_kit::label(ui, label, Type::Meta, Tone::Quiet); + }); + if status == "stale" || self.creation_dirty { + ui.add_space(space::SM); + stitch_kit::inline_notice( + ui, + "triangle-alert", + Tone::Warning, + self.creation["plan"]["invalidReason"].as_str().filter(|s| !s.is_empty()).unwrap_or("资料已变更,请重新确认方案"), + |_| {}, + ); + } + section_break(ui); + if screens.is_empty() { + stitch_kit::label(ui, "还没有页面方案,生成后可以逐页调整", Type::Body, Tone::Quiet); + } + let mut changed = false; + let screen_count = screens.len(); + for (i, screen) in screens.iter_mut().enumerate() { + let screen_id = screen["id"].as_str().filter(|id| !id.is_empty()).map(str::to_owned); + let screen_key = (screen_id.as_deref(), screen_id.is_none().then_some(i)); + stitch_ui::disclosure(ui, egui::Id::unique(("creation-plan-screen", screen_key)), &format!("{} · {}", i + 1, screen["name"].as_str().unwrap_or("页面")), i == 0, self.reduce_motion, |ui| { + let width = ui.available_width(); + field_group(ui, width, "标题", |ui| { + changed |= edit(ui, (field_scope, screen_key, "title"), &mut screen["title"], width, false, "标题"); + }); + ui.add_space(space::SM); + field_group(ui, width, "正文", |ui| { + changed |= edit(ui, (field_scope, screen_key, "body"), &mut screen["body"], width, true, "正文"); + }); + ui.add_space(space::SM); + stitch_ui::disclosure(ui, egui::Id::unique(("creation-image-prompt", screen_key)), "画面要求", false, self.reduce_motion, |ui| { + let width = ui.available_width(); + changed |= edit(ui, (field_scope, screen_key, "imagePrompt"), &mut screen["imagePrompt"], width, true, "画面要求"); + }); + }); + ui.add_space(space::SM); + if i + 1 < screen_count { + stitch_ui::divider(ui); + } + } + self.creation_plan = json!(screens); + if changed { + self.creation_dirty = true; + } + section_break(ui); + ui.horizontal_wrapped(|ui| { + if self.creation_dirty { + let save = stitch_ui::button(ui, "保存方案修改", false); + self.control_geometry("plan-save", save.rect); + if save.clicked() { + self.creation_submit(app, "creation-plan-edit", json!({})); + } + } + let confirm = ui.add_enabled_ui(status == "needs-confirm" && !self.creation_dirty, |ui| stitch_ui::button(ui, "确认方案", false)).inner; + self.control_geometry("plan-confirm", confirm.rect); + if confirm.clicked() { + self.creation_submit(app, "creation-confirm", json!({})); + } + let slots = ui.add_enabled_ui(status == "confirmed" && !self.creation_dirty, |ui| stitch_ui::button(ui, "制作图位", true)).inner; + self.control_geometry("plan-slots", slots.rect); + if slots.clicked() { + self.creation_step = 4; + } + if self.creation_pending.is_some() { + let load = stitch_ui::button(ui, "载入生成结果", false); + self.control_geometry("plan-load", load.rect); + if load.clicked() { + self.creation_submit(app, "creation-load", json!({})); + } + } + }); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/project.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/project.rs new file mode 100644 index 00000000..579bbca2 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/project.rs @@ -0,0 +1,511 @@ +use super::super::{Duration, Instant, PhotocraftApp, Request, Value, Workspace, json}; +use super::super::creation_reads::wizard::CreationStage; +use super::barcode::update_detail_barcode; +use super::brief::{brief_variants, empty_brief, incomplete_brief_stage, non_empty_str, normalized_color_groups, selected_template, set_brief_variants, template_identity}; +use super::review_hints::ReviewHintItem; + +pub(in crate::jiansun) const DELIVERY_DIR_PREF_KEY: &str = "jiansun.deliveryDir"; + +pub(in crate::jiansun) fn remembered_delivery_dir(app: &PhotocraftApp) -> Option { + app.session.prefs().dialogs.get(DELIVERY_DIR_PREF_KEY) + .and_then(Value::as_str) + .map(str::trim) + .filter(|path| !path.is_empty()) + .map(str::to_owned) +} + +pub(in crate::jiansun) fn remember_delivery_dir(app: &mut PhotocraftApp, path: &str) { + let trimmed = path.trim(); + if trimmed.is_empty() { + return; + } + app.session.prefs.edit(|prefs| { + prefs.dialogs.insert(DELIVERY_DIR_PREF_KEY.into(), json!(trimmed)); + }); + let _ = crate::prefs_ui::save_preferences(app); +} + +pub(in crate::jiansun) fn default_delivery_dir_for_home(home: &std::path::Path) -> Option { + let desktop = home.join("Desktop"); + let onedrive_desktop = home.join("OneDrive").join("Desktop"); + let documents = home.join("Documents"); + let base = if desktop.is_dir() { + desktop + } else if onedrive_desktop.is_dir() { + onedrive_desktop + } else if documents.is_dir() { + documents + } else { + desktop + }; + base.join("小壹成品").to_str().map(str::to_owned) +} + +pub(in crate::jiansun) fn default_delivery_dir() -> Option { + let home = std::env::var_os("USERPROFILE") + .or_else(|| std::env::var_os("HOME")) + .map(std::path::PathBuf::from)?; + default_delivery_dir_for_home(&home) +} + +pub(in crate::jiansun) fn preferred_delivery_dir(app: &PhotocraftApp) -> Option { + remembered_delivery_dir(app).or_else(default_delivery_dir) +} + + +impl Workspace { + pub(in crate::jiansun) fn creation_field_scope(&self, app: &PhotocraftApp) -> egui::Id { + self.creation_field_scope_for(self.creation_doc, app.session.active().map(|s| s.doc.id.0)) + } + pub(in crate::jiansun) fn creation_field_scope_for(&self, creation_doc: Option, active_doc: Option) -> egui::Id { + egui::Id::unique(("creation-fields", &self.origin, self.account["id"].as_str(), creation_doc, active_doc)) + } + pub(in crate::jiansun) fn resume_project_brief(&mut self, app: &PhotocraftApp, project: &Value) { + let Some(state) = app.session.active() else { return }; + let Ok(saved_stage) = serde_json::from_value::(project["briefResumeStage"].clone()) else { return }; + if project["briefIncomplete"] != true + || super::canvas_workspace::document_mapping(&state.doc).is_some_and(|mapping| mapping["canvasFirst"] == true) + { + return; + } + let doc = Some(state.doc.id.0); + let dirty_brief = if self.creation_doc == doc && self.creation_dirty { + Some(&self.creation_brief) + } else { + self.current_creation_ui_scope(app).and_then(|scope| self.retained_creation_ui.get(&scope)) + .map(|retained| &retained.draft["brief"]) + }; + let stage = dirty_brief.map_or(saved_stage, |brief| { + incomplete_brief_stage(brief, &Value::Null, |_| true).unwrap_or(CreationStage::Details) + }); + self.creation_reads.staged_new_project = false; + self.creation_reads.staged_prior_draft = None; + self.creation_reads.new_project_doc = None; + self.creation_reads.wizard_stage = Some((self.creation_field_scope_for(doc, doc), stage)); + self.set_creation_destination(0); + } + pub(in crate::jiansun) fn template_binding(&self, doc: Option) -> String { + format!("{}|{}|{:?}", self.account["id"], self.origin, doc) + } + pub(in crate::jiansun) fn brief_with_manual_fields(&self) -> Value { + let mut brief = self.creation_brief.clone(); + if !self.creation_reads.manual_edited_fields.is_empty() { + let mut edited: std::collections::BTreeSet<_> = brief["manualFields"].as_array().into_iter().flatten() + .filter_map(Value::as_str).collect(); + edited.extend(self.creation_reads.manual_edited_fields.iter().map(String::as_str)); + brief["manualFields"] = json!(edited); + } + brief + } + + pub(in crate::jiansun) fn creation_draft(&self) -> Value { + if self.creation_reads.staged_new_project + && let Some(draft) = &self.creation_reads.staged_prior_draft + { + return draft.clone(); + } + if self.creation_restore_draft.is_object() { + return self.creation_restore_draft.clone(); + } + let mut draft = json!({"revision":self.creation["revision"],"brief":self.brief_with_manual_fields(),"width":self.creation_draft_width(), + "screens":self.creation_plan,"direction":self.creation_direction,"selected":self.creation_selected}); + if let Some(path) = &self.creation_delivery_dir { + draft["deliveryDir"] = json!(path); + } + draft + } + pub(in crate::jiansun) fn can_save_creation(&self) -> bool { + self.busy.is_none() && (!self.unknown || self.scoped_production_pending()) + } + pub(in crate::jiansun) fn creation_autosave(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) { + if self.creation_doc != app.session.active().map(|s| s.doc.id.0) || self.creation_doc.is_none() { + return; + } + let signature = self.creation_draft().to_string(); + if self.restored_creation_signature.as_deref() == Some(signature.as_str()) { + return; + } + if signature != self.creation_edit_signature { + self.creation_edit_signature = signature; + self.creation_touched = Instant::now(); + if self.creation_dirty { + self.draft_changed = true; + self.sync_dirty = true; + } + } + if !self.creation_dirty || !self.can_save_creation() || self.creation_failed_signature == self.creation_edit_signature { + return; + } + if self.creation_touched.elapsed() < Duration::from_millis(900) { + ctx.request_repaint_after(Duration::from_millis(150)); + return; + } + let brief_changed = self.creation_brief != self.creation["brief"] + || self.creation["width"].as_u64() != self.creation_draft_width() + || super::product_production::delivery_dir(&self.creation) != self.creation_delivery_dir; + let plan_changed = self.creation_plan != self.creation["plan"]["screens"]; + let method = if brief_changed { + "creation-save" + } else if plan_changed { + "creation-plan-edit" + } else { + "creation-select" + }; + if method == "creation-save" || !self.unknown { + self.creation_submit(app, method, json!({})); + } + } + pub(in crate::jiansun) fn sync_signature(&self) -> String { + json!({"composer":self.composer,"messages":self.messages,"creation":self.creation,"draft":self.creation_draft(),"templateWorkflow":self.template_workflow}).to_string() + } + pub(in crate::jiansun) fn sync_action(&mut self, app: &PhotocraftApp, method: &str, mut input: Value) { + if self.busy.is_some() || self.saving.is_some() || self.project_operation_pending() { + self.error = "请等待当前操作完成".into(); + return; + } + let Some(st) = app.session.active() else { + self.error = "请先打开项目".into(); + return; + }; + if input["status"] == "completed" && (self.creation_dirty || self.unknown) { + self.error = "请先保存资料与方案,并核查原请求后再完结".into(); + return; + } + input["doc"] = json!(st.doc.id.0); + input["revision"] = json!(st.revision); + if input["status"].is_null() { + input["status"] = json!("draft"); + } + let meta = json!({"composer":self.composer,"messages":self.messages,"project":self.project_context,"syncDirty":self.sync_dirty,"creationDraft":self.creation_draft()}); + self.sync_request_meta = self.sync_signature(); + self.draft_changed = false; + let _ = self.tx.send(Request::Save(st.doc.clone(), st.revision, meta)); + self.saving = Some((st.doc.id.0, st.revision)); + self.send(method, input); + } + + pub(in crate::jiansun) fn jump_to_review_hint(&mut self, app: &PhotocraftApp, hint: &ReviewHintItem) { + let output_id = hint + .output_id + .as_deref() + .unwrap_or_else(|| { + if self.canvas_workspace.output.is_empty() { "detail" } else { self.canvas_workspace.output.as_str() } + }) + .to_owned(); + self.template_ui.navigate(&output_id, hint.slot_id.as_deref()); + let mut request = json!({ "outputId": output_id }); + if let Some(variant_id) = hint.variant_id.as_deref() { + request["variantId"] = json!(variant_id); + } + if let Some(slot_id) = hint.slot_id.as_deref() { + request["slotId"] = json!(slot_id); + } + if let Some(layer_id) = hint.layer_id.as_deref() { + request["layerId"] = json!(layer_id); + } + if let Err(error) = self.slot_action(app, "slot-skeleton", request) { + self.product_views.view_error = Some(error.clone()); + self.error = error; + } + self.sync_confirm = false; + self.show_center(super::CenterView::Canvas, true); + self.creation_open = false; + } + pub(in crate::jiansun) fn begin_staged_new_project(&mut self, app: &PhotocraftApp) { + self.retain_creation_ui_draft(app); + if !self.creation_reads.staged_new_project { + self.creation_reads.staged_prior_draft = app.session.active().map(|state| { + if self.creation_doc == Some(state.doc.id.0) { self.creation_draft() } else { Value::Null } + }); + } + self.creation_restore_draft = Value::Null; + self.creation_reads.staged_new_project = true; + self.creation_reads.new_project_doc = None; + self.reset_test_presets(); + self.creation_reads.wizard_stage = None; + self.library = false; + self.material = false; + self.creation_open = true; + self.creation_step = 0; + self.creation_doc = None; + self.creation_brief = empty_brief(); + self.creation = json!({"brief": self.creation_brief.clone()}); + self.creation_dirty = false; + self.creation_read_failed = false; + self.creation_width = 0; + self.creation_delivery_dir = preferred_delivery_dir(app); + self.creation_selected.clear(); + self.creation_direction.clear(); + self.creation_plan = json!([]); + self.creation_progress.clear(); + self.creation_reads.inline_errors.clear(); + self.creation_reads.scroll_to_field = None; + self.creation_reads.manual_edited_fields.clear(); + self.creation_reads.visual_asset_filter = 0; + self.creation_reads.expanded_colors.clear(); + self.creation_reads.expanded_skus.clear(); + self.creation_reads.platform_message.clear(); + self.creation_reads.platform_sync_note.clear(); + self.creation_reads.reference_import_error.clear(); + self.creation_reads.resource_set = Value::Null; + self.creation_reads.resource_component.clear(); + self.creation_reads.resource_image = None; + self.template_workflow = Value::Null; + self.error.clear(); + } + + pub(in crate::jiansun) fn ensure_creation_document(&mut self, app: &mut PhotocraftApp) -> Result<(), String> { + if !self.creation_reads.staged_new_project { + return Ok(()); + } + if self.busy.is_some() { + return Err("请等待当前操作完成".into()); + } + let doc_name = non_empty_str(&self.creation_brief["name"]).unwrap_or("未命名详情页").to_owned(); + app.run("file.new", json!({"name": doc_name, "width": 1440, "height": 1800}))?; + let doc_id = app.session.active().map(|state| state.doc.id.0); + self.creation_doc = doc_id; + self.creation_reads.new_project_doc = doc_id; + self.reference_intro_doc = doc_id; + self.creation_reads.staged_new_project = false; + self.creation_reads.staged_prior_draft = None; + if let Some((_, stage)) = self.creation_reads.wizard_stage { + self.creation_reads.wizard_stage = Some((self.creation_field_scope(app), stage)); + } + Ok(()) + } + + pub(in crate::jiansun) fn focus_brief_field(&mut self, field_key: &str, message: &str) { + if let Some((scope, stage)) = self.creation_reads.wizard_stage { + let template = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + let stage = if matches!(field_key, "brand" | "category" | "template") || !template_identity(&template) { + CreationStage::Template + } else if stage != CreationStage::Details { + CreationStage::Details + } else { + stage + }; + self.creation_reads.wizard_stage = Some((scope, stage)); + } + self.creation_reads.inline_errors.insert(field_key.to_owned(), message.to_owned()); + self.creation_reads.scroll_to_field = Some(field_key.to_owned()); + if let Some(rest) = field_key.strip_prefix("intake-barcode:") + && let Some((code, _)) = rest.split_once(':') + { + self.creation_reads.expanded_skus.remove(&format!("!{code}")); + self.creation_reads.expanded_skus.insert(code.to_owned()); + for group in normalized_color_groups(&self.creation_brief) { + if group.skus.iter().any(|sku| sku.barcode == code) { + self.creation_reads.expanded_colors.insert(group.id); + break; + } + } + } + } + + pub(in crate::jiansun) fn creation_action(&mut self, app: &mut PhotocraftApp, method: &str, mut input: Value) -> Result { + let mut method = method; + if matches!(method, "creation-catalog" | "creation-thumbnail") { + let expected_doc = self.creation_read_doc(app); + if input["doc"].as_u64().is_some_and(|id| Some(id) != expected_doc) { + return Err("项目已切换".into()); + } + if method == "creation-catalog" { + let kind = input["kind"].as_str().ok_or("目录类型无效")?; + self.request_creation_catalog(app, kind, input["query"].as_str().unwrap_or("").into(), input["refresh"] == true); + } else { + let id = input["id"].as_str().filter(|id| !id.is_empty()).ok_or("材质编号无效")?; + self.queue_creation_thumbnail(app, id); + } + return Ok(json!({"submitted":true,"readOnly":true})); + } + if method == "creation-new" { + if self.busy.is_some() { + return Err("请等待当前操作完成".into()); + } + self.creation_reads.staged_new_project = false; + self.creation_reads.staged_prior_draft = None; + self.creation_reads.wizard_stage = None; + app.run("file.new", json!({"name":"未命名详情页","width":1440,"height":1800}))?; + self.reference_intro_doc = app.session.active().map(|state| state.doc.id.0); + self.creation_open = true; + self.creation_step = 0; + self.library = false; + self.material = false; + return Ok(json!({"created":true})); + } + if method == "creation-view" { + self.show_creation_step(input["step"].as_u64().unwrap_or(0).min(4) as usize, app.session.active().is_some() || self.creation_reads.staged_new_project); + return Ok(Value::Null); + } + if self.busy.is_some() { + return Err("请等待当前操作完成".into()); + } + if method == "creation-product-platform" && !self.account["id"].is_string() { + return Err("请先登录素材库账号".into()); + } + if self.unknown && !matches!(method, "creation-recover" | "creation-read" | "creation-load") + && !(method == "creation-save" && self.scoped_production_pending()) + { + return Err("原请求结果待核查,不会重发".into()); + } + if self.creation_reads.staged_new_project { + if input["doc"].as_u64().is_some() { + return Err("新建资料尚未关联画布".into()); + } + self.ensure_creation_document(app)?; + } + let st = app.session.active().ok_or("请先新建项目")?; + if input["doc"].as_u64().is_some_and(|id| id != st.doc.id.0) { + return Err("项目已切换".into()); + } + input["doc"] = json!(st.doc.id.0); + input["baseRevision"] = json!(st.revision); + if method == "creation-import" { + self.creation_read_scope(app); + } + if method == "creation-import" && app.session.authorize.is_some() { + use base64::Engine as _; + let paths = input["paths"].as_array().filter(|a| !a.is_empty() && a.len() <= 8).ok_or("每次最多8张图片")?; + let paths = paths.iter().map(|path| path.as_str().filter(|path| !path.is_empty()).map(str::to_owned).ok_or("图片路径无效")) + .collect::, _>>()?; + let read = app.services.automation_read_limited.as_mut().ok_or("自动化导入尚未提供有界读取")?; + let mut images = Vec::new(); + let mut total = 0usize; + for path in paths { + let limit = (24usize * 1024 * 1024).saturating_sub(total).min(20 * 1024 * 1024); + if limit == 0 { return Err("本次产品图片总量超过24MiB".into()); } + let (name, bytes) = read(&path, limit)?; + if bytes.is_empty() || bytes.len() > limit { return Err("产品图片为空或超过读取上限".into()); } + total += bytes.len(); + images.push(json!({"name":name,"data":base64::engine::general_purpose::STANDARD.encode(bytes)})); + } + input["images"] = json!(images); + input.as_object_mut().ok_or("导入参数无效")?.remove("paths"); + method = "creation-import-data"; + } + if input["revision"].is_null() { + input["revision"] = self.creation["revision"].clone(); + } + if input["brief"].is_null() { + input["brief"] = self.brief_with_manual_fields(); + } + if input["width"].is_null() { + input["width"] = json!(self.creation_draft_width()); + } + if input["selected"].is_null() { + input["selected"] = json!(self.creation_selected); + } + if input["direction"].is_null() { + input["direction"] = json!(self.creation_direction); + } + if input["screens"].is_null() { + input["screens"] = self.creation_plan.clone(); + } + if method == "creation-save" && input.get("deliveryDir").is_none() { + input["deliveryDir"] = json!(self.creation_delivery_dir); + } + if matches!(method, "creation-save" | "creation-facts") { + update_detail_barcode(&mut input["brief"]); + } + input["model"] = json!(self.model); + input["imageModel"] = json!(self.image_model); + if matches!(method, "creation-generate" | "creation-load") { + self.owner_doc = Some(st.doc.id.0); + self.expected_revision = st.revision; + self.creation_base_revision = st.revision; + self.creation_run = None; + self.allow_apply = true; + self.creation_pending = None; + } + if matches!(method, "creation-save" | "creation-select" | "creation-plan-edit") { + self.creation_submitted_draft = Some(self.creation_draft()); + } + self.send(method, input); + Ok(json!({"submitted":self.busy.as_deref()==Some(method)})) + } + pub(in crate::jiansun) fn creation_submit(&mut self, app: &mut PhotocraftApp, method: &str, input: Value) { + if let Err(e) = self.creation_action(app, method, input) { + self.error = e; + } + } + pub(in crate::jiansun) fn catalog(&mut self, app: &mut PhotocraftApp, kind: &str, query: String) { + self.request_creation_catalog(app, kind, query, false); + } + + pub(in crate::jiansun) fn brief_setup_warning(&self) -> Option<(&'static str, &'static str, &'static str)> { + if !self.key_saved { + Some(("尚未连接个人 Key,请先配置个人 Key", "个人 Key 未连接", "配置个人 Key")) + } else if !(self.model_ready && self.image_ready) { + Some(("尚未配置对话或生图模型", "模型未配置", "选择模型")) + } else { + None + } + } + + pub(in crate::jiansun) fn open_brief_setup_settings(&mut self) { + self.open_model_settings(); + if !self.key_saved { + self.key_settings = true; + } + } + + + pub(in crate::jiansun) fn save_sku_colors(&mut self, variants: Vec) { + for field in ["skuBindings", "barcodeBindings"] { + if let Some(bindings) = self.creation_brief.get_mut(field).and_then(Value::as_object_mut) { + if field == "barcodeBindings" && variants.len() == 1 { + if let Some(default) = bindings.remove("default") { + if let Some(id) = variants[0]["id"].as_str() { + bindings.entry(id.to_owned()).or_insert(default); + } + } + } + bindings.retain(|id, _| id == "default" || variants.iter().any(|variant| variant["id"] == *id)); + } + } + set_brief_variants(&mut self.creation_brief, variants); + if !self.creation_brief["outputVariantIds"].is_object() { + self.creation_brief["outputVariantIds"] = json!({}); + } + self.creation_dirty = true; + } + + pub(in crate::jiansun) fn sku_color_removable(&self, variant: &Value) -> bool { + variant["images"].as_array().is_none_or(Vec::is_empty) + && !self.template_workflow["variants"].as_array().into_iter().flatten().any(|saved| saved["id"] == variant["id"]) + && !["detail", "main_images"].into_iter().any(|key| { + self.creation_brief["outputVariantIds"][key].as_array().into_iter().flatten().any(|id| *id == variant["id"]) + }) + } + + + pub(in crate::jiansun) fn enter_creation_canvas(&mut self, app: &mut PhotocraftApp, template: &Value, generate: bool, refinement: Option) { + if let Err(error) = self.ensure_creation_document(app) { + self.error = error; + return; + } + let mut brief = self.creation_brief.clone(); + update_detail_barcode(&mut brief); + let variants = brief_variants(&brief); + set_brief_variants(&mut brief, variants); + brief["templateSelection"] = template.clone(); + if let Err(error) = self.slot_action(app, "slot-skeleton", json!({ + "brief": brief, + "template": template, + "outputId": "detail", + "generateProduct": generate, + "deliveryDir": self.creation_delivery_dir, + "refinement": refinement, + })) { + self.error = error; + } else { + self.creation_reads.new_project_doc = None; + self.creation_open = false; + self.creation_step = 3; + self.library = false; + self.material = false; + } + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/reducers.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/reducers.rs new file mode 100644 index 00000000..dac581b0 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/reducers.rs @@ -0,0 +1,312 @@ +use super::super::{Document, PhotocraftApp, Request, Value, Workspace, json, stitch_ui}; +use super::brief::{image_rows, merge_platform_barcode_cards, merge_platform_brief_preserving_manual_edits, non_empty_str, saved_creation_draft_brief}; +use super::form_widgets_ui::spu_field; +use super::intake::{add_slot_images, assign_platform_images, fill_platform_intake}; + +pub(in crate::jiansun) fn form_editable(busy: Option<&str>, unknown: bool) -> bool { + !unknown && (busy.is_none() || matches!(busy, Some("creation-save" | "creation-select" | "creation-plan-edit" | "pi-rules"))) +} +pub(in crate::jiansun) fn bound(w: &Workspace, app: &PhotocraftApp, value: &Value) -> bool { + value["accountId"] == w.account["id"] && value["origin"] == w.origin && value["doc"].as_u64() == app.session.active().map(|s| s.doc.id.0) +} +pub(in crate::jiansun) fn allowed(w: &mut Workspace, app: &PhotocraftApp, value: &Value) -> Result { + let run = value["run"].as_str().filter(|s| s.len() == 36).ok_or("生成会话无效")?; + let same = bound(w, app, value) + && value["baseRevision"].as_u64() == Some(w.creation_base_revision) + && w.allow_apply + && !w.unknown + && w.busy.as_deref() == Some("creation-generate") + && app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc && s.revision == w.expected_revision); + if same && w.creation_run.is_none() { + w.creation_run = Some(run.into()); + } + Ok(json!({"allowed":same && w.creation_run.as_deref()==Some(run),"revision":w.expected_revision})) +} +pub(in crate::jiansun) fn canvas_received(w: &mut Workspace, app: &mut PhotocraftApp, mut doc: Box, value: Value) { + if !bound(w, app, &value) { + return; + } + let explicit = value["explicit"] == true; + let permitted = w.allow_apply + && app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc && s.revision == w.expected_revision) + && (explicit || (value["baseRevision"].as_u64() == Some(w.creation_base_revision) && value["run"].as_str() == w.creation_run.as_deref())); + if !permitted { + w.creation_pending = Some((doc, value)); + w.creation_progress = "生成结果已保留,点击载入后继续编辑".into(); + return; + } + let Some(id) = app.session.active().map(|s| s.doc.id) else { + return; + }; + doc.id = id; + let label = if explicit { "载入生成结果".into() } else { format!("生成第 {} 屏", value["sequence"].as_u64().unwrap_or(0) + 1) }; + match app.session.edit(&label, move |current, selected| { + *current = *doc; + *selected = None; + Ok(()) + }) { + Ok(()) => { + app.sync_views(); + w.expected_revision = app.session.active().map_or(0, |s| s.revision); + w.creation = value["creation"].clone(); + w.creation_pending = None; + w.creation_open = false; + w.creation_step = 3; + w.library = false; + w.material = false; + w.draft_changed = true; + w.sync_dirty = true; + if explicit { + w.allow_apply = false; + } + } + Err(e) => w.error = e.to_string(), + } +} +pub(in crate::jiansun) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, value: &Value) { + if bound(w, app, value) { + w.receive_template_snapshot(&value["templateWorkflow"], false); + } + if !bound(w, app, value) { + return; + } + if method == "creation-progress" { + w.creation_progress = value["text"].as_str().unwrap_or("").chars().take(4000).collect(); + return; + } + if method == "creation-product-platform" && value["platformBrief"].is_object() { + w.creation_read_scope(app); + let current = w.brief_with_manual_fields(); + let incoming = &value["platformBrief"]; + let current_spu = non_empty_str(¤t["platformFacts"]["spu"]) + .or_else(|| non_empty_str(¤t["normalizedProduct"]["identity"]["spu"])) + .or_else(|| non_empty_str(¤t[spu_field(¤t)])); + let merge_existing = current_spu.is_none_or(|spu| incoming["identifier"] == spu); + let mut next_brief = incoming.clone(); + let mut preserved = 0; + if merge_existing { + let edited = current["manualFields"].as_array().into_iter().flatten() + .filter_map(Value::as_str).map(str::to_owned).collect(); + (next_brief, preserved) = merge_platform_brief_preserving_manual_edits(¤t, incoming, &edited); + if let Some(markers) = current.get("manualFields") { + next_brief["manualFields"] = markers.clone(); + } + fill_platform_intake(&mut next_brief); + merge_platform_barcode_cards(¤t, &mut next_brief, &edited); + } else { + w.creation_reads.manual_edited_fields.clear(); + fill_platform_intake(&mut next_brief); + } + assign_platform_images(&mut next_brief); + w.creation_brief = next_brief; + w.creation_dirty = true; + w.sync_dirty = true; + w.draft_changed = true; + w.creation_reads.platform_message = value["message"].as_str().unwrap_or("").into(); + w.creation_reads.platform_sync_note = if preserved > 0 { + format!("已重新拉取平台资料,保留了你手动修改的 {preserved} 项字段") + } else { + String::new() + }; + return; + } + if let Some(images) = value["images"].as_array() { + if method == "creation-import" { + w.match_imported_reference_paths(app, images); + } + if value["imageSlot"].is_object() { + match add_slot_images(&mut w.creation_brief, &value["imageSlot"], images) { + Ok(()) => { + w.creation_dirty = true; + w.sync_dirty = true; + } + Err(error) => w.creation_reads.reference_import_error = error, + } + return; + } + let mut current = w.creation_brief["images"].as_array().cloned().unwrap_or_default(); + let references = image_rows(&w.creation_brief); + for image in images { + if !references.iter().any(|(existing, _)| existing["source"] == image["source"]) && !current.iter().any(|v| v["source"] == image["source"]) { + current.push(image.clone()); + } + } + w.creation_brief["images"] = json!(current); + w.creation_dirty = true; + w.sync_dirty = true; + } + if value["creation"].is_object() { + let newer_draft = if matches!(method, "creation-save" | "creation-select" | "creation-plan-edit") { + w.creation_submitted_draft.take().filter(|sent| *sent != w.creation_draft()).map(|_| w.creation_draft()) + } else { None }; + let edited_plan = (w.creation_plan != w.creation["plan"]["screens"]).then(|| w.creation_plan.clone()); + let entries = w.creation_brief.get("barcodeEntries").cloned(); + let same_doc = w.creation_doc == value["doc"].as_u64(); + w.creation = value["creation"].clone(); + if same_doc && w.creation["brief"].is_object() + && w.creation["brief"].get("barcodeEntries").is_none() + && let Some(entries) = entries + { + w.creation["brief"]["barcodeEntries"] = entries; + } + w.creation_doc = value["doc"].as_u64(); + let template_binding = w.template_binding(app.session.active().map(|state| state.doc.id.0)); + w.template_ui.bind_project(&template_binding); + w.creation_read_failed = false; + if !w.creation_dirty || !matches!(method, "creation-read" | "creation-import" | "creation-import-data" | "creation-import-library" | "creation-rules") { + w.creation_brief = w.creation["brief"].clone(); + w.creation_dirty = false; + w.creation_selected = + w.creation["sellingPoints"]["selected"].as_array().map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect()).unwrap_or_default(); + w.creation_direction = w.creation["sellingPoints"]["direction"].as_str().unwrap_or("").into(); + w.creation_plan = w.creation["plan"]["screens"].clone(); + w.creation_width = w.creation["width"].as_u64().unwrap_or_default() as u32; + w.creation_delivery_dir = super::product_production::delivery_dir(&w.creation); + if method == "creation-save" + && let Some(plan) = edited_plan + { + w.creation_plan = plan; + w.creation_dirty = true; + } + } + if let Some(draft) = newer_draft { + w.creation_brief = draft["brief"].clone(); + w.creation_width = draft["width"].as_u64().unwrap_or_default() as u32; + w.creation_delivery_dir = super::product_production::delivery_dir(&draft); + w.creation_plan = draft["screens"].clone(); + w.creation_direction = draft["direction"].as_str().unwrap_or("").into(); + w.creation_selected = draft["selected"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); + w.creation_dirty = true; + } + if method == "creation-read" && w.creation_restore_draft.is_object() { + let draft = std::mem::take(&mut w.creation_restore_draft); + if let Some(brief) = saved_creation_draft_brief(&w.creation, &draft) { + w.creation_brief = brief.clone(); + w.creation_width = draft["width"].as_u64().unwrap_or_default() as u32; + if draft["screens"].is_array() { + w.creation_plan = draft["screens"].clone(); + } + if let Some(direction) = draft["direction"].as_str() { + w.creation_direction = direction.into(); + } + if let Some(selected) = draft["selected"].as_array() { + w.creation_selected = selected.iter().filter_map(Value::as_str).take(20).map(str::to_owned).collect(); + } + w.creation_delivery_dir = super::product_production::delivery_dir(&draft); + w.creation_dirty = w.creation_brief != w.creation["brief"] + || w.creation_plan != w.creation["plan"]["screens"] + || w.creation_direction != w.creation["sellingPoints"]["direction"].as_str().unwrap_or("") + || w.creation_delivery_dir != super::product_production::delivery_dir(&w.creation); + w.restored_creation_signature = w.creation_dirty.then(|| w.creation_draft().to_string()); + } + } + } + if method == "creation-read" && !w.creation_dirty && !w.unknown && w.busy.is_none() && value["pending"] != true + && let Some(revision) = value["resumeMaterialDelivery"].as_u64() + { + w.send("project-sync", json!({"doc":value["doc"],"revision":revision,"status":"completed","resume":true})); + } + if method == "creation-facts" && value["pending"] != true { + w.creation_step = 1; + } + if method == "creation-plan" && value["pending"] != true { + w.creation_step = 2; + } + if value["pending"] == true { + w.unknown = true; + w.creation_progress = "原请求待核查".into(); + } else if method == "creation-recover" { + w.unknown = false; + } + if let Some(message) = value["message"].as_str() { + w.creation_progress = message.into(); + } + if method != "creation-read" { + w.sync_dirty = true; + } + if method == "creation-save" { + let _ = w.tx.send(Request::Action("pi-rules".into(), json!({"doc":value["doc"]}))); + } +} +pub(in crate::jiansun) fn sync_received(w: &mut Workspace, app: &PhotocraftApp, value: &Value) { + if !bound(w, app, value) { + return; + } + for key in ["cloudLink", "syncedRevision", "status"] { + if !value[key].is_null() { + w.project_context[key] = value[key].clone(); + } + } + let same = app.session.active().is_some_and(|s| value["revision"].as_u64() == Some(s.revision)); + w.sync_dirty = !(same && value["syncDirty"] != true && w.sync_request_meta == w.sync_signature()); + if let Some(items) = value["projects"].as_array() { + w.merge_project_receipt(app, items); + } + if let Some(id) = value["materialDelivery"]["materialId"].as_str() { + w.project_context["materialDelivery"] = value["materialDelivery"].clone(); + w.note(format!("成品已提交素材库,素材 ID:{id}")); + w.delivery_completion = true; + w.sync_confirm = true; + w.listing_read_at = None; + w.listing_read_error = None; + w.finished_web_error = None; + } + w.project_refresh_requested = true; + w.creation_progress = if value["materialDelivery"]["materialId"].is_string() { + "成品已提交素材库" + } else if w.sync_dirty { "云端已保存该版本,当前仍有新修改" } else { "已同步" }.into(); +} +pub(in crate::jiansun) fn listing_status_received(w: &mut Workspace, app: &PhotocraftApp, value: &Value) { + if !bound(w, app, value) { + return; + } + w.listing_read_error = value["error"].as_str().map(str::to_owned); + if let Some(receipt) = value["delivery"].as_object() { + if receipt.get("materialId").and_then(Value::as_str).is_none() { + return; + } + let current = &mut w.project_context["materialDelivery"]; + if current["materialId"] != value["delivery"]["materialId"] { + *current = Value::Object(receipt.clone()); + } else if current["state"] != "removed" + && (value["delivery"]["state"] == "removed" + || value["delivery"]["listingStatus"]["sequence"].as_u64() >= current["listingStatus"]["sequence"].as_u64()) + { + current["state"] = value["delivery"]["state"].clone(); + current["listingStatus"] = value["delivery"]["listingStatus"].clone(); + } + } +} + +pub(in crate::jiansun) fn finished_web_received(w: &mut Workspace, app: &PhotocraftApp, value: &Value) { + if bound(w, app, value) { + w.finished_web_pending = false; + w.finished_web_error = value["error"].as_str().map(str::to_owned); + } +} + +pub(in crate::jiansun) fn listing_status_text(receipt: &Value) -> (&'static str, stitch_ui::StatusTone) { + use stitch_ui::StatusTone::{Error, Neutral}; + if receipt["state"] == "removed" { + return ("素材已撤回", Neutral); + } + match receipt["listingStatus"]["state"].as_str() { + Some("pending") => ("等待上架", Neutral), + Some("listing") => ("上架中", Neutral), + Some("listed") => ("已上架", Neutral), + Some("failed") => ("上架失败", Error), + _ if receipt["state"] == "completed" => ("暂无上架状态", Neutral), + _ => ("正在查询上架状态", Neutral), + } +} + +// The import worker reports a final receipt rather than intermediate bytes; +// expose activity only and never manufacture an upload percentage. +pub(in crate::jiansun) fn reference_import_activity(busy: Option<&str>) -> Option<&'static str> { + match busy { + Some("creation-import" | "creation-import-data") => Some("正在导入参考图"), + Some("creation-import-library") => Some("正在读取素材库参考图"), + _ => None, + } +} + diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/references_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/references_ui.rs new file mode 100644 index 00000000..9b93adb3 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/references_ui.rs @@ -0,0 +1,253 @@ +use super::super::{PhotocraftApp, Ui, Value, Workspace, agent_panel::rect_value, json, stitch_kit, stitch_state::Tone, stitch_ui}; +use super::REFERENCE_DROP_HINT; +use super::form_widgets_ui::{IntakeScope, edit_named_with_error, image_slot, in_image_slot, intake_fields_with_errors, intake_hint, intake_label, material_thumbnail}; +use super::reducers::form_editable; +use super::structure_preview_ui::{reference_folder_paths, reference_image_path}; +use crate::theme::agent_scale::Type; + +impl Workspace { + pub(in crate::jiansun) fn add_reference_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) -> egui::Rect { + self.reference_picker(app, ui, width, egui::Id::unique("creation-reference-drop"), None, Value::Null) + } + + pub(in crate::jiansun) fn reference_picker(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, + id: egui::Id, labels: Option<(&str, &str)>, slot: Value, + ) -> egui::Rect { + let supported = ui.input(|input| { + let files = &input.raw.hovered_files; + !files.is_empty() && files.len() <= 8 && files.iter().all(|file| { + if let Some(path) = &file.path { + reference_image_path(path) || (slot.is_null() && files.len() == 1 && path.is_dir()) + } else { + matches!(file.mime.as_str(), "image/png" | "image/jpeg" | "image/webp") + } + }) + }); + let enabled = ui.is_enabled() && self.busy.is_none() && !self.unknown; + let drop_pointer = if supported && enabled { + let to_local = ui.ctx().layer_transform_from_global(ui.layer_id()).unwrap_or_default(); + app.services.cursor_pos.as_mut().and_then(|cursor| cursor(ui.ctx())) + .map(|point| to_local * point).filter(|point| ui.clip_rect().contains(*point)) + } else { + None + }; + let add_reference = if let Some((label, placeholder)) = labels { + stitch_ui::labeled_file_drop_zone(ui, id, width, drop_pointer, enabled, self.reduce_motion, label, Some(placeholder)) + } else { + stitch_ui::file_drop_zone(ui, id, width, drop_pointer, enabled, self.reduce_motion) + } + .on_hover_text("支持 PNG、JPG、WebP;每次最多 8 张,单张不超过 20 MB"); + if slot.is_null() { self.control_geometry("reference-add", add_reference.rect); } + if enabled && add_reference.clicked() { + self.open_reference_dialog(app, slot, false); + } + add_reference.rect + } + + pub(in crate::jiansun) fn open_reference_dialog(&mut self, app: &mut PhotocraftApp, slot: Value, folder: bool) { + let id = app.session.active().map(|s| s.doc.id.0); + let staged = self.creation_reads.staged_new_project; + let stage = self.creation_reads.wizard_stage; + let account = self.account["id"].clone(); + let origin = self.origin.clone(); + let request = if folder { + crate::FileDialogRequest::Folder { initial_dir: None } + } else { + crate::FileDialogRequest::Open { + multiple: slot["multiple"] != false, + initial_dir: None, + extensions: Some(vec!["png".into(), "jpg".into(), "jpeg".into(), "webp".into()]), + } + }; + let result = app.ask_file(request, move |app, answer| { + if app.session.active().map(|s| s.doc.id.0) != id || app.jiansun.as_ref().is_none_or(|w| { + w.account["id"] != account || w.origin != origin || (w.creation_doc != id && !staged) + || w.creation_reads.staged_new_project != staged || w.creation_reads.wizard_stage != stage + || !w.creation_open || w.creation_step != 0 || w.library || w.material + }) { + return Err("账号或项目已切换,未导入到其他项目".into()); + } + let paths = match answer { + crate::FileDialogAnswer::Paths(paths) => Ok(paths), + crate::FileDialogAnswer::FolderTo(path) => reference_folder_paths(std::path::Path::new(&path)), + _ => Err("请选择本机产品图片".into()), + }; + if let Err(error) = paths.and_then(|paths| app.import_reference_paths(paths, slot)) + && let Some(w) = app.jiansun.as_mut() + { + w.creation_reads.reference_import_error = error; + } + Ok(Value::Null) + }); + if let Err(error) = result { + self.creation_reads.reference_import_error = error; + } + } + + + pub(in crate::jiansun) fn platform_spu_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32, has_synced: bool) { + let query_id = scope.with("platform-spu-query"); + let seed = if self.creation_brief["identifierType"] == "spu" { &self.creation_brief["identifier"] } + else { &self.creation_brief["deliverySpu"] }; + let mut query = ui.data(|data| data.get_temp::(query_id)).unwrap_or_else(|| seed.clone()); + let loading = self.busy.as_deref() == Some("creation-product-platform"); + let logged_in = self.account["id"].is_string(); + let error = self.creation_reads.inline_errors.get("identifier").cloned(); + let scroll = self.creation_reads.scroll_to_field.as_deref() == Some("identifier"); + if scroll { + self.creation_reads.scroll_to_field = None; + } + ui.horizontal_wrapped(|ui| { + let btn_reserve = 128.0; + let input_w = if width >= 340.0 { (width - btn_reserve).max(140.0) } else { width }; + let (edited, resp) = edit_named_with_error( + ui, + query_id, + &mut query, + input_w, + false, + "输入 SPU 型号或条码", + "SPU 型号", + error.as_deref(), + scroll, + ); + if edited { + self.creation_reads.inline_errors.remove("identifier"); + } + self.control_geometry("identifier", resp.rect); + let spu = query.as_str().unwrap_or("").trim(); + let btn_label = if loading { "拉取中…" } else if has_synced { "重新拉取" } else { "拉取资料" }; + let fetch = stitch_ui::action_button( + ui, + btn_label, + stitch_ui::ButtonRole::Secondary, + logged_in && form_editable(self.busy.as_deref(), self.unknown) && !spu.is_empty(), + ); + self.control_geometry("platform-fetch", fetch.rect); + if loading { + stitch_ui::ai_loader(ui, scope.with("platform-fetch-loader"), true, self.reduce_motion); + } + if fetch.clicked() { + self.creation_reads.platform_message.clear(); + self.creation_reads.platform_sync_note.clear(); + if let Err(error) = self.creation_action(app, "creation-product-platform", json!({"spu":spu})) { + self.creation_reads.platform_message = error; + } + } + }); + ui.data_mut(|data| data.insert_temp(query_id, query)); + let message = if logged_in { self.creation_reads.platform_message.as_str() } else { "请先登录素材库账号后再拉取产品平台资料" }; + if !message.is_empty() { + stitch_kit::inline_notice(ui, "triangle-alert", Tone::Warning, message, |_| {}); + } + } + + #[allow(clippy::too_many_arguments)] + pub(in crate::jiansun) fn barcode_intake_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32, + code: &str, fields: &[&Value], images: &[&Value], + ) { + let mut values = self.creation_brief["intake"]["barcodeValues"][code].clone(); + if !values.is_object() { values = json!({}); } + if !fields.is_empty() && intake_fields_with_errors( + ui, scope, width, fields, IntakeScope::Barcode, &mut values, self.reduce_motion, Some(code), + &mut self.creation_reads.inline_errors, &mut self.creation_reads.scroll_to_field, + &mut self.creation_reads.manual_edited_fields, + ) { + self.creation_brief["intake"]["barcodeValues"][code] = values; + self.creation_dirty = true; + } + for field in images { + self.image_slot_ui(app, ui, width, field, Some(code)); + } + } + + pub(in crate::jiansun) fn image_slot_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, field: &Value, barcode: Option<&str>) { + let slot = image_slot(&self.creation_brief["intake"]["templateId"], field, barcode); + self.image_slot_control_ui(app, ui, width, &intake_label(field), intake_hint(field), slot); + } + + pub(in crate::jiansun) fn image_slot_control_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, label: &str, placeholder: &str, slot: Value) { + stitch_kit::label(ui, label, Type::Meta, Tone::Quiet); + let key = self.creation_field_scope(app).with(("reference-image-slot", slot.to_string())); + let drop = self.reference_picker(app, ui, width, key, Some((label, placeholder)), slot.clone()); + if ui.is_enabled() && let Some(mut target) = self.reference_drop_geometry(app, ui, drop) { + target["slot"] = slot.clone(); + target["label"] = json!(label); + target["placeholder"] = json!(placeholder); + self.creation_view_geometry["imageSlots"][key.value().to_string()] = target; + } + let rows = self.creation_brief["images"].as_array().cloned().unwrap_or_default(); + let mut remove = None; + for (index, image) in rows.iter().enumerate().filter(|(_, image)| in_image_slot(image, &slot)) { + let Some(source) = image["source"].as_str() else { continue }; + self.queue_creation_reference(app, source); + let preview_key = super::creation_reads::reference_key(source); + ui.horizontal(|ui| { + material_thumbnail(ui, self.creation_thumbs.get(&preview_key), self.creation_thumbnail_loading(&preview_key), + self.creation_thumbnail_error(&preview_key).is_some()); + let response = stitch_ui::icon_button(ui, "trash", 28.0, false, "删除图片"); + if response.clicked() { remove = Some(index); } + let name = image["name"].as_str().unwrap_or("图片"); + ui.add(egui::Label::new(egui::RichText::new(name).font(Type::Meta.font_id())).truncate()).on_hover_text(name); + }); + } + if let Some(index) = remove { + self.creation_brief["images"] = json!(rows.into_iter().enumerate() + .filter_map(|(position, image)| (position != index).then_some(image)).collect::>()); + self.creation_dirty = true; + } + } + + pub(in crate::jiansun) fn source_picker(&mut self, ui: &mut Ui) { + let choices = [("upload", "手工录入"), ("product_platform", "产品平台"), ("library", "素材库产品")]; + let options = choices.map(|(_, label)| (label, true)); + let selected = choices.iter().position(|(value, _)| self.creation_brief["source"] == *value).unwrap_or(0); + let rail = stitch_ui::segmented_control(ui, ui.scope_id().with("creation-source"), &options, selected, self.reduce_motion); + if let Some(index) = rail.selected && index != selected { + self.creation_brief["source"] = json!(choices[index].0); + self.creation_dirty = true; + } + let mut bounds = egui::Rect::NOTHING; + let mut geometry = Vec::new(); + for ((value, label), response) in choices.into_iter().zip(rail.responses) { + bounds = bounds.union(response.rect); + self.control_geometry(&format!("source-{value}"), response.rect); + geometry.push(json!({"id":value,"label":label,"ready":true,"selected":self.creation_brief["source"] == value,"rect":rect_value(response.rect)})); + } + self.control_geometry("source", bounds); + self.creation_view_geometry["sourceChoices"] = json!(geometry); + self.creation_view_geometry["popups"]["source"] = json!({"open":false,"loading":false,"ready":true,"rect":null,"rows":[]}); + } + + pub(in crate::jiansun) fn reference_drop_geometry(&self, app: &PhotocraftApp, ui: &Ui, rect: egui::Rect) -> Option { + let visible = rect.intersect(ui.clip_rect()); + if !visible.is_positive() || !visible.is_finite() { + return None; + } + let layer = ui.layer_id(); + let global = ui.ctx().layer_transform_to_global(layer).unwrap_or_default() * visible; + Some(json!({ + "doc":app.session.active().map(|state| state.doc.id.0), + "accountId":self.account["id"],"origin":self.origin,"rect":rect_value(global), + "viewport":ui.ctx().viewport_id().0.value(),"layer":layer.id.value(), + })) + } + + pub(in crate::jiansun) fn references_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { + let gallery = ui.scope(|ui| self.visual_assets_gallery_ui(app, ui, width)); + if gallery.inner { + if let Some(target) = self.reference_drop_geometry(app, ui, gallery.response.rect) { + self.creation_view_geometry["referenceDrop"] = target; + } + } else { + if self.creation_reads.wizard_stage.is_none() { + stitch_kit::caption(ui, "请在「商品档案与款式」中上传模板所需图片。"); + } else if !self.creation_reads.reference_import_error.is_empty() + && self.creation_reads.reference_import_error != REFERENCE_DROP_HINT + { + stitch_ui::status_label(ui, &self.creation_reads.reference_import_error, stitch_ui::StatusTone::Error); + } + } + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/review_hints.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/review_hints.rs new file mode 100644 index 00000000..02539909 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/review_hints.rs @@ -0,0 +1,87 @@ +use super::super::Value; + + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(in crate::jiansun) struct ReviewHintItem { + pub(in crate::jiansun) message: String, + pub(in crate::jiansun) output_id: Option, + pub(in crate::jiansun) variant_id: Option, + pub(in crate::jiansun) slot_id: Option, + pub(in crate::jiansun) layer_id: Option, +} + +impl ReviewHintItem { + pub(in crate::jiansun) fn has_target(&self) -> bool { + self.output_id.is_some() || self.slot_id.is_some() || self.layer_id.is_some() + } +} + +pub(in crate::jiansun) fn infer_review_hint_output_id(message: &str) -> Option { + if message.starts_with("详情页:") { + Some("detail".to_owned()) + } else if message.starts_with("主图:") { + Some("main_images".to_owned()) + } else if message.starts_with("SKU 图:") || message.starts_with("SKU:") { + Some("sku_images".to_owned()) + } else { + None + } +} + +pub(in crate::jiansun) fn parse_review_hints(value: &Value, out: &mut Vec) { + let Some(items) = value.as_array() else { return }; + for entry in items { + let item = if let Some(text) = entry.as_str().map(str::trim).filter(|s| !s.is_empty()) { + ReviewHintItem { + message: text.to_owned(), + output_id: infer_review_hint_output_id(text), + variant_id: None, + slot_id: None, + layer_id: None, + } + } else if let Some(obj) = entry.as_object() { + let Some(message) = obj + .get("message") + .or_else(|| obj.get("text")) + .or_else(|| obj.get("hint")) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + else { + continue; + }; + let output_id = obj + .get("outputId") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .or_else(|| infer_review_hint_output_id(message)); + let slot_id = obj + .get("slotId") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + let layer_id = obj + .get("layerId") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + ReviewHintItem { + message: message.to_owned(), + output_id, + variant_id: obj.get("variantId").and_then(Value::as_str).map(str::to_owned), + slot_id, + layer_id, + } + } else { + continue; + }; + if !out.contains(&item) { + out.push(item); + } + } +} + diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/structure_preview_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/structure_preview_ui.rs new file mode 100644 index 00000000..9d4ae94b --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/structure_preview_ui.rs @@ -0,0 +1,276 @@ +use super::super::{PhotocraftApp, Tokens, Ui, Value, json, stitch_kit, stitch_state::Tone}; +use super::{REFERENCE_DROP_HINT, WIZARD_WIDTH}; +use super::brief::template_identity; +use super::form_widgets_ui::{current_image_slot, preview_size}; +use crate::theme::{AGENT_SEMANTIC, agent_scale::{Type, icon, radius, space}}; +use egui::vec2; + +pub(in crate::jiansun) fn wizard_column(ui: &mut Ui, draw: impl FnOnce(&mut Ui)) { + let width = ui.available_width().min(WIZARD_WIDTH); + let inset = (ui.available_width() - width) / 2.0; + let gap = ui.spacing().item_spacing.x; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + ui.add_space(inset); + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.x = gap; + ui.set_width(width); + draw(ui); + }); + }); +} + + +pub(in crate::jiansun) fn preview_frame(value: &Value, width: f64, height: f64, line: bool) -> Option<[f32; 4]> { + let (x, y, w, h) = (value["x"].as_f64()?, value["y"].as_f64()?, value["width"].as_f64()?, value["height"].as_f64()?); + if ![x, y, w, h].iter().all(|n| n.is_finite()) || x < 0.0 || y < 0.0 || w <= 0.0 || h < 0.0 || (!line && h == 0.0) + || x + w > width + 0.01 || y + h > height + 0.01 { return None; } + Some([x as f32, y as f32, w as f32, h as f32]) +} + +pub(in crate::jiansun) fn preview_color(value: &Value) -> Option { + let value = value.as_str()?; + if value.len() != 7 || !value.starts_with('#') || !value[1..].bytes().all(|b| b.is_ascii_hexdigit()) { return None; } + let n = u32::from_str_radix(&value[1..], 16).ok()?; + Some(egui::Color32::from_rgb((n >> 16) as u8, (n >> 8) as u8, n as u8)) +} + +/// Only accept a geometry preview attached to the exact selected immutable +/// package and current brand/category. It is never a product photograph. +pub(in crate::jiansun) fn verified_structure_preview<'a>(row: &'a Value, selected: &Value, brand: &str, category: &str) -> Option<&'a Value> { + if brand.is_empty() || category.is_empty() || row["brandId"] != brand || row["categoryId"] != category + || row["id"] != selected["id"] || row["version"] != selected["version"] || row["contentHash"] != selected["contentHash"] + || !template_identity(row) { return None; } + let preview = &row["structurePreview"]; + if preview["contentHash"] != row["contentHash"] || preview["outputId"].as_str().is_none_or(str::is_empty) { return None; } + let width = preview["width"].as_f64()?; + let height = preview["height"].as_f64()?; + if !matches!(preview["width"].as_u64(), Some(750 | 1440)) || !height.is_finite() || !(1.0..=30_000.0).contains(&height) + || (!preview["background"].is_null() && preview_color(&preview["background"]).is_none()) { return None; } + let slots = preview["slots"].as_array().filter(|items| !items.is_empty() && items.len() <= 120)?; + if slots.iter().any(|slot| !matches!(slot["kind"].as_str(), Some("image" | "text")) || preview_frame(&slot["frame"], width, height, false).is_none()) { return None; } + let decorations = preview["decorations"].as_array().filter(|items| items.len() <= 120)?; + if decorations.iter().any(|item| { + let kind = item["kind"].as_str(); + !matches!(kind, Some("rect" | "line")) || preview_frame(&item["frame"], width, height, kind == Some("line")).is_none() + || preview_color(&item["color"]).is_none() || !item["opacity"].as_f64().is_some_and(|n| n.is_finite() && (0.0..=1.0).contains(&n)) + }) { return None; } + Some(preview) +} + +/// Paint only validated template geometry. This is a structural diagram, +/// never a substitute for an authorized template cover photograph. +pub(in crate::jiansun) fn paint_template_structure(ui: &Ui, preview: &Value, area: egui::Rect) { + let width = preview["width"].as_f64().unwrap_or(1.0) as f32; + let height = preview["height"].as_f64().unwrap_or(1.0) as f32; + let scale = (area.width() / width).min(area.height() / height); + let page = egui::Rect::from_center_size(area.center(), vec2(width * scale, height * scale)); + let painter = ui.painter().with_clip_rect(page); + painter.rect_filled(page, 2.0, preview_color(&preview["background"]).unwrap_or(egui::Color32::WHITE)); + let paint_frame = |frame: [f32; 4]| egui::Rect::from_min_size(page.min + vec2(frame[0] * scale, frame[1] * scale), vec2(frame[2] * scale, frame[3] * scale)); + let decorations = |above: bool| { + for item in preview["decorations"].as_array().into_iter().flatten().filter(|item| (item["aboveImages"] == true) == above) { + if let (Some(frame), Some(color), Some(opacity)) = (preview_frame(&item["frame"], width as f64, height as f64, item["kind"] == "line"), preview_color(&item["color"]), item["opacity"].as_f64()) { + let rect = paint_frame(frame); + let color = color.gamma_multiply(opacity as f32); + if item["kind"] == "line" { painter.line_segment([rect.left_top(), rect.right_bottom()], egui::Stroke::new(1.0, color)); } + else { painter.rect_filled(rect, 0, color); } + } + } + }; + let t = Tokens::get(ui.ctx()).agent(); + decorations(false); + for slot in preview["slots"].as_array().into_iter().flatten().filter(|slot| slot["kind"] == "image") { + if let Some(frame) = preview_frame(&slot["frame"], width as f64, height as f64, false) { painter.rect_filled(paint_frame(frame), 0, t.text_dim); } + } + decorations(true); + for slot in preview["slots"].as_array().into_iter().flatten().filter(|slot| slot["kind"] == "text") { + if let Some(frame) = preview_frame(&slot["frame"], width as f64, height as f64, false) { + let rect = paint_frame(frame); + painter.rect_stroke(rect, 0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); + } + } +} + +pub(in crate::jiansun) fn structure_preview_card( + ui: &mut Ui, + preview: Option<&Value>, + cover: Option<&egui::TextureHandle>, + name: &str, + version: &str, + screen_count: Option, + canvas_width: u32, + status: Option<&str>, +) { + let t = Tokens::get(ui.ctx()).agent(); + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = space::MD; + let thumb_size = if cover.is_some() || preview.is_some() { vec2(136.0, 184.0) } else { vec2(96.0, 128.0) }; + let (area, _) = ui.allocate_exact_size(thumb_size, egui::Sense::hover()); + ui.painter().rect_filled(area, radius::CONTROL, t.dock); + ui.painter().rect_stroke(area, radius::CONTROL, egui::Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); + if let Some(texture) = cover { + let size = preview_size(texture.size_vec2(), area.shrink(4.0).size()); + let rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, area); + ui.painter().image(texture.id(), rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text); + } else if let Some(preview) = preview { + paint_template_structure(ui, preview, area.shrink(4.0)); + } else { + crate::icons::paint(ui, area.translate(vec2(0.0, -10.0)), "layers", icon::LG, t.text_dim); + ui.painter().text( + egui::pos2(area.center().x, area.center().y + 18.0), + egui::Align2::CENTER_CENTER, + "暂无预览图", + Type::Meta.font_id(), + t.text_dim, + ); + } + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = space::XS; + ui.add(egui::Label::new(egui::RichText::new(name).font(Type::Body.semibold()).color(t.text)).wrap()); + let mut facts = Vec::new(); + if let Some(count) = screen_count { + facts.push(format!("{count} 屏")); + } + if canvas_width > 0 { + facts.push(format!("{canvas_width} px")); + } + if !version.is_empty() { + facts.push(version.to_owned()); + } + if let Some(status) = status { + facts.push(status.to_owned()); + } + if !facts.is_empty() { + stitch_kit::label(ui, facts.join(" · "), Type::Meta, Tone::Quiet); + } + if cover.is_some() { + stitch_kit::caption(ui, "模板原稿预览"); + } else if preview.is_some() { + stitch_kit::caption(ui, "首屏结构示意"); + } else { + stitch_kit::caption(ui, "模板已就绪(当前组件未附带预览图)"); + } + }); + }); +} + +pub(in crate::jiansun) fn drop_contains(value: &Value, point: egui::Pos2) -> bool { + let Some(values) = value.as_array() + .filter(|rect| rect.len() == 4) + .and_then(|rect| rect.iter().map(Value::as_f64).collect::>>()) else { return false }; + values.iter().all(|value| value.is_finite()) && values[2] > 0.0 && values[3] > 0.0 + && egui::Rect::from_min_size( + egui::pos2(values[0] as f32, values[1] as f32), + vec2(values[2] as f32, values[3] as f32), + ).contains(point) +} + +pub(in crate::jiansun) fn reference_image_path(path: &std::path::Path) -> bool { + path.extension().and_then(|ext| ext.to_str()) + .is_some_and(|ext| ["png", "jpg", "jpeg", "webp"].iter().any(|allowed| ext.eq_ignore_ascii_case(allowed))) +} + +pub(in crate::jiansun) fn reference_folder_paths(folder: &std::path::Path) -> Result, String> { + let mut paths = Vec::new(); + for entry in std::fs::read_dir(folder).map_err(|_| "无法读取所选文件夹")? { + let path = entry.map_err(|_| "无法读取所选文件夹")?.path(); + if path.is_file() && reference_image_path(&path) { + if paths.len() == 8 { return Err("文件夹内图片超过 8 张,请改用文件选择".into()); } + paths.push(path.into_os_string().into_string().map_err(|_| "文件名无效")?); + } + } + if paths.is_empty() { return Err("文件夹里没有 PNG、JPG 或 WebP 图片".into()); } + paths.sort(); + Ok(paths) +} + +impl PhotocraftApp { + pub(crate) fn creation_reference_drop( + &mut self, ctx: &egui::Context, files: &[egui::DroppedFileHandle], at: Option, + ) -> bool { + if self.file_dialog_open() { + return false; + } + let product_form_open = super::product_form_open(self); + let Some(w) = self.jiansun.as_mut() else { return false }; + let staged = w.creation_reads.staged_new_project && w.creation_open + && w.creation_step == 0 && !w.library && !w.material; + if !product_form_open && !staged { + return false; + } + let doc = self.session.active().map(|state| state.doc.id.0); + let target = at.and_then(|at| { + let layer = ctx.layer_id_at(at); + w.creation_view_geometry["imageSlots"].as_object().into_iter().flat_map(|slots| slots.values()) + .chain(std::iter::once(&w.creation_view_geometry["referenceDrop"])) + .find(|target| target["doc"] == json!(doc) && target["accountId"] == w.account["id"] + && target["origin"] == w.origin && target["viewport"].as_u64() == Some(ctx.viewport_id().0.value()) + && drop_contains(&target["rect"], at) + && layer.is_none_or(|layer| layer.order == egui::Order::Background + || target["layer"].as_u64() == Some(layer.id.value()))) + }); + let Some(target) = target else { + if files.iter().any(|file| file.path().is_dir() || file.path().extension().and_then(|ext| ext.to_str()) + .is_some_and(|ext| photocraft_codecs::from_extension(ext).is_some() || ext.eq_ignore_ascii_case("svg"))) + { + w.creation_reads.reference_import_error = REFERENCE_DROP_HINT.into(); + return true; + } + return false; + }; + let slot = target["slot"].clone(); + let reject = if (!staged && w.creation_doc != doc) || w.busy.is_some() { + Some("请等待当前操作完成,再添加参考图") + } else if w.unknown { + Some("原请求结果待核查,请先核查后再添加参考图") + } else if slot["multiple"] == false && files.len() != 1 { + Some("此图片框一次只能添加一张图片") + } else if files.is_empty() || files.len() > 8 { + Some("每次请选择 1 至 8 张参考图片") + } else { + None + }; + if let Some(error) = reject { + w.creation_reads.reference_import_error = error.into(); + return true; + } + let paths = if slot.is_null() && matches!(files, [file] if file.path().is_dir()) { + reference_folder_paths(files[0].path()) + } else { + files.iter().map(|file| { + let path = file.path(); + let valid = path.is_absolute() && reference_image_path(path); + valid.then(|| path.to_str().map(str::to_owned)).flatten() + }).collect::>>().ok_or_else(|| "请选择 PNG、JPG 或 WebP 格式的本机图片".to_owned()) + }; + let paths = match paths { + Ok(paths) => paths, + Err(error) => { + w.creation_reads.reference_import_error = error; + return true; + } + }; + if let Err(error) = self.import_reference_paths(paths, slot) + && let Some(w) = self.jiansun.as_mut() + { + w.creation_reads.reference_import_error = error; + } + true + } + pub(in crate::jiansun) fn import_reference_paths(&mut self, paths: Vec, slot: Value) -> Result { + let native = self.session.authorize.is_none(); + if slot.is_object() && self.jiansun.as_ref().is_none_or(|w| !current_image_slot(&w.creation_brief, &slot)) { + return Err("图片框已变化,请重新选择".into()); + } + let result = super::action(self, "creation-import", json!({"paths":paths,"imageSlot":slot}))?; + if let Some(w) = self.jiansun.as_mut() { + w.creation_reads.reference_import_error.clear(); + if native && result["submitted"] == true { + w.creation_reads.reference_import_paths = Some(paths); + } + } + Ok(result) + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/taxonomy_select_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/taxonomy_select_ui.rs new file mode 100644 index 00000000..0d2160ea --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/taxonomy_select_ui.rs @@ -0,0 +1,265 @@ +use super::super::{Duration, PhotocraftApp, Ui, Value, Workspace, agent_panel::rect_value, json, stitch_ui}; +use super::PICKER_HEIGHT; +use super::brief::{brief_variants, variant_identity}; +use super::form_widgets_ui::{MaterialSearchPending, material_search_due, material_thumbnail, picker, picker_height, picker_notice, picker_row, picker_toggle_row}; + +impl Workspace { + pub(in crate::jiansun) fn brand_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { + let rows = self.creation_catalog.get("brands").cloned().unwrap_or_default(); + let selected = self.creation_brief["brandName"].as_str().filter(|s| !s.is_empty()).unwrap_or("选择品牌").to_owned(); + let mut geometry = Vec::new(); + let result = picker(ui, "creation-brand", width, &selected, |ui| { + if !self.creation_catalog.contains_key("brands") && !self.creation_catalog_loading("brands") && self.creation_catalog_error("brands").is_none() { + self.catalog(app, "brands", String::new()); + } + let error = self.creation_catalog_error("brands").map(str::to_owned); + if picker_notice(ui, self.creation_catalog_loading("brands"), error.as_deref(), rows.is_empty(), "暂无品牌") { + self.catalog(app, "brands", String::new()); + } + for row in &rows { + let ready = row["ready"] == true; + let suffix = if !ready { " · 待配置" } else if row["templateCount"].as_u64() == Some(0) { " · 暂无可用模板" } else { "" }; + let label = format!("{}{suffix}", row["name"].as_str().unwrap_or("")); + let response = picker_row(ui, self.creation_brief["brandName"] == row["name"], &label, ready); + geometry.push(json!({"id":row["id"],"label":label,"ready":ready,"rect":rect_value(response.rect)})); + if response.clicked() { + if self.creation_brief["brandName"] == row["name"] { + ui.close(); + continue; + } + self.creation_brief["brandId"] = row["id"].clone(); + self.creation_brief["brandName"] = row["name"].clone(); + self.creation_brief["categoryId"] = json!(""); + self.creation_brief["categoryName"] = json!(""); + self.agent_rule = Value::Null; + self.agent_rule_state = Value::Null; + if let Some(fields) = self.creation_brief.as_object_mut() { fields.remove("intake"); } + self.creation_brief["templateSelection"] = Value::Null; + self.creation_catalog.remove("templates"); + self.creation_catalog.remove("categories"); + self.catalog(app, "categories", String::new()); + self.creation_reads.inline_errors.remove("brand"); + self.creation_reads.manual_edited_fields.insert("brand".into()); + self.creation_dirty = true; + ui.close(); + } + } + }); + if result.response.clicked() && result.inner.is_some() { + self.catalog(app, "brands", String::new()); + } + if self.creation_reads.scroll_to_field.as_deref() == Some("brand") { + self.creation_reads.scroll_to_field = None; + result.response.scroll_to_me(Some(egui::Align::Center)); + result.response.request_focus(); + } + let loading = self.creation_catalog_loading("brands"); + self.picker_geometry(ui, "brand", &result.response, loading, !rows.is_empty() && !loading && self.creation_catalog_error("brands").is_none(), geometry); + if let Some(err) = self.creation_reads.inline_errors.get("brand") { + stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error); + } + } + pub(in crate::jiansun) fn category_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { + let brand = self.creation_brief["brandId"].as_str().unwrap_or("").to_owned(); + let rows = self.creation_catalog.get("categories").cloned().unwrap_or_default().into_iter().filter(|row| row["brandId"] == brand).collect::>(); + let selected = self.creation_brief["categoryName"] + .as_str() + .filter(|s| !s.is_empty()) + .unwrap_or(if brand.is_empty() { "先选择品牌" } else { "选择品类" }) + .to_owned(); + let mut geometry = Vec::new(); + let loading = self.creation_catalog_loading("categories"); + let result = picker(ui, "creation-category", width, &selected, |ui| { + if brand.is_empty() { + ui.weak("先选择品牌"); + } else { + if !self.creation_catalog.contains_key("categories") && !loading && self.creation_catalog_error("categories").is_none() { + self.catalog(app, "categories", String::new()); + } + let error = self.creation_catalog_error("categories").map(str::to_owned); + if picker_notice(ui, loading, error.as_deref(), rows.is_empty(), "暂无已登记的产品品类") { + self.catalog(app, "categories", String::new()); + } + } + for row in &rows { + let ready = row["ready"] == true; + let name = row["name"].as_str().unwrap_or(""); + let label = if ready { name.to_owned() } else { format!("{name} · 待配置") }; + let response = picker_row(ui, self.creation_brief["categoryName"] == row["name"], &label, ready).on_hover_text(if ready { + if row["templateCount"].as_u64() == Some(0) { "知识库已有此品类资料,当前暂无可用模板" } else { "使用该品牌与品类的项目模板" } + } else { + "此品牌尚未配置该品类模板" + }); + geometry.push(json!({"id":row["id"],"label":label,"ready":ready,"rect":rect_value(response.rect)})); + if response.clicked() { + if self.creation_brief["categoryName"] == row["name"] { + ui.close(); + continue; + } + self.creation_brief["categoryId"] = row["id"].clone(); + self.creation_brief["categoryName"] = row["name"].clone(); + self.agent_rule = Value::Null; + self.agent_rule_state = Value::Null; + if let Some(fields) = self.creation_brief.as_object_mut() { fields.remove("intake"); } + self.creation_brief["templateSelection"] = Value::Null; + self.creation_catalog.remove("templates"); + self.creation_reads.inline_errors.remove("category"); + self.creation_reads.manual_edited_fields.insert("category".into()); + self.creation_dirty = true; + ui.close(); + } + } + }); + if result.response.clicked() && result.inner.is_some() && !brand.is_empty() { + self.catalog(app, "categories", String::new()); + } + if self.creation_reads.scroll_to_field.as_deref() == Some("category") { + self.creation_reads.scroll_to_field = None; + result.response.scroll_to_me(Some(egui::Align::Center)); + result.response.request_focus(); + } + self.picker_geometry(ui, "category", &result.response, loading, !rows.is_empty() && !loading, geometry); + if let Some(err) = self.creation_reads.inline_errors.get("category") { + stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error); + } + } + pub(in crate::jiansun) fn material_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { + let rows = self.creation_catalog.get("materials").cloned().unwrap_or_default(); + let mut variants = brief_variants(&self.creation_brief); + let selected = match variants.as_slice() { + [] => "从材质库选择,可多选".to_owned(), + [only] => only["name"].as_str().unwrap_or("花色").to_owned(), + rows => format!("已选 {} 个花色", rows.len()), + }; + let mut geometry = Vec::new(); + let mut material_rows = Vec::new(); + let result = picker_height(ui, "creation-material", width, PICKER_HEIGHT, &selected, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| { + if !self.creation_catalog.contains_key("materials") + && !self.creation_catalog_loading("materials") + && self.creation_catalog_error("materials").is_none() + { + self.catalog(app, "materials", String::new()); + } + let search = stitch_ui::search_field(ui, ui.scope_id().with("creation-material-search"), &mut self.creation_material_query, "搜索材质"); + let now = ui.input(|input| input.time); + let enter = search.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter) + && !input.events.iter().any(|event| matches!(event, egui::Event::Ime(_)))); + let state_id = ui.scope_id().with("creation-material-search-pending"); + let (due, pending) = ui.data_mut(|data| { + let state = data.get_temp_mut_or_default::(state_id); + let due = material_search_due(state, &self.creation_material_query, search.changed(), enter, now); + (due, state.pending) + }); + if pending { ui.ctx().request_repaint_after(Duration::from_millis(50)); } + if due { + self.catalog(app, "materials", self.creation_material_query.clone()); + } + let error = self.creation_catalog_error("materials").map(str::to_owned); + if picker_notice(ui, self.creation_catalog_loading("materials"), error.as_deref(), rows.is_empty(), "暂无匹配材质") { + self.catalog(app, "materials", self.creation_material_query.clone()); + } + let removable = variants.iter().all(|variant| self.sku_color_removable(variant)); + if picker_row(ui, variants.is_empty(), "未指定", removable).on_hover_text("已用于详情图、主图或已有画布的颜色会保留").clicked() { + variants.clear(); + self.save_sku_colors(variants.clone()); + ui.close(); + } + for row in &rows { + let Some(id) = row["id"].as_str().filter(|id| !id.is_empty()) else { continue }; + let label = row["name"].as_str().unwrap_or(""); + let image = self.creation_thumbs.get(id).cloned(); + let error = self.creation_thumbnail_error(id).map(str::to_owned); + let loading = self.creation_thumbnail_loading(id); + let mut image_rect = egui::Rect::NOTHING; + let mut visible = false; + let line = ui.horizontal(|ui| { + let thumbnail = material_thumbnail(ui, image.as_ref(), loading, error.is_some()); + image_rect = thumbnail.rect; + visible = ui.is_rect_visible(image_rect); + if visible && image.is_none() && !loading && error.is_none() { + self.queue_creation_thumbnail(app, id); + } + if let Some(error) = error.as_deref() { + let msg = crate::client_brand::user_error(error, "缩略图读取失败"); + if thumbnail.on_hover_text(format!("{msg}\n点击重新读取")).clicked() { + self.retry_creation_thumbnail(app, id); + } + } else if let Some(image) = image.as_ref() { + self.material_preview(thumbnail, id, label, image); + } + let selected = variants.iter().find(|variant| variant["colorMaterialId"] == row["id"]); + let removable = selected.is_none_or(|variant| self.sku_color_removable(variant)); + let selected = selected.is_some(); + let can_select = removable && (selected || variants.len() < 64); + let response = picker_toggle_row(ui, selected, label, can_select); + let response = if !selected && variants.len() >= 64 { + response.on_hover_text("最多选择 64 个花色") + } else if !removable { + response.on_hover_text("已用于出图、画布或专属参考的颜色会保留") + } else { response }; + if response.clicked() { + if selected { + variants.retain(|variant| variant["colorMaterialId"] != row["id"]); + } else { + variants + .push(json!({"id":variant_identity(id),"name":row["name"],"colorMaterialId":row["id"],"colorName":row["name"],"images":[]})); + } + self.save_sku_colors(variants.clone()); + } + if let Some(image) = image.as_ref() { + self.material_preview(response, id, label, image); + } + }); + let status = if image.is_some() { + "ready" + } else if self.creation_thumbnail_error(id).is_some() { + "failed" + } else if self.creation_thumbnail_loading(id) { + "loading" + } else { + "queued" + }; + geometry.push(json!({"id":id,"label":label,"ready":true,"rect":rect_value(line.response.rect)})); + material_rows.push( + json!({"id":id,"label":label,"rect":rect_value(line.response.rect),"imageRect":rect_value(image_rect),"status":status,"visible":visible}), + ); + } + }); + self.creation_view_geometry["materialRows"] = json!(material_rows); + let loading = self.creation_catalog_loading("materials"); + self.picker_geometry( + ui, + "material", + &result.response, + loading, + !rows.is_empty() && !loading && self.creation_catalog_error("materials").is_none(), + geometry, + ); + } + pub(in crate::jiansun) fn product_search_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + let identifier = self.creation_brief["identifier"].as_str().unwrap_or_default(); + let label = if self.creation_brief["identifierType"] == "spu" { "按 SPU 查找" } else { "查找原项目产品" }; + let search = stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Secondary, !identifier.trim().is_empty()); + if search.clicked() { + self.catalog(app, "products", identifier.to_owned()); + } + self.control_geometry("source-search", search.rect); + } + pub(in crate::jiansun) fn product_select_results(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + let rows = self.creation_catalog.get("products").cloned().unwrap_or_default(); + let error = self.creation_catalog_error("products").map(str::to_owned); + if (self.creation_catalog.contains_key("products") || self.creation_catalog_loading("products") || error.is_some()) + && picker_notice(ui, self.creation_catalog_loading("products"), error.as_deref(), rows.is_empty(), "未找到匹配产品,请核对产品编号") + { + self.catalog(app, "products", self.creation_brief["identifier"].as_str().unwrap_or("").into()); + } + for (index, row) in rows.into_iter().enumerate() { + let title = row["productModel"].as_str().or_else(|| row["name"].as_str()).unwrap_or("产品资料"); + let result = stitch_ui::button(ui, title, false); + self.control_geometry(&format!("source-result-{index}"), result.rect); + if result.clicked() { + self.creation_submit(app, "creation-product", json!({"item":row})); + } + } + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/template_select_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/template_select_ui.rs new file mode 100644 index 00000000..6204330f --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/template_select_ui.rs @@ -0,0 +1,461 @@ +use super::super::{PhotocraftApp, Request, Ui, Value, Workspace, agent_panel::rect_value, json, stitch_kit, stitch_ui}; +use super::super::creation_reads::wizard; +use super::PICKER_HEIGHT; +use super::brief::{default_resource_component, selected_template, template_compatibility_warnings, template_identity}; +use super::form_widgets_ui::{picker, picker_height, picker_notice, template_picker_row}; +use super::intake::set_intake; +use super::structure_preview_ui::{structure_preview_card, verified_structure_preview}; +use crate::theme::agent_scale::{control, space}; +use egui::vec2; + +impl Workspace { + pub(in crate::jiansun) fn resource_template_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, selected: &Value, brand: &str, category: &str) { + let bound = |row: &Value| row["brandId"] == brand && row["categoryId"] == category; + if !bound(&self.creation_reads.resource_set) { + self.creation_reads.resource_set = Value::Null; + self.creation_reads.resource_component.clear(); + self.creation_catalog.remove("resource-set"); + self.creation_catalog.remove("resource-component"); + } + let rows = self.creation_catalog.get("templates").into_iter().flatten().filter(|row| bound(row)).cloned().collect::>(); + if !brand.is_empty() && !category.is_empty() + && !self.creation_catalog.contains_key("templates") && !self.creation_catalog_loading("templates") && self.creation_catalog_error("templates").is_none() + { + self.catalog(app, "templates", String::new()); + } + let label = self.creation_reads.resource_set["name"].as_str().or(selected["name"].as_str()).unwrap_or("选择模板").to_owned(); + let mut geometry = Vec::new(); + let response = picker_height(ui, "creation-template", width, PICKER_HEIGHT, + &label, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| { + if brand.is_empty() || category.is_empty() { + ui.weak("先选择品牌与品类"); + return; + } + ui.horizontal(|ui| { + let query = ui.add_sized([(ui.available_width() - 68.0).max(80.0), 28.0], + egui::TextEdit::singleline(&mut self.creation_reads.resource_query).hint_text("模板名称或编号").char_limit(120)); + if stitch_ui::button(ui, "搜索", false).clicked() || query.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + self.creation_catalog.remove("templates"); + self.catalog(app, "templates", self.creation_reads.resource_query.clone()); + } + }); + let error = self.creation_catalog_error("templates").map(str::to_owned); + if picker_notice(ui, self.creation_catalog_loading("templates"), error.as_deref(), rows.is_empty(), "当前筛选没有模板") { + self.catalog(app, "templates", self.creation_reads.resource_query.clone()); + } + for row in &rows { + let active = self.creation_reads.resource_set["id"] == row["id"]; + let text = format!("{} · {}", row["name"].as_str().unwrap_or("模板"), row["key"].as_str().unwrap_or("")); + let ready = !self.creation_catalog_loading("templates"); + let item = template_picker_row(ui, active, &text, ready, None); + geometry.push(json!({"id":row["id"],"key":row["key"],"ready":ready,"rect":rect_value(item.rect)})); + if item.clicked() { + ui.close(); + if active { + continue; + } + set_intake(&mut self.creation_brief, &row["id"], &row["intake"]); + self.creation_reads.resource_set = row.clone(); + self.creation_reads.resource_component.clear(); + self.creation_reads.resource_image = None; + self.creation_brief["templateSelection"] = Value::Null; + self.creation_reads.inline_errors.remove("template"); + self.creation_dirty = true; + self.creation_catalog.remove("resource-set"); + self.creation_catalog.remove("resource-component"); + self.catalog(app, "resource-set", row["id"].as_str().unwrap_or("").into()); + } + } + }).response; + if self.creation_reads.scroll_to_field.as_deref() == Some("template") { + self.creation_reads.scroll_to_field = None; + response.scroll_to_me(Some(egui::Align::Center)); + response.request_focus(); + } + self.picker_geometry(ui, "template", &response, self.creation_catalog_loading("templates"), !rows.is_empty(), geometry); + if let Some(err) = self.creation_reads.inline_errors.get("template") { + stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error); + } + if let Some(error) = self.creation_catalog_error("templates") { + stitch_ui::status_label(ui, error, stitch_ui::StatusTone::Error); + } + if let Some(progress) = self.resource_progress() { + let wait = progress["retryAfterSeconds"].as_u64(); + ui.horizontal_wrapped(|ui| { + if let Some(seconds) = wait { ui.label(format!("知识库访问受限,约 {seconds} 秒后继续")); } + let cancel = stitch_ui::button(ui, "取消读取", false); + if cancel.clicked() { + let _ = self.tx.send(Request::Action("knowledge-cancel".into(), json!({"jobId":progress["jobId"]}))); + } + }); + } + let Some(set) = self.creation_reads.resource_set["id"].as_str().map(str::to_owned) else { return; }; + let parts = self.creation_catalog.get("resource-set").cloned().unwrap_or_default(); + let error = self.creation_catalog_error("resource-set").map(str::to_owned); + if picker_notice(ui, self.creation_catalog_loading("resource-set"), error.as_deref(), parts.is_empty(), "该资源组没有可用的模板组件") { + self.catalog(app, "resource-set", set.clone()); + } + if ui.is_enabled() + && self.creation_reads.resource_component.is_empty() + && !self.creation_catalog_loading("resource-set") + && let Some(part) = default_resource_component(&parts) + { + self.select_resource_component(app, &set, part); + } + if !parts.is_empty() { + ui.add_space(space::XS); + ui.horizontal_wrapped(|ui| { + for part in &parts { + let Some(id) = part["id"].as_str() else { continue; }; + let name = part["name"].as_str().unwrap_or("模板组件"); + let selected = self.creation_reads.resource_component == id; + let loading = self.creation_catalog_loading("resource-component"); + let action = stitch_ui::segmented_option_sized(ui, name, selected, !loading, vec2(0.0, control::DEFAULT)); + self.control_geometry(&format!("resource-component-{id}"), action.rect); + if action.clicked() && (!selected || !template_identity(&self.creation_brief["templateSelection"])) { + self.select_resource_component(app, &set, part); + } + if !selected || loading { + for issue in part["issues"].as_array().into_iter().flatten().filter_map(Value::as_str) { + stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Error); + } + } + } + }); + } + if self.creation_catalog_loading("resource-component") { + stitch_kit::caption(ui, "正在核对模板资料…"); + } + if let Some(error) = self.creation_catalog_error("resource-component") { + stitch_ui::status_label(ui, error, stitch_ui::StatusTone::Error); + } + let result = self.creation_catalog.get_mut("resource-component").and_then(|rows| rows.first_mut()) + .filter(|row| row["id"] == self.creation_reads.resource_component).map(|row| { + let result = row.clone(); + if let Some(image) = row["image"].as_object_mut() { image.remove("rgba"); } + result + }); + if let Some(result) = result { + self.resource_component_result(app, ui, width, &set, &result); + } else { + let selected_part = parts.iter().find(|part| part["id"] == self.creation_reads.resource_component); + let warnings = template_compatibility_warnings(&[ + &self.creation_reads.resource_set, + selected_part.unwrap_or(&Value::Null), + &self.creation_brief["templateSelection"], + ]); + for warning in warnings { + stitch_ui::status_label(ui, &warning, stitch_ui::StatusTone::Warning); + } + } + self.creation_view_geometry["resourceSet"] = self.creation_reads.resource_set.clone(); + self.creation_view_geometry["templateSelection"] = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + } + + pub(in crate::jiansun) fn select_resource_component(&mut self, app: &mut PhotocraftApp, set: &str, part: &Value) { + let Some(id) = part["id"].as_str() else { return; }; + let preview = part["previews"].as_array().and_then(|images| images.first()).map(|image| &image["id"]); + self.creation_reads.resource_component = id.to_owned(); + self.creation_reads.resource_image = None; + self.creation_catalog.remove("resource-component"); + self.creation_dirty |= !self.creation_brief["templateSelection"].is_null(); + self.creation_brief["templateSelection"] = Value::Null; + self.catalog(app, "resource-component", json!({"resourceSetId":set,"componentId":id,"previewId":preview}).to_string()); + } + + pub(in crate::jiansun) fn resource_component_result(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, set: &str, result: &Value) { + use base64::Engine as _; + let component = result["id"].as_str().unwrap_or(""); + let choice = &result["choice"]; + if ui.is_enabled() && template_identity(choice) && choice["intake"]["version"] == 1 + && choice["id"] == self.creation_brief["templateSelection"]["id"] + && choice["version"] == self.creation_brief["templateSelection"]["version"] + && choice["contentHash"] == self.creation_brief["templateSelection"]["contentHash"] + { + self.creation_dirty |= wizard::refresh_intake_schema_from_catalog(&mut self.creation_brief, choice); + } + if ui.is_enabled() + && self.creation_brief["templateSelection"].is_null() + && template_identity(choice) + && choice["enterprise"]["resourceSetId"] == set + && choice["enterprise"]["componentId"] == component + && choice["brandId"] == self.creation_brief["brandId"] + && choice["categoryId"] == self.creation_brief["categoryId"] + { + let mut choice = choice.clone(); + if let Some(width) = choice["width"].as_u64() { + self.creation_width = width as u32; + } + if let Some(fields) = choice.as_object_mut() { + fields.remove("width"); + if let Some(schema) = fields.remove("intake") { + set_intake(&mut self.creation_brief, &fields["id"], &schema); + } + } + self.creation_brief["templateSelection"] = choice; + self.creation_reads.inline_errors.remove("template"); + self.creation_dirty = true; + } + for issue in result["issues"].as_array().into_iter().flatten().filter_map(Value::as_str) { + stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Error); + } + let selected_part = self.creation_catalog.get("resource-set") + .and_then(|parts| parts.iter().find(|part| part["id"] == component)) + .cloned() + .unwrap_or(Value::Null); + for warning in template_compatibility_warnings(&[ + result, + choice, + &selected_part, + &self.creation_reads.resource_set, + &self.creation_brief["templateSelection"], + ]) { + stitch_ui::status_label(ui, &warning, stitch_ui::StatusTone::Warning); + } + if let Some(error) = result["previewError"].as_str() { + stitch_kit::caption(ui, error); + } + let preview_key = format!("{set}:{component}:{}", result["previewId"]); + if self.creation_reads.resource_image.as_ref().is_none_or(|(key, _)| key != &preview_key) + && let (Some(w), Some(h), Some(rgba)) = (result["image"]["size"][0].as_u64(), result["image"]["size"][1].as_u64(), result["image"]["rgba"].as_str()) + && (1..=320).contains(&w) && (1..=320).contains(&h) + && let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(rgba) + && bytes.len() as u64 == w * h * 4 + { + let image = egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], &bytes); + self.creation_reads.resource_image = Some((preview_key, ui.ctx().load_texture("resource-template-preview", image, egui::TextureOptions::LINEAR))); + } + let tpl_name = self.creation_reads.resource_set["name"].as_str().or(choice["name"].as_str()).unwrap_or("项目模板").to_owned(); + let tpl_width = result["choice"]["width"].as_u64().unwrap_or(self.creation_width as u64) as u32; + let cover_img = self.creation_reads.resource_image.clone().map(|(_, tex)| tex); + let fallback_structure = if cover_img.is_none() { + choice.get("structurePreview").filter(|v| v.is_object()) + } else { + None + }; + if cover_img.is_some() || fallback_structure.is_some() || template_identity(choice) { + ui.add_space(space::SM); + let card = ui.scope(|ui| { + structure_preview_card( + ui, + fallback_structure, + cover_img.as_ref(), + &tpl_name, + "企业知识库", + self.creation_template_screen_count(), + tpl_width, + Some("已就绪"), + ); + }); + self.control_geometry("resource-preview", card.response.rect); + } + if let Some(previews) = result["previews"].as_array().filter(|images| images.len() > 1) { + ui.add_space(space::XS); + let label = result["previewName"].as_str().unwrap_or("切换预览页"); + picker(ui, "resource-preview-select", width.min(320.0), label, |ui| { + for preview in previews { + let Some(id) = preview["id"].as_str() else { continue; }; + if stitch_ui::select_option(ui, preview["name"].as_str().unwrap_or("预览"), result["previewId"] == id, true).clicked() { + self.creation_reads.resource_image = None; + self.catalog(app, "resource-component", json!({"resourceSetId":set,"componentId":component,"previewId":id,"previewOnly":true}).to_string()); + ui.close(); + } + } + }); + } + } + + pub(in crate::jiansun) fn template_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { + let brand = self.creation_brief["brandId"].as_str().unwrap_or("").to_owned(); + let category = self.creation_brief["categoryId"].as_str().unwrap_or("").to_owned(); + let selected = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + if self.template_workflow["canvasFirst"] == true && template_identity(&selected) && selected["enterprise"]["sourceKind"] == "resource-map" { + let name = selected["name"].as_str().unwrap_or("项目模板"); + let view = ui.label(format!("{name} · 已固定")); + self.control_geometry("template", view.rect); + self.creation_view_geometry["templateSelection"] = selected; + return; + } + if brand.starts_with("ekb:brand:") || brand.is_empty() { + if self.template_workflow["canvasFirst"] == true && template_identity(&selected) { + let name = selected["name"].as_str().unwrap_or("项目模板"); + let view = ui.label(format!("{name} · 已固定")); + self.control_geometry("template", view.rect); + self.creation_view_geometry["templateSelection"] = selected; + } else { + self.resource_template_select(app, ui, width, &selected, &brand, &category); + } + return; + } + let rows = self + .creation_catalog + .get("templates") + .cloned() + .unwrap_or_default() + .into_iter() + .filter(|row| row["brandId"] == brand && row["categoryId"] == category && template_identity(row)) + .collect::>(); + let fixed = self.template_workflow["canvasFirst"] == true && template_identity(&selected); + let selected_row = + rows.iter().find(|row| row["id"] == selected["id"] && row["version"] == selected["version"] && row["contentHash"] == selected["contentHash"]); + let name = selected_row.and_then(|row| row["name"].as_str()).or_else(|| selected["name"].as_str()).unwrap_or("项目模板"); + let version_label = if selected["enterprise"].is_object() { "企业知识库" } else { selected["version"].as_str().unwrap_or("") }; + let label = if template_identity(&selected) { format!("{name} · {version_label}") } else { "选择模板".into() }; + if !brand.is_empty() + && !category.is_empty() + && !self.creation_catalog.contains_key("templates") + && !self.creation_catalog_loading("templates") + && self.creation_catalog_error("templates").is_none() + { + self.catalog(app, "templates", String::new()); + } + let has_preview = selected_row.and_then(|row| verified_structure_preview(row, &selected, &brand, &category)).is_some(); + let side_by_side = width >= 620.0 && has_preview; + let picker_width = if side_by_side { (width - 280.0 - space::MD).max(240.0) } else { width }; + let mut geometry = Vec::new(); + let draw_picker = |this: &mut Workspace, app: &mut PhotocraftApp, ui: &mut Ui, p_width: f32, geometry: &mut Vec| { + let response = picker(ui, "creation-template", p_width, &label, |ui| { + if brand.is_empty() || category.is_empty() { + ui.weak("先选择品牌与品类"); + } else { + let error = this.creation_catalog_error("templates").map(str::to_owned); + if picker_notice(ui, this.creation_catalog_loading("templates"), error.as_deref(), rows.is_empty(), "当前品类暂无可用模板") { + this.catalog(app, "templates", String::new()); + } + } + if rows.iter().any(|row| verified_structure_preview(row, row, &brand, &category).is_some()) { + stitch_kit::caption(ui, "首屏结构示意 · 不含图片"); + } + for row in &rows { + let mut choice = json!({"id":row["id"],"name":row["name"],"version":row["version"],"contentHash":row["contentHash"],"brandId":row["brandId"],"categoryId":row["categoryId"]}); + if row["enterprise"].is_object() { choice["enterprise"] = row["enterprise"].clone(); } + let row_warnings = template_compatibility_warnings(&[row]); + if !row_warnings.is_empty() { + choice["compatibilityWarnings"] = json!(row_warnings); + } + let is_selected = selected["id"] == row["id"] && selected["version"] == row["version"] && selected["contentHash"] == row["contentHash"]; + let text = format!("{} · {}", row["name"].as_str().unwrap_or("模板"), if row["enterprise"].is_object() { "企业知识库" } else { row["version"].as_str().unwrap_or("") }); + let preview = verified_structure_preview(row, row, &brand, &category); + let enabled = !fixed || is_selected; + let item = template_picker_row(ui, is_selected, &text, enabled, preview); + geometry.push( + json!({"id":row["id"],"version":row["version"],"contentHash":row["contentHash"],"ready":enabled,"hasStructurePreview":preview.is_some(),"rect":rect_value(item.rect)}), + ); + if item.clicked() && !fixed { + if !is_selected { + set_intake(&mut this.creation_brief, &row["id"], &row["intake"]); + } else { + wizard::refresh_intake_schema_from_catalog(&mut this.creation_brief, row); + } + this.creation_brief["templateSelection"] = choice; + this.creation_reads.inline_errors.remove("template"); + this.creation_dirty = true; + ui.close(); + } + } + }); + if response.response.clicked() && response.inner.is_some() && !fixed && !brand.is_empty() && !category.is_empty() { + this.catalog(app, "templates", String::new()); + } + if this.creation_reads.scroll_to_field.as_deref() == Some("template") { + this.creation_reads.scroll_to_field = None; + response.response.scroll_to_me(Some(egui::Align::Center)); + response.response.request_focus(); + } + this.picker_geometry(ui, "template", &response.response, this.creation_catalog_loading("templates"), !rows.is_empty(), geometry.clone()); + if let Some(err) = this.creation_reads.inline_errors.get("template") { + stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error); + } + if let Some(error) = this.creation_catalog_error("templates") { + let msg = crate::client_brand::user_error(error, "请检查网络或模板配置后重试"); + let notice = stitch_ui::status_label(ui, &format!("模板读取失败:{msg}。"), stitch_ui::StatusTone::Error); + this.control_geometry("template-error", notice.rect); + } + ui.add_space(space::XS); + ui.horizontal_wrapped(|ui| { + let chosen_now = selected_template(&this.creation_brief, &this.template_workflow, &this.creation["brief"]); + let status = if template_identity(&chosen_now) { + if rows.iter().any(|row| row["id"] == chosen_now["id"] && (row["version"] != chosen_now["version"] || row["contentHash"] != chosen_now["contentHash"])) { + Some("可更新") + } else if fixed { + Some("已固定") + } else if rows.iter().find(|row| row["id"] == chosen_now["id"] && row["version"] == chosen_now["version"] && row["contentHash"] == chosen_now["contentHash"]).is_some_and(|row| row["cached"] == true) { + Some("已缓存") + } else { + None + } + } else { + None + }; + if let Some(status) = status { + let badge = ui.scope(|ui| stitch_ui::status_chip(ui, status, stitch_ui::StatusTone::Neutral)); + this.control_geometry("template-status", badge.response.rect); + } + let refresh = ui + .add_enabled_ui(!brand.is_empty() && !category.is_empty() && !this.creation_catalog_loading("templates"), |ui| { + stitch_ui::action_button(ui, "检查模板更新", stitch_ui::ButtonRole::Quiet, true) + }) + .inner; + this.control_geometry("template-update", refresh.rect); + if refresh.clicked() { + this.request_creation_catalog(app, "templates", String::new(), true); + } + }); + }; + + if side_by_side { + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = space::MD; + ui.vertical(|ui| { + ui.set_width(picker_width); + draw_picker(self, app, ui, picker_width, &mut geometry); + }); + let chosen = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + let preview = rows.iter().find_map(|row| verified_structure_preview(row, &chosen, &brand, &category)); + let card_w = (width - picker_width - space::MD).max(220.0); + let card = ui.vertical(|ui| { + ui.set_width(card_w); + structure_preview_card( + ui, + preview, + None, + name, + version_label, + self.creation_template_screen_count(), + self.creation_width, + if fixed { Some("已固定") } else { None }, + ); + }); + self.control_geometry("template-preview-card", card.response.rect); + }); + } else { + draw_picker(self, app, ui, picker_width, &mut geometry); + let chosen = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + let preview = rows.iter().find_map(|row| verified_structure_preview(row, &chosen, &brand, &category)); + if preview.is_some() || template_identity(&chosen) { + ui.add_space(space::SM); + let card = ui.scope(|ui| { + structure_preview_card( + ui, + preview, + None, + name, + version_label, + self.creation_template_screen_count(), + self.creation_width, + if fixed { Some("已固定") } else { None }, + ); + }); + self.control_geometry("template-preview-card", card.response.rect); + } + } + self.creation_view_geometry["templateSelection"] = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + let chosen_now = &self.creation_view_geometry["templateSelection"]; + let chosen_row = rows.iter().find(|row| { + row["id"] == chosen_now["id"] && row["version"] == chosen_now["version"] && row["contentHash"] == chosen_now["contentHash"] + }); + for warning in template_compatibility_warnings(&[chosen_row.unwrap_or(&Value::Null), chosen_now]) { + stitch_ui::status_label(ui, &warning, stitch_ui::StatusTone::Warning); + } + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/test_preset_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/test_preset_ui.rs new file mode 100644 index 00000000..94dac694 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/test_preset_ui.rs @@ -0,0 +1,102 @@ +use super::super::{PhotocraftApp, Ui, Value, Workspace, json, stitch_ui}; +use super::super::creation_reads::{TEST_PRESETS, wizard::CreationStage}; +use super::brief::{empty_brief, template_identity}; +use crate::theme::agent_scale::space; + +impl Workspace { + pub(in crate::jiansun) fn test_preset_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + if !self.can_use_test_presets(app) { + return; + } + if !self.creation_catalog.contains_key(TEST_PRESETS) + && self.creation_catalog_error(TEST_PRESETS).is_none() + && !self.creation_catalog_loading(TEST_PRESETS) + { + self.request_creation_catalog(app, TEST_PRESETS, String::new(), false); + } + let Some(presets) = self.creation_catalog.get(TEST_PRESETS).filter(|rows| !rows.is_empty()) else { + return; + }; + let importing = self.test_preset_import_pending(); + let label = if importing { "正在填入测试商品…" } else { "一键填入测试商品(超管)" }; + let button = stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Secondary, !importing) + .on_hover_text("选择后替换当前商品资料和参考图"); + let mut chosen = None; + egui::Popup::menu(&button).style(stitch_ui::scoped_popup_style(ui)) + .frame(stitch_ui::command_menu_frame(ui.ctx())).show(|ui| { + for preset in presets { + if stitch_ui::action_button(ui, preset["label"].as_str().unwrap_or(""), stitch_ui::ButtonRole::Quiet, true).clicked() { + chosen = Some(preset.clone()); + ui.close(); + } + } + }); + if let Some(preset) = chosen { + self.select_test_preset(app, ui.ctx(), preset); + } + ui.add_space(space::SM); + } + + pub(in crate::jiansun) fn select_test_preset(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, preset: Value) { + if !self.can_use_test_presets(app) || self.test_preset_import_pending() { + return; + } + let staged = self.creation_reads.staged_new_project; + if self.ensure_creation_document(app).is_err() { + return; + } + if staged { + // Detach the old project before queuing the import. The new native + // document has no saved draft to restore on the next frame. + let doc = self.creation_doc; + let brief = std::mem::take(&mut self.creation_brief); + let dirty = self.creation_dirty; + self.switch_project_projection(app, ctx, None); + self.observed_doc = doc; + self.loaded_draft = doc; + self.creation_doc = doc; + self.creation_ui_scope = self.current_creation_ui_scope(app); + self.project_view_parked = false; + self.creation_brief = brief; + self.creation = json!({"brief":empty_brief()}); + self.creation_dirty = dirty; + } + // Carry the same picker across the staged draft's first image import. + let presets = self.creation_catalog.remove(TEST_PRESETS); + self.creation_read_scope(app); + if let Some(presets) = presets { + self.creation_catalog.insert(TEST_PRESETS.into(), presets); + } + self.request_test_preset_import(app, preset); + } + + pub(in crate::jiansun) fn apply_test_preset(&mut self, app: &PhotocraftApp, mut brief: Value) { + let selected = &self.creation_brief["templateSelection"]; + let taxonomy_changed = self.creation_brief["brandId"] != brief["brandId"] + || self.creation_brief["categoryId"] != brief["categoryId"]; + let keep_template = template_identity(selected) + && selected["id"] == brief["intake"]["templateId"] + && !taxonomy_changed; + if keep_template { + brief["templateSelection"] = selected.clone(); + } else if self.creation_reads.wizard_stage.is_some_and(|(_, stage)| stage == CreationStage::Details) { + self.creation_reads.wizard_stage = Some((self.creation_field_scope(app), CreationStage::Template)); + } + if taxonomy_changed { + self.agent_rule = Value::Null; + self.agent_rule_state = Value::Null; + self.creation_catalog.remove("categories"); + self.creation_catalog.remove("templates"); + } + self.creation_brief = brief; + self.creation_reads.manual_edited_fields.clear(); + self.creation_reads.inline_errors.clear(); + self.creation_reads.reference_import_error.clear(); + self.creation_reads.scroll_to_field = None; + self.creation_failed_signature.clear(); + self.creation_dirty = true; + self.sync_dirty = true; + self.draft_changed = true; + } + +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/tests.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/tests.rs new file mode 100644 index 00000000..91f96e02 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/tests.rs @@ -0,0 +1,3974 @@ +use super::*; +use crate::jiansun::{stitch_kit, stitch_state::Tone}; +use crate::theme::agent_scale::space; + +#[cfg(test)] +fn edit_hint(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &mut Value, width: f32, multiline: bool, hint: &str) -> bool { + edit_named(ui, id, value, width, multiline, hint, hint) +} + + +#[cfg(test)] +fn intake_fields(ui: &mut Ui, scope: egui::Id, width: f32, fields: &[&Value], kind: IntakeScope, values: &mut Value, reduced: bool) -> bool { + let mut errors = HashMap::new(); + let mut scroll = None; + let mut edited = HashSet::new(); + intake_fields_with_errors(ui, scope, width, fields, kind, values, reduced, None, &mut errors, &mut scroll, &mut edited) +} + + +#[cfg(test)] +fn barcode_editor(ui: &mut Ui, id: egui::Id, value: &mut String, width: f32, name: &str) -> egui::Response { + let id = creation_editor_id(ui, id); + use crate::theme::agent_scale::Type; + let font_size = if width >= 128.0 { Type::Meta } else { Type::Caption }.size(); + // A one-row multiline editor preserves embedded line breaks in pasted barcodes. + ui.add(stitch_ui::text_input(value, BARCODE_HINT, true) + .desired_rows(1).lock_focus(false).return_key(None) + .id(id).font(egui::FontId::monospace(font_size)).margin(egui::Margin::symmetric(2, 6)) + .desired_width((width - 4.0).max(1.0))).accessible_name(name) +} + + +#[cfg(test)] +fn barcode_issue(brief: &Value, text: &str) -> Option<&'static str> { + let text = text.trim(); + if text.is_empty() { + Some("请输入产品条码") + } else if project_barcodes(brief).any(|barcode| barcode == text) { + Some("此条码已录入当前项目") + } else { + None + } +} + +#[cfg(test)] +fn brief_step(ui: &mut Ui, title: &str, ready: bool, previous_ready: bool) { + let (status, tone) = if ready { ("已就绪", Tone::Success) } + else if previous_ready { ("当前步骤", Tone::Active) } + else { ("待填写", Tone::Quiet) }; + ui.horizontal_wrapped(|ui| { + stitch_kit::section_heading(ui, title); + stitch_kit::label(ui, status, Type::Meta, tone); + }); + ui.add_space(space::SM); +} + + +#[cfg(test)] +#[test] +fn listing_receipt_distinguishes_reported_failure_and_recalled_assets() { + let success = json!({"state":"completed","listingStatus":{"state":"listed"}}); + assert_eq!(listing_status_text(&success).0, "已上架"); + let failed = json!({"state":"completed","listingStatus":{"state":"failed"}}); + assert_eq!(listing_status_text(&failed), ("上架失败", stitch_ui::StatusTone::Error)); + let removed = json!({"state":"removed","listingStatus":{"state":"listed"}}); + assert_eq!(listing_status_text(&removed).0, "素材已撤回"); +} + + +#[cfg(test)] +impl Workspace { + #[cfg(test)] + fn brief_scroll_body_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) -> bool { + let editable = form_editable(self.busy.as_deref(), self.unknown && !self.scoped_production_pending()); + let t = Tokens::get(ui.ctx()).agent(); + let width = ui.available_width(); + let title_text = if self.creation_reads.staged_new_project { "新建项目" } else { "产品资料" }; + if width >= 440.0 { + ui.horizontal(|ui| { + let title = ui.label(egui::RichText::new(title_text).font(Type::Display.semibold()).color(t.text)); + self.control_geometry("brief-title", title.rect); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + self.brief_autosave_status_ui(ui); + }); + }); + } else { + let title = ui.label(egui::RichText::new(title_text).font(Type::Display.semibold()).color(t.text)); + self.control_geometry("brief-title", title.rect); + self.brief_autosave_status_ui(ui); + } + ui.add_space(space::XXS); + stitch_kit::caption(ui, "可先按 SPU 从产品平台或素材库导入,再核对款式、模板与视觉素材。"); + ui.add_space(space::MD); + ui.add_enabled_ui(editable, |ui| self.brief_content_ui(app, ui)).inner + } + + #[cfg(test)] + fn brief_content_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) -> bool { + let field_scope = self.creation_field_scope(app); + let width = ui.available_width(); + let editable = ui.is_enabled(); + + self.source_import_strip_ui(app, ui, field_scope, width); + brief_section_break(ui); + + let template = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + brief_step(ui, "1. 选择模板", template_identity(&template), true); + self.template_and_brand_block_ui(app, ui, width); + brief_section_break(ui); + + let template = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + let template_ready = template_identity(&template); + let archive_ready = brief_readiness(&self.creation_brief, &template).iter() + .filter(|item| !matches!(item.field_key.as_str(), "brand" | "category" | "template" | "images")) + .all(|item| item.ready); + brief_step(ui, "2. 商品档案与款式", archive_ready, template_ready); + self.core_identity_and_specs_ui(app, ui, field_scope, width); + let barcode_pending = self.sku_matrix_ui(app, ui, field_scope, width); + + brief_section_break(ui); + let images_ready = has_selected_product_image(&self.creation_brief); + brief_step(ui, "3. 视觉素材", images_ready, template_ready && archive_ready); + self.references_ui(app, ui, width); + brief_section_break(ui); + + brief_step(ui, "4. 确认制作目标", false, template_ready && archive_ready && images_ready); + self.output_tags_ui(ui); + ui.add_space(space::SM); + self.special_requirements_ui(ui, field_scope); + ui.add_space(space::SM); + let new_project = self.template_workflow["canvasFirst"] != true; + let pending = new_project.then(|| { + let doc = app.session.active().map(|state| state.doc.id.0); + (egui::Id::unique(("production-refinement", self.local_identity(""), doc)), editable) + }); + let _ = self.refinement_ui(ui, pending); + ui.add_space(space::SM); + self.delivery_directory_control(app, ui, editable); + ui.add_space(space::SM); + self.advanced_export_settings_ui(app, ui, field_scope, width, editable); + barcode_pending + } + + #[cfg(test)] + fn source_import_strip_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32) { + let t = Tokens::get(ui.ctx()).agent(); + let np = normalized_product_summary(&self.creation_brief); + let frame = egui::Frame::NONE + .fill(t.dock) + .stroke(egui::Stroke::new(1.0, t.card_border)) + .corner_radius(egui::CornerRadius::same(radius::CONTROL as u8)) + .inner_margin(egui::Margin::same(space::MD as i8)); + frame.show(ui, |ui| { + let inner_width = (width - 2.0 * space::MD - 2.0).max(160.0); + ui.set_width(inner_width); + ui.spacing_mut().item_spacing.y = space::SM; + if inner_width >= 600.0 { + ui.horizontal(|ui| { + ui.allocate_ui_with_layout(vec2(380.0, control::STANDARD), egui::Layout::left_to_right(egui::Align::Center), |ui| { + self.source_picker(ui); + }); + if self.creation_brief["source"] == "library" { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + self.product_search_button(app, ui); + }); + } + }); + } else { + self.source_picker(ui); + if self.creation_brief["source"] == "library" { + self.product_search_button(app, ui); + } + } + if self.creation_brief["source"] == "product_platform" { + self.platform_spu_ui(app, ui, field_scope, inner_width, np.has_platform_data); + } else if self.creation_brief["source"] == "library" { + self.product_select_results(app, ui); + } else { + stitch_kit::caption(ui, "直接填写下方商品档案,或随时切换到「产品平台」按 SPU 拉取规格与图片。"); + } + if !self.creation_reads.platform_sync_note.is_empty() { + stitch_kit::inline_notice(ui, "info", Tone::Verified, &self.creation_reads.platform_sync_note, |_| {}); + } + if np.has_platform_data { + let sku_count = project_barcodes(&self.creation_brief).count(); + let asset_count = selected_visual_asset_count(&self.creation_brief); + let mut meta = vec![format!("已同步 {} {}", np.trace_source, if np.spu.is_empty() { "商品资料" } else { np.spu.as_str() })]; + if sku_count > 0 { + meta.push(format!("{sku_count} 个条码")); + } + if asset_count > 0 { + meta.push(format!("{asset_count} 张素材")); + } + if !np.fetched_at.is_empty() { + meta.push(format!("同步时间 {}", np.fetched_at)); + } + ui.horizontal_wrapped(|ui| { + stitch_kit::label(ui, meta.join(" · "), Type::Meta, Tone::Success); + if !np.raw_field_warnings.is_empty() { + stitch_ui::status_chip(ui, &format!("{} 项字段待核对", np.raw_field_warnings.len()), stitch_ui::StatusTone::Warning); + } + }); + self.unmatched_platform_taxonomy_chips_ui(app, ui, &np); + } + }); + } + + + #[cfg(test)] + pub(super) fn dimensions_row_ui(&mut self, ui: &mut Ui, field_scope: egui::Id, width: f32) { + let row_width = width.min(580.0); + field_group(ui, row_width, "产品尺寸(长 × 宽 × 高)", |ui| { + let dimensions = ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + let text_color = Tokens::get(ui.ctx()).agent().text_dim; + let symbol_width = ui.painter().layout_no_wrap("×".into(), Type::Body.font_id(), text_color).size().x; + let unit_text_width = ["mm", "cm", "m"] + .iter() + .map(|unit| ui.painter().layout_no_wrap((*unit).to_owned(), Type::Meta.font_id(), text_color).size().x) + .fold(0.0_f32, f32::max); + let unit_width = (unit_text_width + 20.0 + 2.0 * ui.spacing().button_padding.x).max(62.0); + let dimension_width = ((row_width - unit_width - 2.0 * symbol_width - 5.0 * ui.spacing().item_spacing.x) / 3.0).max(56.0); + for (position, (key, hint)) in [("length", "长"), ("width", "宽"), ("height", "高")].iter().enumerate() { + if position > 0 { + ui.label(egui::RichText::new("×").font(Type::Body.font_id()).color(text_color)); + } + if edit_hint(ui, (field_scope, "dimensions", *key), &mut self.creation_brief["dimensions"][*key], dimension_width, false, hint) { + self.creation_dirty = true; + self.creation_reads.manual_edited_fields.insert(format!("dimensions:{key}")); + } + } + let unit_label = self.creation_brief["dimensions"]["unit"].as_str().unwrap_or("mm").to_owned(); + let unit = stitch_ui::halo_select(ui, "creation-unit", unit_width, &unit_label, self.reduce_motion, |ui| { + for unit in ["mm", "cm", "m"] { + let option = stitch_ui::select_option(ui, unit, self.creation_brief["dimensions"]["unit"] == unit, true); + self.control_geometry(&format!("unit-option-{unit}"), option.rect); + if option.clicked() { + self.creation_brief["dimensions"]["unit"] = json!(unit); + self.creation_dirty = true; + self.creation_reads.manual_edited_fields.insert("dimensions:unit".into()); + ui.close(); + } + } + }); + self.control_geometry("dimensions-unit", unit.response.rect); + }); + self.control_geometry("dimensions", dimensions.response.rect); + }); + } + + + #[cfg(test)] + fn sku_matrix_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32) -> bool { + let dynamic = self.creation_brief["intake"]["schema"]["version"] == 1; + let platform = self.creation_brief["source"] == "product_platform"; + ui.add_space(space::MD); + if !dynamic && !platform { + if width >= 600.0 { + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = space::MD; + let material_width = (width * 0.44).clamp(320.0, 420.0).min((width - 200.0).max(240.0)); + let heading_width = (width - material_width - space::MD).max(120.0); + let heading = ui.vertical(|ui| { + ui.set_width(heading_width); + stitch_kit::label(ui, "产品花色与款式条码", Type::Body, Tone::Active); + stitch_kit::caption(ui, "从材质库选择或手动添加花色,并录入对应条码。"); + }); + self.control_geometry("material-heading", heading.response.rect); + self.material_select(app, ui, material_width); + }); + } else { + stitch_kit::label(ui, "产品花色与款式条码", Type::Body, Tone::Active); + stitch_kit::caption(ui, "从材质库选择或手动添加花色,并录入对应条码。"); + ui.add_space(space::XS); + self.material_select(app, ui, width.min(420.0)); + } + ui.add_space(space::SM); + self.sku_colors_bar_ui(ui, width, field_scope); + ui.add_space(space::SM); + } else { + stitch_kit::label(ui, "款式与条码矩阵", Type::Body, Tone::Active); + stitch_kit::caption(ui, "按花色分组折叠展示;点选任一行「设为详情主款」或展开编辑单款参数与图片。"); + ui.add_space(space::XS); + } + self.barcode_cards_ui(app, ui, width, field_scope) + } + + + #[cfg(test)] + fn barcode_cards_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, scope: egui::Id) -> bool { + let t = Tokens::get(ui.ctx()).agent(); + let fields = self.creation_brief["intake"]["schema"]["barcodeFields"].clone(); + let images = fields.as_array().into_iter().flatten().filter(|field| field_kind(field) == "image").collect::>(); + let fields = fields.as_array().into_iter().flatten().filter(|field| field_kind(field) != "image").collect::>(); + let has_barcode_schema = !fields.is_empty() || !images.is_empty(); + + // Preserve existing binding groups for adding/removing/renaming barcodes cleanly. + let variants = brief_variants(&self.creation_brief); + let mut binding_groups: Vec<(String, String)> = variants + .iter() + .filter_map(|variant| Some((variant["id"].as_str()?.to_owned(), variant["name"].as_str().unwrap_or("默认花色").to_owned()))) + .collect(); + if binding_groups.is_empty() || binding_barcodes(&self.creation_brief["barcodeBindings"]["default"]).next().is_some() { + binding_groups.insert(0, ("default".into(), "默认花色".into())); + } + + let norm_groups = normalized_color_groups(&self.creation_brief); + let total_barcodes: usize = norm_groups.iter().map(|g| g.skus.len()).sum(); + let default_detail = self.creation_brief["detailBarcode"].as_str().map(str::to_owned); + let mut pending = false; + + // If normalizedProduct or platformFacts grouped multiple colors, render collapsible color matrix. + let use_grouped_matrix = !norm_groups.is_empty() && (self.creation_brief["normalizedProduct"].is_object() || total_barcodes > 4); + + if use_grouped_matrix { + // Active detail-main SKU banner + selector at top of matrix. + update_detail_barcode(&mut self.creation_brief); + let codes: Vec = project_barcodes(&self.creation_brief).map(str::to_owned).collect(); + if codes.len() > 1 { + self.detail_barcode_selector_ui(ui, width, scope, &codes); + ui.add_space(space::SM); + } + let detail_code = self.creation_brief["detailBarcode"].as_str().unwrap_or("").to_owned(); + for (g_idx, group) in norm_groups.iter().enumerate() { + let contains_detail = group.skus.iter().any(|s| s.barcode == detail_code); + let default_open = total_barcodes <= 4 || contains_detail || (detail_code.is_empty() && g_idx == 0); + let is_open = if self.creation_reads.expanded_colors.contains(&group.id) { + true + } else if self.creation_reads.expanded_colors.contains(&format!("!{}", group.id)) { + false + } else { + default_open + }; + let frame = egui::Frame::NONE + .fill(t.dock) + .stroke(egui::Stroke::new(1.0, t.card_border)) + .corner_radius(egui::CornerRadius::same(radius::CONTROL as u8)) + .inner_margin(egui::Margin::symmetric(10, 8)); + frame.show(ui, |ui| { + let inner_w = (width - 22.0).max(140.0); + ui.set_width(inner_w); + let header_label = format!( + "{}({} 个规格){}", + group.color_name, + group.skus.len(), + if contains_detail { " · 含详情主款" } else { "" } + ); + let toggle = ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = space::XS; + ui.add(crate::icons::image(if is_open { "chevron-down" } else { "chevron-right" }, icon::SM, t.text_dim)); + stitch_ui::action_button(ui, &header_label, stitch_ui::ButtonRole::Quiet, true) + }).inner; + self.control_geometry(&format!("color-group-{}", group.id), toggle.rect); + if toggle.clicked() { + if is_open { + self.creation_reads.expanded_colors.remove(&group.id); + self.creation_reads.expanded_colors.insert(format!("!{}", group.id)); + } else { + self.creation_reads.expanded_colors.remove(&format!("!{}", group.id)); + self.creation_reads.expanded_colors.insert(group.id.clone()); + } + } + if is_open { + ui.add_space(space::XS); + for (s_idx, sku) in group.skus.iter().enumerate() { + if s_idx > 0 { + stitch_ui::divider(ui); + } + let code = sku.barcode.as_str(); + let is_detail = self.creation_brief["detailBarcode"] == code; + let closed_key = format!("!{code}"); + let mut sku_open = self.creation_reads.expanded_skus.contains(code) + || (has_barcode_schema && (is_detail || total_barcodes <= 2) + && !self.creation_reads.expanded_skus.contains(&closed_key)); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = space::SM; + let star_label = if is_detail { "详情主款" } else { "设为主款" }; + let star = stitch_ui::segmented_option_sized(ui, star_label, is_detail, true, vec2(76.0, 26.0)); + self.control_geometry(&format!("sku-main-{code}"), star.rect); + if star.clicked() && !is_detail { + self.creation_brief["detailBarcode"] = json!(code); + self.creation_brief["colorName"] = json!(sku.color_name); + self.creation_reads.inline_errors.remove("detail-barcode"); + self.creation_dirty = true; + } + ui.label(egui::RichText::new(code).font(egui::FontId::monospace(Type::Meta.size())).color(t.text)); + let mut meta_parts = Vec::new(); + if !sku.spec.is_empty() { + meta_parts.push(sku.spec.clone()); + } + if let Some(dims) = sku.dimensions_display.as_deref() + && !sku.spec.contains(dims) + { + meta_parts.push(dims.to_owned()); + } + if !meta_parts.is_empty() { + ui.add( + egui::Label::new(egui::RichText::new(meta_parts.join(" · ")).font(Type::Meta.font_id()).color(t.text_dim)) + .wrap_mode(egui::TextWrapMode::Extend), + ); + } + if sku.image_count > 0 { + ui.add( + egui::Label::new(egui::RichText::new(format!("{} 图", sku.image_count)).font(Type::Meta.font_id()).color(Tone::Verified.color(&t))) + .wrap_mode(egui::TextWrapMode::Extend), + ); + } + let expand_label = if sku_open { "收起参数" } else { "展开参数" }; + let expand_btn = stitch_ui::action_button(ui, expand_label, stitch_ui::ButtonRole::Quiet, true); + self.control_geometry(&format!("sku-expand-{code}"), expand_btn.rect); + if expand_btn.clicked() { + if sku_open { + self.creation_reads.expanded_skus.remove(code); + self.creation_reads.expanded_skus.insert(closed_key); + } else { + self.creation_reads.expanded_skus.remove(&closed_key); + self.creation_reads.expanded_skus.insert(code.to_owned()); + } + sku_open = !sku_open; + } + }); + let card_scope = scope.with(("norm-sku", code)); + stitch_ui::morph_surface(ui, card_scope.with("reveal"), sku_open, self.reduce_motion, |ui| { + ui.add_space(space::XS); + if has_barcode_schema { + self.barcode_intake_ui(app, ui, card_scope, inner_w, code, &fields, &images); + } else { + // Show platform SKU attributes / selling points when present. + if let Some(row) = self.creation_brief["normalizedProduct"]["variants"] + .as_array() + .into_iter() + .flatten() + .flat_map(|v| v["barcodes"].as_array().into_iter().flatten()) + .find(|b| non_empty_str(&b["barcode"]) == Some(code)) + { + let points = dedupe_strings(string_list(&row["sellingPoints"])); + for pt in points.iter().take(4) { + stitch_kit::caption(ui, format!("· {pt}")); + } + if let Some(sku_code) = non_empty_str(&row["skuCode"]) { + stitch_kit::caption(ui, format!("SKU 编码:{sku_code}")); + } + } + } + }); + } + } + }); + ui.add_space(space::XS); + } + // Still allow adding a manual barcode into default binding if user wants. + let mut extra_codes: Vec = binding_barcodes(&self.creation_brief["barcodeBindings"]["default"]).map(str::to_owned).collect(); + let (added, entry_pending) = self.barcode_entry_ui(ui, width, scope.with(("barcodes", "default")), "default", "手动补充条码", &mut extra_codes); + pending |= entry_pending; + if added { + self.creation_brief["barcodeBindings"]["default"] = json!(extra_codes); + self.creation_dirty = true; + } + update_detail_barcode(&mut self.creation_brief); + return pending; + } + + // Standard / Legacy editable barcode list (compact rows with inline main-SKU star + editable barcode). + let mut ordinal = 0; + for (id, label) in binding_groups { + let group_scope = scope.with(("barcodes", id.as_str())); + let mut codes: Vec = binding_barcodes(&self.creation_brief["barcodeBindings"][id.as_str()]).map(str::to_owned).collect(); + let single_before_add = project_barcodes(&self.creation_brief).take(2).count() == 1; + let (added, entry_pending) = self.barcode_entry_ui(ui, width, group_scope, &id, &label, &mut codes); + pending |= entry_pending; + let mut changed = added; + let mut remove = None; + for (index, code) in codes.iter_mut().enumerate() { + ordinal += 1; + let card = egui::Frame::NONE + .fill(t.dock) + .stroke(egui::Stroke::new(1.0, t.card_border)) + .corner_radius(egui::CornerRadius::same(radius::CONTROL as u8)) + .inner_margin(8) + .show(ui, |ui| { + let inner_w = (width - 18.0).max(1.0); + ui.set_width(inner_w); + let card_scope = group_scope.with(code.as_str()); + let draft_id = card_scope.with("edit"); + let mut draft = ui.data(|data| data.get_temp::(draft_id)).unwrap_or_else(|| code.clone()); + let mut commit = false; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 8.0; + let number = ui.weak(format!("#{ordinal}")); + let delete_size = 24.0; + let edit_width = (ui.available_width() - delete_size - ui.spacing().item_spacing.x).clamp(1.0, 320.0); + let editor = barcode_editor(ui, card_scope, &mut draft, edit_width, "编辑产品条码"); + self.control_geometry(&format!("barcode-edit-{id}-{index}"), editor.rect); + commit = editor.lost_focus() || (editor.has_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter))); + if ui.input(|input| input.key_pressed(egui::Key::Escape)) && (editor.has_focus() || editor.lost_focus()) { + draft.clone_from(code); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let delete = stitch_ui::icon_button(ui, "trash", delete_size, false, "删除条码"); + self.control_geometry(&format!("barcode-remove-{id}-{index}"), delete.rect); + if delete.clicked() { remove = Some(index); } + }); + self.control_geometry(&format!("barcode-number-{id}-{index}"), number.rect); + }); + if draft.trim() != code.as_str() { + if let Some(issue) = barcode_issue(&self.creation_brief, &draft) { + stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Warning); + } else if commit { + let replacement = draft.trim(); + replace_barcode(&mut self.creation_brief, code, Some(replacement)); + *code = replacement.to_owned(); + changed = true; + } + } + pending |= draft.trim() != code.as_str() && remove != Some(index); + ui.data_mut(|data| { + if draft == *code || commit && draft.trim() == code.as_str() || remove == Some(index) { + data.remove::(draft_id); + } else { + data.insert_temp(draft_id, draft); + } + }); + reveal_template_intake(ui, card_scope.with("reveal"), has_barcode_schema, self.reduce_motion, |ui| { + self.barcode_intake_ui(app, ui, card_scope, inner_w, code, &fields, &images); + }); + if fields.is_empty() { + let facts = &self.creation_brief["platformFacts"]["barcodes"][code.as_str()]; + let mut parts = Vec::new(); + for key in ["colorName", "sizeText", "spec"] { + if let Some(value) = non_empty_str(&facts[key]) + && !parts.iter().any(|existing: &String| existing.eq_ignore_ascii_case(value)) + { + parts.push(value.to_owned()); + } + } + if let Some(dimensions) = dimension_text(&facts["dimensions"]) { + parts.push(dimensions); + } + if !parts.is_empty() { + stitch_kit::caption(ui, parts.join(" · ")); + } + } + }); + self.control_geometry(&format!("barcode-card-{id}-{index}"), card.response.rect); + } + if let Some(index) = remove { + replace_barcode(&mut self.creation_brief, &codes.remove(index), None); + changed = true; + } + if changed { + self.creation_brief["barcodeBindings"][id.as_str()] = json!(codes); + if added && single_before_add && let Some(fields) = self.creation_brief.as_object_mut() { + fields.remove("detailBarcode"); + } + self.creation_dirty = true; + } + } + let _ = default_detail; + update_detail_barcode(&mut self.creation_brief); + let codes: Vec = project_barcodes(&self.creation_brief).map(str::to_owned).collect(); + if codes.len() > 1 { + ui.add_space(space::XS); + self.detail_barcode_selector_ui(ui, width, scope, &codes); + } + pending + } + + + #[cfg(test)] + fn barcode_entry_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id, id: &str, label: &str, codes: &mut Vec) -> (bool, bool) { + let draft_id = scope.with("new-barcode"); + let mut draft = ui.data(|data| data.get_temp::(draft_id)); + let mut opened = false; + ui.horizontal(|ui| { + ui.set_width(width); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let add = stitch_ui::action_button(ui, "+ 添加条码", stitch_ui::ButtonRole::Quiet, true); + self.control_geometry(&format!("barcode-add-{id}"), add.rect); + if add.clicked() { + draft.get_or_insert_with(String::new); + opened = true; + } + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.add(egui::Label::new(egui::RichText::new(label).font(Type::Body.semibold())).truncate()); + }); + }); + }); + let Some(mut text) = draft else { return (false, false) }; + let editor = barcode_editor(ui, draft_id, &mut text, width, "新增产品条码"); + self.control_geometry(&format!("barcode-input-{id}"), editor.rect); + if opened { editor.request_focus(); } + let issue = barcode_issue(&self.creation_brief, &text); + if !text.trim().is_empty() && let Some(issue) = issue { + stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Warning); + } + let mut added = false; + let mut cancelled = false; + ui.horizontal(|ui| { + let confirm = stitch_ui::action_button(ui, "添加", stitch_ui::ButtonRole::Secondary, issue.is_none()); + self.control_geometry(&format!("barcode-confirm-{id}"), confirm.rect); + if issue.is_none() && (confirm.clicked() || ((editor.has_focus() || editor.lost_focus()) && ui.input(|input| input.key_pressed(egui::Key::Enter)))) { + codes.push(text.trim().to_owned()); + added = true; + } + cancelled = stitch_ui::action_button(ui, "取消", stitch_ui::ButtonRole::Quiet, true).clicked(); + }); + let pending = !added && !cancelled && !text.trim().is_empty(); + ui.data_mut(|data| { + if added || cancelled { data.remove::(draft_id); } + else { data.insert_temp(draft_id, text); } + }); + (added, pending) + } + + + #[cfg(test)] + fn brief_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + let barcode_pending = self.brief_scroll_body_ui(app, ui); + ui.add_space(space::MD); + stitch_ui::divider(ui); + ui.add_space(space::MD); + self.brief_footer_ui(app, ui, barcode_pending); + } +} + + use crate::jiansun::test_support::SettleUi; + use photocraft_doc::LayerContent; + use std::sync::{Arc, mpsc}; + + const TEST_PRESET_PICKER_LABEL: &str = "一键填入测试商品(超管)"; + + fn test_preset_wizard( + account: Value, + width: f32, + ) -> (egui_kittest::Harness<'static, (Workspace, PhotocraftApp)>, mpsc::Receiver) { + let (mut w, app, requests) = brief_fixture(); + w.account = account; + w.reduce_motion = true; + w.observed_doc = w.creation_doc; + w.project_context = json!({"localId":"previous-project"}); + w.begin_staged_new_project(&app); + let harness = egui_kittest::Harness::builder() + .with_size(vec2(width, 850.0)) + .with_context_setup(|ctx| { + PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }) + .build_ui_state(|ui, (w, app): &mut (Workspace, PhotocraftApp)| { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| w.creation_ui(app, ui)); + }, (w, app)); + (harness, requests) + } + + fn request_for_test_product_preset(requests: &mpsc::Receiver, kind: &str) -> Option { + requests.try_iter().find_map(|request| match request { + Request::Action(method, input) if method == "creation-catalog" && input["kind"] == kind => Some(input), + _ => None, + }) + } + + #[test] + fn test_product_presets_hide_the_picker_and_skip_the_request_without_super_admin() { + use egui_kittest::kittest::Queryable; + for account in [ + json!({"id":"qa","isSuperAdmin":false}), + json!({"id":"qa","isDepartmentAdmin":true}), + json!({"id":"qa","isSuperAdmin":"true"}), + Value::Null, + ] { + let (mut harness, requests) = test_preset_wizard(account, 460.0); + harness.run_steps(3); + assert!(harness.query_by_label(TEST_PRESET_PICKER_LABEL).is_none()); + assert!(request_for_test_product_preset(&requests, TEST_PRESETS).is_none()); + assert!(harness.query_by_label("选择文件夹").is_some(), "the normal form remains available"); + } + } + + #[test] + fn test_product_presets_fill_and_replace_the_editable_draft_from_picker_selection() { + use egui_kittest::kittest::Queryable; + let (mut harness, requests) = test_preset_wizard(json!({"id":"qa","isSuperAdmin":true}), 460.0); + harness.run_steps(3); + let initial_catalogs = requests.try_iter().filter_map(|request| match request { + Request::Action(method, input) if method == "creation-catalog" => Some(input), + _ => None, + }).collect::>(); + let mut brands = initial_catalogs.iter().find(|input| input["kind"] == "brands").unwrap().clone(); + let mut response = initial_catalogs.into_iter().find(|input| input["kind"] == TEST_PRESETS).unwrap(); + assert_eq!(response["doc"], 0); + assert!(request_for_test_product_preset(&requests, TEST_PRESETS).is_none()); + assert!(harness.query_by_label(TEST_PRESET_PICKER_LABEL).is_none(), "wait for the authorized response"); + { + let (w, app) = harness.state_mut(); + brands["catalog"]["items"] = json!([]); + assert!(w.creation_read_received(app, "creation-catalog", &brands)); + assert!(request_for_test_product_preset(&requests, "materials").is_some()); + } + response["catalog"]["items"] = json!([ + {"id":"oak","label":"橡木换鞋凳"},{"id":"linen","label":"亚麻储物凳"} + ]); + { + let (w, app) = harness.state_mut(); + assert!(w.creation_read_received(app, "creation-catalog", &response)); + } + harness.run_steps(3); + + for (index, (id, name, barcode)) in [("oak", "橡木换鞋凳", "0200000010010"), ("linen", "亚麻储物凳", "0200000020019")].into_iter().enumerate() { + let picker = harness.get_by_label(TEST_PRESET_PICKER_LABEL); + assert!(picker.rect().width() > 0.0 && picker.rect().right() < 460.0); + picker.click(); + harness.run_steps(3); + harness.get_by_label(name).click(); + harness.run_steps(3); + let mut receipt = request_for_test_product_preset(&requests, "test-product-preset-import").unwrap(); + assert_eq!(receipt["id"], id); + assert_ne!(receipt["doc"], 0); + let mut brief = empty_brief(); + brief["name"] = json!(name); + brief["identifier"] = json!("XYQA-ST-001"); + brief["brandId"] = json!("ekb:brand:小壹测试"); + brief["brandName"] = json!("小壹测试"); + brief["categoryId"] = json!("ekb:category:链路验收"); + brief["categoryName"] = json!("链路验收"); + brief["note"] = json!("适用于玄关"); + brief["intake"] = json!({"productValues":{"productBrand":"测试品牌","sellingPoints":"圆角座面","description":"可收纳", + "specifications":"480 × 380 × 420 mm"},"barcodeValues":{barcode:{"length":"480"}}}); + brief["barcodeEntries"] = json!([{"id":barcode,"barcode":barcode}]); + brief["detailBarcode"] = json!(barcode); + brief["images"] = json!([{"source":format!("local:{}", if index == 0 { "a" } else { "b" }.repeat(64)), + "name":format!("{name}.jpg"),"purpose":"product","barcode":barcode}]); + receipt["presetBrief"] = brief.clone(); + let (w, app) = harness.state_mut(); + if index == 0 { + assert!(w.project_context["localId"].is_null()); + } else { + w.project_context["localId"] = json!("new-draft"); + } + let ctx = egui::Context::default(); + assert!(w.tick_context(app, &ctx)); + assert_eq!(w.observed_doc, receipt["doc"].as_u64()); + assert!(w.creation_read_received(app, "creation-catalog", &receipt)); + assert_eq!(w.creation_brief, brief); + assert!(w.creation_dirty && w.sync_dirty); + assert_eq!(app.session.documents().len(), 2, "reselecting keeps the same draft document"); + let template = json!({"id":"QA-FAST-001","version":"1.0","contentHash":"a".repeat(64)}); + assert!(canvas_entry_missing(&w.creation_brief, &template).is_empty()); + w.creation_brief["note"] = json!("手改后仍然可编辑"); + assert_eq!(w.creation_brief["note"], "手改后仍然可编辑"); + harness.run_steps(3); + } + } + + #[test] + fn test_product_presets_hide_failed_responses_without_changing_the_normal_form() { + use egui_kittest::kittest::Queryable; + for error in [json!({"error":"HTTP 403"}), json!({"error":"HTTP 404"}), json!({"catalog":{"items":null}})] { + let (mut harness, requests) = test_preset_wizard(json!({"id":"qa","isSuperAdmin":true}), 900.0); + harness.run_steps(3); + let mut response = request_for_test_product_preset(&requests, TEST_PRESETS).unwrap(); + let (w, app) = harness.state_mut(); + let before = w.creation_brief.clone(); + response.as_object_mut().unwrap().extend(error.as_object().unwrap().clone()); + assert!(w.creation_read_received(app, "creation-catalog", &response)); + assert_eq!(w.creation_brief, before); + assert!(w.error.is_empty()); + harness.run_steps(3); + assert!(harness.query_by_label(TEST_PRESET_PICKER_LABEL).is_none()); + assert!(harness.query_by_label("选择文件夹").is_some()); + assert!(request_for_test_product_preset(&requests, TEST_PRESETS).is_none()); + } + } + + #[test] + fn unhinted_creation_field_has_a_meaningful_accessible_name() { + use egui_kittest::kittest::Queryable; + let mut h = egui_kittest::Harness::builder().with_context_setup(crate::cjk_fonts::install_system_provider_for_tests).with_size(vec2(320.0, 120.0)).build_ui_state( + |ui, value: &mut Value| { edit(ui, "name", value, 280.0, false, "产品名称"); }, json!("桌子")); + h.run_steps(3); + h.check_accessibility(); + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "产品名称"); + } + + #[test] + fn material_search_coalesces_edits_and_clear_without_repeating_requests() { + let mut state = MaterialSearchPending::default(); + assert!(!material_search_due(&mut state, "木", true, false, 0.0)); + assert!(!material_search_due(&mut state, "木纹", true, false, 0.2)); + assert!(!material_search_due(&mut state, "木纹", false, false, 0.49)); + assert!(material_search_due(&mut state, "木纹", false, false, 0.51)); + assert!(!material_search_due(&mut state, "木纹", false, false, 0.8)); + assert!(material_search_due(&mut state, "", true, false, 0.9)); + assert!(!material_search_due(&mut state, "", false, false, 1.3)); + assert!(material_search_due(&mut state, "材质", true, true, 1.4)); + assert!(!material_search_due(&mut state, "材质", false, false, 1.8)); + } + + #[test] + fn creation_halo_field_respects_form_width_and_native_text_focus() { + for width in [180.0, 320.0, 520.0] { + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let mut value = json!(""); + let mut field_rect = egui::Rect::NOTHING; + let run = |value: &mut Value, events, field_rect: &mut egui::Rect| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,400.0))), events, ..Default::default() }, |ui| { + ui.set_width(width); + let start = ui.cursor().min; + edit_hint(ui, "test-name", value, width, false, "输入产品名称"); + *field_rect = egui::Rect::from_min_max(start, ui.min_rect().max); + }); + }; + run(&mut value,vec![],&mut field_rect); + assert!(field_rect.width() <= width + 1.0, "width={width}, rect={field_rect:?}"); + let pos = field_rect.center(); + for pressed in [true,false] { + run(&mut value,vec![egui::Event::PointerMoved(pos),egui::Event::PointerButton { pos, button:egui::PointerButton::Primary, pressed, modifiers:egui::Modifiers::NONE }],&mut field_rect); + } + run(&mut value,vec![egui::Event::Text("产品名称".into())],&mut field_rect); + assert_eq!(value, "产品名称", "native editor retains focus and editing at width {width}"); + } + } + + #[test] + fn creation_editor_focus_survives_an_earlier_field_appearing() { + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let mut earlier = json!(""); + let mut name = json!("原名"); + let frame = |earlier: &mut Value, name: &mut Value, show_earlier: bool, events| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(400.0,300.0))), events, ..Default::default() }, |ui| { + if show_earlier { edit(ui, "earlier", earlier, 250.0, false, "前一字段"); } + edit(ui, "name", name, 250.0, false, "产品名称"); + }); + }; + frame(&mut earlier,&mut name,false,vec![]); + ctx.memory_mut(|memory| memory.request_focus(egui::Id::unique("creation-field").with("name").with("editor"))); + frame(&mut earlier,&mut name,true,vec![egui::Event::Text("新".into())]); + assert!(name.as_str().unwrap().contains('新')); + assert_eq!(earlier, ""); + } + + #[test] + fn creation_escape_closes_popup_then_editor_then_view_without_losing_draft() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_open = true; + w.library = false; + w.material = false; + w.creation_step = 0; + w.creation_dirty = true; + w.creation_brief["images"] = json!([]); + w.creation_brief["variants"] = json!([]); + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { + let mut leaked = false; + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(1000.0,900.0))),events,..Default::default() }, |ui| { + w.creation_ui(app,ui); + leaked = ui.input(|input| input.key_pressed(egui::Key::Escape)); + }); + leaked + }; + let key = |pressed| egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed, repeat:false, modifiers:egui::Modifiers::NONE }; + frame(&mut w,&mut app,vec![]); + let before = w.creation_brief.clone(); + let editor = egui::Id::unique("creation-field").with((w.creation_field_scope(&app),"name")).with("editor"); + ctx.memory_mut(|memory| memory.request_focus(editor)); + frame(&mut w,&mut app,vec![]); + egui::Popup::open_id(&ctx,egui::Id::unique("creation-test-popup")); + assert!(!frame(&mut w,&mut app,vec![key(true)])); + assert!(!egui::Popup::is_any_open(&ctx)); + assert_eq!(w.creation_step,0); + frame(&mut w,&mut app,vec![key(false)]); + assert!(!frame(&mut w,&mut app,vec![key(true)])); + assert!(!ctx.memory(|memory| memory.has_focus(editor))); + assert_eq!(w.creation_step,0); + frame(&mut w,&mut app,vec![key(false)]); + assert!(!frame(&mut w,&mut app,vec![key(true)])); + assert_eq!(w.creation_reads.wizard_stage.unwrap().1, CreationStage::Template); + frame(&mut w,&mut app,vec![key(false)]); + assert!(!frame(&mut w,&mut app,vec![key(true)])); + assert_eq!(w.creation_reads.wizard_stage.unwrap().1, CreationStage::Source); + frame(&mut w,&mut app,vec![key(false)]); + assert!(!frame(&mut w,&mut app,vec![key(true)])); + assert!(!w.creation_open); + assert!(w.library); + assert!(w.creation_dirty); + assert_eq!(w.creation_brief,before); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn creation_escape_waits_for_ime_composition_and_preserves_active_task() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_open=true; + w.creation_step=2; + w.busy=Some("pi-agent".into()); + let ctx=egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(1000.0,900.0))),events,..Default::default() }, |ui| w.creation_ui(app,ui)); + }; + let key=|pressed| egui::Event::Key { key:egui::Key::Escape,physical_key:Some(egui::Key::Escape),pressed,repeat:false,modifiers:egui::Modifiers::NONE }; + frame(&mut w,&mut app,vec![egui::Event::Ime(egui::ImeEvent::Preedit { text:"shuru".into(),active_range_chars:None }),key(true)]); + assert_eq!(w.creation_step,2); + frame(&mut w,&mut app,vec![key(false),egui::Event::Ime(egui::ImeEvent::Commit("输入".into()))]); + frame(&mut w,&mut app,vec![key(true)]); + assert_eq!(w.creation_step,1); + assert_eq!(w.busy.as_deref(),Some("pi-agent")); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn creation_editor_undo_is_isolated_by_account_origin_and_document() { + let (mut w, mut app, requests) = brief_fixture(); + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + w.origin = "local-a".into(); + w.account = json!({"id":"account-a"}); + w.creation_doc = app.session.active().map(|s| s.doc.id.0); + let a = w.creation_field_scope(&app); + w.account = json!({"id":"account-b"}); + let b = w.creation_field_scope(&app); + assert_ne!(a,b); + w.account = json!({"id":"account-a"}); + w.origin = "local-b".into(); + assert_ne!(a,w.creation_field_scope(&app)); + w.origin = "local-a".into(); + app.session.execute("file.new",json!({"width":32,"height":32})).unwrap(); + assert_ne!(a,w.creation_field_scope(&app)); + let frame = |scope:egui::Id, value:&mut Value, time:f64, events| { + let id = egui::Id::unique("creation-field").with((scope,"name")).with("editor"); + ctx.memory_mut(|memory| memory.request_focus(id)); + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(400.0,300.0))), time:Some(time), events, ..Default::default() }, |ui| { + edit(ui,(scope,"name"),value,250.0,false,"产品名称"); + }); + }; + // egui's Windows input adapter sets both ctrl and logical command; + // TextEdit recognizes undo through the platform-independent command. + let undo = || egui::Event::Key { key:egui::Key::Z, physical_key:Some(egui::Key::Z), pressed:true, repeat:false, + modifiers:egui::Modifiers { ctrl:true, command:true, ..Default::default() } }; + let mut av = json!("原始A"); + let mut bv = json!("原始B"); + frame(a,&mut av,0.0,vec![]); + frame(a,&mut av,0.1,vec![egui::Event::Text("输入A".into())]); + frame(a,&mut av,1.4,vec![]); + assert!(av.as_str().unwrap().contains("输入A")); + frame(b,&mut bv,2.0,vec![]); + frame(b,&mut bv,2.1,vec![undo()]); + assert_eq!(bv,"原始B", "another account cannot undo the first account's text"); + frame(b,&mut bv,2.2,vec![egui::Event::Key { key:egui::Key::Z, physical_key:Some(egui::Key::Z), pressed:false, repeat:false, modifiers:egui::Modifiers::NONE }]); + frame(a,&mut av,2.3,vec![undo()]); + assert_eq!(av,"原始A", "returning to the original account retains its own undo history"); + assert!(requests.try_recv().is_err()); + } + + #[test] + #[ignore = "offscreen GPU creation-field acceptance; requires PHOTOCRAFT_AGENT_QA_OUT"] + fn creation_halo_visual_acceptance() { + let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + for width in [250.0, 520.0] { + let mut h = egui_kittest::Harness::builder().with_size(vec2(width, 300.0)).with_pixels_per_point(1.5).wgpu().build_ui_state( + |ui, value: &mut Value| { + if !stitch_ui::ui_fonts_ready(ui) { return; } + ui.painter().rect_filled(ui.max_rect(), 0.0, Tokens::get(ui.ctx()).agent().dock); + stitch_ui::scope(ui, |ui| { + field_group(ui, ui.available_width(), "产品名称", |ui| { + edit_hint(ui, "test-name", value, ui.available_width(), false, "输入产品名称"); + }); + field_group(ui, ui.available_width(), "产品描述", |ui| { + let mut description = json!("保留木纹与真实材质。"); + edit(ui, "test-description", &mut description, ui.available_width(), true, "产品描述"); + }); + }); + }, json!("长产品名称 · 木纹书桌")); + crate::PhotocraftApp::setup_context(&h.ctx,crate::theme::ThemeKind::ProMedium); + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join(format!("creation-halo-{width}.png"))).unwrap(); + } + } + + fn bounded_import_fixture() -> (Workspace, PhotocraftApp, mpsc::Receiver) { + let (workspace, mut app, requests) = brief_fixture(); + app.session.authorize = Some(|_, _| Ok(())); + (workspace, app, requests) + } + + #[test] + fn creation_import_automation_uses_only_the_bounded_capability_and_retains_the_current_scope() { + use base64::Engine as _; + use std::{cell::RefCell, rc::Rc}; + let (mut workspace, mut app, requests) = bounded_import_fixture(); + let calls = Rc::new(RefCell::new(Vec::new())); + let seen = calls.clone(); + app.services.automation_read = Some(Box::new(|_| panic!("unbounded capability must never be called"))); + app.services.automation_read_limited = Some(Box::new(move |path, limit| { + seen.borrow_mut().push((path.to_owned(), limit)); + Ok((format!("imported-{path}"), path.as_bytes().to_vec())) + })); + let before = workspace.creation_brief.clone(); + let doc = app.session.active().unwrap().doc.id.0; + workspace.creation_action(&mut app, "creation-import", json!({"doc":doc,"paths":["first.png","second.png"]})).unwrap(); + assert_eq!(calls.borrow().as_slice(), &[("first.png".into(), 20 * 1024 * 1024), ("second.png".into(), 20 * 1024 * 1024)]); + let Request::Action(method, payload) = requests.try_recv().unwrap() else { panic!("expected the scoped import") }; + assert_eq!(method, "creation-import-data"); + assert_eq!(payload["doc"], doc); + assert_eq!(payload["baseRevision"].as_u64(), app.session.active().map(|native| native.revision)); + assert_eq!(payload["brief"], before); + assert!(payload.get("paths").is_none(), "backend receives capability-read bytes, never an ambient path"); + for (index, path) in ["first.png", "second.png"].iter().enumerate() { + assert_eq!(payload["images"][index]["name"], format!("imported-{path}")); + assert_eq!(base64::engine::general_purpose::STANDARD.decode(payload["images"][index]["data"].as_str().unwrap()).unwrap(), path.as_bytes()); + } + assert_eq!(workspace.creation_brief, before, "a dispatch does not preempt the backend's verified import receipt"); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn creation_import_automation_passes_the_remaining_batch_budget_before_reading() { + use std::{cell::RefCell, rc::Rc}; + let (mut workspace, mut app, requests) = bounded_import_fixture(); + let limits = Rc::new(RefCell::new(Vec::new())); + let seen = limits.clone(); + app.services.automation_read_limited = Some(Box::new(move |path, limit| { + seen.borrow_mut().push(limit); + let bytes = if path == "first.png" { 20 * 1024 * 1024 } else { 4 * 1024 * 1024 }; + Ok((path.to_owned(), vec![7; bytes])) + })); + workspace.creation_action(&mut app, "creation-import", json!({"paths":["first.png","second.png"]})).unwrap(); + assert_eq!(limits.borrow().as_slice(), &[20 * 1024 * 1024, 4 * 1024 * 1024]); + let Request::Action(method, payload) = requests.try_recv().unwrap() else { panic!("expected one bounded batch") }; + assert_eq!(method, "creation-import-data"); + assert_eq!(payload["images"].as_array().unwrap().len(), 2); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn creation_import_automation_rejects_empty_oversize_or_failed_reads_without_dispatch() { + use std::{cell::RefCell, rc::Rc}; + for scenario in ["empty", "oversize-single", "oversize-remaining", "budget-exhausted", "capability-error"] { + let (mut workspace, mut app, requests) = bounded_import_fixture(); + let before = workspace.creation_brief.clone(); + let calls = Rc::new(RefCell::new(Vec::new())); + let seen = calls.clone(); + app.services.automation_read_limited = Some(Box::new(move |path, limit| { + seen.borrow_mut().push(limit); + match scenario { + "empty" => Ok((path.into(), vec![])), + "oversize-single" => Ok((path.into(), vec![0; limit + 1])), + "capability-error" => Err("directory capability denied this file".into()), + "oversize-remaining" if path == "second.png" => Ok((path.into(), vec![0; limit + 1])), + _ => Ok((path.into(), vec![0; limit])), + } + })); + let paths = match scenario { + "oversize-remaining" => json!(["first.png", "second.png"]), + "budget-exhausted" => json!(["first.png", "second.png", "third.png"]), + _ => json!(["first.png"]), + }; + let error = workspace.creation_action(&mut app, "creation-import", json!({"paths":paths})).unwrap_err(); + assert!(!error.is_empty()); + if matches!(scenario, "oversize-remaining" | "budget-exhausted") { + assert_eq!(calls.borrow().as_slice(), &[20 * 1024 * 1024, 4 * 1024 * 1024], "no third read after the 24MiB budget is exhausted"); + } else { assert_eq!(calls.borrow().as_slice(), &[20 * 1024 * 1024]); } + assert_eq!(workspace.creation_brief, before, "{scenario} must preserve every image owner and draft field"); + assert!(workspace.busy.is_none(), "{scenario} must not leave a phantom import in flight"); + assert!(requests.try_recv().is_err(), "{scenario} must not dispatch a partial batch"); + } + } + + #[test] + fn creation_import_automation_never_falls_back_to_an_unbounded_reader() { + use std::{cell::Cell, rc::Rc}; + let (mut workspace, mut app, requests) = bounded_import_fixture(); + let calls = Rc::new(Cell::new(0)); + let seen = calls.clone(); + app.services.automation_read = Some(Box::new(move |_| { + seen.set(seen.get() + 1); + Ok(("unexpected.png".into(), vec![1])) + })); + let before = workspace.creation_brief.clone(); + let error = workspace.creation_action(&mut app, "creation-import", json!({"paths":["first.png"]})).unwrap_err(); + assert!(error.contains("有界读取")); + assert_eq!(calls.get(), 0); + assert_eq!(workspace.creation_brief, before); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn creation_import_automation_validates_paths_and_live_scope_before_any_read() { + use std::{cell::Cell, rc::Rc}; + for scenario in ["empty-paths", "too-many", "invalid-path", "empty-path", "stale-document", "busy", "unknown"] { + let (mut workspace, mut app, requests) = bounded_import_fixture(); + let calls = Rc::new(Cell::new(0)); + let seen = calls.clone(); + app.services.automation_read_limited = Some(Box::new(move |_, _| { + seen.set(seen.get() + 1); + Ok(("unexpected.png".into(), vec![1])) + })); + let before = workspace.creation_brief.clone(); + let input = match scenario { + "empty-paths" => json!({"paths":[]}), + "too-many" => json!({"paths":["1","2","3","4","5","6","7","8","9"]}), + "invalid-path" => json!({"paths":["first.png",42]}), + "empty-path" => json!({"paths":["first.png",""]}), + "stale-document" => json!({"doc":u64::MAX,"paths":["first.png"]}), + "busy" => { workspace.busy = Some("agent".into()); json!({"paths":["first.png"]}) } + _ => { workspace.unknown = true; json!({"paths":["first.png"]}) } + }; + assert!(workspace.creation_action(&mut app, "creation-import", input).is_err(), "{scenario}"); + assert_eq!(calls.get(), 0, "{scenario}"); + assert_eq!(workspace.creation_brief, before, "{scenario}"); + assert!(requests.try_recv().is_err(), "{scenario}"); + } + } + + #[test] + fn reference_import_progress_is_visible_only_while_import_is_in_flight() { + let (mut w, mut app) = setup(); + w.creation_brief = empty_brief(); + let ctx = egui::Context::default(); + for (busy, shown) in [(Some("creation-import"), true), (Some("creation-import-library"), true), (Some("agent"), false), (None, false)] { + w.busy = busy.map(str::to_owned); + w.creation_view_geometry = json!({"controls":{}}); + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }, |ui| { + w.references_ui(&mut app, ui, 500.0); + }); + assert_eq!(!w.creation_view_geometry["controls"]["reference-import-progress"].is_null(), shown, "unexpected activity for {busy:?}"); + } + } + + #[test] + fn template_structure_preview_rejects_stale_identity_and_invalid_geometry() { + let hash = "a".repeat(64); + let selected = json!({"id":"template","version":"v1","contentHash":hash,"brandId":"brand","categoryId":"category"}); + let mut row = selected.clone(); + row["structurePreview"] = json!({"contentHash":selected["contentHash"],"outputId":"S01","width":1440,"height":2000, + "background":"#ffffff","slots":[{"kind":"image","frame":{"x":0,"y":0,"width":1440,"height":1500}}, + {"kind":"text","frame":{"x":100,"y":100,"width":500,"height":80}}],"decorations":[]}); + assert!(verified_structure_preview(&row, &selected, "brand", "category").is_some()); + assert!(verified_structure_preview(&row, &selected, "other", "category").is_none()); + assert!(verified_structure_preview(&row, &selected, "brand", "other").is_none()); + let mut other = selected.clone(); + other["version"] = json!("v2"); + assert!(verified_structure_preview(&row, &other, "brand", "category").is_none()); + row["structurePreview"]["contentHash"] = json!("b".repeat(64)); + assert!(verified_structure_preview(&row, &selected, "brand", "category").is_none()); + row["structurePreview"]["contentHash"] = selected["contentHash"].clone(); + row["structurePreview"]["slots"][0]["frame"]["width"] = json!(1441); + assert!(verified_structure_preview(&row, &selected, "brand", "category").is_none()); + row["structurePreview"] = Value::Null; + assert!(verified_structure_preview(&row, &selected, "brand", "category").is_none()); + } + #[test] + fn template_structure_picker_clicks_only_enabled_real_preview_and_fits_narrow_width() { + let preview = json!({"width":1440,"height":2000,"background":"#ffffff", + "slots":[{"kind":"image","frame":{"x":0,"y":0,"width":1440,"height":1500}}],"decorations":[]}); + for enabled in [true, false] { + let ctx = egui::Context::default(); + let draw = |events| { + let mut response = None; + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(240.0, 200.0))), events, ..Default::default() }, |ui| { + ui.set_width(180.0); + response = Some(template_picker_row(ui, false, "非常长的真实模板名称 · v1", enabled, Some(&preview))); + }); + response.unwrap() + }; + let initial = draw(vec![]); + assert!(initial.rect.width() <= 181.0, "preview must fit the narrow picker"); + let point = initial.rect.left_top() + vec2(10.0, PICKER_ROW_HEIGHT / 2.0); + draw(vec![egui::Event::PointerMoved(point), egui::Event::PointerButton { pos:point, button:egui::PointerButton::Primary, pressed:true, modifiers:Default::default() }]); + let response = draw(vec![egui::Event::PointerButton { pos:point, button:egui::PointerButton::Primary, pressed:false, modifiers:Default::default() }]); + assert_eq!(response.clicked(), enabled, "thumbnail selection must respect the template lock"); + } + } + + #[test] + fn resource_template_defaults_to_detail_or_a_single_component() { + let detail = json!({"id":"detail","kind":"detail"}); + let main = json!({"id":"main_images","kind":"main_images"}); + let sku = json!({"id":"800","kind":"sku_images"}); + assert_eq!(default_resource_component(&[main, detail.clone(), sku.clone()]), Some(&detail)); + assert_eq!(default_resource_component(std::slice::from_ref(&sku)), Some(&sku)); + assert!(default_resource_component(&[sku, json!({"id":"750","kind":"sku_images"})]).is_none()); + assert!(default_resource_component(&[]).is_none()); + } + + #[test] + fn resource_template_result_binds_the_component_without_an_extra_click() { + let (mut w, mut app, _) = brief_fixture(); + w.creation_brief["templateSelection"] = Value::Null; + w.creation_dirty = false; + let result = json!({"id":"detail","choice":{ + "id":"desk","version":"map-version","contentHash":"a".repeat(64), + "brandId":"brand","categoryId":"category","width":750, + "enterprise":{"resourceSetId":"selected-set","componentId":"detail"} + }}); + let ctx = egui::Context::default(); + let mut render = |set, result: &Value| { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + w.resource_component_result(&mut app, ui, 500.0, set, result); + }); + output.textures_delta.clear(); + (w.creation_brief["templateSelection"].clone(), w.creation_width, w.creation_dirty) + }; + assert!(render("previous-set", &result).0.is_null()); + let (selected, width, dirty) = render("selected-set", &result); + assert_eq!(selected["enterprise"]["componentId"], "detail"); + assert_eq!(width, 750); + assert!(dirty); + let (after_preview, _, _) = render("selected-set", &json!({"id":"detail","previewId":"another"})); + assert_eq!(after_preview, selected); + } + + #[test] + fn canvas_entry_uses_product_and_exact_template_without_ai_stage_confirmation() { + let mut brief = empty_brief(); + brief["name"] = json!("测试桌"); + brief["brandId"] = json!("brand"); + brief["categoryId"] = json!("desk"); + brief["images"] = json!([{"name":"产品实拍","source":"local:unit-test","purpose":"product"}]); + let template = json!({"id":"real-template-identity-contract","version":"2","contentHash":"a".repeat(64),"brandId":"brand","categoryId":"desk"}); + assert!(canvas_entry_missing(&brief, &template).is_empty(), "facts/selling points/AI plan are not prerequisites for opening the structure"); + assert_eq!(selected_template(&brief, &Value::Null, &brief), Value::Null, "a directory's first item cannot silently become the user's selection"); + brief["templateSelection"] = template.clone(); + assert_eq!(selected_template(&brief, &Value::Null, &brief), template); + assert_eq!(canvas_entry_missing(&brief, &json!({"id":"template","version":"2","contentHash":"not-a-hash"})), ["模板"]); + brief["images"][0]["purpose"] = json!("scene"); + assert_eq!(canvas_entry_missing(&brief, &template), ["产品图"]); + brief["name"] = json!(" "); + assert_eq!(canvas_entry_missing(&brief, &Value::Null), ["模板", "产品名称", "产品图"]); + } + #[test] + fn installed_legacy_template_is_pinned_but_not_relabelled_for_a_changed_brand() { + let mut brief = empty_brief(); + brief["brandId"] = json!("original-brand"); + brief["categoryId"] = json!("desk"); + let canonical = brief.clone(); + let workflow = json!({"templateId":"fixed","templateVersion":"1","templateHash":"a".repeat(64)}); + assert_eq!(selected_template(&brief, &workflow, &canonical)["id"], "fixed"); + brief["brandId"] = json!("different-brand"); + assert!(selected_template(&brief, &workflow, &canonical).is_null()); + assert_eq!(workflow["templateVersion"], "1", "reading a selection never upgrades the old project"); + } + #[test] + fn variant_identity_survives_reordering_and_keeps_the_original_product_option() { + let material = "82f3a6b7-6323-4cf5-a741-d990182f382c"; + assert_eq!(variant_identity(material), material); + let fallback = variant_identity("legacy-material-code"); + assert_eq!(fallback, variant_identity("legacy-material-code")); + assert_ne!(fallback, variant_identity("another-material-code")); + assert_eq!(fallback.len(), 36); + assert_eq!(fallback.chars().nth(14), Some('8')); + let mut brief = empty_brief(); + brief["variant"] = json!("单孔 K 型"); + brief["colorMaterialId"] = json!(material); + brief["colorName"] = json!("柚木色"); + let mut variants = brief_variants(&brief); + assert_eq!(variants[0]["id"], material, "legacy single color survives an empty new variants field"); + variants.push(json!({"id":variant_identity("black"),"name":"黑色","colorMaterialId":"black","colorName":"黑色","images":[]})); + variants.reverse(); + set_brief_variants(&mut brief, variants); + assert_eq!(brief["variant"], "单孔 K 型"); + assert_eq!(brief["colorName"], "黑色", "the first selected color keeps old single-color readers compatible"); + assert_eq!(brief["variants"][1]["id"], material); + } + #[test] + fn specific_variant_references_never_remain_common_or_leak_into_another_color() { + let image = json!({"name":"柚木实拍","source":"local:photo","purpose":"product"}); + let mut brief = empty_brief(); + let teak = variant_identity("teak"); + let black = variant_identity("black"); + set_brief_variants( + &mut brief, + vec![ + json!({"id":teak,"name":"柚木色","colorMaterialId":"teak","colorName":"柚木色","images":[]}), + json!({"id":black,"name":"黑色","colorMaterialId":"black","colorName":"黑色","images":[]}), + ], + ); + brief["images"] = json!([image.clone()]); + store_image_rows(&mut brief, vec![(image.clone(), teak.clone())]).unwrap(); + assert!(brief["images"].as_array().unwrap().is_empty()); + assert_eq!(brief["variants"][0]["images"], json!([image.clone()])); + assert!(brief["variants"][1]["images"].as_array().unwrap().is_empty()); + let unchanged = brief.clone(); + assert!(store_image_rows(&mut brief, vec![(image.clone(), "missing-variant".into())]).is_err()); + assert_eq!(brief, unchanged, "an invalid owner cannot silently turn a private reference into shared evidence"); + store_image_rows(&mut brief, vec![(image.clone(), String::new())]).unwrap(); + assert_eq!(brief["images"], json!([image])); + assert!(brief["variants"].as_array().unwrap().iter().all(|variant| variant["images"].as_array().unwrap().is_empty())); + } + #[test] + fn reimporting_a_variant_image_does_not_silently_make_it_common() { + let (mut w, app) = setup(); + let image = json!({"name":"指定花色实拍","source":"local:original-color","purpose":"product"}); + w.creation_brief = empty_brief(); + set_brief_variants( + &mut w.creation_brief, + vec![json!({"id":variant_identity("teak"),"name":"柚木色","colorMaterialId":"teak","colorName":"柚木色","images":[image.clone()]})], + ); + let mut value = reference(&w); + value.as_object_mut().unwrap().remove("creation"); + value["images"] = json!([image]); + received(&mut w, &app, "creation-import", &value); + assert!(w.creation_brief["images"].as_array().unwrap().is_empty()); + assert_eq!(w.creation_brief["variants"][0]["images"].as_array().unwrap().len(), 1); + } + fn picker_frame(ctx: &egui::Context, populated: bool) -> egui::Id { + let mut id = egui::Id::NULL; + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1000.0, 800.0))), ..Default::default() }, |ui| { + id = picker(ui, "stable-picker", 320.0, "选择品牌", |ui| { + if populated { + for i in 0..16 { + picker_row(ui, false, &format!("品牌 {i} · 很长的目录名称应在固定宽度内截断"), true); + } + } else { + picker_notice(ui, true, None, false, ""); + } + }) + .response + .id; + }); + output.textures_delta.clear(); + id + } + #[test] + fn dynamic_picker_keeps_width_and_fits_loading_or_loaded_content() { + let ctx = egui::Context::default(); + // The shipped native theme adds scroll content margins. Omitting those + // in a default-context test misses a first-frame width expansion. + ctx.all_styles_mut(|style| style.spacing.scroll.content_margin = egui::Margin::same(1)); + let id = picker_frame(&ctx, false); + let popup = id.with("popup"); + egui::Popup::open_id(&ctx, popup); + picker_frame(&ctx, false); + picker_frame(&ctx, false); + let loading = ctx.memory(|memory| memory.area_rect(popup)).unwrap(); + picker_frame(&ctx, true); + picker_frame(&ctx, true); + let populated = ctx.memory(|memory| memory.area_rect(popup)).unwrap(); + egui::Popup::close_id(&ctx, popup); + picker_frame(&ctx, true); + egui::Popup::open_id(&ctx, popup); + picker_frame(&ctx, true); + picker_frame(&ctx, true); + let reopened = ctx.memory(|memory| memory.area_rect(popup)).unwrap(); + assert!(loading.height() < PICKER_HEIGHT / 2.0, "a short loading state should not reserve an empty list: {loading:?}"); + assert!(populated.height() >= PICKER_HEIGHT, "a long list retains its scroll area: {populated:?}"); + for rect in [populated, reopened] { + assert!((rect.width() - loading.width()).abs() <= 1.0, "menu width is independent of loaded labels: {loading:?} {rect:?}"); + } + assert!((reopened.height() - populated.height()).abs() <= 1.0, "the same list keeps its height on reopen"); + } + #[test] + fn material_thumbnail_reserves_identical_space_in_all_read_states() { + let ctx = egui::Context::default(); + let texture = ctx.load_texture("material-test", egui::ColorImage::filled([48, 24], egui::Color32::WHITE), egui::TextureOptions::LINEAR); + let mut sizes = Vec::new(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + for (image, loading, failed) in [(None, false, false), (None, true, false), (None, false, true), (Some(&texture), false, false)] { + sizes.push(material_thumbnail(ui, image, loading, failed).rect.size()); + } + }); + output.textures_delta.clear(); + assert!(sizes.iter().all(|size| *size == vec2(MATERIAL_THUMB_SIDE, MATERIAL_THUMB_SIDE))); + // Scaling uses f32; accept sub-millipixel rounding while checking both + // the maximum size and the preserved aspect ratio. + for (source, expected) in [(vec2(1600.0, 800.0), vec2(240.0, 120.0)), (vec2(400.0, 1600.0), vec2(60.0, 240.0))] { + assert!((preview_size(source, vec2(240.0, 240.0)) - expected).abs().max_elem() < 0.001); + } + assert_eq!(preview_size(vec2(0.0, 10.0), vec2(240.0, 240.0)), egui::Vec2::ZERO); + } + #[test] + fn material_popup_exposes_each_cached_image_and_its_hover_target() { + let (mut w, mut app) = setup(); + let ctx = egui::Context::default(); + w.creation_brief = empty_brief(); + w.creation_view_geometry = json!({"controls":{},"popups":{},"materialRows":[],"hoverPreview":null}); + let rows: Vec<_> = (0..6).map(|i| json!({"id":format!("material-{i}"),"name":format!("材质 {i}")})).collect(); + for row in &rows { + let id = row["id"].as_str().unwrap(); + w.creation_thumbs.insert(id.into(), ctx.load_texture(id, egui::ColorImage::filled([40, 20], egui::Color32::WHITE), egui::TextureOptions::LINEAR)); + } + w.creation_catalog.insert("materials".into(), rows); + let popup = ui_rect_popup_id(&ctx, &w); + egui::Popup::open_id(&ctx, popup); + for _ in 0..2 { + let mut output = ctx + .run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1000.0, 800.0))), ..Default::default() }, |ui| { + w.material_select(&mut app, ui, 320.0) + }); + output.textures_delta.clear(); + } + let visible: Vec<_> = w.creation_view_geometry["materialRows"].as_array().unwrap().iter().filter(|r| r["visible"] == true).collect(); + assert!(visible.len() >= 4, "a full native popup exposes several material thumbnails"); + for row in visible { + assert_eq!(row["status"], "ready"); + assert_eq!(row["imageRect"][2].as_f64(), Some(f64::from(MATERIAL_THUMB_SIDE))); + assert_eq!(row["imageRect"][3].as_f64(), Some(f64::from(MATERIAL_THUMB_SIDE))); + } + } + fn ui_rect_popup_id(ctx: &egui::Context, w: &Workspace) -> egui::Id { + // Obtain the same native id without inventing an automation-only widget path. + let mut id = egui::Id::NULL; + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + id = picker(ui, "creation-material", 320.0, w.creation_brief["colorName"].as_str().unwrap_or("选择材质颜色"), |_| {}).response.id; + }); + output.textures_delta.clear(); + id.with("popup") + } + fn setup() -> (Workspace, PhotocraftApp) { + let (tx, _) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + 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()); + w.account = json!({"id":"qa"}); + w.origin = "http://localhost:3138".into(); + let st = app.session.active().unwrap(); + w.owner_doc = Some(st.doc.id.0); + w.expected_revision = st.revision; + w.creation_base_revision = st.revision; + w.allow_apply = true; + w.busy = Some("creation-generate".into()); + (w, app) + } + fn reference(w: &Workspace) -> Value { + json!({"doc":w.owner_doc,"accountId":w.account["id"],"origin":w.origin,"run":"00000000-0000-4000-8000-000000000001","baseRevision":w.creation_base_revision,"sequence":1,"creation":{}}) + } + + fn brief_fixture() -> (Workspace, PhotocraftApp, mpsc::Receiver) { + let (mut w, app) = setup(); + let (tx, requests) = mpsc::channel(); + w.tx = tx; + w.busy = None; + w.unknown = false; + w.key_saved = true; + w.creation_brief = empty_brief(); + w.creation_brief["name"] = json!("实木多功能产品 · 用于核对窄窗口的完整产品名称"); + w.creation_brief["brandId"] = json!("brand"); + w.creation_brief["brandName"] = json!("长品牌名称 / 原生资料完整保留"); + w.creation_brief["categoryId"] = json!("category"); + w.creation_brief["categoryName"] = json!("玄关与收纳家具 / 多功能衣帽架"); + w.creation_brief["variant"] = json!("原产品规格文字"); + w.creation_brief["images"] = json!([{"source":"common-image","name":"产品白底参考与需要完整保留的很长文件名.png","purpose":"product"}]); + set_brief_variants( + &mut w.creation_brief, + vec![ + json!({"id":"oak","name":"原木色","colorMaterialId":"material-oak","images":[]}), + json!({"id":"walnut","name":"胡桃木色","colorMaterialId":"material-walnut","images":[{"source":"walnut-image","name":"胡桃木色专属参考.png","purpose":"scene"}]}), + ], + ); + let template = + json!({"id":"template","name":"极简详情模板","version":"1.2","contentHash":"a".repeat(64),"brandId":"brand","categoryId":"category","cached":true}); + w.creation_brief["templateSelection"] = template.clone(); + w.creation_catalog.insert("brands".into(), vec![json!({"id":"brand","name":"长品牌名称","ready":true})]); + w.creation_catalog.insert("materials".into(), vec![]); + w.creation_catalog.insert("templates".into(), vec![template]); + w.agent_categories = vec![json!({"id":"category","name":"玄关与收纳家具"})]; + w.agent_rules = vec![json!({"shopId":"brand","categoryId":"category"})]; + w.creation_doc = app.session.active().map(|state| state.doc.id.0); + w.creation = json!({"brief":w.creation_brief.clone()}); + (w, app, requests) + } + + fn brief_frame(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Context, width: f32, events: Vec) -> egui::Rect { + brief_frame_at_size(w, app, ctx, vec2(width, 2600.0), events) + } + + fn brief_frame_at_size(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Context, size: egui::Vec2, events: Vec) -> egui::Rect { + let mut bounds = egui::Rect::NOTHING; + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }, + |ui| { + bounds = ui.available_rect_before_wrap(); + stitch_ui::scope(ui, |ui| w.brief_ui(app, ui)); + }, + ); + output.textures_delta.clear(); + bounds + } + + + fn barcode_fixture() -> (Workspace, PhotocraftApp, mpsc::Receiver) { + let (mut w, app, requests) = brief_fixture(); + set_brief_variants(&mut w.creation_brief, vec![]); + w.creation_brief["images"] = json!([]); + w.creation_brief["barcodeBindings"] = json!({"default":["DNZ030516N717V01","CY001307N35V01"]}); + set_intake(&mut w.creation_brief, &json!("template"), &json!({"version":1, + "productFields":[ + {"id":"summary","label":"固定卖点","type":"text"}, + {"id":"new_kind","label":"扩展字段","type":"future-kind"} + ], + "barcodeFields":[ + {"id":"color","label":"颜色组合","type":"text"}, + {"id":"length","label":"长度","type":"number","unit":"mm"}, + {"id":"width","label":"宽度","type":"number","unit":"mm"}, + {"id":"height","label":"高度","type":"number","unit":"mm"} + ]})); + w.creation_brief["intake"]["barcodeValues"]["DNZ030516N717V01"] = json!({"length":1200,"width":580,"height":750}); + (w, app, requests) + } + + #[test] + fn platform_facts_fill_template_fields_and_keep_missing_fields_empty() { + let (mut w, mut app, requests) = barcode_fixture(); + let mut brief = w.creation_brief.clone(); + brief["source"] = json!("product_platform"); + brief["identifierType"] = json!("spu"); + brief["identifier"] = json!("00-Model"); + brief["barcodeBindings"] = json!({"default":["00-a,01","00-B"]}); + brief["detailBarcode"] = json!("00-a,01"); + brief["platformFacts"] = json!({"spu":"00-Model","shared":{"material":"织物"},"barcodes":{ + "00-a,01":{"colorName":"灰色","dimensions":{"unit":"mm","length":1800,"width":900,"height":700}}, + "00-B":{"colorName":"米色","dimensions":{"unit":"mm","width":880}} + }}); + brief["intake"]["schema"]["productFields"].as_array_mut().unwrap() + .push(json!({"id":"material","label":"材质","type":"text"})); + let doc = app.session.active().unwrap().doc.id.0; + let receipt = json!({"doc":doc,"origin":w.origin,"accountId":w.account["id"],"platformBrief":brief}); + received(&mut w, &app, "creation-product-platform", &receipt); + assert_eq!(w.creation_brief["intake"]["productValues"], json!({"material":"织物"})); + assert_eq!(w.creation_brief["intake"]["barcodeValues"]["00-a,01"], json!({"color":"灰色","length":1800,"width":900,"height":700})); + assert_eq!(w.creation_brief["intake"]["barcodeValues"]["00-B"], json!({"color":"米色","width":880})); + assert_eq!(field_fact(&json!({"id":"length","type":"number","unit":"cm"}), + &w.creation_brief["platformFacts"]["barcodes"]["00-a,01"]), Some(json!(180.0))); + let ctx = egui::Context::default(); + w.account = Value::Null; + let before = w.creation_brief.clone(); + brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); + assert!(!w.creation_view_geometry["controls"]["platform-fetch"].is_null()); + assert!(w.creation_action(&mut app, "creation-product-platform", json!({"spu":"00-Model"})).unwrap_err().contains("登录")); + assert_eq!(w.creation_brief, before); + assert!(!requests.try_iter().any(|request| matches!(request, Request::Action(method, _) if method == "creation-product-platform"))); + } + + #[test] + fn template_image_slots_use_drop_and_picker_with_exact_roles_and_barcode() { + let (mut w, mut app, requests) = barcode_fixture(); + w.creation_open = true; + w.library = false; + let schema = json!({"version":1,"productFields":[ + {"key":"hero","kind":"image","label":"产品图片","imageRole":"product","placeholder":"拖入产品图"}], + "barcodeFields":[{"key":"fabric","kind":"image","label":"材质图片","imageRole":"material","multiple":false,"placeholder":"拖入材质图"}]}); + set_intake(&mut w.creation_brief, &json!("image-template"), &schema); + let (picker, asked) = crate::file_dialog::fake(vec![Some(crate::FileDialogAnswer::Paths(vec![if cfg!(windows) { r"D:\photos\fabric.png" } else { "/tmp/photos/fabric.png" }.into()]))]); + app.services.file_dialog = Some(picker); + let ctx = egui::Context::default(); + for width in [380.0, 850.0] { + brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let bounds = brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let slots = w.creation_view_geometry["imageSlots"].as_object().unwrap(); + assert_eq!(slots.len(), 3); + assert!(slots.values().all(|target| { + let rect = &target["rect"]; + rect[0].as_f64().unwrap_or_default() >= f64::from(bounds.left()) && + rect[0].as_f64().unwrap_or_default() + rect[2].as_f64().unwrap_or_default() <= f64::from(bounds.right()) + })); + assert!(w.creation_view_geometry["controls"]["reference-add"].is_null()); + } + let slots = w.creation_view_geometry["imageSlots"].as_object().unwrap(); + let product = slots.values().find(|row| row["label"] == "产品图片").unwrap().clone(); + let fabric = slots.values().find(|row| row["label"] == "材质图片" + && row["slot"]["barcode"] == "DNZ030516N717V01").unwrap().clone(); + let center = |rect: &Value| egui::pos2((rect[0].as_f64().unwrap()+rect[2].as_f64().unwrap()/2.0) as f32, + (rect[1].as_f64().unwrap()+rect[3].as_f64().unwrap()/2.0) as f32); + assert_eq!(product["placeholder"], "拖入产品图"); + assert_eq!(fabric["placeholder"], "拖入材质图"); + app.jiansun = Some(w); + app.open_dropped(&ctx, vec![reference_drop(if cfg!(windows) { r"D:\photos\product.png" } else { "/tmp/photos/product.png" })], Some(center(&product["rect"]))); + let Some(Request::Action(_, input)) = requests.try_iter() + .find(|request| matches!(request, Request::Action(method, _) if method == "creation-import")) + else { panic!("expected import"); }; + assert_eq!(input["imageSlot"]["imageRole"], "product"); + let mut w = app.jiansun.take().unwrap(); + w.busy = None; + let pixels = json!([{"source":format!("local:{}", "d".repeat(64)),"purpose":"product","name":"样品"}]); + let draft = w.creation_brief.clone(); + let doc = app.session.active().unwrap().doc.id.0; + let import = |slot: &Value| json!({"doc":doc,"origin":product["origin"],"accountId":product["accountId"],"images":pixels,"imageSlot":slot}); + received(&mut w, &app, "creation-import", &import(&input["imageSlot"])); + brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); + let slot = w.creation_view_geometry["imageSlots"].as_object().unwrap().values() + .find(|row| row["slot"] == fabric["slot"]).unwrap(); + let click = center(&slot["rect"]); + brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(click)); + app.jiansun = Some(w); + app.poll_file_dialog(&ctx, None); + assert!(matches!(asked.borrow().first(), Some(crate::FileDialogRequest::Open { multiple:false, .. }))); + let Some(Request::Action(_, input)) = requests.try_iter() + .find(|request| matches!(request, Request::Action(method, _) if method == "creation-import")) + else { panic!("expected import"); }; + assert_eq!(input["imageSlot"], fabric["slot"]); + let mut w = app.jiansun.take().unwrap(); + received(&mut w, &app, "creation-import", &import(&input["imageSlot"])); + assert_eq!(w.creation_brief["images"][0]["imageRole"], "product"); + assert_eq!(w.creation_brief["images"][1]["imageRole"], "material"); + assert_eq!(w.creation_brief["images"][1]["barcode"], "DNZ030516N717V01"); + assert_eq!(w.creation_brief["intake"], draft["intake"]); + } + + #[test] + fn barcode_bindings_read_legacy_lists_and_deduplicate_the_complete_trimmed_values() { + let legacy = json!(" DNZ030516N717V01,;CY001307N35V01、\r\nDNZ030516N717V01 "); + assert_eq!(binding_barcodes(&legacy).collect::>(), ["DNZ030516N717V01", "CY001307N35V01"]); + let exact = "0007 台面/甲+乙,A;B\n编码\t二🪑"; + let brief = json!({"barcodeBindings":{"default":["DNZ030516N717V01", "CY001307N35V01", exact]}}); + assert_eq!(project_barcodes(&brief).last(), Some(exact)); + assert_eq!(barcode_issue(&brief, &format!(" {exact} ")), Some("此条码已录入当前项目")); + assert_eq!(barcode_issue(&brief, "cy001307n35v01"), None); + assert_eq!(barcode_issue(&brief, "cy001301N35"), None); + assert_eq!(barcode_issue(&brief, "SJ021613N16V01"), None); + assert_eq!(barcode_issue(&brief, &"A".repeat(121)), None); + assert_eq!(barcode_issue(&brief, " \t\n"), Some("请输入产品条码")); + } + + #[test] + fn pasted_barcode_survives_the_form_and_save_payload_without_losing_characters() { + let (mut w, mut app, requests) = barcode_fixture(); + w.creation_brief["barcodeBindings"] = json!({}); + w.reduce_motion = true; + let ctx = egui::Context::default(); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); } + let add = control_rect(&w, "barcode-add-default").center(); + brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(add)); + let exact = "0007 台面/甲+乙,A;B\r\n编码\t二🪑"; + brief_frame(&mut w, &mut app, &ctx, 760.0, vec![egui::Event::Paste(format!(" \t{exact}\n "))]); + let apply = control_rect(&w, "barcode-confirm-default").center(); + brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(apply)); + assert_eq!(w.creation_brief["barcodeBindings"]["default"], json!([exact])); + assert_eq!(w.creation_brief["detailBarcode"], exact); + w.creation_action(&mut app, "creation-save", json!({})).unwrap(); + assert!(matches!(requests.try_recv(), Ok(Request::Action(method, input)) if method == "creation-save" + && input["brief"]["barcodeBindings"]["default"] == json!([exact]) + && input["brief"]["detailBarcode"] == exact)); + } + + #[test] + fn detail_barcode_defaults_for_one_and_follows_rename_or_removal() { + let (mut w, mut app, requests) = barcode_fixture(); + assert!(!update_detail_barcode(&mut w.creation_brief)); + assert!(canvas_entry_missing(&w.creation_brief, &Value::Null).contains(&"详情页出图条码")); + w.creation_brief["detailBarcode"] = json!("DNZ030516N717V01"); + replace_barcode(&mut w.creation_brief, "DNZ030516N717V01", Some("SG008839N1049V01")); + w.creation_brief["barcodeBindings"]["default"] = json!(["SG008839N1049V01","CY001307N35V01"]); + assert_eq!(w.creation_brief["detailBarcode"], "SG008839N1049V01"); + assert_eq!(w.creation_brief["intake"]["barcodeValues"]["SG008839N1049V01"]["length"], 1200); + w.creation_action(&mut app, "creation-save", json!({})).unwrap(); + assert!(matches!(requests.try_recv(), Ok(Request::Action(method, input)) if + method == "creation-save" && input["brief"]["detailBarcode"] == "SG008839N1049V01")); + replace_barcode(&mut w.creation_brief, "SG008839N1049V01", None); + w.creation_brief["barcodeBindings"]["default"] = json!(["CY001307N35V01"]); + assert!(update_detail_barcode(&mut w.creation_brief)); + assert_eq!(w.creation_brief["detailBarcode"], "CY001307N35V01"); + } + + #[test] + fn dynamic_intake_reads_optional_hints_and_multiline_without_requiring_schema_changes() { + let explicit = json!({"id":"copy","type":"text","placeholder":" 如:收拢深度 35 cm ","help":"旧说明","multiline":true}); + let legacy_long = json!({"id":"notes","type":"text","label":"注意事项","help":"如:远离火源"}); + let legacy_short = json!({"id":"material","type":"text","label":"材质"}); + let a = json!({"id":"length","type":"number","help":"按本款确认资料填写;尺寸注明单位,暂无资料可留空。"}); + let b = json!({"id":"wood","type":"select","help":"请按确认资料填写。"}); + let c = json!({"id":"finish","type":"text","help":" 请按确认资料填写。 "}); + assert_eq!(intake_hint(&explicit), "如:收拢深度 35 cm"); + assert_eq!(intake_hint(&legacy_long), "如:远离火源"); + assert_eq!(intake_hint(&legacy_short), ""); + assert_eq!(intake_hint(&a), "数字"); + assert_eq!(intake_hint(&b), "请按确认资料填写。"); + assert_eq!(intake_hint(&c), "请按确认资料填写。"); + for key in ["hint", "example", "promptHint", "description"] { + assert_eq!(intake_hint(&json!({(key):"如:白蜡木"})), "如:白蜡木"); + } + assert!(intake_multiline(&explicit)); + assert!(intake_multiline(&legacy_long)); + assert!(!intake_multiline(&legacy_short)); + assert!(!intake_multiline(&json!({"type":"text","label":"注意事项","multiline":false}))); + assert!(is_product_name_field(&json!({"id":"name","label":"产品名称","type":"text"}))); + assert!(is_product_name_field(&json!({"id":"title","label":"商品名 * ","type":"text"}))); + assert!(!is_product_name_field(&json!({"id":"english","label":"英文产品名称","type":"text"}))); + } + + #[test] + fn dynamic_product_intake_reflows_short_fields_and_spans_long_text() { + use egui_kittest::{Harness, kittest::Queryable}; + assert_eq!(product_intake_columns(559.0), 1); + assert_eq!(product_intake_columns(560.0), 2); + for width in [420.0, 640.0] { + let mut harness = Harness::builder().with_size(vec2(width + 40.0, 460.0)) + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .build_ui_state(|ui, values: &mut Value| { + let fields = [ + json!({"id":"a","label":"材质","type":"text","placeholder":"如:橡木"}), + json!({"id":"b","label":"产地","type":"text","help":"如:江苏"}), + json!({"id":"c","label":"核心卖点","type":"text","multiline":true}), + ]; + let fields = fields.iter().collect::>(); + intake_fields(ui, egui::Id::unique("product-intake-test"), width, &fields, + IntakeScope::Product, values, true); + }, json!({})); + harness.run_steps(2); + let a = harness.get_by_role_and_label(egui::accesskit::Role::TextInput, "材质").rect(); + let b = harness.get_by_role_and_label(egui::accesskit::Role::TextInput, "产地").rect(); + let c = harness.get_by_role_and_label(egui::accesskit::Role::MultilineTextInput, "核心卖点").rect(); + if width >= 560.0 { + assert!((a.top() - b.top()).abs() < 1.0 && a.right() < b.left()); + assert!(c.width() > a.width() * 1.9); + } else { + assert!(b.top() > a.bottom() && (a.left() - b.left()).abs() < 1.0); + assert!((c.width() - a.width()).abs() < 1.0); + } + assert!(c.top() > b.bottom() && c.height() > a.height()); + harness.get_by_role_and_label(egui::accesskit::Role::TextInput, "材质").click(); + harness.run_steps(2); + harness.event(egui::Event::Text("橡木".to_owned())); + harness.run_steps(2); + assert_eq!(harness.state(), &json!({"a":"橡木"})); + } + } + + #[test] + fn dynamic_barcode_form_keeps_cards_and_controls_within_wide_and_narrow_bounds() { + assert_eq!(intake_columns(178.0), 2); + assert_eq!(intake_columns(460.0), 3); + for width in [248.0, 760.0, 900.0] { + let (mut w, mut app, _) = barcode_fixture(); + let ctx = egui::Context::default(); + w.reduce_motion = true; + brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let bounds = brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let card = control_rect(&w, "barcode-card-default-0"); + let second = control_rect(&w, "barcode-card-default-1"); + let edit = control_rect(&w, "barcode-edit-default-0"); + let delete = control_rect(&w, "barcode-remove-default-0"); + let number = control_rect(&w, "barcode-number-default-0"); + assert!(card.right() <= bounds.right() + 1.0 && second.right() <= bounds.right() + 1.0); + assert!(card.contains_rect(edit) && card.contains_rect(delete)); + assert!(bounds.contains_rect(control_rect(&w, "source-library"))); + assert!(edit.left() < card.left() + 52.0 && edit.right() < delete.left()); + assert!(edit.left() - number.right() >= 7.0); + if width == 900.0 { + assert!(edit.width() >= 280.0); + } + assert!(card.bottom() <= second.top()); + assert!(w.creation_view_geometry["controls"]["dimensions"].is_null()); + assert!(w.creation_view_geometry["controls"]["material"].is_null()); + assert!(w.creation_view_geometry["controls"]["output-width"].is_null()); + assert!(w.creation_view_geometry["controls"]["barcode-input-default"].is_null()); + let add = control_rect(&w, "barcode-add-default").center(); + brief_frame(&mut w, &mut app, &ctx, width, click_events(add)); + assert!(control_rect(&w, "barcode-input-default").is_positive(), "SPU can still be blank"); + } + } + + #[test] + fn detail_barcode_selector_changes_the_brief_used_by_the_form() { + let (mut w, mut app, requests) = barcode_fixture(); + w.creation_brief["identifier"] = json!("QA-DESK-001"); + w.creation_brief["images"] = json!([{"source":"test-reference","name":"产品图.png","purpose":"product"}]); + let ctx = egui::Context::default(); + w.reduce_motion = true; + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); } + let picker = control_rect(&w, "detail-barcode").center(); + brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(picker)); + brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); + let option = control_rect(&w, "detail-barcode-option-1").center(); + brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(option)); + assert_eq!(w.creation_brief["detailBarcode"], "CY001307N35V01"); + assert_eq!(w.creation_draft()["brief"]["detailBarcode"], "CY001307N35V01"); + let enter = control_rect(&w, "enter-canvas").center(); + brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(enter)); + assert!(matches!(requests.try_recv(), Ok(Request::Save(_, _, _)))); + assert_eq!(w.pending_slot_apply.as_ref().unwrap()["brief"]["detailBarcode"], "CY001307N35V01"); + } + + #[test] + fn template_form_shows_unknown_fields_and_keeps_requirements_input_visible() { + let (mut w, mut app, _) = barcode_fixture(); + w.creation_brief["note"] = json!("已保存的特殊制作要求"); + w.reduce_motion = true; + let ctx = egui::Context::default(); + brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); + assert!(control_rect(&w, "special-requirements-input").is_positive()); + assert_eq!(w.creation_brief["note"], "已保存的特殊制作要求"); + + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let field = json!({"id":"unexpected","label":"扩展字段","type":"future-kind"}); + intake_fields(ui, egui::Id::unique("unknown-field-test"), 360.0, + &[&field], IntakeScope::Product, &mut json!({}), true); + }); + let text = out.shapes.iter().filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) => Some(text.galley.text()), + _ => None, + }).collect::>(); + assert!(text.iter().any(|text| text.contains("暂不支持此字段类型(future-kind)")), "{text:?}"); + out.textures_delta.clear(); + } + + #[test] + #[ignore = "offscreen GPU visual evidence; requires PHOTOCRAFT_AGENT_QA_OUT"] + fn barcode_form_visual_acceptance() { + let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + for (width, height) in [(248.0, 2100.0), (760.0, 1760.0), (900.0, 1600.0)] { + let (mut w, app, _) = barcode_fixture(); + w.creation_brief["name"] = json!("轻量可调工作台"); + w.creation_brief["intake"]["schema"]["productFields"] = json!([ + {"id":"name","label":"产品名称","type":"text","required":true}, + {"id":"species","label":"主要材质","type":"text","placeholder":"如:白橡木"}, + {"id":"load","label":"承重","type":"number","unit":"kg","help":"如:60"}, + {"id":"finish","label":"表面处理","type":"select","options":["木蜡油","水性漆"],"placeholder":"选择表面处理"}, + {"id":"origin","label":"产地","type":"text","help":"如:江苏"}, + {"id":"copy","label":"核心卖点","type":"text","multiline":true,"placeholder":"如:台面高度可调。折叠后靠墙收纳。"}, + ]); + w.creation_brief["identifier"] = json!("QA-DESK-001"); + w.creation_brief["detailBarcode"] = json!("CY001307N35V01"); + w.reduce_motion = true; + let mut h = egui_kittest::Harness::builder().with_size(vec2(width, height)) + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests).wgpu().build_ui_state( + |ui, state: &mut (Workspace, PhotocraftApp)| { + if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { + stitch_ui::scope(ui, |ui| state.0.brief_ui(&mut state.1, ui)); + } + }, (w, app)); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join(format!("barcode-form-{width}.png"))).unwrap(); + } + } + + #[test] + #[ignore = "offscreen GPU image-slot acceptance; requires PHOTOCRAFT_AGENT_QA_OUT"] + fn template_image_slots_visual_acceptance() { + let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + for width in [380.0, 850.0] { + let (mut w, app, _) = barcode_fixture(); + w.creation_brief["source"] = json!("product_platform"); + w.creation_brief["identifierType"] = json!("spu"); + w.creation_brief["identifier"] = json!("SPU-001"); + w.creation_brief["name"] = json!("可调工作台"); + set_intake(&mut w.creation_brief, &json!("visual-template"), &json!({"version":1, + "productFields":[ + {"id":"material","type":"text","label":"材质","promptHint":"例如:白蜡木"}, + {"id":"selling-points","type":"text","label":"核心卖点","description":"例如:台面可折叠,收纳后深度为 35 cm。"}, + {"key":"product","kind":"image","label":"产品图片","placeholder":"拖入产品图或点击选择","imageRole":"product"} + ], + "barcodeFields":[{"key":"material","kind":"image","label":"材质图片","placeholder":"拖入材质图或点击选择","imageRole":"material"}]})); + w.reduce_motion = true; + let mut h = egui_kittest::Harness::builder().with_size(vec2(width, 1600.0)) + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests).wgpu().build_ui_state( + |ui, state: &mut (Workspace, PhotocraftApp)| { + if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { + stitch_ui::scope(ui, |ui| state.0.brief_ui(&mut state.1, ui)); + } + }, (w, app)); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join(format!("track-h-form-{width}.png"))).unwrap(); + } + } + + #[test] + fn resumed_project_shows_continue_after_the_originals_settle() { + let (mut w, mut app, _) = brief_fixture(); + w.model_ready = true; + w.image_ready = true; + w.unknown = true; + w.product_checkpoint = json!({"active":true,"phase":"paused"}); + w.template_workflow = json!({"productionStages":[]}); + let ctx = egui::Context::default(); + brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); + assert!(control_rect(&w, "resume-product").is_positive()); + assert!(!w.can_resume_product()); + w.unknown = false; + brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); + assert!(control_rect(&w, "resume-product").is_positive()); + assert!(w.can_resume_product()); + } + + #[test] + fn a_scoped_pending_slot_leaves_the_production_resume_button_usable() { + let (mut w, mut app, requests) = brief_fixture(); + w.unknown = true; + w.model_ready = true; + w.image_ready = true; + w.models = vec![ + json!({"key":"text","id":"text-only","supportsImageInput":false,"productionReady":false}), + json!({"key":"vision","id":"visual-chat","supportsImageInput":true,"productionReady":true}), + ]; + w.model = "text".into(); + w.template_workflow = json!({"scopedProductionPending":true, + "productionStages":[{"outputId":"detail","variantId":"oak"}]}); + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } + let button = control_rect(&w, "resume-product").center(); + brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(button)); + assert!(w.error.contains("text-only 暂无同时开放读图和工具调用的线路")); + assert!(w.pending_slot_apply.is_none() && requests.try_recv().is_err()); + w.model = "vision".into(); + brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(button)); + assert!(matches!(requests.try_recv(), Ok(Request::Save(_, _, _)))); + assert!(requests.try_recv().is_err()); + assert_eq!(w.pending_slot_apply.as_ref().unwrap()["resumeProduct"], true); + assert!(w.unknown); + assert_eq!(w.creation_brief, original); + } + + #[derive(Debug)] + struct ReferenceDrop(std::path::PathBuf); + impl egui::DroppedFile for ReferenceDrop { + fn path(&self) -> &std::path::Path { &self.0 } + fn bytes(&self) -> Result, String> { Err("the native backend reads the selected path".into()) } + } + fn reference_drop(path: &str) -> egui::DroppedFileHandle { Arc::new(ReferenceDrop(path.into())) } + + #[test] + fn reference_drop_feedback_requires_real_file_hover_inside_visible_target() { + fn labels(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| labels(shape,out)), + egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), + _ => {} + } + } + let (mut w, mut app, requests) = brief_fixture(); + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + for (path, mime, point, expected) in [ + (None, "", egui::pos2(50.0,20.0), false), + (Some("oak.PNG"), "", egui::pos2(50.0,20.0), true), + (Some("oak.png"), "", egui::pos2(500.0,20.0), false), + (Some("notes.txt"), "text/plain", egui::pos2(50.0,20.0), false), + (None, "image/webp", egui::pos2(50.0,20.0), true), + (None, "text/plain", egui::pos2(50.0,20.0), false), + ] { + app.services.cursor_pos = Some(Box::new(move |_| Some(point))); + let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(400.0,300.0))), + hovered_files:if path.is_some() || !mime.is_empty() { vec![egui::HoveredFile { path:path.map(std::path::PathBuf::from), mime:mime.into() }] } else { vec![] }, ..Default::default() }, |ui| { + stitch_ui::scope(ui, |ui| w.add_reference_button(&mut app,ui,260.0)); + }); + let mut text = Vec::new(); + for shape in output.shapes { labels(&shape.shape,&mut text); } + assert_eq!(text.iter().any(|label| label == "释放以上传图片"), expected); + assert!(requests.try_recv().is_err(), "hover does not import or send a request"); + } + } + + #[test] + fn reference_dropzone_blocks_click_and_file_hover_while_busy_or_unknown() { + for mode in ["busy", "unknown"] { + let (mut w, mut app, requests) = brief_fixture(); + let (dialog, calls) = crate::file_dialog::fake(vec![]); + app.services.file_dialog = Some(dialog); + if mode == "busy" { w.busy = Some("agent".into()); } else { w.unknown = true; } + let point = egui::pos2(50.0, 20.0); + app.services.cursor_pos = Some(Box::new(move |_| Some(point))); + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + for pressed in [true,false] { + let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(400.0,300.0))), + hovered_files:vec![egui::HoveredFile { path:Some(if cfg!(windows) { r"D:\photos\oak.png" } else { "/tmp/photos/oak.png" }.into()), mime:String::new() }], + events:vec![egui::Event::PointerMoved(point),egui::Event::PointerButton { pos:point,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }], ..Default::default() }, |ui| { + stitch_ui::scope(ui, |ui| w.add_reference_button(&mut app,ui,260.0)); + }); + assert!(!output.shapes.iter().any(|shape| matches!(&shape.shape,egui::Shape::Text(text) if text.galley.text()=="释放以上传图片")), "{mode} must not offer release to upload"); + } + assert!(!app.file_dialog_open()); + assert!(calls.borrow().is_empty()); + assert!(requests.try_recv().is_err()); + } + } + + #[test] + fn shared_modal_and_retained_exit_block_reference_drop_without_changing_scope() { + for interactive in [true,false] { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_open = true; + w.library = false; + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + for _ in 0..2 { brief_frame(&mut w,&mut app,&ctx,850.0,vec![]); } + let point = control_rect(&w,"reference-add").center(); + let original = w.creation_brief.clone(); + let doc = app.session.active().unwrap().doc.id; + let revision = app.session.active().unwrap().revision; + let account = w.account.clone(); + app.jiansun = Some(w); + for time in [0.1,0.2] { + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(850.0,2600.0))), time:Some(time), ..Default::default() }, |ui| { + let _ = stitch_ui::modal(ui.ctx(),egui::Id::unique("reference-drop-modal-test"),stitch_ui::OverlayVisual { render:true, interactive, opacity:0.5 },false, |ui| { ui.label("项目弹窗"); }); + }); + } + assert!(ctx.memory(|memory| memory.top_modal_layer().is_some())); + app.open_dropped(&ctx,vec![reference_drop(if cfg!(windows) { r"D:\photos\oak.png" } else { "/tmp/photos/oak.png" })],Some(point)); + assert_eq!(app.session.documents().len(),1); + assert_eq!(app.session.active().unwrap().doc.id,doc); + assert_eq!(app.session.active().unwrap().revision,revision); + assert_eq!(app.jiansun.as_ref().unwrap().creation_brief,original); + assert_eq!(app.jiansun.as_ref().unwrap().account,account); + assert!(requests.try_recv().is_err()); + } + } + + #[test] + fn real_reference_drop_uses_the_existing_import_and_preserves_variant_owners() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_open = true; + w.library = false; + let ctx = egui::Context::default(); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } + let at = control_rect(&w, "reference-0").center(); + let before = w.creation_brief.clone(); + let doc = app.session.active().unwrap().doc.id.0; + app.jiansun = Some(w); + app.open_dropped(&ctx, vec![reference_drop(if cfg!(windows) { r"D:\photos\oak.png" } else { "/tmp/photos/oak.png" }), reference_drop(if cfg!(windows) { r"D:\photos\detail.JPG" } else { "/tmp/photos/detail.JPG" })], Some(at)); + let request = requests.try_recv().unwrap(); + let Request::Action(method, payload) = request else { panic!("expected reference import") }; + assert_eq!(method, "creation-import"); + assert_eq!(payload["doc"], doc); + assert_eq!(payload["paths"], json!([if cfg!(windows) { r"D:\photos\oak.png" } else { "/tmp/photos/oak.png" }, if cfg!(windows) { r"D:\photos\detail.JPG" } else { "/tmp/photos/detail.JPG" }])); + assert_eq!(payload["brief"], before, "drop must not reassign any existing references or colors"); + assert_eq!(app.session.documents().len(), 1, "a reference drop is not opened as another native document"); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn reference_drop_accepts_the_empty_product_card() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_open = true; + w.library = false; + w.creation_brief["images"] = json!([]); + w.creation_brief["variants"] = json!([]); + let ctx = egui::Context::default(); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } + let at = control_rect(&w, "reference-empty").center(); + let before = w.creation_brief.clone(); + let doc = app.session.active().unwrap().doc.id.0; + app.jiansun = Some(w); + + let files = [if cfg!(windows) { r"D:\photos\椅子-左视图.webp" } else { "/tmp/photos/椅子-左视图.webp" }, if cfg!(windows) { r"D:\photos\oak.png" } else { "/tmp/photos/oak.png" }, if cfg!(windows) { r"D:\photos\detail.jpg" } else { "/tmp/photos/detail.jpg" }]; + app.open_dropped(&ctx, files.into_iter().map(reference_drop).collect(), Some(at)); + + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected reference import") }; + assert_eq!(method, "creation-import"); + assert_eq!(input["paths"], json!(files)); + assert_eq!(input["brief"], before); + let images = files.iter().enumerate().map(|(i, path)| json!({ + "source":format!("local:{i:064x}"),"purpose":"product","name":path.rsplit(['\\', '/']).next().unwrap(), + })).collect::>(); + let mut w = app.jiansun.take().unwrap(); + let receipt = json!({ + "doc":doc,"origin":w.origin,"accountId":w.account["id"],"images":images, + }); + received(&mut w, &app, "creation-import", &receipt); + assert_eq!(w.creation_brief["images"].as_array().unwrap().len(), 3); + assert_eq!(w.creation_brief["name"], before["name"]); + assert_eq!(app.session.active().unwrap().doc.id.0, doc); + assert_eq!(app.session.documents().len(), 1); + } + + #[test] + fn product_form_drop_outside_reference_cards_keeps_the_active_draft() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_open = true; + w.library = false; + w.creation_brief["name"] = json!("已填写产品名称"); + w.creation_dirty = true; + let ctx = egui::Context::default(); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } + let at = control_rect(&w, "name").center(); + let before = w.creation_brief.clone(); + let doc = app.session.active().unwrap().doc.id.0; + app.jiansun = Some(w); + + for point in [Some(at), Some(egui::pos2(0.0, 0.0)), None] { + app.open_dropped(&ctx, vec![reference_drop(if cfg!(windows) { r"D:\photos\oak.png" } else { "/tmp/photos/oak.png" })], point); + } + + let workspace = app.jiansun.as_ref().unwrap(); + assert_eq!(app.session.active().unwrap().doc.id.0, doc); + assert_eq!(app.session.documents().len(), 1); + assert_eq!(workspace.creation_brief, before); + assert!(workspace.creation_dirty); + assert_eq!(workspace.creation_reads.reference_import_error, REFERENCE_DROP_HINT); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn existing_assets_receive_drops_with_template_slots_on_the_form_layer() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_open = true; + w.library = false; + set_intake(&mut w.creation_brief, &json!("image-template"), &json!({"version":1,"productFields":[ + {"key":"hero","kind":"image","label":"产品图片","imageRole":"product"}, + ]})); + let ctx = egui::Context::default(); + let layer = egui::LayerId::new(egui::Order::Middle, egui::Id::unique("brief-drop-layer")); + for _ in 0..3 { + let mut output = ctx.run_ui(egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(900.0, 2600.0))), + ..Default::default() + }, |ui| { + egui::Area::new(layer.id).order(layer.order) + .fixed_pos(egui::pos2(20.0, 20.0)).default_size(vec2(850.0, 2500.0)) + .show(ui.ctx(), |ui| { + ui.set_min_size(vec2(850.0, 2500.0)); + w.creation_ui(&mut app, ui); + }); + }); + output.textures_delta.clear(); + } + let at = control_rect(&w, "reference-0").center(); + assert_eq!(ctx.layer_id_at(at), Some(layer), "drop point {at:?} in {:?}", ctx.memory(|m| m.area_rect(layer.id))); + assert!(drop_contains(&w.creation_view_geometry["product-form-viewport"], at)); + assert!(drop_contains(&w.creation_view_geometry["referenceDrop"]["rect"], at)); + let before = w.creation_brief.clone(); + app.jiansun = Some(w); + app.open_dropped(&ctx, vec![reference_drop(if cfg!(windows) { r"D:\photos\chair.webp" } else { "/tmp/photos/chair.webp" })], Some(at)); + let input = requests.try_iter().find_map(|request| match request { + Request::Action(method, input) if method == "creation-import" => Some(input), + _ => None, + }).unwrap(); + assert_eq!(input["brief"], before); + assert!(input["imageSlot"].is_null()); + assert_eq!(app.session.documents().len(), 1); + } + + #[test] + fn reference_drop_only_intercepts_the_visible_current_project_target() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_open = true; + w.library = false; + let ctx = egui::Context::default(); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } + let at = control_rect(&w, "reference-add").center(); + app.jiansun = Some(w); + let files = [reference_drop(if cfg!(windows) { r"D:\photos\oak.png" } else { "/tmp/photos/oak.png" })]; + assert!(app.creation_reference_drop(&ctx, &files, None)); + assert!(app.creation_reference_drop(&ctx, &files, Some(egui::pos2(1.0, 1.0)))); + app.jiansun.as_mut().unwrap().account = json!({"id":"another"}); + assert!(app.creation_reference_drop(&ctx, &files, Some(at))); + app.jiansun.as_mut().unwrap().account = json!({"id":"qa"}); + app.session.execute("file.new", json!({"width":32,"height":32})).unwrap(); + assert!(app.creation_reference_drop(&ctx, &files, Some(at))); + assert_eq!(app.jiansun.as_ref().unwrap().creation_reads.reference_import_error, REFERENCE_DROP_HINT); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn reference_drop_rejects_busy_unknown_and_unsupported_files_without_opening_them() { + for mode in ["busy", "unknown", "format", "count"] { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_open = true; + w.library = false; + let ctx = egui::Context::default(); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } + let at = control_rect(&w, "reference-add").center(); + if mode == "busy" { w.busy = Some("agent".into()); } + if mode == "unknown" { w.unknown = true; } + app.jiansun = Some(w); + let files = if mode == "format" { vec![reference_drop("D:\\photos\\file.pdf")] } + else if mode == "count" { (0..9).map(|_| reference_drop(if cfg!(windows) { r"D:\photos\oak.png" } else { "/tmp/photos/oak.png" })).collect() } + else { vec![reference_drop(if cfg!(windows) { r"D:\photos\oak.png" } else { "/tmp/photos/oak.png" })] }; + app.open_dropped(&ctx, files, Some(at)); + assert!(!app.jiansun.as_ref().unwrap().creation_reads.reference_import_error.is_empty(), "{mode} should explain why the drop was not imported"); + assert_eq!(app.session.documents().len(), 1, "{mode} should not accidentally open a new document"); + assert!(requests.try_recv().is_err(), "{mode} must not dispatch an import"); + } + } + + fn control_rect(w: &Workspace, name: &str) -> egui::Rect { + let rect = w.creation_view_geometry["controls"][name].as_array().unwrap_or_else(|| panic!("missing control {name}")); + egui::Rect::from_min_size( + egui::pos2(rect[0].as_f64().unwrap() as f32, rect[1].as_f64().unwrap() as f32), + vec2(rect[2].as_f64().unwrap() as f32, rect[3].as_f64().unwrap() as f32), + ) + } + + fn click_events(pos: egui::Pos2) -> Vec { + vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }, + ] + } + + #[test] + fn selling_point_toggle_keeps_key_and_request_contract() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation["sellingPoints"] = json!({"batches":[{"id":"batch","items":["实木结构"]}]}); + let ctx = egui::Context::default(); + fn draw(ctx: &egui::Context, w: &mut Workspace, app: &mut PhotocraftApp, events: Vec) { + let _ = ctx.settle_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(850.0, 1000.0))), events, ..Default::default() }, + |ui| { stitch_ui::scope_with_motion(ui, w.reduce_motion, |ui| w.points_ui(app, ui)); }, + ); + } + draw(&ctx, &mut w, &mut app, vec![]); + let point = control_rect(&w, "selling-point-0-0").center(); + draw(&ctx, &mut w, &mut app, click_events(point)); + assert_eq!(w.creation_selected, vec!["batch:0"]); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected selection request") }; + assert_eq!(method, "creation-select"); + assert_eq!(input["selected"], json!(["batch:0"])); + w.busy = None; + // A pointer click does not promise keyboard focus in egui. Exercise the + // actual Tab focus path in a fresh context instead of assuming it did. + let keyboard_ctx = egui::Context::default(); + draw(&keyboard_ctx, &mut w, &mut app, vec![]); + let point = control_rect(&w, "selling-point-0-0").center(); + let mut reached = false; + for _ in 0..12 { + draw(&keyboard_ctx, &mut w, &mut app, key_events(egui::Key::Tab)); + let focus = keyboard_ctx.memory(|memory| memory.focused()); + if focus.and_then(|id| keyboard_ctx.read_response(id)) + .is_some_and(|response| response.rect.center().distance(point) < 0.5) + { + reached = true; + break; + } + } + assert!(reached, "Tab traversal reaches the selling-point toggle"); + draw(&keyboard_ctx, &mut w, &mut app, key_events(egui::Key::Space)); + assert!(w.creation_selected.is_empty(), "Tab then Space supports keyboard deselection"); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected selection request") }; + assert_eq!(method, "creation-select"); + assert_eq!(input["selected"], json!([])); + } + + fn key_events(key: egui::Key) -> Vec { + [true, false].into_iter().map(|pressed| egui::Event::Key { + key, physical_key: Some(key), pressed, repeat: false, modifiers: egui::Modifiers::NONE, + }).collect() + } + + #[test] + fn brief_autosave_keeps_form_active_and_preserves_newer_edits() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation["revision"] = json!(1); + w.creation_dirty = true; + let delivery = std::env::temp_dir().join("成品"); + w.creation_delivery_dir = Some(delivery.to_string_lossy().into_owned()); + w.creation_action(&mut app, "creation-save", json!({})).unwrap(); + assert!(form_editable(w.busy.as_deref(), false)); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("save request") }; + assert_eq!(method, "creation-save"); + assert_eq!(input["deliveryDir"], json!(delivery)); + w.creation_delivery_dir = None; + w.creation_brief["name"] = json!("保存过程中继续输入的产品名"); + w.creation_brief["categoryName"] = json!("新选品类"); + let draft = w.creation_draft(); + let value = json!({"doc":w.creation_doc,"accountId":w.account["id"],"origin":w.origin, + "creation":{"revision":2,"deliveryDir":input["deliveryDir"],"brief":input["brief"],"width":input["width"],"screenCount":input["screenCount"],"plan":{"screens":input["screens"]}}}); + received(&mut w, &app, "creation-save", &value); + assert_eq!(w.creation_brief, draft["brief"]); + assert!(w.creation_dirty); + assert!(w.creation_delivery_dir.is_none(), "clearing the folder supersedes the in-flight save"); + assert_eq!(w.creation["revision"], 2); + assert!(!form_editable(Some("creation-import"), false)); + assert!(!form_editable(None, true)); + } + + #[test] + fn sku_color_plan_adds_multiple_colors_and_saves_selected_subsets() { + for width in [900.0, 380.0] { + let (mut w, mut app, requests) = brief_fixture(); + w.reduce_motion = true; + let ctx = egui::Context::default(); + let draw = |w: &mut Workspace, app: &mut PhotocraftApp, events| { + brief_frame_at_size(w, app, &ctx, vec2(width, 3200.0), events) + }; + draw(&mut w, &mut app, vec![]); + let bounds = draw(&mut w, &mut app, vec![]); + let field = control_rect(&w, "sku-color-input"); + assert!(bounds.contains_rect(field)); + draw(&mut w, &mut app, click_events(field.center())); + draw(&mut w, &mut app, vec![egui::Event::Text("暖白色".into())]); + let add = control_rect(&w, "sku-color-add"); + draw(&mut w, &mut app, click_events(add.center())); + let white = variant_identity("manual-sku:暖白色"); + assert_eq!(w.creation_brief["variants"][2]["id"], white); + let adv = control_rect(&w, "advanced-export-settings"); + draw(&mut w, &mut app, click_events(adv.center())); + draw(&mut w, &mut app, vec![]); + let select = |w: &mut Workspace, app: &mut PhotocraftApp, output: &str, ids: &[&str]| { + let trigger = control_rect(w, &format!("sku-output-{output}")); + assert!(bounds.contains_rect(trigger), "{output} trigger {trigger:?} outside {bounds:?}"); + draw(w, app, click_events(trigger.center())); + for _ in 0..25 { draw(w, app, vec![]); } + for id in ids { + let option = control_rect(w, &format!("sku-output-{output}-{id}")); + draw(w, app, click_events(option.center())); + } + draw(w, app, key_events(egui::Key::Escape)); + for _ in 0..25 { draw(w, app, vec![]); } + }; + select(&mut w, &mut app, "detail", &["oak", "walnut"]); + select(&mut w, &mut app, "main_images", &[&white]); + let expected = json!({"detail":["oak","walnut"],"main_images":[white]}); + assert_eq!(w.creation_brief["outputVariantIds"], expected); + for row in w.creation_brief["variants"].as_array().unwrap() { + assert!(!w.sku_color_removable(row)); + } + assert!(w.creation_dirty); + w.creation_action(&mut app, "creation-save", json!({})).unwrap(); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("save brief") }; + assert_eq!(method, "creation-save"); + assert_eq!(input["brief"]["outputVariantIds"], expected); + assert_eq!(input["brief"]["variants"][2]["colorName"], "暖白色"); + } + } + + #[test] + #[ignore = "native GPU visual evidence; requires PHOTOCRAFT_AGENT_QA_OUT"] + fn sku_color_plan_form_visual_acceptance() { + let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + for (width, height) in [(900.0, 1500.0), (420.0, 2200.0)] { + let (mut w, app, _requests) = brief_fixture(); + w.creation_brief["outputVariantIds"] = json!({"detail":["oak","walnut"],"main_images":["oak"]}); + w.creation_dirty = true; + w.unknown = true; + w.template_workflow = json!({"canvasFirst":true,"scopedProductionPending":true}); + let mut h = egui_kittest::Harness::builder().with_size(vec2(width, height)).wgpu().build_ui_state( + |ui, state: &mut (Workspace, PhotocraftApp)| { + if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { + stitch_ui::scope(ui, |ui| state.0.brief_ui(&mut state.1, ui)); + } + }, + (w, app), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join(format!("sku-colors-{width}.png"))).unwrap(); + } + } + + #[test] + fn stitch_brief_resizes_without_losing_reference_ownership_or_overflowing_controls() { + let (mut w, mut app, requests) = brief_fixture(); + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + for width in [900.0, 720.0, 600.0, 380.0] { + brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let bounds = brief_frame(&mut w, &mut app, &ctx, width, vec![]); + for name in ["brief-title", "name", "brand", "category", "dimensions", "identifier", "material", "template", "reference-0", "reference-1", "enter-canvas"] { + let rect = control_rect(&w, name); + assert!( + rect.left() >= bounds.left() - 1.0 && rect.right() <= bounds.right() + 1.0, + "{name} must remain inside the {width}px form: {rect:?}, bounds {bounds:?}" + ); + } + for index in 0..2 { + let card = control_rect(&w, &format!("reference-{index}")); + let preview = control_rect(&w, &format!("reference-preview-{index}")); + let purpose = control_rect(&w, &format!("reference-purpose-{index}")); + let owner = control_rect(&w, &format!("reference-owner-{index}")); + assert!( + card.contains_rect(preview) && card.contains_rect(purpose) && card.contains_rect(owner), + "reference controls stay in their own card at {width}px" + ); + assert!(preview.right() < purpose.left(), "reference preview and its controls are side by side at {width}px"); + assert!(purpose.bottom() < owner.top(), "reference controls keep a vertical flow inside the grid cell"); + assert!(card.height() <= 190.0, "reference rows stay compact rather than reserving an oversized image card at {width}px"); + } + let name = control_rect(&w, "name"); + let brand = control_rect(&w, "brand"); + let category = control_rect(&w, "category"); + assert!(control_rect(&w, "brief-title").bottom() < name.top(), "page title precedes the editable product fields"); + let template = control_rect(&w, "template"); + assert!(brand.top() <= category.top()); + assert!(category.bottom() < template.top()); + assert!(template.bottom() < name.top(), "template selection precedes product fields"); + assert!(name.bottom() < control_rect(&w, "reference-0").top(), "product fields precede the visual asset gallery"); + for control in ["name", "brand", "category", "dimensions", "identifier", "template"] { + assert!((control_rect(&w, control).height() - 34.0).abs() < 0.8, "{control} has a consistent field height"); + } + assert_eq!(w.creation_brief, original, "resizing never resets product options, colors, sources or purpose"); + } + assert!(requests.try_recv().is_err(), "painting a fully cached form does not execute a read or model action"); + } + + #[test] + fn output_tags_toggle_real_scopes_without_fake_upcoming_pills() { + let (mut w, mut app, requests) = brief_fixture(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + w.creation_dirty = false; + for width in [900.0, 380.0] { + brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let bounds = brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let mut rects: Vec = Vec::new(); + for (id, _, _) in OUTPUT_SCOPE_OPTIONS { + let rect = control_rect(&w, id); + assert!(bounds.contains_rect(rect), "{id} at {width}: {rect:?}"); + assert!(rects.iter().all(|other| !other.intersects(rect)), "{id} overlaps at {width}"); + rects.push(rect); + } + assert!(w.creation_view_geometry["controls"]["output-tag-main_video"].is_null()); + assert!(w.creation_view_geometry["controls"]["output-tag-seeding_video"].is_null()); + } + let pos = control_rect(&w, "output-tag-sku_images").center(); + brief_frame(&mut w, &mut app, &ctx, 380.0, click_events(pos)); + assert!(w.creation_dirty); + assert_eq!(selected_output_scopes(&w.creation_brief), vec!["detail", "main_images"]); + let pos_main = control_rect(&w, "output-tag-main_images").center(); + brief_frame(&mut w, &mut app, &ctx, 380.0, click_events(pos_main)); + assert_eq!(selected_output_scopes(&w.creation_brief), vec!["detail"]); + // Cannot deselect the final remaining scope. + let pos_detail = control_rect(&w, "output-tag-detail").center(); + brief_frame(&mut w, &mut app, &ctx, 380.0, click_events(pos_detail)); + assert_eq!(selected_output_scopes(&w.creation_brief), vec!["detail"]); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn brief_library_search_and_entry_actions_reflow_without_dispatching() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_brief["source"] = json!("library"); + w.creation["productionBudgetMinutes"] = json!(90); + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + for width in [900.0, 380.0] { + brief_frame(&mut w, &mut app, &ctx, width, vec![]); + brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let source = control_rect(&w, "source"); + let search = control_rect(&w, "source-search"); + let hint = control_rect(&w, "entry-hint"); + assert!(w.creation_draft().get("productionBudgetMinutes").is_none()); + let advanced = control_rect(&w, "advanced-export-settings"); + let enter = control_rect(&w, "enter-canvas"); + assert!(advanced.bottom() <= hint.top() && hint.bottom() <= enter.top()); + assert!(advanced.right() <= width + 1.0); + if width >= 900.0 { + assert!(source.right() < search.left() && source.top() < search.bottom() && search.top() < source.bottom(), "wide source and lookup share a row"); + } else { + assert!(source.bottom() < search.top(), "narrow lookup follows its source"); + } + assert_eq!(w.creation_brief, original); + } + assert!(requests.try_recv().is_err(), "rendering must not search or dispatch model actions"); + } + + #[test] + fn brief_grid_boundaries_keep_fields_separate() { + let (mut w, mut app, requests) = brief_fixture(); + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + for width in [380.0, 519.0, 520.0, 779.0, 780.0, 808.0] { + for _ in 0..2 { + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 2600.0))), ..Default::default() }, + |ui| { stitch_ui::scope(ui, |ui| w.brief_content_ui(&mut app, ui)); }, + ); + output.textures_delta.clear(); + } + let fields: Vec<_> = ["name", "brand", "category", "dimensions", "identifier"].iter().map(|name| control_rect(&w, name)).collect(); + for (index, field) in fields.iter().enumerate() { + assert!(field.left() >= -1.0 && field.right() <= width + 1.0, "field {index} overflows at {width}px: {field:?}"); + for other in fields.iter().skip(index + 1) { + assert!(!field.intersects(*other), "fields overlap at {width}px: {field:?} and {other:?}"); + } + } + assert_eq!(w.creation_brief, original); + } + assert!(requests.try_recv().is_err()); + } + + #[test] + fn dimension_row_fits_its_column_and_displays_the_complete_unit() { + fn text_is_visible(shape: &egui::Shape, expected: &str, selector: egui::Rect, clip: egui::Rect) -> bool { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| text_is_visible(shape, expected, selector, clip)), + egui::Shape::Text(text) => { + let painted: String = text.galley.rows.iter().flat_map(|row| row.glyphs.iter().map(|glyph| glyph.chr)).collect(); + let bounds = egui::Rect::from_min_size(text.pos, text.galley.size()); + painted == expected && selector.contains_rect(bounds) && clip.contains_rect(bounds) + } + _ => false, + } + } + for width in [380.0, 519.0, 780.0, 1000.0] { + for unit in ["mm", "cm", "m"] { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_brief["dimensions"]["unit"] = json!(unit); + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let mut output = None; + for _ in 0..2 { + output = Some(ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(width,2600.0))), ..Default::default() }, + |ui| { stitch_ui::scope(ui, |ui| w.brief_content_ui(&mut app,ui)); })); + } + let row = control_rect(&w, "dimensions"); + let selector = control_rect(&w, "dimensions-unit"); + assert!(row.width() <= width + 1.0, "{width}: dimensions {row:?} exceed container"); + assert!(row.width() >= 320.0, "{width}: dimensions row must remain generous and never crush inputs: {row:?}"); + assert!(row.contains_rect(selector), "{width}: unit selector stays inside the row"); + assert!(output.unwrap().shapes.iter().any(|shape| text_is_visible(&shape.shape,unit,selector,shape.clip_rect)), "{width}: complete unit {unit} must be painted within its selector and clip"); + assert!(requests.try_recv().is_err()); + } + } + } + + #[test] + fn dimension_filter_chip_changes_only_the_selected_unit() { + fn find(shape:&egui::Shape, text:&str) -> Option { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().find_map(|shape| find(shape,text)), + egui::Shape::Text(shape) if shape.galley.text() == text => Some(shape.pos + shape.galley.size() * 0.5), + _ => None, + } + } + let (mut w, mut app, requests) = brief_fixture(); + w.reduce_motion = true; + w.creation_brief["dimensions"]["length"] = json!("1200"); + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { + ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(900.0,1200.0))),events,..Default::default() }, + |ui| { stitch_ui::scope(ui,|ui| w.brief_content_ui(app,ui)); }) + }; + frame(&mut w,&mut app,vec![]); + let anchor = control_rect(&w,"dimensions-unit").center(); + for pressed in [true,false] { + frame(&mut w,&mut app,vec![egui::Event::PointerMoved(anchor),egui::Event::PointerButton { pos:anchor,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); + } + let output = frame(&mut w,&mut app,vec![]); + let cm = output.shapes.iter().find_map(|shape| find(&shape.shape,"cm")).expect("unit popup exposes cm filter chip"); + for pressed in [true,false] { + frame(&mut w,&mut app,vec![egui::Event::PointerMoved(cm),egui::Event::PointerButton { pos:cm,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE }]); + } + let mut expected = original; + expected["dimensions"]["unit"] = json!("cm"); + assert_eq!(w.creation_brief,expected); + assert!(w.creation_dirty); + assert!(requests.try_recv().is_err(),"choosing a unit only edits the local draft"); + } + + #[test] + fn full_creation_surface_resets_horizontal_parent_and_centering_row_layouts() { + let (mut w, mut app, requests) = brief_fixture(); + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + w.creation_open = true; + w.library = false; + w.material = false; + for (window_width, dock_width) in [(1535.0, 519.0), (1100.0, 360.0), (850.0, 360.0)] { + for (stage, controls) in [ + (CreationStage::Source, &["source", "reference-add"][..]), + (CreationStage::Template, &["brand", "category", "template"][..]), + (CreationStage::Details, &["name", "identifier", "reference-0", "reference-1", "enter-canvas"][..]), + ] { + w.creation_reads.wizard_stage = Some((w.creation_field_scope(&app), stage)); + let mut central = egui::Rect::NOTHING; + for _ in 0..2 { + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(window_width, 1032.0))), ..Default::default() }, + |ui| { + ui.horizontal(|ui| { + ui.allocate_ui_with_layout( + vec2(window_width - dock_width - ui.spacing().item_spacing.x, 1032.0), + egui::Layout::left_to_right(egui::Align::Min), + |ui| { + central = ui.available_rect_before_wrap(); + w.creation_ui(&mut app, ui); + }, + ); + ui.allocate_exact_size(vec2(dock_width, 1032.0), egui::Sense::hover()); + }); + }, + ); + output.textures_delta.clear(); + } + for name in controls { + let rect = control_rect(&w, name); + assert!( + rect.left() >= central.left() && rect.right() <= central.right(), + "{name} escaped the real horizontal workspace at {window_width}px: {rect:?}, central {central:?}" + ); + } + } + for (key, value) in original.as_object().unwrap() { + assert_eq!(&w.creation_brief[key], value, "{key}"); + } + } + assert!(requests.try_recv().is_err()); + } + + #[test] + fn library_product_can_add_references_without_changing_its_source_or_existing_owners() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_brief["source"] = json!("library"); + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + brief_frame(&mut w, &mut app, &ctx, 540.0, vec![]); + let add = control_rect(&w, "reference-add"); + assert!(add.width() > 0.0 && add.height() >= 34.0, "library references retain the same visible local image picker"); + assert_eq!(w.creation_brief, original); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn empty_reference_picker_fits_narrow_form_without_changing_variants() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_brief["images"] = json!([]); + let mut variants = brief_variants(&w.creation_brief); + for variant in &mut variants { variant["images"] = json!([]); } + set_brief_variants(&mut w.creation_brief, variants); + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); + let bounds = brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); + let add = control_rect(&w, "reference-add"); + assert!(add.width() >= 100.0 && add.height() >= 72.0); + assert!(add.left() >= bounds.left() && add.right() <= bounds.right(), "the image picker remains inside the narrow form"); + assert_eq!(w.creation_brief, original, "rendering the empty picker must preserve all variant identities"); + assert!(requests.try_recv().is_err(), "rendering an empty picker must not initiate an import"); + } + + #[test] + fn brief_source_buttons_switch_without_discarding_the_draft() { + let (mut w, mut app, requests) = brief_fixture(); + let mut expected = w.creation_brief.clone(); + let ctx = egui::Context::default(); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } + assert_eq!(w.creation_view_geometry["sourceChoices"][0]["selected"], true); + assert_eq!(w.creation_view_geometry["sourceChoices"][1]["selected"], false); + assert_eq!(w.creation_view_geometry["popups"]["source"]["open"], false); + let rail = control_rect(&w, "source"); + for control in ["source-upload", "source-product_platform", "source-library"] { + let segment = control_rect(&w, control); + assert!(rail.contains_rect(segment) && segment.height() >= control::MENU_ROW); + } + let library = control_rect(&w, "source-library").center(); + brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(library)); + expected["source"] = json!("library"); + assert_eq!(w.creation_brief, expected, "switching source must preserve names, images, variants and template identity"); + assert_eq!(w.creation_view_geometry["sourceChoices"][0]["selected"], false); + assert_eq!(w.creation_view_geometry["sourceChoices"][2]["selected"], true); + assert!(w.creation_dirty); + brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); + let upload = control_rect(&w, "source-upload").center(); + brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(upload)); + expected["source"] = json!("upload"); + assert_eq!(w.creation_brief, expected); + assert!(requests.try_recv().is_err(), "switching source is local and must not load or overwrite data"); + } + + #[test] + fn material_toggle_row_remains_full_width_and_respects_disabled_state() { + fn draw(ctx: &egui::Context, selected: &mut bool, enabled: bool, events: Vec) -> egui::Rect { + let mut rect = egui::Rect::NOTHING; + let _ = ctx.settle_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 200.0))), events, ..Default::default() }, + |ui| { + ui.set_width(240.0); + let response = picker_toggle_row(ui, *selected, "长花色名称", enabled); + rect = response.rect; + if response.clicked() { *selected = !*selected; } + }, + ); + rect + } + let ctx = egui::Context::default(); + let mut selected = false; + let rect = draw(&ctx, &mut selected, true, vec![]); + let at = rect.right_center() - vec2(5.0, 0.0); + assert!(rect.width() >= 240.0 && rect.height() >= PICKER_ROW_HEIGHT, "the entire material row remains an accessible hit target"); + draw(&ctx, &mut selected, true, click_events(at)); + assert!(selected, "clicking the far edge selects the actual material"); + draw(&ctx, &mut selected, false, click_events(at)); + assert!(selected, "a locked material cannot be removed through the shared toggle"); + } + + #[test] + fn brief_source_buttons_are_keyboard_accessible() { + let (mut w, _, requests) = brief_fixture(); + let mut expected = w.creation_brief.clone(); + let ctx = egui::Context::default(); + let frame = |w: &mut Workspace, events| { + ctx.settle_ui(egui::RawInput { events, ..Default::default() }, |ui| { + stitch_ui::scope(ui, |ui| w.source_picker(ui)); + }); + }; + frame(&mut w, vec![]); + frame(&mut w, key_events(egui::Key::Tab)); + frame(&mut w, key_events(egui::Key::Tab)); + frame(&mut w, key_events(egui::Key::Enter)); + expected["source"] = json!("product_platform"); + assert_eq!(w.creation_brief, expected, "keyboard can select the product platform without changing the draft"); + frame(&mut w, key_events(egui::Key::Tab)); + frame(&mut w, key_events(egui::Key::Enter)); + expected["source"] = json!("library"); + assert_eq!(w.creation_brief, expected, "keyboard can select the library without changing the draft"); + assert_eq!(w.creation_view_geometry["sourceChoices"][2]["selected"], true); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn brief_library_segment_search_and_result_keep_request_identity() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_brief["identifier"] = json!("QA-001"); + w.creation_brief["identifierType"] = json!("spu"); + let ctx = egui::Context::default(); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } + let library = control_rect(&w, "source-library").center(); + brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(library)); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } + let search = control_rect(&w, "source-search").center(); + brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(search)); + let Request::Action(method, input) = requests.try_recv().expect("the search dispatches a catalog request") else { panic!("expected catalog action") }; + assert_eq!(method, "creation-catalog"); + assert_eq!(input["kind"], "products"); + assert_eq!(input["identifier"], "QA-001"); + assert_eq!(input["identifierType"], "spu"); + let row = json!({"id":"synthetic-product","name":"测试产品"}); + w.creation_catalog.insert("products".into(), vec![row.clone()]); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); } + let result = control_rect(&w, "source-result-0").center(); + brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(result)); + let request = requests.try_iter().find(|request| matches!(request, Request::Action(method, _) if method == "creation-product")); + let Some(Request::Action(_, input)) = request else { panic!("the chosen product must be submitted") }; + assert_eq!(input["item"], row); + assert_eq!(input["brief"]["source"], "library"); + assert_eq!(input["brief"]["identifier"], "QA-001"); + } + + #[test] + fn brief_material_heading_does_not_shrink_the_catalog() { + let (mut w, mut app, _requests) = brief_fixture(); + let ctx = egui::Context::default(); + for width in [600.0, 780.0, 808.0] { + for _ in 0..2 { + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 2600.0))), ..Default::default() }, + |ui| { stitch_ui::scope(ui, |ui| w.brief_content_ui(&mut app, ui)); }, + ); + output.textures_delta.clear(); + } + let heading = control_rect(&w, "material-heading"); + let material = control_rect(&w, "material"); + assert!(heading.right() < material.left(), "material heading overlaps its picker at {width}px"); + assert!((heading.top() - material.top()).abs() <= 1.0, "material heading and picker must share a compact row at {width}px"); + assert!(material.width() >= 320.0, "material picker and popup must retain readable catalog width at {width}px"); + } + } + + #[test] + fn brief_reference_grid_handles_empty_and_multiple_long_named_images() { + for width in [380.0, 650.0, 850.0] { + for count in 0..=4 { + let (mut w, mut app, _requests) = brief_fixture(); + w.creation_brief["images"] = json!((0..count).map(|index| json!({ + "source": format!("reference-{index}"), + "name": format!("需要完整保留的超长中文产品参考图片名称-{index}.png"), + "purpose": if index % 2 == 0 { "product" } else { "scene" }, + })).collect::>()); + w.creation_brief["variants"][1]["images"] = json!([]); + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, width, vec![]); } + let add = control_rect(&w, "reference-add"); + assert!(add.left() >= -1.0 && add.right() <= width + 1.0, "add control overflows at {width}px with {count} images: {add:?}"); + for index in 0..count { + let card = control_rect(&w, &format!("reference-{index}")); + let preview = control_rect(&w, &format!("reference-preview-{index}")); + let purpose = control_rect(&w, &format!("reference-purpose-{index}")); + let owner = control_rect(&w, &format!("reference-owner-{index}")); + assert!(card.contains_rect(preview) && card.contains_rect(purpose) && card.contains_rect(owner), "controls escape card {index} at {width}px"); + assert!(!card.intersects(add), "add control overlaps card {index} at {width}px"); + for other in (index + 1)..count { + assert!(!card.intersects(control_rect(&w, &format!("reference-{other}"))), "reference cards overlap at {width}px"); + } + } + assert_eq!(w.creation_brief, original, "layout must preserve images, purposes, owners and template"); + } + } + } + + #[test] + fn a_pending_image_allows_editing_and_saving_other_variant_references() { + for width in [380.0, 900.0] { + let (mut w, mut app, requests) = brief_fixture(); + w.unknown = true; + w.template_workflow = json!({"canvasFirst":true,"scopedProductionPending":true}); + let original = w.creation_brief["variants"][0].clone(); + let ctx = egui::Context::default(); + brief_frame(&mut w, &mut app, &ctx, width, vec![]); + brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let remove = control_rect(&w, "reference-remove-1").center(); + brief_frame(&mut w, &mut app, &ctx, width, click_events(remove)); + assert!(w.creation_brief["variants"][1]["images"].as_array().unwrap().is_empty()); + assert_eq!(w.creation_brief["variants"][0], original); + assert!(w.unknown); + assert!(w.creation_dirty && w.can_save_creation()); + w.creation_action(&mut app, "creation-save", json!({})).unwrap(); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected local brief save") }; + assert_eq!(method, "creation-save"); + assert_eq!(input["brief"]["variants"][0], original); + assert!(requests.try_recv().is_err()); + } + } + + #[test] + fn product_brief_save_without_template_preserves_color_references_and_stays_in_form() { + for width in [380.0, 900.0] { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_open = true; + w.creation_step = 0; + w.creation_brief["templateSelection"] = Value::Null; + w.creation_catalog.insert("templates".into(), vec![]); + w.creation_dirty = true; + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let bounds = brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let enter = control_rect(&w, "enter-canvas"); + assert!(bounds.contains_rect(enter)); + assert!(w.creation_view_geometry["controls"]["save-brief"].is_null()); + w.creation_action(&mut app, "creation-save", json!({})).unwrap(); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected local brief save") }; + assert_eq!(method, "creation-save"); + assert_eq!(input["brief"], original); + assert!(requests.try_recv().is_err()); + assert!(w.pending_slot_apply.is_none()); + assert!(w.creation_open && w.creation_step == 0); + } + } + + #[test] + fn new_project_shows_one_refinement_switch_and_the_start_carries_its_choice() { + let (mut w, mut app, requests) = brief_fixture(); + w.model_ready = true; + w.image_ready = true; + let ctx = egui::Context::default(); + brief_frame(&mut w, &mut app, &ctx, 900.0, vec![]); + brief_frame(&mut w, &mut app, &ctx, 900.0, vec![]); + let switch = control_rect(&w, "refinement").center(); + brief_frame(&mut w, &mut app, &ctx, 900.0, click_events(switch)); + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(900.0, 2600.0))), ..Default::default() }; + let output = ctx.run_ui(input, |ui| { stitch_ui::scope(ui, |ui| w.brief_ui(&mut app, ui)); }); + fn walk(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| walk(shape, out)), + _ => {} + } + } + let mut drawn = Vec::new(); + output.shapes.iter().for_each(|clipped| walk(&clipped.shape, &mut drawn)); + output.drop_without_applying_deltas(); + assert_eq!(drawn.iter().filter(|text| *text == "精修").count(), 1, "one refinement switch: {drawn:?}"); + assert!(!drawn.iter().any(|text| text == "不精修"), "no second refinement chooser: {drawn:?}"); + let start = control_rect(&w, "generate-product").center(); + brief_frame(&mut w, &mut app, &ctx, 900.0, click_events(start)); + assert!(requests.try_iter().any(|request| matches!(request, Request::Save(_, _, _))), "the start saves the project first"); + let start = w.pending_slot_apply.as_ref().expect("the start waits for the save"); + assert_eq!((&start["generateProduct"], &start["refinement"]), (&json!(true), &json!(true)), "{start}"); + } + + #[test] + fn product_brief_update_button_requests_fresh_catalog_and_keeps_draft_on_failure() { + let (mut w, mut app, requests) = brief_fixture(); + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); + brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); + let target = control_rect(&w, "template-update").center(); + brief_frame(&mut w, &mut app, &ctx, 380.0, click_events(target)); + let Request::Action(method, mut input) = requests.try_recv().unwrap() else { panic!("expected template read") }; + assert_eq!(method, "creation-catalog"); + assert_eq!(input["kind"], "templates"); + assert_eq!(input["refresh"], true); + input["error"] = json!("资源不存在或无权访问"); + assert!(w.creation_read_received(&app, "creation-catalog", &input)); + let bounds = brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); + assert!(bounds.contains_rect(control_rect(&w, "template-error"))); + assert_eq!(w.creation_brief, original); + assert!(requests.try_recv().is_err(), "a failed explicit check is not automatically replayed"); + } + + #[test] + fn stitch_brief_canvas_action_saves_the_same_exact_template_and_color_references_before_switching() { + let (mut w, mut app, requests) = brief_fixture(); + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); + brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); + let target = control_rect(&w, "enter-canvas").center(); + brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(target)); + assert!(matches!(requests.try_recv(), Ok(Request::Save(_, _, _))), "entering canvas first preserves the native document"); + assert!(requests.try_recv().is_err(), "no model or skeleton is dispatched before save acknowledgement"); + let pending = w.pending_slot_apply.as_ref().expect("a guarded skeleton switch waits for save"); + assert_eq!(pending["brief"], original); + assert_eq!(pending["template"], original["templateSelection"]); + assert_eq!(pending["outputId"], "detail"); + assert_eq!(w.busy.as_deref(), Some("slot-apply-save")); + } + + #[test] + fn stitch_brief_unknown_canvas_action_never_dispatches_or_discards_the_draft() { + let (mut w, mut app, requests) = brief_fixture(); + w.unknown = true; + let original = w.creation_brief.clone(); + let ctx = egui::Context::default(); + brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); + brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); + let target = control_rect(&w, "enter-canvas").center(); + brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(target)); + assert!(requests.try_recv().is_err()); + assert!(w.pending_slot_apply.is_none()); + assert_eq!(w.creation_brief, original); + assert!(w.unknown); + } + + #[test] + fn stitch_plan_unsaved_changes_keep_confirmation_and_slot_creation_disabled() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation_step = 2; + w.creation_dirty = true; + w.creation["plan"] = json!({"status":"confirmed"}); + w.creation_plan = json!([{"name":"首屏","title":"原产品标题","body":"原产品正文","imagePrompt":"保留真实产品"}]); + let original = w.creation_plan.clone(); + let ctx = egui::Context::default(); + let draw = |w: &mut Workspace, app: &mut PhotocraftApp, events: Vec| { + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(700.0, 1800.0))), events, ..Default::default() }, + |ui| { + stitch_ui::scope(ui, |ui| w.plan_ui(app, ui)); + }, + ); + output.textures_delta.clear(); + }; + draw(&mut w, &mut app, vec![]); + draw(&mut w, &mut app, vec![]); + for control in ["plan-confirm", "plan-slots"] { + let target = control_rect(&w, control).center(); + draw(&mut w, &mut app, click_events(target)); + } + assert_eq!(w.creation_step, 2, "an unsaved plan must not enter the slot workflow"); + assert_eq!(w.creation_plan, original); + assert!(w.creation_dirty); + assert!(requests.try_recv().is_err(), "disabled confirmation never publishes a request"); + } + + #[test] + fn read_only_catalog_requests_do_not_take_or_clear_a_model_execution_lease() { + let (mut w, mut app) = setup(); + let (tx, rx) = mpsc::channel(); + w.tx = tx; + w.unknown = true; + let busy = w.busy.clone(); + let result = w.creation_action(&mut app, "creation-catalog", json!({"kind":"brands","query":""})).unwrap(); + assert_eq!(result["readOnly"], true); + assert_eq!(w.busy, busy); + assert!(w.unknown, "a read cannot resolve or replace the original pending model request"); + let Request::Action(method, input) = rx.try_recv().unwrap() else { panic!("expected independent catalog request") }; + assert_eq!(method, "creation-catalog"); + assert_eq!(input["doc"].as_u64(), app.session.active().map(|s| s.doc.id.0)); + assert_eq!(input["accountId"], "qa"); + assert!(w.creation_action(&mut app, "creation-catalog", json!({"kind":"brands","doc":u64::MAX})).is_err()); + } + #[test] + fn creation_generation_requires_current_identity_revision_and_human_permission() { + let (mut w, mut app) = setup(); + let v = reference(&w); + assert_eq!(allowed(&mut w, &app, &v).unwrap()["allowed"], true); + let mut changed = v.clone(); + changed["accountId"] = json!("other"); + assert_eq!(allowed(&mut w, &app, &changed).unwrap()["allowed"], false); + changed = v.clone(); + changed["run"] = json!("00000000-0000-4000-8000-000000000002"); + assert_eq!(allowed(&mut w, &app, &changed).unwrap()["allowed"], false); + app.session.execute("type.create", json!({"text":"用户已编辑","font":"Noto Sans SC","size":32,"box":[20,20,500,90]})).unwrap(); + assert_eq!(allowed(&mut w, &app, &v).unwrap()["allowed"], false); + w.expected_revision = app.session.active().unwrap().revision; + w.handover(); + assert_eq!(allowed(&mut w, &app, &v).unwrap()["allowed"], false); + } + #[test] + fn generated_canvas_uses_native_undo_and_preserves_late_human_edits() { + let (mut w, mut app) = setup(); + let v = reference(&w); + allowed(&mut w, &app, &v).unwrap(); + let original = app.session.active().unwrap().doc.id; + let before = app.session.active().unwrap().doc.clone(); + let mut generated = photocraft_engine::Session::new(); + generated.execute("file.new", json!({"name":"实际生成结果","width":1440,"height":3600})).unwrap(); + generated.execute("type.create", json!({"text":"真实可编辑标题","font":"Noto Sans SC","size":32,"box":[20,20,500,90]})).unwrap(); + let result = (*generated.active().unwrap().doc).clone(); + canvas_received(&mut w, &mut app, Box::new(result.clone()), v.clone()); + assert_eq!(app.session.active().unwrap().doc.id, original); + assert_eq!(app.session.active().unwrap().doc.size.height, 3600); + assert!(app.session.active().unwrap().doc.walk().iter().any(|(_, _, l)| matches!(&l.content, LayerContent::Text(_)))); + app.session.execute("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.size, before.size); + assert_eq!(app.session.active().unwrap().doc.walk().len(), before.walk().len()); + let revision = app.session.active().unwrap().revision; + canvas_received(&mut w, &mut app, Box::new(result), v); + assert!(w.creation_pending.is_some()); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.session.active().unwrap().doc.size, before.size); + } + #[test] + fn sync_does_not_clear_dirty_when_backend_detects_a_newer_snapshot() { + let (mut w, app) = setup(); + w.sync_request_meta = w.sync_signature(); + let mut value = reference(&w); + value["revision"] = json!(app.session.active().unwrap().revision); + value["syncDirty"] = json!(true); + sync_received(&mut w, &app, &value); + assert!(w.sync_dirty); + value["syncDirty"] = json!(false); + sync_received(&mut w, &app, &value); + assert!(!w.sync_dirty); + } + + #[test] + fn finished_web_feedback_is_bound_to_the_delivery_project() { + let (mut w, app) = setup(); + let mut receipt = reference(&w); + receipt["materialDelivery"] = json!({"materialId":"delivered-detail", "kind":"detail"}); + receipt["status"] = json!("completed"); + sync_received(&mut w, &app, &receipt); + assert!(w.sync_confirm && w.delivery_completion); + assert!(!w.finished_web_pending, "the completion receipt does not open the workbench on its own"); + + w.finished_web_pending = true; + let mut other_project = receipt.clone(); + other_project["doc"] = json!(receipt["doc"].as_u64().unwrap().wrapping_add(1)); + other_project["error"] = json!("其他项目的错误"); + finished_web_received(&mut w, &app, &other_project); + assert!(w.finished_web_pending && w.finished_web_error.is_none()); + + receipt["error"] = json!("成品上架工作台暂时无法连接,请稍后再试"); + finished_web_received(&mut w, &app, &receipt); + assert!(!w.finished_web_pending); + assert_eq!(w.finished_web_error.as_deref(), receipt["error"].as_str()); + } + + #[test] + fn changed_candidate_or_text_requires_sync_even_when_canvas_revision_is_identical() { + let (mut w, app) = setup(); + let canvas_revision = app.session.active().unwrap().revision; + let baseline = json!({"revision":1,"confirmed":true,"slots":[{"id":"image","selectedCandidateId":"a","fields":[{"id":"title","value":"原文"}]}]}); + w.sync_dirty = false; + w.draft_changed = false; + assert!(w.receive_template_snapshot(&baseline, false)); + assert!(!w.sync_dirty, "loading the existing project establishes a baseline"); + for changed in ["candidate", "text"] { + w.sync_dirty = false; + w.draft_changed = false; + w.sync_request_meta = w.sync_signature(); + let original_signature = w.sync_request_meta.clone(); + let mut next = w.template_workflow.clone(); + next["revision"] = json!(next["revision"].as_u64().unwrap() + 1); + if changed == "candidate" { + next["slots"][0]["selectedCandidateId"] = json!("b"); + } else { + next["slots"][0]["fields"][0]["value"] = json!("人工编辑的标题"); + } + assert!(w.receive_template_snapshot(&next, false), "a read may reconcile a newly completed or edited journal"); + assert!(w.sync_dirty && w.draft_changed, "{changed} changes need a fresh backup"); + assert_ne!(w.sync_signature(), original_signature); + assert_eq!(app.session.active().unwrap().revision, canvas_revision); + let mut receipt = reference(&w); + receipt["revision"] = json!(canvas_revision); + receipt["syncDirty"] = json!(false); + sync_received(&mut w, &app, &receipt); + assert!(w.sync_dirty, "the previous same-canvas sync ACK cannot claim the newer {changed} snapshot"); + } + } + + #[test] + fn first_and_identical_template_reads_do_not_create_an_endless_dirty_cycle() { + let (mut w, _) = setup(); + let snapshot = json!({"revision":7,"confirmed":true,"slots":[{"id":"owned","selectedCandidateId":"a"}]}); + w.sync_dirty = false; + w.draft_changed = false; + assert!(w.receive_template_snapshot(&snapshot, false)); + let loaded_signature = w.sync_signature(); + for _ in 0..3 { + assert!(w.receive_template_snapshot(&snapshot, false)); + assert!(!w.sync_dirty && !w.draft_changed); + assert_eq!(w.sync_signature(), loaded_signature); + } + w.template_workflow = Value::Null; + assert!(w.receive_template_snapshot(&json!({"revision":1,"confirmed":true,"slots":[]}), true)); + assert!(w.sync_dirty && w.draft_changed, "an explicit first template install is a mutation, not a passive baseline read"); + } + #[test] + fn delayed_rules_refresh_updates_canonical_revision_without_overwriting_the_users_draft() { + let (mut w, app) = setup(); + w.creation = json!({"revision":2,"brief":empty_brief(),"sellingPoints":{"selected":["old:0"],"direction":"原方向"},"plan":{"status":"confirmed","screens":[{"id":"one","title":"原方案"}]},"width":1440,"screenCount":3,"designSnapshot":{"rules":{"id":"old-rule"}}}); + w.creation_brief = w.creation["brief"].clone(); + w.creation_brief["name"] = json!("刚输入的产品名称"); + w.creation_brief["dimensions"]["length"] = json!("1800"); + w.creation_selected = vec!["new:1".into()]; + w.creation_direction = "刚输入的表达方向".into(); + w.creation_plan = json!([{"id":"one","title":"尚未保存的标题"}]); + w.creation_width = 750; + w.creation_dirty = true; + let draft = w.creation_draft(); + let mut value = reference(&w); + value["creation"] = w.creation.clone(); + value["creation"]["revision"] = json!(3); + value["creation"]["designSnapshot"]["rules"] = json!({"id":"fixed-rule","contentHash":"a".repeat(64)}); + value["creation"]["plan"]["status"] = json!("stale"); + received(&mut w, &app, "creation-rules", &value); + assert_eq!(w.creation_draft()["brief"], draft["brief"]); + for field in ["screens", "direction", "selected", "width", "screenCount"] { + assert_eq!(w.creation_draft()[field], draft[field]); + } + assert!(w.creation_dirty); + assert_eq!(w.creation["revision"], 3); + assert_eq!(w.creation["designSnapshot"]["rules"]["id"], "fixed-rule"); + assert_eq!(w.creation["plan"]["status"], "stale"); + // With no local edits, the normal canonical plan state remains visible. + w.creation_dirty = false; + received(&mut w, &app, "creation-rules", &value); + assert_eq!(w.creation_plan, value["creation"]["plan"]["screens"]); + assert!(!w.creation_dirty); + } + + fn normalized_product_fixture() -> (Workspace, PhotocraftApp, mpsc::Receiver) { + let (mut w, app, requests) = brief_fixture(); + w.creation_brief["source"] = json!("product_platform"); + w.creation_brief["identifierType"] = json!("spu"); + w.creation_brief["identifier"] = json!("SPU-8802"); + w.creation_brief["name"] = json!("北欧实木升降双人餐桌"); + w.creation_brief["dimensions"] = json!({"length":"1600","width":"850","height":"750","unit":"mm"}); + w.creation_brief["detailBarcode"] = json!("BC-ASH-160"); + w.creation_brief["barcodeBindings"] = json!({"default":["BC-ASH-160","BC-ASH-180","BC-WAL-160","BC-WAL-180","BC-GRY-160"]}); + w.creation_brief["normalizedProduct"] = json!({ + "identity": { + "spu": "SPU-8802", + "productName": "北欧实木升降双人餐桌", + "platformBrand": "原木生活家", + "platformCategory": "餐厅家具/实木餐桌", + "seriesOrModel": "云栖 2026" + }, + "specs": { + "dimensions": { "length": 1600, "width": 850, "height": 750, "unit": "mm", "display": "1600 × 850 × 750 mm" }, + "packageDimensions": null, + "materials": ["北美白蜡木", "食品级木蜡油"], + "colors": ["原木白蜡", "暖胡桃", "星夜灰"], + "attributes": [ + {"key":"load","label":"静态承重","value":"120 kg","group":"specs"}, + {"key":"craft","label":"榫卯工艺","value":"全实木直拼","group":"specs"}, + {"key":"origin","label":"产地","value":"江苏南通","group":"specs"}, + {"key":"assembly","label":"安装方式","value":"预约上门安装","group":"service"} + ] + }, + "copy": { + "summary": "整块北美白蜡木直拼桌面,圆角防磕碰,适配中小户型餐厅与书房场景。", + "sellingPoints": [ + "北美 FAS 级白蜡木,自然大纹理不易开裂", + "圆润 R12 倒角设计,呵护儿童与老人", + "隐藏式加强横梁,稳固承重不晃动", + "环保净味木蜡油涂装,即买即用" + ] + }, + "variants": [ + { + "id": "v-ash", + "colorName": "原木白蜡", + "barcodes": [ + {"barcode":"BC-ASH-160","skuCode":"SKU-A16","skuName":"1.6米标准版","spec":"1.6m×0.85m","dimensions":{"length":1600,"width":850,"height":750,"unit":"mm","display":"1600×850×750 mm"},"sellingPoints":["4-6人日常用餐"],"attributes":[],"imageIds":["a1","a2"]}, + {"barcode":"BC-ASH-180","skuCode":"SKU-A18","skuName":"1.8米加长版","spec":"1.8m×0.90m","dimensions":{"length":1800,"width":900,"height":750,"unit":"mm","display":"1800×900×750 mm"},"sellingPoints":["6-8人聚餐"],"attributes":[],"imageIds":["a3"]} + ] + }, + { + "id": "v-walnut", + "colorName": "暖胡桃", + "barcodes": [ + {"barcode":"BC-WAL-160","skuCode":"SKU-W16","skuName":"1.6米标准版","spec":"1.6m×0.85m","dimensions":{"length":1600,"width":850,"height":750,"unit":"mm","display":"1600×850×750 mm"},"sellingPoints":[],"attributes":[],"imageIds":["a4"]}, + {"barcode":"BC-WAL-180","skuCode":"SKU-W18","skuName":"1.8米加长版","spec":"1.8m×0.90m","dimensions":{"length":1800,"width":900,"height":750,"unit":"mm","display":"1800×900×750 mm"},"sellingPoints":[],"attributes":[],"imageIds":[]} + ] + }, + { + "id": "v-grey", + "colorName": "星夜灰", + "barcodes": [ + {"barcode":"BC-GRY-160","skuCode":"SKU-G16","skuName":"1.6米标准版","spec":"1.6m×0.85m","dimensions":{"length":1600,"width":850,"height":750,"unit":"mm","display":"1600×850×750 mm"},"sellingPoints":[],"attributes":[],"imageIds":[]} + ] + } + ], + "assets": [ + {"id":"a1","url":"https://cdn.example/a1.jpg","kind":"whiteBackground","label":"白蜡木正面全貌白底图","barcode":"BC-ASH-160","colorName":"原木白蜡","localSource":null,"selectedForProject":true}, + {"id":"a2","url":"https://cdn.example/a2.jpg","kind":"main","label":"餐厅自然光场景主图","barcode":"BC-ASH-160","colorName":"原木白蜡","localSource":null,"selectedForProject":true}, + {"id":"a3","url":"https://cdn.example/a3.jpg","kind":"sku","label":"1.8m 款式规格图","barcode":"BC-ASH-180","colorName":"原木白蜡","localSource":null,"selectedForProject":true}, + {"id":"a4","url":"https://cdn.example/a4.jpg","kind":"reference","label":"木纹与倒角细节特写","barcode":"BC-WAL-160","colorName":"暖胡桃","localSource":null,"selectedForProject":false} + ], + "trace": { + "source": "产品平台", + "fetchedAt": "2026-12-02 10:15", + "upstreamSpu": "SPU-8802", + "rawFieldWarnings": ["包装尺寸缺失,已忽略空值", "条码 BC-GRY-160 暂无官方白底图"] + } + }); + w.creation_width = 1440; + w.creation["screenCount"] = json!(8); + w.creation["brief"] = w.creation_brief.clone(); + w.model_ready = true; + w.image_ready = true; + (w, app, requests) + } + + #[test] + fn normalized_product_renders_grouped_color_matrix_and_toggles_assets_preserving_kind() { + let (mut w, mut app, requests) = normalized_product_fixture(); + assert_eq!(sku_display_label(&w.creation_brief, "BC-ASH-160"), "原木白蜡 · 1.6m×0.85m (BC-ASH-160)"); + assert_eq!(sku_short_label(&w.creation_brief, "BC-ASH-160"), "原木白蜡 · 1.6m×0.85m"); + let groups = normalized_color_groups(&w.creation_brief); + assert_eq!(groups.len(), 3); + assert_eq!(groups[0].color_name, "原木白蜡"); + assert_eq!(groups[0].skus.len(), 2); + + let ctx = egui::Context::default(); + w.reduce_motion = true; + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 900.0, vec![]); } + assert!(control_rect(&w, "color-group-v-ash").is_positive()); + assert!(control_rect(&w, "color-group-v-walnut").is_positive()); + // Detail SKU color group is default-expanded; other color groups stay collapsed when total > 4. + assert!(control_rect(&w, "sku-main-BC-ASH-160").is_positive()); + assert!(w.creation_view_geometry["controls"]["sku-main-BC-WAL-160"].is_null()); + + // Toggle platform asset selectedForProject while preserving kind. + let toggle = control_rect(&w, "platform-asset-toggle-3").center(); + brief_frame(&mut w, &mut app, &ctx, 900.0, click_events(toggle)); + assert_eq!(w.creation_brief["normalizedProduct"]["assets"][3]["selectedForProject"], true); + assert_eq!(w.creation_brief["normalizedProduct"]["assets"][3]["kind"], "reference"); + assert!(w.creation_dirty); + assert!(requests.try_recv().is_err()); + } + + #[test] + fn platform_refetch_preserves_manually_edited_fields() { + let (mut w, app, _) = normalized_product_fixture(); + w.creation_brief["name"] = json!("手工改过的精准品名"); + w.creation_brief["note"] = json!("必须突出圆角倒角"); + w.creation_brief["dimensions"] = json!({"length":"1650","width":"860","height":"760","unit":"mm"}); + w.creation_reads.manual_edited_fields.insert("name".into()); + w.creation_reads.manual_edited_fields.insert("note".into()); + w.creation_reads.manual_edited_fields.insert("dimensions".into()); + + let mut incoming = w.creation_brief.clone(); + incoming["name"] = json!("上游覆盖品名"); + incoming["note"] = json!(""); + incoming["dimensions"] = json!({"length":"1600","width":"850","height":"750","unit":"mm"}); + let doc = app.session.active().unwrap().doc.id.0; + let receipt = json!({"doc":doc,"origin":w.origin,"accountId":w.account["id"],"platformBrief":incoming,"message":""}); + received(&mut w, &app, "creation-product-platform", &receipt); + assert_eq!(w.creation_brief["name"], "手工改过的精准品名"); + assert_eq!(w.creation_brief["note"], "必须突出圆角倒角"); + assert_eq!(w.creation_brief["dimensions"]["length"], "1650"); + assert!(w.creation_reads.platform_sync_note.contains("保留了你手动修改的 3 项字段")); + } + + #[test] + fn saved_platform_refetch_fills_barcode_fields_and_preserves_intentional_clears() { + let (mut w, app, _) = normalized_product_fixture(); + let mut incoming = w.creation_brief.clone(); + incoming["normalizedProduct"] = Value::Null; + incoming["barcodeBindings"] = json!({"default":["001","002"]}); + incoming["name"] = json!("上游品名"); + incoming["platformFacts"] = json!({"spu":"SPU-8802","shared":{},"barcodes":{ + "001":{"material":"实木","dimensions":{"unit":"mm","length":1600,"width":650,"height":750}}, + "002":{"material":"板材","dimensions":{"unit":"mm","depth":400,"secondaryHeight":120}} + }}); + w.creation_brief["name"] = json!(""); + w.creation_brief["barcodeBindings"] = json!({"default":["001"]}); + w.creation_brief["barcodeEntries"] = json!([{ + "id":"kept","barcode":"001","material":"","dimensions":{"unit":"cm","length":"161","height":""},"images":[] + }]); + w.creation_brief["manualFields"] = json!(["name","barcode-card:kept:material","barcode-card:kept:dimensions.height"]); + let doc = app.session.active().unwrap().doc.id.0; + let receipt = json!({"doc":doc,"origin":w.origin,"accountId":w.account["id"],"platformBrief":incoming}); + received(&mut w, &app, "creation-product-platform", &receipt); + assert_eq!(w.creation_brief["name"], ""); + let rows = w.creation_brief["barcodeEntries"].as_array().unwrap(); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0]["id"], "kept"); + assert_eq!(rows[0]["material"], ""); + assert_eq!(rows[0]["dimensions"], json!({"unit":"cm","length":"161","width":"65","height":""})); + assert_eq!(rows[1]["barcode"], "002"); + assert_eq!(rows[1]["dimensions"]["width"], "400"); + assert_eq!(rows[1]["dimensions"]["secondaryHeight"], "120"); + } + + #[test] + fn readiness_checklist_highlights_required_intake_fields_and_opens_model_picker() { + let (mut w, mut app, _) = barcode_fixture(); + w.creation_brief["name"] = json!(""); + w.creation_brief["intake"]["schema"]["productFields"] = json!([ + {"id":"origin","label":"产地","type":"text","required":true} + ]); + w.model_ready = false; + w.image_ready = false; + let ctx = egui::Context::default(); + w.reduce_motion = true; + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 900.0, vec![]); } + + let req_chip = control_rect(&w, "readiness-intake-product:origin").center(); + brief_frame(&mut w, &mut app, &ctx, 900.0, click_events(req_chip)); + assert!(w.creation_reads.inline_errors.contains_key("intake-product:origin")); + + let model_btn = control_rect(&w, "select-model").center(); + brief_frame(&mut w, &mut app, &ctx, 900.0, click_events(model_btn)); + assert!(w.model_settings); + } + + fn brief_settings_harness(size: egui::Vec2) -> (egui_kittest::Harness<'static, PhotocraftApp>, mpsc::Receiver) { + let (tx, requests) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut w = Workspace::new(tx, rx); + w.account = json!({"id":"qa"}); + w.origin = "http://localhost:3138".into(); + w.busy = None; + w.reduce_motion = true; + w.creation_catalog.insert("brands".into(), vec![]); + w.creation_catalog.insert("materials".into(), vec![]); + w.configure_client_update(json!({"version":"1.0.0"}), true, |_| Ok(())); + w.begin_staged_new_project(&app); + w.key_saved = true; + app.jiansun = Some(w); + let mut h = egui_kittest::Harness::builder() + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(size) + .build_ui_state(|ui, app| { + if stitch_ui::ui_fonts_ready(ui) { + crate::panels::right_dock(app, ui); + } + }, app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(5); + (h, requests) + } + + #[test] + fn brief_footer_settings_stays_open_after_models_become_ready() { + use egui_kittest::kittest::{NodeT, Queryable}; + + let (mut h, requests) = brief_settings_harness(vec2(1440.0, 900.0)); + let footer = control_rect(h.state().jiansun.as_ref().unwrap(), "select-model"); + h.query_all_by_label("选择模型") + .find(|button| footer.contains(button.rect().center())).unwrap().click(); + h.run_steps(4); + let title = h.get_by_label("小壹设置").accesskit_node().locate(); + assert!(h.query_by_label("对话模型").is_some()); + assert!(h.query_by_label("生图模型").is_some()); + let checks = requests.try_iter().filter(|request| { + matches!(request, Request::Action(method, input) if method == "client-update" && input["op"] == "check") + }).count(); + assert_eq!(checks, 1); + + let w = h.state_mut().jiansun.as_mut().unwrap(); + w.model_ready = true; + w.image_ready = true; + for _ in 0..4 { + h.step(); + assert_eq!(h.get_by_label("小壹设置").accesskit_node().locate(), title); + } + assert!(h.state().jiansun.as_ref().unwrap().creation_view_geometry["controls"]["select-model"].is_null()); + + h.get_by_label("关闭模型设置").click_accesskit(); + h.run_steps(3); + assert!(h.query_by_label("小壹设置").is_none()); + let w = h.state().jiansun.as_ref().unwrap(); + assert!(!w.model_settings); + assert_eq!(w.agent_page(h.state()), "brief"); + } + + #[test] + fn brief_copilot_opens_one_settings_popup() { + use egui_kittest::kittest::Queryable; + + let (mut h, _requests) = brief_settings_harness(vec2(1440.0, 900.0)); + let footer = control_rect(h.state().jiansun.as_ref().unwrap(), "select-model"); + assert!(h.query_by_label("建项协作者").is_some()); + assert_eq!(h.query_all_by_label("选择模型").count(), 2); + h.query_all_by_label("选择模型") + .find(|button| !footer.contains(button.rect().center())).unwrap().click(); + h.run_steps(4); + assert_eq!(h.query_all_by_label("小壹设置").count(), 1); + assert!(h.query_by_label("对话模型").is_some()); + assert!(h.query_by_label("生图模型").is_some()); + assert!(!h.state().jiansun.as_ref().unwrap().key_settings); + } + + #[test] + fn brief_key_warning_opens_the_personal_key_editor_from_both_surfaces() { + use egui_kittest::kittest::Queryable; + + for from_footer in [true, false] { + let (mut h, requests) = brief_settings_harness(vec2(1440.0, 900.0)); + let w = h.state_mut().jiansun.as_mut().unwrap(); + w.key_saved = false; + w.model_ready = true; + w.image_ready = true; + h.run_steps(4); + assert!(h.query_by_label("选择模型").is_none()); + assert_eq!(h.query_all_by_label("配置个人 Key").count(), 2); + let footer = control_rect(h.state().jiansun.as_ref().unwrap(), "configure-personal-key"); + h.query_all_by_label("配置个人 Key") + .find(|button| footer.contains(button.rect().center()) == from_footer).unwrap().click(); + h.run_steps(4); + let w = h.state().jiansun.as_ref().unwrap(); + assert!(w.model_settings && w.key_settings); + assert!(h.query_by_label("小壹设置").is_some()); + assert!(h.query_by_label("模型 API Key").is_some()); + assert!(requests.try_iter().any(|request| { + matches!(request, Request::Action(method, input) if method == "client-update" && input["op"] == "check") + })); + } + } + + #[test] + fn brief_footer_opens_settings_with_the_agent_dock_collapsed_or_switched() { + use egui_kittest::kittest::Queryable; + + for collapsed in [true, false] { + let size = vec2(760.0, 650.0); + let (mut h, _requests) = brief_settings_harness(size); + let app = h.state_mut(); + if collapsed { + app.ui.dock.set_collapsed(crate::dock::Group::Color, true); + } else { + app.ui.dock_tabs.color = 0; + } + h.run_steps(4); + assert!(h.query_by_label("建项协作者").is_none()); + h.get_by_label("选择模型").click(); + h.run_steps(4); + let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, size); + assert!(viewport.contains_rect(h.get_by_label("小壹设置").rect())); + assert!(viewport.contains_rect(h.get_by_label("关闭模型设置").rect())); + assert!(h.query_by_label("对话模型").is_some()); + assert!(h.query_by_label("生图模型").is_some()); + + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(h.query_by_label("小壹设置").is_none()); + assert_eq!(h.state().jiansun.as_ref().unwrap().agent_page(h.state()), "brief"); + } + } + + #[test] + fn reopening_saved_incomplete_projects_resumes_the_missing_step_with_the_saved_draft() { + let template = json!({"id":"template","version":"1","contentHash":"a".repeat(64),"brandId":"brand","categoryId":"category"}); + let images = json!([{"source":format!("local:{}", "a".repeat(64)),"purpose":"product","name":"餐桌正面"}]); + for (stage, canvas_first) in [(Some(CreationStage::Source), false), (Some(CreationStage::Template), false), + (Some(CreationStage::Details), false), (None, true)] + { + let ctx = egui::Context::default(); + let (tx, _requests) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + w.account = json!({"id":"owner"}); + w.origin = "http://localhost:3138".into(); + w.busy = Some("open".into()); + w.library = true; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut opened = photocraft_engine::Session::new(); + opened.execute("file.new", json!({"name":"餐桌草稿","width":64,"height":64})).unwrap(); + let doc = opened.active().unwrap().doc.as_ref().clone(); + let id = doc.id.0; + let mut brief = empty_brief(); + brief["note"] = json!("保留用户填写的备注"); + if matches!(stage, Some(CreationStage::Template | CreationStage::Details)) { + brief["images"] = images.clone(); + } + if stage == Some(CreationStage::Details) { + brief["brandId"] = json!("brand"); + brief["categoryId"] = json!("category"); + brief["templateSelection"] = template.clone(); + } + let workflow = json!({"canvasFirst":canvas_first}); + assert_eq!(incomplete_brief_stage(&brief, &workflow, |_| true), stage); + let (revision, draft_revision) = if stage == Some(CreationStage::Template) { + (0, Value::Null) + } else { + (4, json!(4)) + }; + let card = json!({"source":"native","id":"saved-project","briefIncomplete":stage.is_some(),"briefResumeStage":stage}); + let mut meta = card.clone(); + meta["localId"] = json!("saved-project"); + meta["path"] = json!("saved-project.pcraft"); + meta["accountId"] = w.account["id"].clone(); + meta["origin"] = json!(w.origin); + let _ = ctx.settle_ui(egui::RawInput::default(), |ui| { + w.receive_opened(&mut app, ui.ctx(), Box::new(doc.clone()), meta.clone()); + assert_eq!(w.creation_open, stage.is_some()); + w.receive_json_draft(&mut app, ui.ctx(), json!({"doc":id,"localId":"saved-project", + "creationDraft":{"revision":draft_revision,"brief":brief}})); + w.receive_creation_ui(&app, "creation-read", &json!({"doc":id,"accountId":"owner","origin":w.origin, + "creation":{"revision":revision,"brief":empty_brief()},"templateWorkflow":workflow})); + }); + assert_eq!(w.creation_brief, brief); + if let Some(stage) = stage { + assert_eq!(w.creation_step, 0); + assert_eq!(w.creation_reads.wizard_stage, Some((w.creation_field_scope(&app), stage))); + assert_eq!(w.agent_page(&app), "brief"); + w.handle_wizard_navigation(&app, WizardFooterOutcome::Cancel); + assert_eq!(w.agent_page(&app), "projects"); + w.request_project_open(&mut app, card).unwrap(); + assert_eq!(w.creation_reads.wizard_stage, Some((w.creation_field_scope(&app), stage))); + assert_eq!(w.agent_page(&app), "brief"); + } else { + assert_eq!(w.agent_page(&app), "canvas"); + } + } + } + + #[test] + fn staged_import_uses_a_new_document_and_preserves_the_active_draft() { + let (mut w, mut app, requests) = brief_fixture(); + let old_doc = app.session.active().unwrap().doc.id.0; + let old_draft = w.creation_draft(); + w.begin_staged_new_project(&app); + w.creation_brief["note"] = json!("新项目简报"); + assert_eq!(w.creation_draft(), old_draft); + assert_eq!(app.session.documents().len(), 1); + w.creation_action(&mut app, "creation-import", json!({"paths":["D:/references/new.png"]})).unwrap(); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected reference import") }; + assert_eq!(method, "creation-import"); + assert_ne!(input["doc"], old_doc); + assert_eq!(input["brief"]["note"], "新项目简报"); + assert_eq!(app.session.documents().len(), 2); + assert_eq!(app.session.documents()[0].doc.id.0, old_doc); + } + + #[test] + fn structured_barcode_save_sends_entries_and_legacy_template_values() { + let (mut w, mut app, requests) = brief_fixture(); + let schema = json!([{"id":"length","type":"number","unit":"mm"},{"id":"material","type":"text"}]); + w.creation_brief["intake"] = json!({"schema":{"version":1,"barcodeFields":schema},"productValues":{"origin":"佛山"},"barcodeValues":{}}); + let mut rows = vec![wizard::barcode_row("0007", &json!("oak"), &json!("原木色"), &Value::Null)]; + rows[0]["dimensions"] = json!({"length":"180","width":"85","height":"75","unit":"cm"}); + rows[0]["material"] = json!("白蜡木"); + write_legacy_barcode_fields(&mut w.creation_brief, &mut rows, &schema); + w.creation_brief["barcodeEntries"] = json!(rows); + w.creation_action(&mut app, "creation-save", json!({})).unwrap(); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected brief save") }; + let brief = &input["brief"]; + assert_eq!(method, "creation-save"); + assert_eq!(brief["barcodeEntries"][0]["barcode"], "0007"); + assert_eq!(brief["barcodeBindings"]["oak"], json!(["0007"])); + assert_eq!(brief["detailBarcode"], "0007"); + assert_eq!(brief["dimensions"], brief["barcodeEntries"][0]["dimensions"]); + assert_eq!(brief["intake"]["barcodeValues"]["0007"]["length"].as_f64(), Some(1800.0)); + assert_eq!(brief["intake"]["barcodeValues"]["0007"]["material"], "白蜡木"); + assert_eq!(brief["intake"]["productValues"]["origin"], "佛山"); + } + + #[test] + fn staged_new_project_defers_document_creation_until_entering_canvas() { + let (tx, requests) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + w.busy = None; + w.account = json!({"id":"qa"}); + w.origin = "http://localhost:3138".into(); + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + + w.begin_staged_new_project(&app); + assert!(app.session.documents().is_empty(), "starting a new project must not eagerly spawn an empty canvas tab"); + assert!(w.creation_reads.staged_new_project); + assert_eq!(w.agent_page(&app), "brief"); + + w.creation_brief["name"] = json!("延迟建档餐桌"); + w.creation_brief["brandId"] = json!("brand"); + w.creation_brief["brandName"] = json!("品牌A"); + w.creation_brief["categoryId"] = json!("cat"); + w.creation_brief["categoryName"] = json!("餐桌"); + w.creation_brief["images"] = json!([{"source":"local:img","name":"白底.png","purpose":"product"}]); + w.creation_brief["templateSelection"] = json!({ + "id":"tpl","name":"标准模板","version":"1.0","contentHash":"a".repeat(64),"brandId":"brand","categoryId":"cat" + }); + use egui_kittest::kittest::Queryable; + w.reduce_motion = true; + let mut harness = egui_kittest::Harness::builder() + .with_size(vec2(900.0, 900.0)) + .with_context_setup(|ctx| { + PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }) + .build_ui_state(|ui, state: &mut (Workspace, PhotocraftApp)| { + egui::CentralPanel::default().frame(egui::Frame::NONE) + .show(ui, |ui| state.0.creation_ui(&mut state.1, ui)); + }, (w, app)); + harness.run_steps(3); + assert!(harness.state().1.session.documents().is_empty(), "editing staged brief keeps session clean"); + for (button, stage) in [("下一步:选择模板", CreationStage::Template), ("下一步:填写产品资料", CreationStage::Details)] { + harness.get_by_label(button).click(); + harness.run_steps(3); + assert_eq!(harness.state().0.creation_reads.wizard_stage.unwrap().1, stage); + } + harness.get_by_label("进入模板画布").click(); + harness.run(); + let (w, app) = harness.state(); + assert_eq!(app.session.documents().len(), 1, "entering canvas materializes the document"); + assert!(!w.creation_reads.staged_new_project); + assert!(requests.try_iter().any(|r| matches!(r, Request::Save(_, _, _)))); + } + + #[test] + fn merge_platform_brief_skips_intake_when_incoming_lacks_or_changes_template() { + let mut edited = HashSet::new(); + edited.insert("intake-product:origin".to_owned()); + edited.insert("intake-barcode:SKU001:size".to_owned()); + + let current = json!({ + "name": "老款实木餐桌", + "intake": { + "templateId": "tpl-a", + "schema": {"version": 1}, + "productValues": {"origin": "广东佛山"}, + "barcodeValues": {"SKU001": {"size": "1.6米"}} + } + }); + + let incoming_no_intake = json!({"name": "新平台餐桌"}); + let (merged_null, preserved_null) = + merge_platform_brief_preserving_manual_edits(¤t, &incoming_no_intake, &edited); + assert_eq!(preserved_null, 0); + assert!(merged_null.get("intake").is_none()); + + let incoming_other_template = json!({ + "name": "新平台餐桌", + "intake": { + "templateId": "tpl-b", + "schema": {"version": 1}, + "productValues": {"origin": "默认产地"}, + "barcodeValues": {"SKU001": {"size": "1.8米"}} + } + }); + let (merged_other, preserved_other) = + merge_platform_brief_preserving_manual_edits(¤t, &incoming_other_template, &edited); + assert_eq!(preserved_other, 0); + assert_eq!(merged_other["intake"]["productValues"]["origin"], "默认产地"); + assert_eq!(merged_other["intake"]["barcodeValues"]["SKU001"]["size"], "1.8米"); + + let incoming_same_template = json!({ + "name": "新平台餐桌", + "intake": { + "templateId": "tpl-a", + "schema": {"version": 1}, + "productValues": {"origin": "平台产地"}, + "barcodeValues": {"SKU001": {"size": "平台尺寸"}} + } + }); + let (merged_same, preserved_same) = + merge_platform_brief_preserving_manual_edits(¤t, &incoming_same_template, &edited); + assert_eq!(preserved_same, 2); + assert_eq!(merged_same["intake"]["productValues"]["origin"], "广东佛山"); + assert_eq!(merged_same["intake"]["barcodeValues"]["SKU001"]["size"], "1.6米"); + } + + #[test] + fn test_product_presets_and_consecutive_saves_sync_revision_without_conflict() { + let (mut w, mut app, requests) = brief_fixture(); + w.creation["revision"] = json!(1); + w.creation_plan = w.creation["plan"]["screens"].clone(); + w.creation_failed_signature = "old-failed-signature".into(); + let mut preset_brief = empty_brief(); + preset_brief["name"] = json!("超管预置商品"); + preset_brief["brandId"] = json!("brand-a"); + preset_brief["brandName"] = json!("品牌A"); + preset_brief["categoryId"] = json!("cat-a"); + preset_brief["categoryName"] = json!("品类A"); + + w.apply_test_preset(&app, preset_brief.clone()); + assert!(w.creation_failed_signature.is_empty()); + assert!(w.creation_dirty); + + w.creation_action(&mut app, "creation-save", json!({})).unwrap(); + let Ok(Request::Action(method, first_input)) = requests.try_recv() else { panic!("expected first creation-save"); }; + assert_eq!(method, "creation-save"); + assert_eq!(first_input["brief"]["name"], "超管预置商品"); + + let first_doc = first_input["doc"].clone(); + let first_reply = json!({ + "doc": first_doc, + "accountId": w.account["id"], + "origin": w.origin, + "creation": { + "revision": 2, + "deliveryDir": w.creation_delivery_dir, + "brief": first_input["brief"], + "width": first_input["width"], + "screenCount": 3, + "sellingPoints": {"selected": w.creation_selected, "direction": w.creation_direction, "batches": [], "stale": false}, + "plan": {"status": "idle", "screens": w.creation_plan} + } + }); + received(&mut w, &app, "creation-save", &first_reply); + w.busy = None; + assert_eq!(w.creation["revision"], 2); + assert!(!w.creation_dirty); + + w.creation_brief["templateSelection"] = json!({ + "id": "tpl-2", + "name": "老模板", + "version": "1", + "contentHash": "a".repeat(64), + "brandId": "brand-a", + "categoryId": "cat-a" + }); + w.creation_dirty = true; + w.creation_action(&mut app, "creation-save", json!({})).unwrap(); + let mut second_input = None; + while let Ok(req) = requests.try_recv() { + if let Request::Action(m, inp) = req && m == "creation-save" { + second_input = Some(inp); + } + } + let second_input = second_input.expect("expected second creation-save"); + assert_eq!(second_input["revision"], 2); + let second_reply = json!({ + "doc": first_doc, + "accountId": w.account["id"], + "origin": w.origin, + "creation": { + "revision": 3, + "deliveryDir": w.creation_delivery_dir, + "brief": second_input["brief"], + "width": second_input["width"], + "screenCount": 3, + "sellingPoints": {"selected": w.creation_selected, "direction": w.creation_direction, "batches": [], "stale": false}, + "plan": {"status": "idle", "screens": w.creation_plan} + } + }); + received(&mut w, &app, "creation-save", &second_reply); + assert_eq!(w.creation["revision"], 3); + assert_eq!(w.creation_brief["templateSelection"]["id"], "tpl-2"); + } + + #[test] + fn template_compatibility_warnings_render_as_non_blocking_warning_and_allow_next_step() { + use egui_kittest::kittest::Queryable as _; + let (mut w, app, _requests) = brief_fixture(); + w.creation_read_scope(&app); + w.reduce_motion = true; + w.creation_open = true; + w.creation_step = 0; + w.library = false; + w.material = false; + w.creation_brief["brandId"] = json!("ekb:brand:test"); + w.creation_brief["brandName"] = json!("测试品牌"); + w.creation_brief["categoryId"] = json!("ekb:category:test"); + w.creation_brief["categoryName"] = json!("测试品类"); + w.creation_brief["templateSelection"] = Value::Null; + let version = format!("map-{}", "a".repeat(64)); + let set_row = json!({ + "id": "b".repeat(32), + "name": "老版本兼容模板", + "key": "TPL-LEGACY", + "brandId": "ekb:brand:test", + "categoryId": "ekb:category:test" + }); + w.creation_reads.resource_set = set_row.clone(); + w.creation_reads.resource_component = "detail".into(); + w.creation_catalog.insert("templates".into(), vec![set_row]); + w.creation_catalog.insert("resource-set".into(), vec![json!({ + "id": "detail", + "name": "详情页", + "kind": "detail", + "previews": [] + })]); + w.creation_catalog.insert("resource-component".into(), vec![json!({ + "id": "detail", + "choice": { + "id": "tpl-compat", + "name": "老版本兼容模板", + "version": version, + "contentHash": "a".repeat(64), + "brandId": "ekb:brand:test", + "categoryId": "ekb:category:test", + "width": 1440, + "enterprise": { + "adapterVersion": 4, + "sourceKind": "resource-map", + "snapshotVersion": version, + "resourceSetId": "b".repeat(32), + "componentId": "detail" + }, + "compatibilityWarnings": ["模板缺少映射版本信息,已按兼容模式加载"] + } + })]); + w.creation_reads.wizard_stage = Some((w.creation_field_scope(&app), CreationStage::Template)); + + let mut harness = egui_kittest::Harness::builder() + .with_size(vec2(1024.0, 820.0)) + .with_context_setup(|ctx| { + PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }) + .build_ui_state( + |ui, (w, app): &mut (Workspace, PhotocraftApp)| { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| w.creation_ui(app, ui)); + }, + (w, app), + ); + harness.run_steps(4); + assert_eq!( + harness.state().0.creation_brief["templateSelection"]["compatibilityWarnings"], + json!(["模板缺少映射版本信息,已按兼容模式加载"]) + ); + assert!(harness.query_by_label("模板缺少映射版本信息,已按兼容模式加载").is_some()); + let next_btn = harness.get_by_label("下一步:填写产品资料"); + next_btn.click(); + harness.run_steps(2); + let (w, _) = harness.state(); + assert_eq!(w.creation_reads.wizard_stage.unwrap().1, CreationStage::Details); + assert_eq!( + w.creation_brief["templateSelection"]["compatibilityWarnings"], + json!(["模板缺少映射版本信息,已按兼容模式加载"]) + ); + } + + #[test] + #[ignore = "Vulkan wizard visual inspection; requires PHOTOCRAFT_AGENT_QA_OUT"] + fn creation_wizard_visual_acceptance() { + let _gpu = photocraft_testkit::gpu_lock(); + let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory")); + std::fs::create_dir_all(&directory).unwrap(); + for (width, height) in [(1440.0, 900.0), (960.0, 720.0)] { + for (name, stage) in [("source", CreationStage::Source), ("template", CreationStage::Template), ("details", CreationStage::Details)] { + let (mut w, app, requests) = brief_fixture(); + w.reduce_motion = true; + w.creation_open = true; + w.creation_step = 0; + w.library = false; + w.material = false; + w.key_saved = false; + w.creation_brief["dimensions"] = json!({"length":"1800","width":"850","height":"750","unit":"mm"}); + if stage == CreationStage::Source { + w.creation_brief = empty_brief(); + } else if stage == CreationStage::Details { + w.creation_brief["barcodeBindings"]["oak"] = json!(["DNZ030516N717V01"]); + w.creation_brief["identifier"] = json!("DNZ030516"); + } + w.creation_reads.wizard_stage = Some((w.creation_field_scope(&app), stage)); + let mut setup = eframe::egui_wgpu::WgpuSetupCreateNew::without_display_handle(); + setup.instance_descriptor.backends = eframe::wgpu::Backends::VULKAN; + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(width, height)) + .with_context_setup(|ctx| { + PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }) + .wgpu_setup(eframe::egui_wgpu::WgpuSetup::CreateNew(setup)) + .build_ui_state( + |ui, state: &mut Box<(Workspace, PhotocraftApp)>| { + let (w, app) = &mut **state; + egui::Panel::right("qa-brief-copilot").resizable(false).exact_size(330.0) + .frame(egui::Frame::NONE.fill(Tokens::get(ui.ctx()).agent().dock)) + .show(ui, |ui| stitch_ui::scope(ui, |ui| w.brief_copilot_header_ui(app, ui))); + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| w.creation_ui(app, ui)); + }, + Box::new((w, app)), + ); + h.run_steps(4); + let image = h.render().unwrap(); + assert_eq!(image.dimensions(), (width as u32, height as u32)); + image.save(directory.join(format!("wizard-{name}-{width}x{height}.png"))).unwrap(); + drop(requests); + } + } + } + + #[test] + fn review_hints_parse_both_strings_and_structured_targets_and_jump_switches_output() { + let mut hints = Vec::new(); + parse_review_hints( + &json!([ + "详情页:固定图层「旧卖点」保留了模板旧文字,请人工核对。", + { "message": "主图 S01 字体已回退", "outputId": "main_images", "slotId": "S01", "layerId": "L9" }, + "详情页:固定图层「旧卖点」保留了模板旧文字,请人工核对。" + ]), + &mut hints, + ); + assert_eq!(hints.len(), 2); + assert_eq!(hints[0].output_id.as_deref(), Some("detail")); + assert_eq!(hints[1].output_id.as_deref(), Some("main_images")); + assert_eq!(hints[1].slot_id.as_deref(), Some("S01")); + assert_eq!(hints[1].layer_id.as_deref(), Some("L9")); + + let (mut w, app, requests) = brief_fixture(); + let doc_id = app.session.active().unwrap().doc.id.0; + w.library = false; + w.loaded_draft = Some(doc_id); + w.open_projects.insert(doc_id, w.local_identity("proj-1")); + w.sync_confirm = true; + w.creation_open = true; + w.jump_to_review_hint(&app, &hints[1]); + assert!(!w.sync_confirm); + assert!(!w.creation_open); + let dispatched: Vec<_> = requests.try_iter().collect(); + let queued_slot_switch = w.pending_slot_apply.as_ref().is_some_and(|pending| { + pending["outputId"] == "main_images" + && pending["slotId"] == "S01" + && pending["layerId"] == "L9" + }); + let direct_slot_switch = dispatched.iter().any(|req| { + matches!( + req, + Request::Action(method, input) + if method == "slot-skeleton" + && input["outputId"] == "main_images" + && input["slotId"] == "S01" + && input["layerId"] == "L9" + ) + }); + assert!(queued_slot_switch || direct_slot_switch, "expected slot-skeleton jump to main_images/S01/L9, error={}", w.error); + } + + #[test] + fn enter_creation_canvas_switches_to_canvas_immediately_and_recovers_on_early_error() { + let (mut w, mut app, _requests) = brief_fixture(); + w.creation_open = true; + w.creation_step = 0; + w.library = false; + w.material = false; + let template = json!({"id": "tpl-fast", "title": "极速模板"}); + w.enter_creation_canvas(&mut app, &template, true, Some(false)); + assert!(!w.creation_open, "should switch off creation form immediately"); + assert_eq!(w.creation_step, 3, "should switch to canvas step immediately"); + assert!(!w.library && !w.material); + assert!(w.product_start_queued, "should queue product preparation"); + + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + w.receive_json_event(&mut app, &ctx, "slot-skeleton".into(), Err("模板原稿缺失,请检查模板".into())); + assert!(!w.product_start_queued); + assert_eq!(w.error, "模板原稿缺失,请检查模板"); + } + +#[cfg(test)] +mod delivery_dir_tests { + use super::*; +use crate::jiansun::{stitch_kit, stitch_state::Tone}; +use crate::theme::agent_scale::space; + use std::sync::mpsc; + + #[test] + fn default_delivery_dir_prefers_desktop_then_documents() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path(); + let docs = home.join("Documents"); + std::fs::create_dir_all(&docs).unwrap(); + assert_eq!(default_delivery_dir_for_home(home).as_deref(), docs.join("小壹成品").to_str()); + + let desktop = home.join("Desktop"); + std::fs::create_dir_all(&desktop).unwrap(); + assert_eq!(default_delivery_dir_for_home(home).as_deref(), desktop.join("小壹成品").to_str()); + } + + #[test] + fn begin_staged_new_project_remembers_last_delivery_dir() { + let (tx, _rx) = mpsc::channel(); + let (_, event_rx) = mpsc::channel(); + let mut w = Workspace::new(tx, event_rx); + let session = photocraft_engine::Session::new(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + + remember_delivery_dir(&mut app, "/tmp/custom-xiaoyi-output"); + w.begin_staged_new_project(&app); + assert_eq!(w.creation_delivery_dir.as_deref(), Some("/tmp/custom-xiaoyi-output")); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/wizard_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/wizard_ui.rs new file mode 100644 index 00000000..cc0a4924 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/wizard_ui.rs @@ -0,0 +1,431 @@ +use super::super::{PhotocraftApp, Tokens, Ui, Value, Workspace, json, stitch_kit, stitch_state::Tone, stitch_ui}; +use super::super::creation_reads::wizard::{self, CreationStage, WizardFooterOutcome, WizardFooterState}; +use super::REFERENCE_DROP_HINT; +use super::barcode::{project_barcodes, replace_barcode, structured_barcode_field, write_legacy_barcode_fields}; +use super::brief::{non_empty_str, normalized_product_summary, selected_template, selected_visual_asset_count, template_identity}; +use super::form_widgets_ui::{brief_section_break, edit_named, field_key, field_kind, intake_hint, preview_size}; +use super::reducers::form_editable; +use super::structure_preview_ui::wizard_column; +use crate::theme::{AGENT_SEMANTIC, agent_scale::{Type, icon, radius, space}}; +use egui::vec2; + +impl Workspace { + pub(in crate::jiansun) fn creation_wizard_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, pad_x: i8) { + let scope = self.creation_field_scope(app); + let selected = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + let has_template = template_identity(&selected); + let mut stage = self.creation_reads.wizard_stage + .filter(|(owner, _)| *owner == scope) + .map(|(_, stage)| stage) + .unwrap_or_else(|| wizard::resolve_initial_stage(self.creation_reads.staged_new_project, has_template)); + if wizard::ensure_default_barcode(&mut self.creation_brief) { + wizard::migrate_legacy_top_dimensions_to_barcode(&mut self.creation_brief); + } + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(pad_x, 12)).show(ui, |ui| { + wizard_column(ui, |ui| { + wizard::wizard_stepper_ui(ui, &mut stage, true, has_template, self.reduce_motion); + stitch_ui::divider(ui); + }); + }); + self.creation_reads.wizard_stage = Some((scope, stage)); + + let pending_id = scope.with("wizard-barcode-pending"); + let barcode_pending = ui.data(|data| data.get_temp::(pending_id)).unwrap_or(false); + let background = Tokens::get(ui.ctx()).agent().dock; + egui::Panel::bottom("creation-sticky-footer") + .resizable(false) + .show_separator_line(true) + .frame(egui::Frame::NONE.fill(background).inner_margin(egui::Margin::symmetric(pad_x, 7))) + .show(ui, |ui| wizard_column(ui, |ui| { + if stage == CreationStage::Details { + self.brief_footer_ui(app, ui, barcode_pending); + } else { + self.reference_drop_warning_ui(ui); + let setup_warning = self.brief_setup_warning(); + let key_saved = self.key_saved; + let mut open_settings = false; + let mut cfg_rect = None; + let action = wizard::wizard_footer_ui_with_status( + ui, + WizardFooterState { + stage, + can_continue: form_editable(self.busy.as_deref(), self.unknown) + && (stage == CreationStage::Source || has_template), + can_enter_canvas: false, + can_start: false, + }, + true, + |ui| { + if let Some((message, _, action)) = setup_warning { + let configure = stitch_ui::action_button(ui, action, stitch_ui::ButtonRole::Quiet, true).on_hover_text(message); + cfg_rect = Some(configure.rect); + if configure.clicked() { + open_settings = true; + } + } + }, + |_, _| {}, + ); + if let Some(rect) = cfg_rect { + self.control_geometry(if key_saved { "select-model" } else { "configure-personal-key" }, rect); + } + if open_settings { + self.open_brief_setup_settings(); + } + self.handle_wizard_navigation(app, action); + } + })); + if !self.editing_product_brief() || self.creation_step != 0 { + return; + } + let (scope, stage) = self.creation_reads.wizard_stage.unwrap_or((scope, stage)); + let opacity = wizard::stage_reveal_opacity(ui.ctx(), scope.with("wizard-reveal"), stage, self.reduce_motion); + ui.spacing_mut().scroll.floating = true; + let scrolled = egui::ScrollArea::vertical().id_salt((scope, stage)).auto_shrink([false, false]).show(ui, |ui| { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(pad_x, 12)).show(ui, |ui| { + wizard_column(ui, |ui| { + ui.multiply_opacity(opacity); + let title = ui.label(egui::RichText::new(stage.title()).font(Type::TitleLg.semibold()).color(Tokens::get(ui.ctx()).agent().text)); + self.control_geometry("brief-title", title.rect); + ui.add_space(space::SM); + self.creation_notices_ui(app, ui); + let editable = form_editable(self.busy.as_deref(), self.unknown && !self.scoped_production_pending()); + ui.add_enabled_ui(editable, |ui| { + let width = ui.available_width(); + if stage != CreationStage::Template { + self.test_preset_ui(app, ui); + } + match stage { + CreationStage::Source => self.wizard_source_ui(app, ui, scope, width), + CreationStage::Template => { + let np = normalized_product_summary(&self.creation_brief); + self.unmatched_platform_taxonomy_chips_ui(app, ui, &np); + self.template_and_brand_block_ui(app, ui, width); + } + CreationStage::Details => { + let pending = self.wizard_details_ui(app, ui, scope, width, editable); + ui.data_mut(|data| data.insert_temp(pending_id, pending)); + } + } + }); + }); + }); + }); + self.control_geometry("product-form-viewport", scrolled.inner_rect.intersect(ui.clip_rect())); + } + + pub(in crate::jiansun) fn handle_wizard_navigation(&mut self, app: &PhotocraftApp, action: WizardFooterOutcome) { + let Some((scope, stage)) = self.creation_reads.wizard_stage else { return }; + let next = match (stage, action) { + (_, WizardFooterOutcome::Cancel) => { + self.retain_creation_ui_draft(app); + self.creation_reads.new_project_doc = None; + if self.creation_reads.staged_new_project { + self.creation_reads.staged_new_project = false; + self.creation_restore_draft = self.creation_reads.staged_prior_draft.take().unwrap_or(Value::Null); + self.show_center(super::CenterView::Projects, app.session.active().is_some()); + self.creation_open = false; + } else if self.template_workflow["canvasFirst"] != true { + self.show_center(super::CenterView::Projects, app.session.active().is_some()); + } else { + self.set_creation_destination(3); + self.creation_open = false; + } + return; + } + (CreationStage::Source, WizardFooterOutcome::Next) | (CreationStage::Details, WizardFooterOutcome::Back) => CreationStage::Template, + (CreationStage::Template, WizardFooterOutcome::Next) => CreationStage::Details, + (CreationStage::Template, WizardFooterOutcome::Back) => CreationStage::Source, + _ => return, + }; + self.creation_reads.wizard_stage = Some((scope, next)); + } + + + pub(in crate::jiansun) fn reference_drop_warning_ui(&mut self, ui: &mut Ui) { + if self.creation_reads.reference_import_error == REFERENCE_DROP_HINT { + let status = stitch_ui::status_label(ui, REFERENCE_DROP_HINT, stitch_ui::StatusTone::Warning); + self.control_geometry("reference-import-error", status.rect); + } + } + + pub(in crate::jiansun) fn wizard_source_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32) { + self.source_picker(ui); + ui.add_space(space::MD); + match self.creation_brief["source"].as_str() { + Some("product_platform") => { + let np = normalized_product_summary(&self.creation_brief); + self.platform_spu_ui(app, ui, scope, width, np.has_platform_data); + if np.has_platform_data { + stitch_kit::label(ui, format!("已同步 {} 张素材", selected_visual_asset_count(&self.creation_brief)), Type::Meta, Tone::Success); + } + if !self.creation_reads.platform_sync_note.is_empty() { + stitch_kit::label(ui, &self.creation_reads.platform_sync_note, Type::Meta, Tone::Quiet); + } + } + Some("library") => { + self.product_search_button(app, ui); + self.product_select_results(app, ui); + } + _ => { + self.poll_imported_reference_previews(app, ui.ctx()); + wizard::section_heading_with_tip(ui, "本机资料", "支持 PNG、JPG、WebP。每次最多 8 张,单张不超过 20 MB。"); + ui.add_space(space::XS); + let rect = self.reference_picker(app, ui, width, scope.with("source-drop"), + Some(("拖入产品图片或文件夹", "拖入图片或文件夹,或点击浏览文件")), Value::Null); + self.control_geometry("reference-add", rect); + if ui.is_enabled() && let Some(target) = self.reference_drop_geometry(app, ui, rect) { + self.creation_view_geometry["referenceDrop"] = target; + } + ui.add_space(space::XS); + let count = self.creation_brief["images"].as_array().map_or(0, Vec::len); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = space::MD; + if stitch_ui::action_button(ui, "选择文件夹", stitch_ui::ButtonRole::Quiet, true).clicked() { + self.open_reference_dialog(app, Value::Null, true); + } + if count > 0 { + stitch_kit::label(ui, format!("已添加 {count} 张图片"), Type::Meta, Tone::Success); + } + }); + if count > 0 { + ui.add_space(space::XS); + let t = Tokens::get(ui.ctx()).agent(); + let images = self.creation_brief["images"].as_array().cloned().unwrap_or_default(); + let mut remove_idx = None; + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(space::SM, space::SM); + for (idx, img) in images.iter().enumerate() { + let src = img["source"].as_str().unwrap_or(""); + let name = img["name"].as_str().unwrap_or("产品图片"); + let key = super::creation_reads::reference_key(src); + ui.vertical(|ui| { + ui.set_width(76.0); + ui.spacing_mut().item_spacing.y = 4.0; + let (thumb_rect, thumb_resp) = ui.allocate_exact_size(vec2(76.0, 76.0), egui::Sense::hover()); + ui.painter().rect_filled(thumb_rect, radius::ROW, t.field); + ui.painter().rect_stroke(thumb_rect, radius::ROW, egui::Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); + if ui.is_rect_visible(thumb_rect) && !src.is_empty() { + self.queue_creation_reference(app, src); + } + if let Some(tex) = self.creation_thumbs.get(&key).cloned() { + let size = preview_size(tex.size_vec2(), thumb_rect.shrink(3.0).size()); + let fit = egui::Align2::CENTER_CENTER.align_size_within_rect(size, thumb_rect); + ui.painter().image(tex.id(), fit, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text); + self.material_preview(thumb_resp, &key, name, &tex); + } else { + crate::icons::paint(ui, thumb_rect, "image", icon::MD, t.text_dim); + } + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + ui.add_sized( + vec2(54.0, 18.0), + egui::Label::new(egui::RichText::new(name).font(Type::Meta.font_id()).color(t.text_dim)).truncate(), + ).on_hover_text(name); + if stitch_ui::icon_button(ui, "trash", 18.0, false, "移除此图片").clicked() { + remove_idx = Some(idx); + } + }); + }); + } + }); + if let Some(idx) = remove_idx + && let Some(list) = self.creation_brief["images"].as_array_mut() + && idx < list.len() + { + list.remove(idx); + self.creation_dirty = true; + } + } + if !self.creation_reads.reference_import_error.is_empty() && self.creation_reads.reference_import_error != REFERENCE_DROP_HINT { + stitch_ui::status_label(ui, &self.creation_reads.reference_import_error, stitch_ui::StatusTone::Error); + } + brief_section_break(ui); + wizard::section_heading_with_tip(ui, "文字简报(选填)", "可填写产品用途、需要呈现的卖点和制作要求。"); + ui.add_space(space::XS); + if edit_named(ui, (scope, "source-note"), &mut self.creation_brief["note"], width, true, + "输入产品说明或制作要求", "文字简报") + { + self.creation_reads.manual_edited_fields.insert("note".into()); + self.creation_dirty = true; + } + } + } + } + + pub(in crate::jiansun) fn wizard_barcode_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32) -> bool { + let seeded = wizard::ensure_default_barcode(&mut self.creation_brief); + if seeded { + wizard::migrate_legacy_top_dimensions_to_barcode(&mut self.creation_brief); + } + let previous = self.creation_brief["barcodeEntries"].as_array().cloned().unwrap_or_default(); + let mut rows = previous.clone(); + let schema = self.creation_brief["intake"]["schema"]["barcodeFields"].clone(); + let fields = schema.as_array().into_iter().flatten() + .filter(|field| field_kind(field) != "image" && !structured_barcode_field(field)) + .collect::>(); + let images = schema.as_array().into_iter().flatten().filter(|field| field_kind(field) == "image").collect::>(); + + self.poll_imported_reference_previews(app, ui.ctx()); + let hint = |key| schema.as_array().into_iter().flatten() + .find(|field| structured_barcode_field(field) && field_key(field) == key).map(intake_hint).unwrap_or(""); + let mut open_image_for_barcode: Option = None; + let action = wizard::barcode_cards_section_ui( + ui, + scope, + &mut rows, + self.reduce_motion, + hint, + |ui, id, slot| match slot { + wizard::BarcodeSlotRender::Image { row, size, editable: editable_slot } => { + let t = Tokens::get(ui.ctx()).agent(); + let code = non_empty_str(&row["barcode"]); + let matched_sources: Vec<(String, String)> = self.creation_brief["images"] + .as_array() + .into_iter() + .flatten() + .filter(|img| code.is_some() && img["barcode"].as_str() == code) + .filter_map(|img| Some((img["source"].as_str()?.to_owned(), img["name"].as_str().unwrap_or("条码图片").to_owned()))) + .collect(); + let sense = if editable_slot && code.is_some() { egui::Sense::click() } else { egui::Sense::hover() }; + let (rect, resp) = ui.allocate_exact_size(vec2(size, size), sense); + ui.painter().rect_filled(rect, radius::ROW, t.field); + let stroke_color = if resp.hovered() && editable_slot && code.is_some() { t.primary_bg } else { t.card_border }; + ui.painter().rect_stroke(rect, radius::ROW, egui::Stroke::new(1.0, stroke_color), egui::StrokeKind::Inside); + if let Some((first_src, first_name)) = matched_sources.first() { + if ui.is_rect_visible(rect) { + self.queue_creation_reference(app, first_src); + } + let key = super::creation_reads::reference_key(first_src); + if let Some(tex) = self.creation_thumbs.get(&key).cloned() { + let fit_sz = preview_size(tex.size_vec2(), rect.shrink(2.0).size()); + let fit = egui::Align2::CENTER_CENTER.align_size_within_rect(fit_sz, rect); + ui.painter().image(tex.id(), fit, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text); + } else { + crate::icons::paint(ui, rect, "image", if size >= 48.0 { icon::MD } else { icon::SM }, t.text_dim); + } + if matched_sources.len() > 1 { + let badge = egui::Rect::from_min_size(egui::pos2(rect.right() - 18.0, rect.bottom() - 15.0), vec2(17.0, 14.0)); + ui.painter().rect_filled(badge, 3.0, egui::Color32::from_rgba_unmultiplied(15, 16, 18, 210)); + ui.painter().text(badge.center(), egui::Align2::CENTER_CENTER, format!("{}", matched_sources.len()), Type::Meta.font_id(), t.text); + } + let tip = if editable_slot { format!("{first_name}(点击继续添加条码图)") } else { first_name.clone() }; + let resp = resp.on_hover_text(tip); + if resp.clicked() && let Some(c) = code { + open_image_for_barcode = Some(c.to_owned()); + } + } else { + crate::icons::paint(ui, rect, if editable_slot { "plus" } else { "image" }, if size >= 48.0 { icon::MD } else { icon::SM }, t.text_dim); + let tip = if !editable_slot { + "暂无条码专属图片" + } else if code.is_some() { + "点击为该条码添加图片" + } else { + "请先填写条码编码,再添加图片" + }; + let resp = resp.on_hover_text(tip); + if resp.clicked() && let Some(c) = code { + open_image_for_barcode = Some(c.to_owned()); + } + } + } + wizard::BarcodeSlotRender::Related { row } => { + let Some(code) = non_empty_str(&row["barcode"]) else { return; }; + if !project_barcodes(&self.creation_brief).any(|existing| existing == code) { return; } + if !fields.is_empty() || !images.is_empty() { + self.barcode_intake_ui(app, ui, id, width, code, &fields, &images); + } + } + }, + ); + if let Some(code) = open_image_for_barcode { + self.open_reference_dialog(app, json!({"scope":"barcode","barcode":code,"purpose":"product","multiple":true}), false); + } + if let Some(index) = action.remove_index { + rows.remove(index); + } + if action.add_barcode || rows.is_empty() { + rows.push(wizard::barcode_row("", &Value::Null, &Value::Null, &Value::Null)); + } + if action.changed { + for row in &rows { + let Some(id) = row["id"].as_str() else { continue; }; + let Some(old) = previous.iter().find(|previous| previous["id"] == id) else { continue; }; + for field in ["material", "boardType", "colorName"] { + if row[field] != old[field] { + self.creation_reads.manual_edited_fields.insert(format!("barcode-card:{id}:{field}")); + } + } + for axis in ["length", "width", "height", "depth", "secondaryHeight", "unit"] { + if row["dimensions"][axis] != old["dimensions"][axis] { + self.creation_reads.manual_edited_fields.insert(format!("barcode-card:{id}:dimensions.{axis}")); + } + } + } + for old in &previous { + let Some(code) = non_empty_str(&old["barcode"]) else { continue; }; + let new = rows.iter().find(|row| row["id"] == old["id"]).and_then(|row| non_empty_str(&row["barcode"])); + if new != Some(code) { + self.creation_reads.manual_edited_fields.insert(format!("removed-barcode:{code}")); + replace_barcode(&mut self.creation_brief, code, new); + if let Some(new) = new + && let Some(assets) = self.creation_brief.get_mut("normalizedProduct").and_then(|value| value.get_mut("assets")).and_then(Value::as_array_mut) + { + for asset in assets.iter_mut().filter(|asset| asset["barcode"] == code) { + asset["barcode"] = json!(new); + } + } + if let Some(variants) = self.creation_brief.get_mut("normalizedProduct").and_then(|value| value.get_mut("variants")).and_then(Value::as_array_mut) { + for variant in variants { + if let Some(barcodes) = variant["barcodes"].as_array_mut() { + if let Some(new) = new { + for row in barcodes.iter_mut().filter(|row| row["barcode"] == code) { + row["barcode"] = json!(new); + } + } else { + barcodes.retain(|row| row["barcode"] != code); + } + } + } + } + } + } + write_legacy_barcode_fields(&mut self.creation_brief, &mut rows, &schema); + self.creation_dirty = true; + } + if self.creation_brief["barcodeEntries"] != Value::Array(rows.clone()) { + self.creation_brief["barcodeEntries"] = Value::Array(rows); + } + let codes: Vec = project_barcodes(&self.creation_brief).map(str::to_owned).collect(); + if codes.len() > 1 { + ui.add_space(space::SM); + self.detail_barcode_selector_ui(ui, width, scope, &codes); + } + action.pending + } + + pub(in crate::jiansun) fn wizard_details_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32, editable: bool) -> bool { + self.core_identity_and_specs_ui(app, ui, scope, width); + brief_section_break(ui); + let pending = self.wizard_barcode_ui(app, ui, scope, width); + brief_section_break(ui); + self.references_ui(app, ui, width); + brief_section_break(ui); + wizard::section_heading_with_tip(ui, "制作设置", "选择要制作的成品和适用的花色。"); + self.output_tags_ui(ui); + stitch_ui::disclosure(ui, scope.with("wizard-output-colors"), "成品花色范围", false, self.reduce_motion, |ui| { + self.material_select(app, ui, width.min(420.0)); + self.sku_colors_bar_ui(ui, width, scope); + }); + self.special_requirements_ui(ui, scope); + if self.template_workflow["canvasFirst"] != true { + let doc = app.session.active().map(|state| state.doc.id.0); + let id = egui::Id::unique(("production-refinement", self.local_identity(""), doc)); + let _ = self.refinement_ui(ui, Some((id, editable))); + } + self.delivery_directory_control(app, ui, editable); + self.advanced_export_settings_ui(app, ui, scope, width, editable); + pending + } + +}