diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 9f1d95cd..a2651cde 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -1592,10 +1592,19 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { ctx.request_repaint(); }); } else if method == "agent-image-preview" { - match backend.agent_image_preview(&input) { - Ok((reference, image)) => { + let reference_thumbnail = input["taskId"].as_str().is_some_and(images::reference_preview_id); + let preview = if reference_thumbnail { + backend.reference_image_preview(&input) + } else { + backend.agent_image_preview(&input).map(Some) + }; + match preview { + Ok(Some((reference, image))) => { let _ = events.send(Event::Preview(reference, image)); } + // The turn publishes its thumbnail after saving it. + Ok(None) => {} + Err(error) if reference_thumbnail => log::warn!("reference thumbnail unavailable: {error}"), Err(error) => { let _ = events.send(Event::Json(method, Err(error))); } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs index 7d234aab..83689627 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs @@ -22,6 +22,21 @@ pub(super) fn reference_preview_id(id: &str) -> bool { id.strip_prefix("ref-").is_some_and(|digest| digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit())) } +fn read_reference_thumbnail(file: &Path) -> R> { + let file = match fs::File::open(file) { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(_) => return Err("引用预览读取失败".into()), + }; + let mut bytes = Vec::new(); + file.take(256 * 1024).read_to_end(&mut bytes).map_err(|_| "引用预览读取失败")?; + let image = photocraft_codecs::decode_with(&bytes, &photocraft_codecs::DecodeOptions { + limits: photocraft_codecs::Limits { max_width: 256, max_height: 256, max_pixels: 65_536, max_alloc: 1024 * 1024 }, + ..Default::default() + }).map_err(|_| "引用预览无法显示")?.convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8); + Ok(Some(egui::ColorImage::from_rgba_unmultiplied([image.width() as usize, image.height() as usize], image.data()))) +} + pub(super) fn pending(dir: &Path) -> R { let file = dir.join("image-task.json"); Ok(file.exists() && matches!(read_json(&file)?["phase"].as_str(), Some("dispatched" | "unknown" | "running"))) @@ -408,21 +423,19 @@ impl Backend { self.auth["account"] = value["account"].clone(); Ok(()) } + pub(super) fn reference_image_preview(&self, input: &Value) -> R> { + let doc = input["doc"].as_u64().ok_or("项目身份无效")?; + self.ensure_owner(doc)?; + let id = input["taskId"].as_str().filter(|id| reference_preview_id(id)).ok_or("引用预览身份无效")?; + let file = self.project_dir(doc)?.join("reference-previews").join(format!("{id}.jpg")); + Ok(read_reference_thumbnail(&file)?.map(|image| { + (json!({"purpose":"agent-image","doc":doc,"taskId":id,"accountId":self.auth["account"]["id"],"origin":self.origin}), image) + })) + } + pub(super) fn agent_image_preview(&self, input: &Value) -> R<(Value, egui::ColorImage)> { let doc = input["doc"].as_u64().ok_or("项目身份无效")?; self.ensure_owner(doc)?; - if let Some(id) = input["taskId"].as_str().filter(|id| reference_preview_id(id)) { - let file = self.project_dir(doc)?.join("reference-previews").join(format!("{id}.jpg")); - let mut bytes = Vec::new(); - fs::File::open(file).map_err(|_| "引用预览尚未就绪")?.take(256 * 1024).read_to_end(&mut bytes) - .map_err(|_| "引用预览读取失败")?; - let image = photocraft_codecs::decode_with(&bytes, &photocraft_codecs::DecodeOptions { - limits: photocraft_codecs::Limits { max_width: 256, max_height: 256, max_pixels: 65_536, max_alloc: 1024 * 1024 }, - ..Default::default() - }).map_err(|_| "引用预览无法显示")?.convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8); - return Ok((json!({"purpose":"agent-image","doc":doc,"taskId":id,"accountId":self.auth["account"]["id"],"origin":self.origin}), - egui::ColorImage::from_rgba_unmultiplied([image.width() as usize, image.height() as usize], image.data()))); - } let task_id = input["taskId"].as_str().filter(|s| Uuid::parse_str(s).is_ok()).ok_or("图片任务身份无效")?; let dir = self.project_dir(doc)?.join("image-jobs").join(task_id); let task = read_json(&dir.join("task.json"))?; @@ -865,6 +878,29 @@ impl Backend { #[cfg(test)] mod tests { use super::*; + + #[test] + fn reference_thumbnail_is_pending_until_the_jpeg_is_published() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("reference-previews").join("reference.jpg"); + assert!(read_reference_thumbnail(&file).unwrap().is_none()); + fs::create_dir(dir.path().join("reference-previews")).unwrap(); + assert!(read_reference_thumbnail(&file).unwrap().is_none()); + + let thumbnail = egui::ColorImage::filled([7, 5], egui::Color32::WHITE); + let encoded = photocraft_ui_egui::jiansun::reference_jpeg(&thumbnail, 256).unwrap(); + photocraft_format::atomic_write(&file, &STANDARD.decode(encoded).unwrap()).unwrap(); + assert_eq!(read_reference_thumbnail(&file).unwrap().unwrap().size, [7, 5]); + } + + #[test] + fn reference_thumbnail_decode_failure_is_distinct_from_pending() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("corrupt.jpg"); + fs::write(&file, b"not an image").unwrap(); + assert_eq!(read_reference_thumbnail(&file).unwrap_err(), "引用预览无法显示"); + } + #[test] fn layered_native_smart_references_render_without_mutating_the_source() { let mut session = photocraft_engine::Session::new(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs index edcf37eb..d8630b34 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -512,7 +512,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender std::fs::create_dir_all(dir.join("reference-previews")).map_err(|_| "无法保存引用图片")?; photocraft_format::atomic_write(&path, &bytes).map_err(|_| "无法保存引用图片")?; } - if let Ok((meta, image)) = b.agent_image_preview(&json!({"doc":doc,"taskId":id})) { + if let Ok(Some((meta, image))) = b.reference_image_preview(&json!({"doc":doc,"taskId":id})) { let _ = events.send(Event::Preview(meta, image)); ctx.request_repaint(); }