From 2a119f443461ba62cb6d20f31d546f382f43d9d1 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Fri, 27 Nov 2026 10:46:19 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E6=8A=9B=E5=85=89=E5=B0=8F=E5=A3=B9?= =?UTF-8?q?=E5=88=B6=E4=BD=9C=E6=97=B6=E9=97=B4=E6=B5=81=E5=92=8C=E7=AA=84?= =?UTF-8?q?=E7=AA=97=E5=B7=A5=E4=BD=9C=E5=8F=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../crates/ui-egui/src/jiansun/agent_panel.rs | 190 ++++++++++++++++-- .../ui-egui/src/jiansun/agent_stream.rs | 31 ++- .../jiansun/canvas_native_adoption_tests.rs | 7 + .../ui-egui/src/jiansun/canvas_workspace.rs | 52 +++-- .../crates/ui-egui/src/jiansun/creation.rs | 43 +++- .../crates/ui-egui/src/jiansun/stitch_kit.rs | 27 ++- .../ui-egui/src/jiansun/stitch_timeline.rs | 81 ++++---- .../crates/ui-egui/src/jiansun/stitch_ui.rs | 11 +- 8 files changed, 339 insertions(+), 103 deletions(-) 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 45b4aae1..1ff9a149 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 @@ -1185,12 +1185,19 @@ impl Workspace { && (self.template_workflow["canvasFirst"] == true || staged_production || detail_output)) .then(|| if staged_production { self.can_resume_product() } else { detail_output && self.can_start_turn() }); let composer_width = (ui.available_width() - 20.0).max(1.0); - let wrap_suggestions = suggestions.is_some_and(|(_, prompts)| { - use super::agent_stream::{SUGGESTION_GAP, suggestion_width}; - let chips_width = prompts.iter().map(|(label, _)| suggestion_width(ui, label)).sum::() - + SUGGESTION_GAP - + whole_detail.map_or(0.0, |_| suggestion_width(ui, CONTINUE_PRODUCTION) + SUGGESTION_GAP); - chips_width > composer_width + use super::agent_stream::{SUGGESTION_GAP, SuggestionSize}; + let (suggestion_size, wrap_suggestions) = suggestions.map_or((SuggestionSize::Standard, false), |(_, prompts)| { + let width = |size: SuggestionSize| { + prompts.iter().map(|(label, _)| size.width(ui, label)).sum::() + SUGGESTION_GAP + + whole_detail.map_or(0.0, |_| size.width(ui, CONTINUE_PRODUCTION) + SUGGESTION_GAP) + }; + if width(SuggestionSize::Standard) <= composer_width { + (SuggestionSize::Standard, false) + } else if width(SuggestionSize::Compact) <= ui.available_width() - 4.0 { + (SuggestionSize::Compact, false) + } else { + (SuggestionSize::Standard, true) + } }); let suggestion_height = if suggestions.is_none() { 0.0 } else { super::agent_stream::SUGGESTION_ROW_HEIGHT @@ -1198,15 +1205,27 @@ impl Workspace { }; let composer_height = self.composer_notice_height(ui) + 20.0 + self.composer_surface_height(app, ui, composer_width, morph) + suggestion_height; + let compact_suggestions = matches!(suggestion_size, SuggestionSize::Compact); + let inset = if compact_suggestions { 0 } else { 10 }; self.pi_ui_decorations(ui,true); egui::Panel::bottom("jiansun-composer") .resizable(false).show_separator_line(false).exact_size(composer_height) - .frame(Frame::NONE.fill(t.dock).inner_margin(10)) + .frame(Frame::NONE.fill(t.dock).inner_margin(egui::Margin::symmetric(inset, 10))) .show(ui, |ui| { if let Some((key, prompts)) = suggestions { - self.suggestion_row(app, ui, key, prompts, whole_detail, wrap_suggestions); + if compact_suggestions { + Frame::NONE.inner_margin(egui::Margin::symmetric(2, 0)).show(ui, |ui| { + self.suggestion_row(app, ui, key, prompts, whole_detail, suggestion_size, wrap_suggestions); + }); + } else { + self.suggestion_row(app, ui, key, prompts, whole_detail, suggestion_size, wrap_suggestions); + } + } + if compact_suggestions { + Frame::NONE.inner_margin(egui::Margin::symmetric(10, 0)).show(ui, |ui| self.composer_ui(app, ui)); + } else { + self.composer_ui(app, ui); } - self.composer_ui(app, ui); }); self.pi_ui_decorations(ui,false); if production { self.production_head_ui(app, ui); } @@ -1930,7 +1949,10 @@ impl Workspace { return None; } let step = value["step"].as_str().unwrap_or("正在生成图片…"); - let (rect, response) = ui.allocate_exact_size(size, Sense::hover()); + 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::hover()), + ).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)); @@ -2161,7 +2183,7 @@ impl Workspace { suggestions } - fn suggestion_row(&mut self, app: &PhotocraftApp, ui: &mut Ui, key: &str, suggestions: [(&'static str, &'static str); 2], whole_detail: Option, wrap: bool) { + fn suggestion_row(&mut self, app: &PhotocraftApp, ui: &mut Ui, key: &str, suggestions: [(&'static str, &'static str); 2], whole_detail: 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); @@ -2170,7 +2192,7 @@ impl Workspace { ui.spacing_mut().item_spacing = vec2(SUGGESTION_GAP, SUGGESTION_GAP); if let Some(enabled) = whole_detail { let hint = "按图位完成剩余图片,保留已采纳结果和现有图层"; - let response = suggestion_chip(ui, "sparkles", CONTINUE_PRODUCTION, enabled, self.reduce_motion) + 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() { @@ -2179,7 +2201,7 @@ impl Workspace { } } let items = suggestions.map(|(label, _)| ("sparkles", label)); - let responses = timeline::suggestion_row(ui, &items, draft_ready, self.reduce_motion); + 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}"))); @@ -4003,13 +4025,10 @@ mod tests { 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:?}"); - if width > 250.0 { - 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())); - } + 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); } - if width == 250.0 { assert!(previous.unwrap().top() > first.top()); } requests.try_iter().for_each(drop); harness.get_by_label("填入输入框:核对已有结果").click(); @@ -4170,6 +4189,138 @@ mod tests { 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); + }); + }, 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); + 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["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(), 4); + 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(); @@ -7006,14 +7157,13 @@ mod tests { harness.run_steps(12); }; // The head opens in place for the per-slot detail of every sub-agent. - let named = harness.query_all_by_label("D").count(); 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); // Each sub-agent keeps the letter of the summary row, and every badge // shares one width: the waiting one owns no dots but still lines up. - assert_eq!(harness.query_all_by_label("D").count(), named + 1, "复核保留字母:面板宽 {width}"); + assert_eq!(harness.query_all_by_label("D").count(), 1, "复核保留字母:面板宽 {width}"); let rows = w.panel_geometry["productionWorkers"].as_array().unwrap(); assert_eq!(rows.len(), 4, "面板宽 {width}"); assert_eq!(rows[rows.len() - 1]["review"], true); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs index 64e46d37..3f81b9e3 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs @@ -239,29 +239,42 @@ pub(super) fn cell_rail(ui: &mut Ui, id: Id, label: &str, cells: &[Cell], compac json!({"total":count,"filled":filled,"verified":verified,"rect":rect_value(rect),"bar":use_bar,"clicked":clicked}) } -pub(super) fn suggestion_width(ui: &Ui, label: &str) -> f32 { - let font = Type::Title.font_id(); - ui.painter().layout_no_wrap(label.to_owned(), font, Color32::WHITE).size().x + 26.0 +#[derive(Clone, Copy)] +pub(super) enum SuggestionSize { Standard, Compact } + +impl SuggestionSize { + fn metrics(self) -> (Type, f32, f32, f32) { + match self { + Self::Standard => (Type::Title, 13.0, 4.0, 4.0), + Self::Compact => (Type::Caption, 8.0, 1.0, 0.0), + } + } + + pub(super) fn width(self, ui: &Ui, label: &str) -> f32 { + let (font, icon, gap, padding) = self.metrics(); + ui.painter().layout_no_wrap(label.to_owned(), font.font_id(), Color32::WHITE).size().x + icon + gap + padding * 2.0 + } } /// A borderless composer shortcut. Disabled shortcuts keep their place and lose contrast. -pub(super) fn suggestion_chip(ui: &mut Ui, glyph: &str, label: &str, enabled: bool, reduced: bool) -> Response { +pub(super) fn suggestion_chip(ui: &mut Ui, glyph: &str, label: &str, enabled: bool, reduced: bool, size: SuggestionSize) -> Response { let t = Tokens::get(ui.ctx()).agent(); let enabled = enabled && ui.is_enabled(); let background = super::agent_motion::reserve_background(ui); let tint = if enabled { t.text_dim } else { t.text_faint }; - let width = suggestion_width(ui, label); + let width = size.width(ui, label); + let (font, icon, gap, padding) = size.metrics(); let response = ui .allocate_ui_with_layout(vec2(width, SUGGESTION_CHIP_HEIGHT), Layout::left_to_right(egui::Align::Center), |ui| { - ui.spacing_mut().button_padding = vec2(4.0, 5.0); + ui.spacing_mut().button_padding = vec2(padding, 5.0); ui.add_enabled( enabled, egui::Button::image_and_text( - crate::icons::image(glyph, 13.0, tint), - RichText::new(label).font(Type::Title.font_id()).color(tint), + crate::icons::image(glyph, icon, tint), + RichText::new(label).font(font.font_id()).color(tint), ) .frame(false) - .gap(4.0) + .gap(gap) .min_size(vec2(width, SUGGESTION_CHIP_HEIGHT)), ) }) diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_native_adoption_tests.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_native_adoption_tests.rs index 9a562e6d..1afbeec0 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_native_adoption_tests.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_native_adoption_tests.rs @@ -16,6 +16,13 @@ fn native_adoption_prewarm_single_commit_and_canvas_crossfade() { let _gpu = photocraft_testkit::gpu_lock(); let _guard = ADOPTION_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner()); let (mut workspace, mut app, _requests, layer, bytes) = native_fixture(); + let source = tempfile::tempdir().unwrap(); + let original = source.path().join("original.png"); + let doc = Arc::make_mut(&mut app.session.active_mut().unwrap().doc); + let LayerContent::Smart(smart) = &mut doc.layer_mut(photocraft_doc::LayerId(layer)).unwrap().content else { panic!("smart fixture") }; + let photocraft_doc::SmartSource::Embedded { bytes: original_bytes, .. } = &smart.source else { panic!("embedded fixture") }; + std::fs::write(&original, original_bytes.as_ref()).unwrap(); + smart.source = photocraft_doc::SmartSource::Linked { path: original.to_string_lossy().into_owned() }; warm_fixture_target(&mut app, layer); let active = app.session.active().unwrap(); let doc = active.doc.id.0; diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs index a66c6ab1..da19a969 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs @@ -1792,7 +1792,7 @@ impl Workspace { self.canvas_workspace.professional_controls.clear(); super::stitch_ui::scope(ui, |ui| { ui.horizontal_top(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Min).with_main_wrap(true), |ui| { let canvas_first = self.template_workflow["canvasFirst"] == true; // Allocate the complete right-hand action before the left // controls can consume its space at larger application scales. @@ -1829,7 +1829,8 @@ impl Workspace { { self.canvas_workspace.initial_focus = true; } - let left_width = ui.available_width(); + let room = ui.available_size_before_wrap().x; + let left_width = if room < 290.0 { ui.max_rect().width() } else { room }; ui.allocate_ui_with_layout(vec2(left_width, 40.0), egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true), |ui| { if super::stitch_ui::action_button(ui, "产品资料", super::stitch_ui::ButtonRole::Secondary, true).clicked() { self.creation_open = true; @@ -3449,9 +3450,16 @@ impl Workspace { let id=field["fieldId"].as_str().unwrap_or(""); self.canvas_workspace.geometry.insert(format!("field-state:{status}:{id}"),[rect.min.x,rect.min.y,rect.width(),rect.height()]); } - let label=format!("原稿 · 未处理 {original} 小壹已处理 {processed}{}",if changed>0{format!(" 已修改 {changed}")}else{String::new()}); - let galley=painter.layout_no_wrap(label,FontId::proportional(12.0),t.text); - let badge=Rect::from_min_size(xf.rect.min+vec2(12.0,12.0),galley.size()+vec2(20.0,12.0)); + let mut labels = vec![format!("原稿 · 未处理 {original}"), format!("小壹已处理 {processed}")]; + if changed > 0 { labels.push(format!("已修改 {changed}")); } + let font = crate::theme::agent_scale::Type::Meta.font_id(); + let visible = xf.rect.intersect(ui.clip_rect()); + let width = (visible.width() - 44.0).max(1.0); + let one_line = painter.layout_no_wrap(labels.join(" "), font.clone(), t.text); + let galley = if one_line.size().x <= width { one_line } else { + painter.layout(labels.join("\n"), font, t.text, width) + }; + let badge=Rect::from_min_size(visible.min+vec2(12.0,12.0),galley.size()+vec2(20.0,12.0)); painter.rect_filled(badge,5.0,t.card); painter.galley(badge.min+vec2(10.0,6.0),galley,t.text); } @@ -3749,10 +3757,10 @@ mod tests { let doc = app.session.active().unwrap().doc.id.0; let ctx = egui::Context::default(); w.agent_images.begin_frame(); - let _ = ctx.run_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(pos2(0.0,0.0),vec2(1200.0,800.0))),..Default::default()}, |ui| { + ctx.run_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(pos2(0.0,0.0),vec2(1200.0,800.0))),..Default::default()}, |ui| { let xf = ViewXform {rect:ui.max_rect(),zoom:1.0,center:[1700.0,400.0],flip:false,rotation:0.0,aspect:1.0}; let _ = w.workspace_canvas(&mut app, ui, xf, doc, 1440.0); - }); + }).drop_without_applying_deltas(); w.agent_images.finish_pins(); let requested: Vec<_> = requests.try_iter().filter_map(|request| match request { Request::Action(method, input) if method == "agent-image-preview" => input["taskId"].as_str().map(str::to_owned), @@ -3797,9 +3805,9 @@ mod tests { let xf = ViewXform { rect: Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)), zoom: 0.5, center: [200.0, 250.0], flip, rotation, aspect: 1.0 }; let mut result = None; - let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + ctx.run_ui(egui::RawInput::default(), |ui| { result = Some(candidate_image_shape(ui.ctx(), egui::TextureId::User(42), image, xf, 1.0)); - }); + }).drop_without_applying_deltas(); let egui::Shape::Vec(shapes) = result.unwrap() else { panic!("transformed image should use meshes") }; assert!(!shapes.is_empty()); let bounds = shapes.iter().map(egui::Shape::visual_bounding_rect).reduce(|a, b| a.union(b)).unwrap(); @@ -3884,7 +3892,7 @@ mod tests { for viewport_width in [800.0_f32, 180.0] { let ctx = egui::Context::default(); let mut measured = Vec::new(); - let _ = ctx.run_ui(egui::RawInput { + ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(viewport_width, 600.0))), ..Default::default() }, |ui| { @@ -3896,7 +3904,7 @@ mod tests { } }); }); - }); + }).drop_without_applying_deltas(); let allowed = 176.0_f32.min(viewport_width - 32.0); assert_eq!(measured.len(), 3); assert!(measured.iter().all(|width| *width <= allowed + 1.0), "candidate menu rows exceeded {allowed}: {measured:?}"); @@ -4094,13 +4102,13 @@ mod tests { fn ordinary_native_professional_toolbar_requires_one_current_smart_image() { fn enabled(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { let doc = app.session.active().unwrap().doc.id.0; - let _ = ctx.run_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0,800.0))), ..Default::default() }, |ui| { + ctx.run_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0,800.0))), ..Default::default() }, |ui| { w.canvas_workspace.clear_frame_geometry(); w.workspace_toolbar(app, ui); let xf = ViewXform { rect:Rect::from_min_size(pos2(0.0,50.0),vec2(1200.0,720.0)), zoom:1.0, center:[600.0,400.0], flip:false, rotation:0.0, aspect:1.0 }; let _ = w.workspace_canvas(app, ui, xf, doc, 1440.0); - }); + }).drop_without_applying_deltas(); assert!(w.canvas_workspace.geometry.contains_key("professionalEnter"), "the real toolbar bounds survive the canvas overlay in the same frame"); w.canvas_workspace.professional_controls["professionalEnter"] } @@ -4161,7 +4169,7 @@ mod tests { app.jiansun = Some(w); super::super::begin_frame(&mut app); let ctx = egui::Context::default(); - let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + ctx.run_ui(egui::RawInput::default(), |ui| { let mut w = app.jiansun.take().unwrap(); let apply = super::super::stitch_ui::button(ui, "回填详情页", true); let back = super::super::stitch_ui::button(ui, "返回详情页", false); @@ -4180,7 +4188,7 @@ mod tests { assert_eq!(w.canvas_workspace.geometry["professionalReturn"], [back.rect.min.x,back.rect.min.y,back.rect.width(),back.rect.height()]); assert!(!w.canvas_workspace.geometry.contains_key("unexpected")); app.jiansun = Some(w); - }); + }).drop_without_applying_deltas(); super::super::begin_frame(&mut app); let w = app.jiansun.as_ref().unwrap(); assert!(w.canvas_workspace.geometry.is_empty(), "a hidden toolbar cannot publish the previous frame's clickable bounds"); @@ -5300,7 +5308,7 @@ mod tests { let (mut w, mut app, requests, layer, bytes) = native_fixture(); let ctx = egui::Context::default(); let workflow = w.template_workflow.clone(); - let _ = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())).drop_without_applying_deltas(); w.template_workflow = workflow; assert!(w.enforce_canvas_scope(&app)); while requests.try_recv().is_ok() {} @@ -5317,7 +5325,7 @@ mod tests { std::thread::yield_now(); } events.send(super::super::Event::SlotAdopt {bytes, meta}).unwrap(); - let mut frame = || { let _ = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); }; + let mut frame = || { ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())).drop_without_applying_deltas(); }; frame(); drop(frame); assert_eq!(app.session.active().unwrap().revision, before, "receipt cannot commit on arrival frame"); @@ -5325,7 +5333,7 @@ mod tests { assert!(w.pending()); assert!(requests.try_recv().is_err(), "ACK cannot precede native commit"); while w.canvas_workspace.adoption_preparing() { - let _ = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())).drop_without_applying_deltas(); assert!(std::time::Instant::now() < deadline); std::thread::yield_now(); } @@ -5600,9 +5608,9 @@ mod tests { w.canvas_workspace.candidate_menu = Some(menu); let ctx = egui::Context::default(); for time in [1.0, 1.3] { - let _ = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { super::super::stitch_ui::overlay_transition(ui.ctx(), popup, true, reduced); - }); + }).drop_without_applying_deltas(); } workspace_frame_at(&mut w, &mut app, &ctx, vec![], Some(1.31)); assert_eq!(w.canvas_workspace.candidate_menu.is_some(), !reduced, "exit should be retained only when motion is enabled"); @@ -5632,11 +5640,11 @@ mod tests { let ctx = egui::Context::default(); let doc = app.session.active().unwrap().doc.id.0; let frame = |w: &mut Workspace, app: &mut PhotocraftApp, events| { - let _ = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { let xf = ViewXform { rect: Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0)), zoom: 0.3, center: [2500.0, 850.0], flip: false, rotation: 0.0, aspect: 1.0 }; let _ = w.workspace_canvas(app, ui, xf, doc, 1440.0); - }); + }).drop_without_applying_deltas(); }; frame(&mut w, &mut app, vec![]); let rect = w.canvas_workspace.geometry["image-slot/candidate-one"]; 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 f2d88e54..68af5def 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs @@ -837,25 +837,50 @@ impl Workspace { } pub(super) fn sync_controls(&mut self, app: &PhotocraftApp, ui: &mut Ui) { let changed = self.has_sync_changes(app); - if let Some(status) = self.navigation_sync_status(app) { - stitch_ui::status_label(ui, status, stitch_ui::StatusTone::Neutral); - } + let visible_width = ui.available_rect_before_wrap().intersect(ui.clip_rect()).width().max(1.0); + let compact = visible_width < 220.0; let idle = self.busy.is_none() && self.saving.is_none() && !self.project_operation_pending(); let sync_failed = self.project_operation["phase"] == "failed" && self.project_operation["kind"] == "sync" && self.project_operation["accountId"] == self.account["id"] && self.project_operation["origin"] == self.origin && self.current_sync_item(app).is_some_and(|item| item["id"] == self.project_operation["projectId"]); - let label = if self.project_operation_pending() {"正在处理…"} else if sync_failed {"同步失败"} else if changed {"云同步"} else {"已同步"}; + let status = self.navigation_sync_status(app); + let label = if compact && status == Some("正在同步") {"正在同步"} else if self.project_operation_pending() {"正在处理…"} + else if sync_failed {"同步失败"} else if changed {"云同步"} else {"已同步"}; let chat_option = ui.scope_id().with(("cloud-chat-history", self.origin.as_str(), self.account["id"].as_str(), app.session.active().map(|state| state.doc.id.0))); let mut chat = ui.ctx().data(|data| data.get_temp::(chat_option)).unwrap_or(false); - if ui.add_enabled(idle && changed, egui::Checkbox::new(&mut chat, "同步对话")).changed() { - ui.ctx().data_mut(|data| data.insert_temp(chat_option, chat)); - } let hint = if sync_failed { self.project_operation["message"].as_str().unwrap_or("同步未完成,请查看我的项目") } else { "备份工程和资料到当前素材库账户" }; - if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Secondary, idle && changed && !self.creation_dirty).on_hover_text(hint).clicked() { + let chat_control = |ui: &mut Ui, chat: &mut bool| { + if ui.add_enabled(idle && changed, egui::Checkbox::new(chat, "同步对话")).changed() { + ui.ctx().data_mut(|data| data.insert_temp(chat_option, *chat)); + } + }; + let actions = |ui: &mut Ui, height| { + let sync = stitch_ui::action_button_height(ui, label, stitch_ui::ButtonRole::Secondary, idle && changed && !self.creation_dirty, height) + .on_hover_text(hint).on_disabled_hover_text(hint).clicked(); + let finish = stitch_ui::action_button_height(ui, "完结", stitch_ui::ButtonRole::Primary, idle && !self.unknown && !self.creation_dirty, height).clicked(); + (sync, finish) + }; + let (sync, finish) = if compact { + ui.allocate_ui_with_layout(egui::vec2(visible_width, 38.0), egui::Layout::top_down(egui::Align::Max), |ui| { + ui.spacing_mut().item_spacing = egui::vec2(4.0, 0.0); + ui.spacing_mut().button_padding = egui::vec2(4.0, 1.0); + ui.spacing_mut().interact_size.y = 18.0; + let buttons = ui.horizontal(|ui| actions(ui, 18.0)).inner; + chat_control(ui, &mut chat); + buttons + }).inner + } else { + if let Some(status) = status { + stitch_ui::status_label(ui, status, stitch_ui::StatusTone::Neutral); + } + chat_control(ui, &mut chat); + actions(ui, crate::theme::agent_scale::control::DEFAULT) + }; + if sync { self.sync_action(app, "project-sync", json!({"status":"draft","syncChatHistory":chat})); } - if stitch_ui::action_button(ui, "完结", stitch_ui::ButtonRole::Primary, idle && !self.unknown && !self.creation_dirty).clicked() { + if finish { self.sync_confirm = true; } let closed = stitch_ui::dialog(ui, egui::Id::unique("xiaoyi-finish-project"), "完结项目", self.sync_confirm, self.reduce_motion, 360.0, |ui| { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_kit.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_kit.rs index 30834162..50e7914e 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_kit.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_kit.rs @@ -63,10 +63,12 @@ pub(super) fn inline_notice(ui: &mut Ui, glyph: &str, tone: Tone, title: &str, a ui.allocate_ui_with_layout(vec2(ui.available_width().max(1.0), 0.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.spacing_mut().item_spacing.x = space::SM; action(ui); - let text_width = (ui.available_width() - icon::MD - space::SM).max(1.0); - let text = ui.painter().layout(title.to_owned(), Type::Body.font_id(), t.text, text_width); - ui.add(egui::Label::new(text)); - ui.add(crate::icons::image(glyph, icon::MD, tone.color(&t))) + ui.allocate_ui_with_layout(vec2(ui.available_width().max(1.0), 0.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = space::SM; + let icon = ui.add(crate::icons::image(glyph, icon::MD, tone.color(&t))); + let text = RichText::new(title).font(Type::Body.font_id()).color(t.text); + icon.union(ui.add(egui::Label::new(text).wrap())) + }).inner }).inner }).response } @@ -364,6 +366,23 @@ mod tests { } } + #[test] + fn short_notice_without_an_action_starts_next_to_its_icon() { + let ctx = egui::Context::default(); + fonts(&ctx); + let mut notice = Rect::NOTHING; + let output = render(&ctx, 0.0, |ui| { + ui.set_width(360.0); + notice = inline_notice(ui, "info", Tone::Quiet, "已完成", |_| {}).rect; + }); + let text = output.shapes.iter().find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "已完成" => Some(text.pos), + _ => None, + }).expect("notice text is painted"); + let expected = notice.left() + space::SM + icon::MD + space::SM; + assert!((text.x - expected).abs() <= 1.0, "{text:?} in {notice:?}"); + } + #[test] fn stop_button_has_one_hint_and_two_sizes() { let ctx = egui::Context::default(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs index 9fe163f5..af629ac7 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs @@ -249,8 +249,8 @@ pub(super) fn run_outcome_card(ui: &mut Ui, outcome: RunOutcome<'_>, action: Opt } /// 输入框上方的建议行:只填入草稿,点击后的行为由调用方持有。 -pub(super) fn suggestion_row(ui: &mut Ui, items: &[(&str, &str)], enabled: bool, reduced: bool) -> Vec { - items.iter().map(|(glyph, text)| agent_stream::suggestion_chip(ui, glyph, text, enabled, reduced)).collect() +pub(super) fn suggestion_row(ui: &mut Ui, items: &[(&str, &str)], enabled: bool, reduced: bool, size: agent_stream::SuggestionSize) -> Vec { + items.iter().map(|(glyph, text)| agent_stream::suggestion_chip(ui, glyph, text, enabled, reduced, size)).collect() } // --------------------------------------------------------------------------- @@ -468,23 +468,23 @@ fn paint_ring(ui: &mut Ui, fraction: Option, fill: Color32) { } } -/// 子代理在摘要中自动换行,避免窄栏截掉后续子代理。 -fn worker_summary(ui: &mut Ui, id: egui::Id, workers: &[WorkerState<'_>], compact: bool, reduced: bool) { +/// 子代理与当前步骤成组换行。 +fn worker_summary(ui: &mut Ui, id: egui::Id, workers: &[WorkerState<'_>], reduced: bool) { + let t = Tokens::get(ui.ctx()).agent(); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = vec2(space::SM, space::XS); for worker in workers { let letter = worker_name(worker.number); let hint = format!("子代理 {letter} · {} · {}", worker.stage.label(), worker.slot); - if compact { - caption(ui, format!("{letter} {}", worker.stage.label())).on_hover_text(&hint); - } else { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = space::XS; - let kind = if !worker.active || worker.stage.waiting() { kit::BadgeKind::Neutral } else { kit::BadgeKind::Running }; - kit::badge(ui, id.with(("stage", worker.number)), kind, &letter, reduced).on_hover_text(&hint); - caption(ui, worker.stage.label()); - }); - } + let status = ui.painter().layout_no_wrap(worker.stage.label().into(), Type::Meta.font_id(), Tone::Quiet.color(&t)); + let width = WORKER_BADGE_WIDTH + space::XS + status.size().x; + let group = ui.allocate_ui_with_layout(vec2(width, control::ROW), Layout::left_to_right(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = space::XS; + let kind = if !worker.active || worker.stage.waiting() { kit::BadgeKind::Neutral } else { kit::BadgeKind::Running }; + kit::badge_sized(ui, id.with(("stage", worker.number)), kind, &letter, reduced, WORKER_BADGE_WIDTH); + ui.add(egui::Label::new(status)); + }); + group.response.on_hover_text(hint); } }); } @@ -499,7 +499,7 @@ fn worker_list(ui: &mut Ui, workers: &[WorkerState<'_>], reduced: bool) -> Vec 0).then(|| format!("{} {count}", stage.label())) }).collect::>().join(" · "); if !counts.is_empty() { caption(ui, counts); } - adaptive_grid(ui, ui.scope_id().with("production-workers"), GridColumns { min_cell: 181.0, max_cell: 600.0, most: 2 }, space::SM, workers.len(), |ui, index| { + adaptive_grid(ui, ui.scope_id().with("production-workers"), GridColumns { min_cell: 140.0, max_cell: 600.0, most: 2 }, space::SM, workers.len(), |ui, index| { let Some(worker) = workers.get(index) else { return }; let letter = worker_name(worker.number); let running = worker.active && !worker.stage.waiting(); @@ -543,24 +543,26 @@ fn roadmap(ui: &mut Ui, id: egui::Id, stages: &[GoalStage<'_>], panel: &GoalProg if stage.total > 0 && stage.done >= stage.total { AGENT_SEMANTIC.success } else { AGENT_SEMANTIC.progress }); }); caption(ui, count); - if let Some(elapsed) = stage.elapsed { - caption(ui, format!("· {}", coarse(elapsed))); - } - if let Some(tokens) = stage.tokens { - caption(ui, format!("· {} tokens", compact(tokens))); - } }); + if stage.elapsed.is_some() || stage.tokens.is_some() { + ui.horizontal_wrapped(|ui| { + if let Some(elapsed) = stage.elapsed { caption(ui, coarse(elapsed)); } + if let Some(tokens) = stage.tokens { caption(ui, format!("{} tokens", compact(tokens))); } + }); + } if stage.slots.is_empty() { continue; } - egui::ScrollArea::vertical().id_salt(id.with(("stage-slots", index))).max_height(104.0).show(ui, |ui| ui.horizontal_wrapped(|ui| { + ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = vec2(space::SM, space::XS); for slot in &stage.slots { let text = if slot.state == SlotState::Done { slot.label.to_owned() } else { format!("{} · {}", slot.label, slot.state.label()) }; - let button = kit::icon_action_button(ui, slot.state.glyph(), &text, false, 0.0, true) - .on_hover_text(&text); + let text_width = ui.painter().layout_no_wrap(text.clone(), Type::Title.font_id(), t.text).size().x; + let width = (text_width + icon::LG + space::SM + 2.0 * ui.spacing().button_padding.x).min(ui.max_rect().width()); + let button = ui.allocate_ui_with_layout(vec2(width, control::STANDARD), Layout::left_to_right(egui::Align::Center), + |ui| kit::icon_action_button(ui, slot.state.glyph(), &text, false, width, true).on_hover_text(&text)).inner; if button.clicked() { clicked = Some(slot_index); } slot_index += 1; } - })); + }); } clicked } @@ -604,7 +606,7 @@ where ui.allocate_ui_with_layout(vec2(rest, agent_stream::ROW), Layout::left_to_right(egui::Align::Center), |ui| { ui.spacing_mut().item_spacing.x = space::SM; paint_ring(ui, fraction, ring); - title = ui.add_sized(vec2(ui.available_width().max(1.0), agent_stream::ROW), + title = ui.add( egui::Label::new(RichText::new(heading.as_str()).font(Type::Title.semibold()).color(if waiting { t.warning } else { t.text })).truncate()) .on_hover_text(heading.as_str()).rect; }); @@ -636,21 +638,27 @@ where // 还没有逐格进度时先给一条总进度:颜色与进度格同一套。 rail = Some(kit::progress_bar_tinted(ui, id, &heading, fraction, reduced || !running || waiting, agent_stream::cell_filled(&t)).rect); } - if !panel.workers.is_empty() { + if !expanded && !panel.workers.is_empty() { ui.add_space(space::XS); - worker_summary(ui, id, panel.workers, compact, reduced); + worker_summary(ui, id, panel.workers, reduced); } // 路线图抽屉:展开与收起带实测高度的过渡,收起后不再占位。 let open = expanded && (panel.roadmap.is_some() || !panel.workers.is_empty()); let _drawer = kit::morph_surface(ui, id.with("roadmap"), open, reduced, |ui| { - ui.add_space(space::XS); - if let Some(stages) = panel.roadmap { - slot_clicked = roadmap(ui, id, stages, &panel); - } - if !panel.workers.is_empty() { - workers = worker_list(ui, panel.workers, reduced); - } + egui::ScrollArea::vertical().id_salt(id.with("roadmap-scroll")) + .max_height((ui.available_height() - 100.0).max(72.0)).show(ui, |ui| { + ui.add_space(space::XS); + if !panel.workers.is_empty() { + workers = worker_list(ui, panel.workers, reduced); + } + if let Some(stages) = panel.roadmap { + slot_clicked = roadmap(ui, id, stages, &panel); + } + }); }); + if panel.state == RunState::Running { + caption(ui, "正在推进目标"); + } background }); if toggle_clicked { @@ -777,7 +785,7 @@ mod tests { 2 }); interaction = card.inner; - suggestions = suggestion_row(ui, &[("sparkles", "继续做剩下的 SKU 图"), ("sparkles", "先看详情页草稿")], true, true); + suggestions = suggestion_row(ui, &[("sparkles", "继续做剩下的 SKU 图"), ("sparkles", "先看详情页草稿")], true, true, agent_stream::SuggestionSize::Standard); }); }); assert!(target.height() > 0.0 && head_rect.width() > 0.0); @@ -917,6 +925,7 @@ mod tests { assert!(first.workers.is_empty(), "the list stays closed until asked for"); assert!(drawn.iter().any(|text| text.contains("主图 60%")), "{name}: the current stage reports its share"); assert!(drawn.iter().any(|text| text == "4m / 90m"), "{name}: stage and budget share the second row"); + assert!(drawn.iter().any(|text| text == "正在推进目标")); let _ = click(&ctx, first.toggle.rect.center(), 1.0, |ui| { ui.set_width(width); show(ui, RunState::Running); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs index c1978610..e6d8e925 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs @@ -1371,6 +1371,10 @@ fn primary_button_fills(t: Tokens) -> (Color32, Color32, Color32) { } pub(super) fn action_button(ui: &mut Ui, label: &str, role: ButtonRole, enabled: bool) -> Response { + action_button_height(ui, label, role, enabled, control::DEFAULT) +} + +pub(super) fn action_button_height(ui: &mut Ui, label: &str, role: ButtonRole, enabled: bool, height: f32) -> Response { let t = Tokens::get(ui.ctx()).agent(); let material_slot=super::agent_motion::reserve_background(ui); let (text, fill, hover, pressed, border) = match role { @@ -1388,7 +1392,7 @@ pub(super) fn action_button(ui: &mut Ui, label: &str, role: ButtonRole, enabled: let rule = QuietRule::new(ui, role, enabled); // Reserve the whole control in the parent layout before creating a style // scope: a zero-sized scope cannot wrap an already-painted child row. - let response = ui.allocate_ui_with_layout(Vec2::new(width, control::DEFAULT), egui::Layout::left_to_right(egui::Align::Center), |ui| { + let response = ui.allocate_ui_with_layout(Vec2::new(width, height), egui::Layout::left_to_right(egui::Align::Center), |ui| { let widgets = &mut ui.style_mut().visuals.widgets; for (visual, background) in [ (&mut widgets.inactive, fill), @@ -1405,7 +1409,7 @@ pub(super) fn action_button(ui: &mut Ui, label: &str, role: ButtonRole, enabled: .corner_radius(radius::CONTROL) .stroke(if role==ButtonRole::Secondary || role==ButtonRole::Destructive {Stroke::NONE} else {Stroke::new(1.0, border)}) .wrap_mode(egui::TextWrapMode::Truncate) - .min_size(Vec2::new(width, control::DEFAULT)); + .min_size(Vec2::new(width, height)); let button=if role==ButtonRole::Secondary || role==ButtonRole::Destructive {button.fill(Color32::TRANSPARENT)} else {button}; ui.add_enabled(enabled,button) }).inner; @@ -3311,7 +3315,8 @@ mod tests { }, true); band(ui, top); let top = ui.cursor().top(); - let suggestion = super::super::agent_stream::suggestion_chip(ui, "sparkles", "梳理资料", true, true); + use super::super::agent_stream::{SuggestionSize, suggestion_chip}; + let suggestion = suggestion_chip(ui, "sparkles", "梳理资料", true, true, SuggestionSize::Standard); band(ui, top); let top = ui.cursor().top(); let (reference, remove) = reference_chip_with_preview(ui, "layers", "沙发图层", "沙发图层", 0.0, 132.0, None); From 93de08babf9a6a5180f3de63ff3d0db05322b55f Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Fri, 27 Nov 2026 11:21:09 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=B0=8F=E5=A3=B9?= =?UTF-8?q?=E8=BF=9B=E5=BA=A6=E6=A0=BC=E3=80=81=E6=AD=A3=E6=96=87=E5=8A=A8?= =?UTF-8?q?=E6=95=88=E5=92=8C=E5=B7=A5=E5=85=B7=E5=9B=9E=E6=89=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/detail-agent-pi/src/activity-event.mjs | 6 +- .../test/activity-event.test.mjs | 18 ++ apps/detail-photocraft/DESIGN.md | 7 +- .../crates/ui-egui/src/jiansun/agent_panel.rs | 209 +++++++++--------- .../ui-egui/src/jiansun/agent_stream.rs | 105 +++------ .../crates/ui-egui/src/jiansun/pi_bridge.rs | 52 +---- .../ui-egui/src/jiansun/stitch_state.rs | 24 +- .../ui-egui/src/jiansun/stitch_timeline.rs | 73 ++---- .../crates/ui-egui/src/jiansun/stitch_ui.rs | 185 ++++++++++++++-- 9 files changed, 378 insertions(+), 301 deletions(-) create mode 100644 apps/detail-agent-pi/test/activity-event.test.mjs diff --git a/apps/detail-agent-pi/src/activity-event.mjs b/apps/detail-agent-pi/src/activity-event.mjs index 7c48b84d..84039891 100644 --- a/apps/detail-agent-pi/src/activity-event.mjs +++ b/apps/detail-agent-pi/src/activity-event.mjs @@ -8,7 +8,8 @@ const labels = Object.freeze({ workflow_propose: '添加待审核建议', workflow_execute: '执行创作操作', native_catalog: '查询原生命令', native_call: '执行原生操作', native_reconcile: '核查原生任务', codemode: '组合画布操作', tool_search: '查找工具', canvas_candidate_image: '核对图位和候选', bash: '运行项目终端', - open_production_output: '打开制作画布', + open_production_output: '打开制作画布', produce_current_output: '制作并验收当前输出', + generate_slot_image: '生成候选图片', plan_production: '读取制作进度', start_production_strategy: '准备制作策划', read_production_knowledge: '读取制作规则', read_copy_fields: '查看待处理图文', delegate_image_slots: '分派图片图位', review_image_slots: '查看图位结果', retire_production_image: '清理已退回的候选图', read_slot_images: '查看图位图片', use_product_image: '取用商品实拍', transform_slot_image: '调整候选图片', @@ -21,6 +22,7 @@ const labels = Object.freeze({ plan_page_copy: '规划整页卖点', write_copy_fields: '填写画布文案', review_page_copy: '复核整页文案', }); const safeId = value => typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(value) ? value : undefined; +const safeToolCallId = value => typeof value === 'string' && /^[A-Za-z0-9_.:|-]{1,200}$/.test(value) ? value : undefined; const safeNumber = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined; const operationCategories = Object.freeze({ @@ -99,7 +101,7 @@ export function activitySummary(event) { return details(event).summary; } export function toolActivity(event, scope, timestampMs = Date.now()) { if (!['tool_execution_start', 'tool_execution_end'].includes(event?.type)) return null; - const toolCallId = safeId(event.toolCallId); + const toolCallId = safeToolCallId(event.toolCallId); if (!toolCallId || safeNumber(timestampMs) === undefined) return null; const durationMs = safeNumber(event.durationMs); const activity = details(event); diff --git a/apps/detail-agent-pi/test/activity-event.test.mjs b/apps/detail-agent-pi/test/activity-event.test.mjs new file mode 100644 index 00000000..6a2847ae --- /dev/null +++ b/apps/detail-agent-pi/test/activity-event.test.mjs @@ -0,0 +1,18 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { activityScope, toolActivity } from '../src/activity-event.mjs'; + +test('Responses call IDs join start and completion without widening scope IDs', () => { + const id = 'call_4fca7b5|fc_0c72ae9'; + const scope = activityScope({ scope: 'account', project: 'project' }, { run: 'run' }, {}); + const call = { toolCallId: id, toolName: 'start_production_strategy' }; + const start = toolActivity({ ...call, type: 'tool_execution_start' }, scope, 100); + const end = toolActivity({ ...call, type: 'tool_execution_end', durationMs: 80 }, scope, 180); + assert.equal(start.toolCallId, id); + assert.equal(end.toolCallId, id); + assert.equal(start.status, 'started'); + assert.equal(end.status, 'completed'); + assert.equal(end.summary, '完成:准备制作策划'); + assert.deepEqual(activityScope({ scope: id, project: id }, { run: id }, {}), {}); + assert.equal(toolActivity({ ...call, toolCallId: 'call/foo', type: 'tool_execution_start' }, scope, 100), null); +}); diff --git a/apps/detail-photocraft/DESIGN.md b/apps/detail-photocraft/DESIGN.md index 43da5bf6..683862cb 100644 --- a/apps/detail-photocraft/DESIGN.md +++ b/apps/detail-photocraft/DESIGN.md @@ -421,13 +421,12 @@ Agent 导入的完全透明页面背景以原生“无填充”表达,保留 - 思考:只有一行状态,原文不展示;token 数和速度放在悬停说明里,不占行。 - 通知:按类型取图标;等待中用亮色,核查类用告警色,失败用危险色。同一句状态反复记入时,时间线只显示最新一条,更早的相同记录留在对话数据里不再占一行。 -- 工具调用:标题是“工具调用”加已完成数,展开后是一张任务卡,逐行列出图标、名称、状态徽章和真实耗时。含进行中工具的组首次展开,其余折叠,每组独立记忆自己的开合。耗时按人读的粗细写:1 秒以内写毫秒,10 秒以内保留一位小数,一分钟以内写整秒,再长写几分几秒,统一由 `duration_text` 生成。 -- 回复:正文保持无框;复制按钮只在鼠标指向这条回复或按钮持有焦点时出现。 -- 过程说明:制作轮里,后面还有工具或思考的叙述收成一行,超过一段时带段数,悬停可见首句。点开后是 12 点次要色的段落,缩进与行标题对齐,每段各自记忆开合。最后一次工作之后的回复才是收尾回复,保持 14 点正文。普通对话不折叠。 +- 工具调用:标题是“工具调用”加已完成数,展开后是一张任务卡,逐行列出图标、名称、状态徽章和真实耗时。进行中的工具组自动展开,成功完成后停留 1.2 秒再收起。失败组保持展开,手动开合优先于自动行为。历史成功组默认收起。耗时按人读的粗细写:1 秒以内写毫秒,10 秒以内保留一位小数,一分钟以内写整秒,再长写几分几秒,统一由 `duration_text` 生成。 +- 回复:正文按到达顺序直接显示。新回复逐字入场,流式转为记录时延续当前字形动画,历史正文直接显示。复制按钮只在鼠标指向这条回复或按钮持有焦点时出现。 - 图片结果:标题是“生成图片”或“图片来源”加数量;图片按自身比例排列,说明文字统一为左下角白字衬底。 - 空对话:还没有任何消息时,时间线顶部用几行说明小壹在这里能做哪三件事、从输入框或一条建议开始;没有打开项目时另给“我的项目”入口。第一条消息出现后即消失,不发送任何请求。 -**顶部状态头。** 整套制作期间,状态头固定在对话滚动区上方,向上翻看历史时不动。收起时依次是:标题行(等待指示或时钟、当前步骤、展开钮、停止钮)、图片与文案各一条单行进度格、一行子代理字母与阶段。进度格不折行:格子随宽度收缩到 3 点,更窄时换成同比例的进度条。展开后追加每个子代理的图位与步骤汇总。标题行在窄栏把位置让给步骤名:侧栏不超过 260 点时不放等待指示和时钟,九个字的步骤名完整显示,等待状态由标题的告警色表达。子代理只有一个写法:汇总行和展开列表用同一个字母,展开列表里的胶囊同宽,等待中没有动画点的胶囊也占同样的宽度,图位名从同一列开始。状态头只有一套进度色:还没有图位格子时用同比例的进度条,已填未验同为琥珀。进度数字显示已上画布的数量,含已显示的首图预览和已写入的文案初稿。蓝格显示已核验,悬停可查看单格状态。 +**顶部状态头。** 整套制作期间,状态头固定在对话滚动区上方,向上翻看历史时不动。收起时依次是:标题行(等待指示或时钟、当前步骤、展开钮、停止钮)、图片与文案各有一组独立圆角进度格,子代理字母与阶段按网格排列。进度格保持 5–7 点,空间不足时在对应统计标签右侧换行。展开后追加每个子代理的图位与步骤汇总。标题行在窄栏把位置让给步骤名:侧栏不超过 260 点时不放等待指示和时钟,九个字的步骤名完整显示,等待状态由标题的告警色表达。子代理只有一个写法:汇总行和展开列表用同一个字母,展开列表里的胶囊同宽,等待中没有动画点的胶囊也占同样的宽度,图位名从同一列开始。状态头只有一套进度色:还没有图位格子时用同比例的进度条,已填未验同为琥珀。进度数字显示已上画布的数量,含已显示的首图预览和已写入的文案初稿。蓝格显示已核验,悬停可查看可定位的图片图位。 **生图占位。** 单张生图的等待卡把光球、状态和停止钮左对齐成一行,不再把状态文字撑到卡片正中;卡身仍是这块光涌表面,高度跟随待生成图片的比例。停止后卡片保留到请求结束并整张淡出,状态文字同样靠左。正在生图的图位保留生图请求选定的画幅、光涌和光球,左上角是子代理角标;还在排队的图位收成 32 点高的一行,出图开始时在原位置长成卡片。新卡按首条实际图片进度回执追加,候选在原位置显示预览,角标展示待验图、验图通过、已采纳、未选用、已退回或待核查;退回说明可从候选查阅。列数由侧栏宽度决定。已返回的图片在对话末尾由“图片资源”一行索引,默认折叠。任务待核查时保留原请求,其他图位按已有证据继续。 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 1ff9a149..bf8c3038 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 @@ -599,7 +599,7 @@ fn production_image_cells( #[cfg(test)] fn assistant_reply(ui: &mut Ui, id: Id, text: &str) -> Response { - timeline::reply(ui, id, timeline::Reply { text, streaming: false }, false) + 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 { @@ -1319,7 +1319,7 @@ impl Workspace { let display = product.then(|| production_reply_text(&self.stream_reply, running)); let response = agent_motion::message_visual(ui, stream_enter, |ui| { ui.set_width(column_width); - timeline::reply(ui, reply_id, timeline::Reply { text: display.as_deref().unwrap_or(&self.stream_reply), streaming: running }, self.reduce_motion); + timeline::reply(ui, reply_id, timeline::Reply { text: display.as_deref().unwrap_or(&self.stream_reply), streaming: running, animate_final: false }, self.reduce_motion); if self.unknown { ui.label(RichText::new("输出未完成").small().color(t.warning)); } @@ -1760,7 +1760,10 @@ impl Workspace { if row.clicked() { locate = Some(target.clone()); } } let reply_id = turn_reply_id(conversation_id, turn.user_index); - if let Some(text) = stream { remember_visible_stream(ui, reply_id, text); } + 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, @@ -1770,29 +1773,14 @@ impl Workspace { 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)); - timeline::reply(ui, reply_id, timeline::Reply { text: display.as_deref().unwrap_or(text), streaming: turn_running }, self.reduce_motion); + 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); }; - // Narration that more work follows is process, not the answer. A - // production turn keeps each run of it in one row that opens on - // request; an ordinary conversation still shows every word in place. - let last_work = turn.items.iter() - .rposition(|item| matches!(item, TurnItem::Tools(_) | TurnItem::Thinking(_))); - let mut narration = Vec::new(); for (position, item) in turn.items.into_iter().enumerate() { - if product && last_work.is_some_and(|work| position < work) && let TurnItem::Reply(text, index) = item { - narration.push((production_reply_text(text, false), index)); - continue; - } - if !narration.is_empty() { - let paragraphs = narration.iter().map(|(text, _)| text.as_str()).collect::>(); - super::agent_stream::narration(ui, conversation_id.with(("process-narration", narration[0].1)), ¶graphs, self.reduce_motion); - ui.add_space(8.0); - narration.clear(); - } match item { TurnItem::Thinking(thinking) => { thinking_ui(ui, thinking, turn_running, self.reduce_motion); @@ -1832,11 +1820,10 @@ impl Workspace { paint_stream(ui, text); continue; } - let handoff = if is_last_reply { final_handoff(ui, reply_id, text) } else { None }; - let already_visible = handoff.is_some(); + 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 enter = if already_visible { 1.0 } else { arrival }; - let anchor = if already_visible { reply_id } else { conversation_id.with(("reply", index)) }; + let anchor = reply_id.with(index); let display = product.then(|| production_reply_text(text, false)); let text = display.as_deref().unwrap_or(text); let copy_id = anchor.with("copy"); @@ -1852,20 +1839,21 @@ impl Workspace { ui.ctx().request_repaint(); ui.data_mut(|data| data.insert_temp(copy_id.with("shown"), shown)); } - let response = ui.push_id(anchor, |ui| agent_motion::message_visual(ui, enter, |ui| { - if handoff == Some(ReplyHandoff::Displayed) { - super::stitch_ui::prepare_final_handoff(ui, reply_id, text); + 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); } - let layout_id = if is_last_reply { reply_id } else { reply_id.with(index) }; - timeline::reply(ui, layout_id, timeline::Reply { text, streaming: false }, self.reduce_motion); + 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)); - agent_motion::message_repaint(ui, response.response.rect, enter); ui.add_space(8.0); } TurnItem::Images(first, images) => { @@ -4276,6 +4264,13 @@ mod tests { 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)) @@ -4299,7 +4294,7 @@ mod tests { 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(), 4); + 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(); @@ -4705,7 +4700,7 @@ mod tests { } #[test] - fn cell_rail_stays_on_one_line_and_keeps_its_counts_at_every_dock_width() { + 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); @@ -4724,16 +4719,19 @@ mod tests { }, |ui| { ui.set_width(width); let before = ui.cursor().top(); - let rail = cell_rail(ui, Id::unique(("rail", width as u64)), "文案", &cells, width == 250.0, false, |index| format!("第 {} 项", index + 1)); + 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(), spent)); + 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, spent) in rails { + 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!(rail_height, json!(ROW), "one line, never an orphan cell on a second row"); - assert!(rail_width.as_f64().unwrap() > 200.0); - assert!((spent - ROW).abs() < 8.0, "the rail spends its own row and nothing below it"); + 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); + } } @@ -5242,10 +5240,11 @@ mod tests { 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=="组合画布操作"), "a six-second provider wait is still the same active turn"); + assert!(!gap.iter().any(|(text,_)|text=="组合画布操作"), "completed tools fold during a provider wait"); assert!(gap.iter().find(|(text,_)|text.starts_with("工具调用")).unwrap().1.top() < gap.iter().find(|(text,_)|text==&w.stream_reply).unwrap().1.top()); let header = gap.iter().find(|(text,_)|text.starts_with("工具调用")).unwrap().1.center(); click(&ctx,w,6.3,header); + click(&ctx,w,6.6,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![]); @@ -5264,12 +5263,13 @@ mod tests { 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=="组合画布操作"), "completion does not change disclosure"); + assert!(frame(&automatic,w,31.7,vec![]).iter().any(|(text,_)|text=="组合画布操作"), "the group stays visible during the completion hold"); + assert!(!frame(&automatic,w,32.3,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,32.0,vec![]); + let next = frame(&automatic,w,32.4,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"); @@ -5325,7 +5325,7 @@ mod tests { } #[test] - fn production_narration_folds_between_work_and_opens_in_place() { + 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)), @@ -5368,47 +5368,12 @@ mod tests { } for _ in 0..2 { frame(&ctx, app.jiansun.as_ref().unwrap(), vec![]); } let labels = frame(&ctx, app.jiansun.as_ref().unwrap(), vec![]); - // Two runs of narration, each one closed row; the paragraphs are off screen. - let rows = rows_of(&labels, "过程说明"); - assert_eq!(rows.len(), 2, "{labels:?}"); - assert!(shows(&labels, "2 段"), "the first run counts its two paragraphs: {labels:?}"); - for hidden in ["我先核对原图。", "模板已就绪。", "正在安排图位。"] { - assert!(!shows(&labels, hidden), "{hidden} is folded: {labels:?}"); - } - let (work, thought, answer) = (rows_of(&labels, "工具调用")[0], rows_of(&labels, "已深度思考")[0], rows_of(&labels, "全部图位已完成。")[0]); - assert!(rows[0] < work && work < rows[1] && rows[1] < thought && thought < answer, - "rows {rows:?}, tools {work}, thought {thought}, answer {answer}"); - // The first row opens in place; the second keeps its own closed state. - let point = labels.iter().find(|(text, _)| text.as_str() == "过程说明").unwrap().1.center(); - for pressed in [true, false] { - frame(&ctx, app.jiansun.as_ref().unwrap(), vec![egui::Event::PointerMoved(point), egui::Event::PointerButton { - pos: point, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }]); - } - let labels = frame(&ctx, app.jiansun.as_ref().unwrap(), vec![]); - assert!(shows(&labels, "我先核对原图。") && shows(&labels, "模板已就绪。"), "the first run is open: {labels:?}"); - assert!(!shows(&labels, "正在安排图位。"), "the second run stays closed: {labels:?}"); - let (first, second, work) = (rows_of(&labels, "我先核对原图。")[0], rows_of(&labels, "模板已就绪。")[0], rows_of(&labels, "工具调用")[0]); - assert!(rows_of(&labels, "过程说明")[0] < first && first < second && second < work, - "open paragraphs stay between their row and the work that follows: {labels:?}"); - assert!(requests.try_recv().is_err(), "opening narration never issues a provider or native mutation"); - // The closing reply after the last piece of work is never folded. - { - let w = app.jiansun.as_mut().unwrap(); - w.messages.push(json!({"role":"assistant","kind":"reply","text":"全部图位已完成。"})); - w.stream_reply.clear(); - w.busy = None; - } - let labels = frame(&ctx, app.jiansun.as_ref().unwrap(), vec![]); - assert_eq!(rows_of(&labels, "过程说明").len(), 2, "settled turns keep their folded narration: {labels:?}"); - assert_eq!(rows_of(&labels, "全部图位已完成。").len(), 1, "the closing reply is on screen once: {labels:?}"); - // An ordinary conversation still shows every word in place. - { - let w = app.jiansun.as_mut().unwrap(); - w.messages[0]["text"] = json!("请检查这个图位"); - } - let labels = frame(&ctx, app.jiansun.as_ref().unwrap(), vec![]); - assert!(!shows(&labels, "过程说明") && shows(&labels, "我先核对原图。") && shows(&labels, "正在安排图位。"), - "a conversation turn keeps its narration in place: {labels:?}"); + 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); @@ -5661,7 +5626,9 @@ mod tests { 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.busy = None; + 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, meshes) = handoff_frame(&ctx,w,0.5,id); let (_,rect,alpha,sections) = after.iter().find(|(text,_,_,_)|text=="已完成矩形").unwrap(); assert_eq!(rect.top(), top); @@ -7129,22 +7096,21 @@ mod tests { assert_eq!(copy["total"], 45); assert_eq!(copy["filled"], 37); assert_eq!(copy["verified"], 8); - assert_eq!(copy["bar"], width == 250.0); - assert_eq!(w.panel_geometry["productionImageCells"]["bar"], width == 250.0); + 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!((90.0..=150.0).contains(&head.height()), "状态头保持紧凑:面板宽 {width}, {head:?}"); + 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}"); - // The narrow dock gives the title row to the step's name: nine - // characters of the title size fit with room to spare. let name = geometry(w, "productionTitle"); - assert!(name.width() >= 9.0 * super::super::agent_stream::TEXT_TITLE + 6.0, "标题行放得下九个字:面板宽 {width}, {name:?}"); + 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(); @@ -7425,24 +7391,57 @@ mod tests { } h.run_steps(8); save(&mut h, "expanded"); - // Narration that more work follows is process: one closed row that opens in place. - assert!(h.query_by_label("我先核对商品原图和模板,再安排制作。").is_none(), "closed narration is off screen"); - let narration = h.get_by_label("过程说明").rect().center(); - h.hover_at(narration); - h.run_steps(2); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { - pos: narration, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, - }); - h.run_steps(1); - } - h.run_steps(8); - assert!(h.query_by_label("我先核对商品原图和模板,再安排制作。").is_some(), "opened narration is on screen"); - save(&mut h, "process-open"); + 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":"activity","event":{"version":1,"type":"tool","run":"visual", + "toolCallId":"call_4fca7b5|fc_0c72ae9","toolName":"canvas_read","status":"started"}}), + ]; + 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); + }); + }, 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[2]["event"]["status"] = json!("completed"); + w.messages[2]["event"]["durationMs"] = json!(320); + w.messages.push(json!({"role":"assistant","kind":"reply","text":"首屏原片与文案一致,接下来核对主图的构图和规格。"})); + h.run_steps(19); + save(&mut h, "inline-reveal"); + h.run_steps(89); + save(&mut h, "tool-completion-hold"); + h.run_steps(38); + save(&mut h, "tool-collapsing"); + h.run_steps(60); + save(&mut h, "tool-folded"); + assert!(requests.try_recv().is_err()); + } + #[test] #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] fn response_refinement_visual_acceptance() { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs index 3f81b9e3..6baf1a11 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs @@ -30,7 +30,6 @@ pub(super) fn cell_verified(t: &Tokens) -> Color32 { t.agent_semantic().verified /// no dots. The list gives both the same width so their labels share a column. pub(super) const WORKER_BADGE_WIDTH: f32 = 50.0; /// How much of a folded narration's first line its hover preview carries. -const PREVIEW_CHARS: usize = 48; /// A row's colour only. Rows never animate: the one waiting mark of a turn /// belongs to the status row, so `Active` just brightens the text. @@ -80,7 +79,7 @@ pub(super) fn event_row(ui: &mut Ui, id: Id, row: EventRow<'_>, reduced: bool) - let interactive = !matches!(row.action, RowAction::None); let background = super::agent_motion::reserve_background(ui); let (_, rect) = ui.allocate_space(vec2(width, ROW)); - let response = ui.interact(rect, id, if interactive { Sense::click() } else { Sense::hover() }); + let response = ui.interact(rect, id, if interactive { Sense::click() } else if row.hint.is_some() { Sense::hover() } else { Sense::empty() }); let hover = if interactive && ui.is_rect_visible(rect) { // Keyboard focus lights a row exactly like hover: the rows are the // timeline's links and disclosures, and they have no frame of their own. @@ -135,39 +134,6 @@ pub(super) fn event_row(ui: &mut Ui, id: Id, row: EventRow<'_>, reduced: bool) - if interactive { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response } } -/// The model's narration between two pieces of work in a production turn. -/// Closed, it is one quiet row that counts the paragraphs and previews the -/// first on hover; open, the paragraphs sit under the row's label in the meta -/// size and colour. Events and the closing reply keep the lead either way. -pub(super) fn narration(ui: &mut Ui, id: Id, paragraphs: &[&str], reduced: bool) -> Rect { - let open = ui.data(|data| data.get_temp::(id.with("open"))).unwrap_or(false); - let count = paragraphs.len(); - let first = paragraphs.first().copied().unwrap_or("").lines().next().unwrap_or(""); - let shortened = first.chars().count() > PREVIEW_CHARS; - let preview: String = first.chars().take(PREVIEW_CHARS).chain(shortened.then_some('…')).collect(); - let count = (count > 1).then(|| format!("{count} 段")); - let row = event_row(ui, id, EventRow { - glyph: "message-square", text: "过程说明", meta: count.as_deref(), tone: EventTone::Quiet, - hint: (!preview.is_empty()).then_some(preview.as_str()), action: RowAction::Expand(open), - }, reduced); - let rect = row.rect; - if row.clicked() { - ui.data_mut(|data| data.insert_temp(id.with("open"), !open)); - } - if open { - let t = Tokens::get(ui.ctx()).agent(); - ui.add_space(4.0); - for paragraph in paragraphs { - ui.horizontal_top(|ui| { - ui.add_space(26.0); - ui.add(egui::Label::new(RichText::new(*paragraph).size(TEXT_META).color(t.text_dim)).wrap().selectable(true)); - }); - ui.add_space(4.0); - } - } - rect -} - #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(super) enum Cell { Empty, @@ -175,59 +141,50 @@ pub(super) enum Cell { Verified, } -/// One labelled row of waiting cells. The cells share one line at every dock -/// width: they shrink to 3pt and, past that, give way to a single bar with the -/// same fraction. Nothing here estimates progress; the caller's cells decide. -pub(super) fn cell_rail(ui: &mut Ui, id: Id, label: &str, cells: &[Cell], compact: bool, locate: bool, describe: impl Fn(usize) -> String) -> Value { +/// One rounded cell per item, wrapped within the track to the right of the counts. +pub(super) fn cell_rail(ui: &mut Ui, id: Id, label: &str, cells: &[Cell], locate: bool, describe: impl Fn(usize) -> String) -> Value { let t = Tokens::get(ui.ctx()).agent(); let width = ui.available_width().max(1.0); + let count = cells.len(); let verified = cells.iter().filter(|cell| **cell == Cell::Verified).count(); let filled = cells.iter().filter(|cell| **cell != Cell::Empty).count(); - let counts = format!("{filled}/{}", cells.len()); - let (rect, response) = ui.allocate_exact_size(vec2(width, ROW), Sense::hover()); + let counts = format!("{filled}/{count}"); + let label_galley = ui.painter().layout_no_wrap(label.to_owned(), Type::Meta.font_id(), t.text); + let count_galley = ui.painter().layout_no_wrap(counts.clone(), Type::Meta.font_id(), t.text_dim); + let counts_offset = label_galley.size().x + 6.0; + let lead = counts_offset + count_galley.size().x + 10.0; + let track_width = (width - lead).max(5.0); + let gap = 2.0; + let row_gap = 3.0; + let side = ((track_width + gap) / count.max(1) as f32 - gap).clamp(5.0, 7.0); + let per_row = (((track_width + gap) / (side + gap)).floor() as usize).max(1); + let rows = count.div_ceil(per_row).max(1); + let height = ROW + (rows - 1) as f32 * (side + row_gap); + let (rect, response) = ui.allocate_exact_size(vec2(width, height), Sense::empty()); let summary = format!("{label}已上画布 {counts} · 已核验 {verified}"); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ProgressIndicator, true, &summary)); - if !ui.is_rect_visible(rect) || cells.is_empty() { - return json!({"total":cells.len(),"filled":filled,"verified":verified,"rect":rect_value(rect)}); - } - let painter = ui.painter_at(rect.intersect(ui.clip_rect())); - let label_galley = painter.layout_no_wrap(label.to_owned(), Type::Meta.font_id(), t.text); - let count_galley = painter.layout_no_wrap(counts, Type::Meta.font_id(), t.text_dim); - let counts_left = rect.left() + label_galley.size().x + 6.0; - let lead = counts_left - rect.left() + count_galley.size().x + 10.0; - painter.galley(egui::pos2(rect.left(), rect.center().y - label_galley.size().y * 0.5), label_galley, t.text); - painter.galley(egui::pos2(counts_left, rect.center().y - count_galley.size().y * 0.5), count_galley, t.text_dim); - let track = Rect::from_min_size(egui::pos2(rect.left() + lead, rect.top()), vec2((width - lead).max(1.0), ROW)); - let gap = 2.0; - let count = cells.len(); - let side = ((track.width() - gap * count.saturating_sub(1) as f32) / count as f32).clamp(3.0, 7.0); - let use_bar = compact || (side + gap) * count as f32 - gap > track.width() + 0.5; let mut clicked = None; - if use_bar { - let bar = Rect::from_min_size(egui::pos2(track.left(), rect.center().y - 4.0), vec2(track.width(), 8.0)); - painter.rect_filled(bar, 3.0, t.field); - response.on_hover_text(summary); - for (total, color) in [(filled, cell_filled(&t)), (verified, cell_verified(&t))] { - if total > 0 { - let end = bar.left() + bar.width() * total as f32 / count as f32; - painter.rect_filled(Rect::from_min_max(bar.min, egui::pos2(end, bar.bottom())), 3.0, color); - } - } - } else { + if ui.is_rect_visible(rect) { + let painter = ui.painter_at(rect.intersect(ui.clip_rect())); + let first_center = rect.top() + ROW * 0.5; + painter.galley(egui::pos2(rect.left(), first_center - label_galley.size().y * 0.5), label_galley, t.text); + painter.galley(egui::pos2(rect.left() + counts_offset, first_center - count_galley.size().y * 0.5), count_galley, t.text_dim); for (index, state) in cells.iter().enumerate() { - let origin = egui::pos2(track.left() + index as f32 * (side + gap), rect.center().y - 3.5); - let square = Rect::from_min_size(origin, vec2(side, 7.0)); + let origin = egui::pos2( + rect.left() + lead + (index % per_row) as f32 * (side + gap), + first_center - side * 0.5 + (index / per_row) as f32 * (side + row_gap), + ); + let square = Rect::from_min_size(origin, Vec2::splat(side)); let fill = match state { Cell::Empty => t.card_border, Cell::Filled => cell_filled(&t), Cell::Verified => cell_verified(&t), }; painter.rect_filled(square, 2.0, fill); - let target = if locate { square.expand2(vec2(1.0, (ROW - 7.0) * 0.5)) } else { square }; - let description = describe(index); - let response = ui.interact(target, id.with(index), if locate { Sense::click() } else { Sense::hover() }) - .on_hover_text(&description); if locate { + let target = square.expand2(vec2(gap * 0.5, row_gap * 0.5)); + let description = describe(index); + let response = ui.interact(target, id.with(index), Sense::click()).on_hover_text(&description); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &description)); if response.hovered() || response.has_focus() { painter.rect_stroke(square, 2.0, Stroke::new(1.0, t.text), egui::StrokeKind::Outside); @@ -236,7 +193,7 @@ pub(super) fn cell_rail(ui: &mut Ui, id: Id, label: &str, cells: &[Cell], compac } } } - json!({"total":count,"filled":filled,"verified":verified,"rect":rect_value(rect),"bar":use_bar,"clicked":clicked}) + json!({"total":count,"filled":filled,"verified":verified,"rect":rect_value(rect),"bar":false,"clicked":clicked}) } #[derive(Clone, Copy)] diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs index 95e2642c..4856e6bd 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs @@ -47,51 +47,11 @@ fn tool_activity(w: &Workspace, event: &Value) -> Result { if event["version"] != 1 || event["type"] != "tool" { return Err("工具状态版本无效".into()); } - let call = id(&event["toolCallId"]).ok_or("工具状态编号无效")?; + let call = event["toolCallId"].as_str().filter(|value| { + (1..=200).contains(&value.len()) && value.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"_.:|-".contains(&byte)) + }).ok_or("工具状态编号无效")?; let name = event["toolName"].as_str().ok_or("工具状态名称无效")?; - let label = match name { - "context_read" => "读取项目规则", - "ask_user" => "等待用户回复", - "memory_set" => "记录事实", - "memory_search" => "检索历史", - "tool_develop" => "编写并测试工具", - "tool_run" => "运行工具", - "canvas_read" => "读取画布", - "canvas_template_image" => "读取模板原图", - "bash" => "运行项目终端", - "open_production_output" => "打开制作画布", - "plan_production" => "读取制作进度", "read_production_knowledge" => "读取制作规则", - "read_copy_fields" => "读取画布文字格", "read_slot_images" => "查看图位图片", - "use_product_image" => "取用商品实拍", "transform_slot_image" => "调整候选图片", "prepare_image_request" => "准备生图请求", - "dispatch_image_request" => "生成候选图片", "delegate_image_slots" => "分派图片图位", - "await_image_slots" => "等待子代理回执", "review_image_slots" => "查看图位结果", - "adopt_production_image" => "回填候选图片", "retire_production_image" => "清理已退回的候选图", - "reconcile_image_slots" => "核查图片原请求", - "defer_production_output" => "保留当前草稿", - "read_output_screen" => "查看实际画布", "finish_production" => "提交成品导出", - "canvas_candidate_image" => "核对图位和候选", - "produce_current_output" => "制作并验收当前输出", - "canvas_edit" => "更新图层", - "canvas_preview" => "预览修改", - "copywriting_options" => "生成卖点选项", "copywriting_fields" => "准备逐格文案", - "save_product_strategy" => "保存商品策划", "review_product_strategy" => "核对卖点证据", - "plan_page_copy" => "规划整页卖点", "write_copy_fields" => "填写画布文案", - "review_page_copy" => "复核整页文案", - "check_page_copy" => "发起文案复核", - "check_image_slots" => "发起验图", - "record_screen_check" => "记录本屏复核", - "native_catalog" => "查询原生命令", - "native_call" => "执行原生操作", - "native_reconcile" => "核查原生任务", - "codemode" => "组合画布操作", - "tool_search" => "查找工具", - "workflow_read" => "读取创作进度", - "workflow_navigate" => "切换创作视图", - "workflow_propose" => "添加待审核建议", - "workflow_execute" => "执行创作操作", - "other" => "工具", - _ => return Err("工具状态名称无效".into()), - }; + let label = super::stitch_state::known_tool_label(name).ok_or("工具状态名称无效")?; let state = event["status"].as_str().ok_or("工具状态无效")?; let prefix = match state { "started" => "开始", @@ -1026,9 +986,11 @@ mod tests { #[test] fn tool_activity_uses_real_states_and_never_persists_provider_content() { let (mut w, mut app, mut input) = activity_fixture(); + input["event"]["toolCallId"] = json!("call_4fca7b5|fc_0c72ae9"); action(&mut w, &mut app, "pi-activity", &input).unwrap(); let pos = w.messages.len() - 1; assert_eq!(w.messages[pos]["event"]["status"], "started"); + assert_eq!(w.messages[pos]["event"]["toolCallId"], "call_4fca7b5|fc_0c72ae9"); assert_eq!(w.messages[pos]["text"], "开始:读取画布"); assert!(!w.messages[pos].to_string().contains("PRIVATE_SECRET")); input["event"]["status"] = json!("completed"); @@ -1047,7 +1009,7 @@ mod tests { #[test] fn reconciliation_and_workflow_activity_use_scoped_fixed_labels() { let (w, _, mut input) = activity_fixture(); - for (name, label) in [("native_reconcile", "核查原生任务"), ("workflow_execute", "执行创作操作"), ("canvas_preview", "预览修改"), ("other", "工具")] { + for (name, label) in [("native_reconcile", "核查原生任务"), ("workflow_execute", "执行创作操作"), ("canvas_preview", "预览修改"), ("start_production_strategy", "准备制作策划"), ("read_archived_images", "查找同款历史候选"), ("stage_archived_image", "加入待验历史候选"), ("other", "工具")] { input["event"]["toolName"] = json!(name); let clean = tool_activity(&w, &input["event"]).unwrap(); assert_eq!(clean["summary"], format!("开始:{label}")); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs index 6989294a..b2128772 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs @@ -394,7 +394,11 @@ impl WaitingState { /// 工具的公开名称由本地给出,绝不来自它的参数、输出或错误原文;不认识的一律叫"工具"。 pub(super) fn tool_label(tool: &str) -> &'static str { - match tool { + known_tool_label(tool).unwrap_or("工具") +} + +pub(super) fn known_tool_label(tool: &str) -> Option<&'static str> { + Some(match tool { "context_read" => "读取项目规则", "memory_set" => "记录事实", "memory_search" => "检索历史", @@ -415,11 +419,20 @@ pub(super) fn tool_label(tool: &str) -> &'static str { "copywriting_options" => "生成卖点选项", "copywriting_fields" => "准备逐格文案", "bash" => "运行项目终端", + "open_production_output" => "打开制作画布", + "start_production_strategy" => "准备制作策划", + "read_archived_images" => "查找同款历史候选", + "stage_archived_image" => "加入待验历史候选", + "use_product_image" => "取用商品实拍", + "transform_slot_image" => "调整候选图片", + "prepare_image_request" => "准备生图请求", + "dispatch_image_request" | "generate_slot_image" => "生成候选图片", + "retire_production_image" => "清理已退回的候选图", + "check_page_copy" => "发起文案复核", "plan_production" => "读取制作进度", "read_production_knowledge" => "读取制作规则", - "read_copy_fields" => "读取画布文字格", + "read_copy_fields" => "查看待处理图文", "read_slot_images" => "查看图位图片", - "generate_slot_image" => "生成候选图片", "delegate_image_slots" => "分派图片图位", "check_image_slots" => "发起验图", "record_screen_check" => "记录本屏复核", @@ -439,8 +452,9 @@ pub(super) fn tool_label(tool: &str) -> &'static str { "review_page_copy" => "复核整页文案", "codemode" => "组合画布操作", "tool_search" => "查找工具", - _ => "工具", - } + "other" => "工具", + _ => return None, + }) } /// 工具行的图标:按工具类别,不按状态。 diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs index af629ac7..9c244272 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs @@ -49,36 +49,19 @@ pub(super) fn thinking_row(ui: &mut Ui, id: egui::Id, status: ThinkingStatus, us } /// 4. 工具调用组:计数与成败由数字给出,标题文案由库里拼,调用方不必先拼文案再让库拆回去。 -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(super) struct ToolGroupHead { pub total: usize, pub completed: usize, pub failed: usize, pub active: bool } - -impl ToolGroupHead { - pub(super) fn tone(self) -> Tone { - if self.failed > 0 { Tone::Failure } else if self.active { Tone::Active } else { Tone::Quiet } - } - - pub(super) fn count(self) -> String { - let mut count = format!("{}/{} 已完成", self.completed, self.total); - if self.failed > 0 { - count.push_str(&format!(" · {} 项失败", self.failed)); - } - count - } -} +pub(super) use kit::ToolGroupHead; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct ToolRow<'a> { pub tool: &'a str, pub name: &'a str, pub status: ToolStatus, pub elapsed: Option<&'a str> } pub(super) fn tool_group(ui: &mut Ui, id: egui::Id, head: ToolGroupHead, rows: &[ToolRow<'_>], reduced: bool) { - kit::tool_group_head(ui, id, "工具调用", Some(&head.count()), head.tone(), reduced, |ui| { + kit::tool_group_head(ui, id, "工具调用", Some(&head.count()), head, reduced, |ui| { for (index, row) in rows.iter().enumerate() { kit::task_status_row(ui, id.with(("tool", index)), tool_glyph(row.tool), row.name, row.status, row.elapsed, reduced); } }); } -// 5. 过程说明沿用 `agent_stream::narration`。 - /// 6. 通知:图标与色调取自 `NoticeKind`,失败、待核查、未执行不再共用一个图标。 #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct Notice<'a> { pub kind: NoticeKind, pub text: &'a str, pub hint: Option<&'a str> } @@ -86,20 +69,16 @@ pub(super) struct Notice<'a> { pub kind: NoticeKind, pub text: &'a str, pub hint pub(super) fn notice_row(ui: &mut Ui, id: egui::Id, notice: Notice<'_>, reduced: bool) -> Response { agent_stream::event_row(ui, id, EventRow { glyph: notice.kind.glyph(), text: notice.text, meta: None, tone: notice.kind.tone().into(), - hint: notice.hint.or(Some(notice.text)), action: RowAction::None, + hint: notice.hint, action: RowAction::None, }, reduced) } /// 7. 回复正文:沿用 `stitch_ui::streaming_reply`(含逐字扩散与流式光标)。 #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct Reply<'a> { pub text: &'a str, pub streaming: bool } +pub(super) struct Reply<'a> { pub text: &'a str, pub streaming: bool, pub animate_final: bool } pub(super) fn reply(ui: &mut Ui, id: egui::Id, model: Reply<'_>, reduced: bool) -> Response { - if model.streaming || reduced { - kit::streaming_reply(ui, id, model.text, model.streaming, reduced) - } else { - kit::reply(ui, id, model.text) - } + kit::reply_with_arrival(ui, id, model.text, model.streaming, model.animate_final, reduced) } /// 8. 图片集:标题行加自适应网格;每一格画什么由调用方的闭包决定。 @@ -412,7 +391,6 @@ pub(super) struct GoalProgressResponse { } /// 窄栏阈值:不超过它时主条把整行让给步骤名,流水线收起。 -const NARROW: f32 = 260.0; /// 路线图里阶段名那一列的宽度。 const STAGE_NAME_WIDTH: f32 = 60.0; /// 展开列表里一行子代理的高度。 @@ -453,7 +431,7 @@ fn state_title(state: RunState) -> &'static str { fn paint_ring(ui: &mut Ui, fraction: Option, fill: Color32) { let t = Tokens::get(ui.ctx()).agent(); - let (rect, _) = ui.allocate_exact_size(vec2(icon::LG, icon::LG), egui::Sense::hover()); + let (rect, _) = ui.allocate_exact_size(vec2(icon::LG, icon::LG), egui::Sense::empty()); let center = rect.center(); let radius = icon::LG * 0.5 - 1.5; let painter = ui.painter(); @@ -471,21 +449,15 @@ fn paint_ring(ui: &mut Ui, fraction: Option, fill: Color32) { /// 子代理与当前步骤成组换行。 fn worker_summary(ui: &mut Ui, id: egui::Id, workers: &[WorkerState<'_>], reduced: bool) { let t = Tokens::get(ui.ctx()).agent(); - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(space::SM, space::XS); - for worker in workers { - let letter = worker_name(worker.number); - let hint = format!("子代理 {letter} · {} · {}", worker.stage.label(), worker.slot); - let status = ui.painter().layout_no_wrap(worker.stage.label().into(), Type::Meta.font_id(), Tone::Quiet.color(&t)); - let width = WORKER_BADGE_WIDTH + space::XS + status.size().x; - let group = ui.allocate_ui_with_layout(vec2(width, control::ROW), Layout::left_to_right(egui::Align::Center), |ui| { - ui.spacing_mut().item_spacing.x = space::XS; - let kind = if !worker.active || worker.stage.waiting() { kit::BadgeKind::Neutral } else { kit::BadgeKind::Running }; - kit::badge_sized(ui, id.with(("stage", worker.number)), kind, &letter, reduced, WORKER_BADGE_WIDTH); - ui.add(egui::Label::new(status)); - }); - group.response.on_hover_text(hint); - } + adaptive_grid(ui, id.with("worker-summary"), GridColumns { min_cell: 90.0, max_cell: 140.0, most: 4 }, 8.0, workers.len(), |ui, index| { + let worker = &workers[index]; + let letter = worker_name(worker.number); + let kind = if !worker.active || worker.stage.waiting() { kit::BadgeKind::Neutral } else { kit::BadgeKind::Running }; + ui.allocate_ui_with_layout(vec2(ui.available_width(), control::ROW), Layout::left_to_right(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = space::XS; + kit::badge_sized(ui, id.with(("stage", worker.number)), kind, &letter, reduced, WORKER_BADGE_WIDTH); + ui.add(egui::Label::new(RichText::new(worker.stage.label()).font(Type::Meta.font_id()).color(t.text_dim)).extend()); + }); }); } @@ -508,7 +480,9 @@ fn worker_list(ui: &mut Ui, workers: &[WorkerState<'_>], reduced: bool) -> Vec ui.available_width(); + let slot = ui.add(egui::Label::new(RichText::new(worker.slot).font(Type::Meta.font_id()).color(t.text)).truncate()); + if needs_hint { slot.on_hover_text(worker.slot); } caption(ui, worker.stage.label()); }); badge @@ -558,7 +532,7 @@ fn roadmap(ui: &mut Ui, id: egui::Id, stages: &[GoalStage<'_>], panel: &GoalProg let text_width = ui.painter().layout_no_wrap(text.clone(), Type::Title.font_id(), t.text).size().x; let width = (text_width + icon::LG + space::SM + 2.0 * ui.spacing().button_padding.x).min(ui.max_rect().width()); let button = ui.allocate_ui_with_layout(vec2(width, control::STANDARD), Layout::left_to_right(egui::Align::Center), - |ui| kit::icon_action_button(ui, slot.state.glyph(), &text, false, width, true).on_hover_text(&text)).inner; + |ui| kit::icon_action_button(ui, slot.state.glyph(), &text, false, width, true)).inner; if button.clicked() { clicked = Some(slot_index); } slot_index += 1; } @@ -578,7 +552,6 @@ where let running = panel.state.running(); let can_stop = running || panel.state == RunState::WaitingUser; let waiting = panel.state.waiting(); - let compact = ui.available_width() <= NARROW; let heading = if panel.state == RunState::Running { panel.title.to_owned() } else { format!("{} · {}", state_title(panel.state), panel.title) }; let (done, total) = progress_of(&panel); @@ -608,7 +581,7 @@ where paint_ring(ui, fraction, ring); title = ui.add( egui::Label::new(RichText::new(heading.as_str()).font(Type::Title.semibold()).color(if waiting { t.warning } else { t.text })).truncate()) - .on_hover_text(heading.as_str()).rect; + .rect; }); }); let budget = panel.budget.text(); @@ -629,10 +602,10 @@ where } if show_cells { if !panel.image_cells.is_empty() { - image_cells = agent_stream::cell_rail(ui, id.with("productionImageCells"), "图片", panel.image_cells, compact, true, &describe); + image_cells = agent_stream::cell_rail(ui, id.with("productionImageCells"), "图片", panel.image_cells, true, &describe); } if !panel.copy_cells.is_empty() { - copy_cells = agent_stream::cell_rail(ui, id.with("productionCopyCells"), "文案", panel.copy_cells, compact, false, |index| format!("文案 {}", index + 1)); + copy_cells = agent_stream::cell_rail(ui, id.with("productionCopyCells"), "文案", panel.copy_cells, false, |index| format!("文案 {}", index + 1)); } } else if running && !waiting || fraction.is_some() { // 还没有逐格进度时先给一条总进度:颜色与进度格同一套。 @@ -769,7 +742,7 @@ mod tests { ], true); notice_row(ui, id.with("notice"), Notice { kind: NoticeKind::Failed, text: "主图 4 · 细节特写没生成出来", hint: None }, true); notice_row(ui, id.with("check"), Notice { kind: NoticeKind::NeedsCheck, text: "有一条对话未确认结果", hint: None }, true); - reply(ui, id.with("reply"), Reply { text: "整套已经推进到主图这一步。", streaming: false }, true); + reply(ui, id.with("reply"), Reply { text: "整套已经推进到主图这一步。", streaming: false, animate_final: false }, true); let (heading, cells) = image_set(ui, id.with("images"), ImageSet::conversation("生成图片", Some("2"), 2), true, |ui, _index, _width| { ui.allocate_exact_size(vec2(ui.available_width(), 90.0), egui::Sense::hover()).1.rect }); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs index e6d8e925..54af2e74 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs @@ -155,6 +155,7 @@ pub(super) fn morph_surface(ui: &mut Ui, id: egui::Id, open: bool, reduced: b } /// One selectable native label preserves selection and copying across paragraphs. +#[cfg(test)] pub(super) fn reply(ui: &mut Ui, id: egui::Id, text: &str) -> Response { streaming_reply(ui, id, text, false, false) } @@ -308,15 +309,67 @@ pub(super) fn ai_loader(ui: &mut Ui, id: egui::Id, running: bool, reduced: bool) /// Each group keeps its own disclosure choice as tool states change. The /// heading is the same quiet row as every other timeline event; only an open /// group spends a card on its rows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct ToolGroupHead { pub total: usize, pub completed: usize, pub failed: usize, pub active: bool } + +impl ToolGroupHead { + pub(super) fn tone(self) -> Tone { + if self.failed > 0 { Tone::Failure } else if self.active { Tone::Active } else { Tone::Quiet } + } + + pub(super) fn count(self) -> String { + let mut count = format!("{}/{} 已完成", self.completed, self.total); + if self.failed > 0 { + count.push_str(&format!(" · {} 项失败", self.failed)); + } + count + } +} + /// 工具调用组的外壳:标题行与可折叠的卡片。计数与成败由调用方结构化给出,不从标题文案里拆。 -pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, count: Option<&str>, tone: Tone, reduced: bool, body: impl FnOnce(&mut Ui) -> R) { +#[derive(Clone, Copy, Default)] +struct ToolDisclosure { + open: bool, + user_pinned: Option, + was_active: bool, + finished_at: Option, +} + +impl ToolDisclosure { + const HOLD_SECONDS: f64 = 1.2; + + fn update(&mut self, now: f64, active: bool, failed: bool) { + if active { + self.finished_at = None; + } else if self.was_active && !failed { + self.finished_at = Some(now); + } + self.was_active = active; + self.open = self.user_pinned.unwrap_or_else(|| active || failed + || self.finished_at.is_some_and(|finished| now < finished + Self::HOLD_SECONDS)); + } +} + +pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, count: Option<&str>, head: ToolGroupHead, reduced: bool, body: impl FnOnce(&mut Ui) -> R) { use super::agent_stream::{EventRow, EventTone, RowAction}; - let mut open = ui.data(|data| data.get_temp::(id.with("open"))).unwrap_or(tone == Tone::Active); + let key = id.with("disclosure"); + let now = ui.input(|input| input.time); + let mut state = ui.data(|data| data.get_temp::(key)).unwrap_or_default(); + state.update(now, head.active, head.failed > 0); let header = super::agent_stream::event_row(ui, id.with("header"), EventRow { - glyph: "settings", text: heading, meta: count, tone: EventTone::from(tone), hint: None, action: RowAction::Expand(open), + glyph: "settings", text: heading, meta: count, tone: EventTone::from(head.tone()), + hint: None, action: RowAction::Expand(state.open), }, reduced); - if header.clicked() { open = !open; } - if open { + if header.clicked() { + state.open = !state.open; + state.user_pinned = Some(state.open); + } + if state.open && state.user_pinned.is_none() && head.failed == 0 && ui.is_rect_visible(header.rect) + && let Some(finished) = state.finished_at + { + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((finished + ToolDisclosure::HOLD_SECONDS - now).max(0.0))); + } + morph_surface(ui, id.with("tool-body"), state.open, reduced, |ui| { ui.horizontal(|ui| { ui.add_space(space::MD); surface(ui, SurfaceRole::Task, |ui| { @@ -326,8 +379,8 @@ pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, count }); }); }); - } - ui.data_mut(|data| data.insert_temp(id.with("open"), open)); + }); + ui.data_mut(|data| data.insert_temp(key, state)); } /// 旧签名垫片:标题形如"工具调用 · 3/5 已完成 · 1 项失败",成败仍从文案里读。 @@ -335,8 +388,8 @@ pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, count #[cfg(test)] pub(super) fn tool_group(ui: &mut Ui, id: egui::Id, title: &str, active: bool, reduced: bool, body: impl FnOnce(&mut Ui) -> R) { let (heading, count) = title.split_once(" · ").map_or((title, None), |(heading, count)| (heading, Some(count))); - let tone = if title.contains("失败") { Tone::Failure } else if active { Tone::Active } else { Tone::Quiet }; - tool_group_head(ui, id, heading, count, tone, reduced, body) + let head = ToolGroupHead { active, failed: usize::from(title.contains("失败")), total: 0, completed: 0 }; + tool_group_head(ui, id, heading, count, head, reduced, body) } /// A static capacity ring; missing measurements show only the neutral track. @@ -379,7 +432,7 @@ pub(super) fn task_status_row(ui: &mut Ui, _id: egui::Id, glyph: &str, name: &st ui.add(crate::icons::image(glyph, icon::MD, t.text_dim)); ui.label(RichText::new(name).size(Type::Meta.size()).color(t.text)); let size = vec2(space::SM + icon::SM + space::XS + status_galley.size().x + space::SM, badge_height); - let (rect, response) = ui.allocate_exact_size(size, egui::Sense::hover()); + let (rect, response) = ui.allocate_exact_size(size, egui::Sense::empty()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, state)); ui.painter().rect_filled(rect, radius::CONTROL, t.field); let color = match status { @@ -425,7 +478,7 @@ pub(super) fn disclosure(ui: &mut Ui, id: egui::Id, title: &str, default_open } #[derive(Clone, Default)] -struct ResponseArrival { rendered: String, arrivals: Vec, was_streaming: bool, caret_exit: Option<(f64, f32)>, rest_at: f64 } +struct ResponseArrival { rendered: String, arrivals: Vec, was_streaming: bool, caret_exit: Option<(f64, f32)>, rest_at: f64, reveal_final: bool } // Cubic-bezier(.23, 1, .32, 1): invert x before evaluating y. pub(super) fn response_ease(x: f32) -> f32 { @@ -496,6 +549,20 @@ fn response_arrivals(state: &mut ResponseArrival, rendered: &str, now: f64, is_s } } +/// Move the live glyph clock to the durable message, whose index stays stable +/// when the next tool or reply appears. +pub(super) fn move_response_arrival(ui: &Ui, stream_id: egui::Id, receipt_id: egui::Id) -> bool { + ui.data_mut(|data| { + if data.get_temp::(receipt_id).is_some() { return false; } + if let Some(state) = data.remove_temp::(stream_id) { + data.insert_temp(receipt_id, state); + true + } else { + false + } + }) +} + /// Preserve the already rendered suffix when a final receipt is a suffix of /// the stream. This is only used for an explicitly matched final handoff; /// ordinary stream updates retain their strict append-prefix semantics. @@ -751,6 +818,10 @@ pub(super) fn streaming_reply_held(ui: &Ui) -> usize { /// Selectable Markdown layout with independent arrival batches and a streaming caret. pub(super) fn streaming_reply(ui: &mut Ui, id: egui::Id, text: &str, is_streaming: bool, reduced: bool) -> Response { + reply_with_arrival(ui, id, text, is_streaming, false, reduced) +} + +pub(super) fn reply_with_arrival(ui: &mut Ui, id: egui::Id, text: &str, is_streaming: bool, animate_final: bool, reduced: bool) -> Response { let now = ui.input(|input| input.time); let t = Tokens::get(ui.ctx()).agent(); // Reserve the inline caret's 1pt gap and up to 2pt stroke for every @@ -761,7 +832,10 @@ pub(super) fn streaming_reply(ui: &mut Ui, id: egui::Id, text: &str, is_streamin let background = super::agent_motion::reserve_background(ui); let state = ui.data_mut(|data| { let state = data.get_temp_mut_or_default::(id); - response_arrivals(state, &layout.rendered, now, is_streaming); + if state.rendered.is_empty() { + state.reveal_final = animate_final && !reduced; + } + response_arrivals(state, &layout.rendered, now, (is_streaming || state.reveal_final) && !reduced); if is_streaming { state.caret_exit = None; } else if state.was_streaming && !reduced { @@ -775,7 +849,7 @@ pub(super) fn streaming_reply(ui: &mut Ui, id: egui::Id, text: &str, is_streamin // 标点、选区几何与代码块背景都留在原位。定稿的回复一个顶点都不碰。 let mut frame = RevealPaint::default(); if now < state.rest_at { - frame = animate_galley(&mut galley, &state.arrivals, now, reduced, is_streaming, reveal::RevealInk::agent(t)); + frame = animate_galley(&mut galley, &state.arrivals, now, reduced, is_streaming || state.reveal_final, reveal::RevealInk::agent(t)); } let response = ui.add(egui::Label::new(galley.clone()).selectable(true)); let pos = response.rect.min; @@ -830,7 +904,7 @@ pub(super) fn approval_options(ui: &mut Ui, id: egui::Id, labels: &[&str], resol let t = Tokens::get(ui.ctx()).agent(); let deciding = resolved.is_none(); let progress = morph_value(ui.ctx(), id.with("answers"), deciding, reduced); - let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width().max(1.0), control::DEFAULT), egui::Sense::hover()); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width().max(1.0), control::DEFAULT), egui::Sense::empty()); let opacity = ui.opacity(); let mut answers = Vec::new(); if progress > 0.001 { @@ -1942,7 +2016,7 @@ pub(super) fn badge(ui:&mut Ui,id:egui::Id,kind:BadgeKind,text:&str,reduced:bool /// narrower than a running one; where the two share a column the caller sets /// one width, and the letter stays centred in either. pub(super) fn badge_sized(ui:&mut Ui,id:egui::Id,kind:BadgeKind,text:&str,reduced:bool,width:f32)->Response { - let (rect,response)=ui.allocate_exact_size(vec2(width.min(ui.available_width().max(1.0)),control::ROW),egui::Sense::hover()); + let (rect,response)=ui.allocate_exact_size(vec2(width.min(ui.available_width().max(1.0)),control::ROW),egui::Sense::empty()); paint_badge(ui,id,rect,kind,text,reduced); response.widget_info(||egui::WidgetInfo::labeled(egui::Role::Label,true,text)); response @@ -2382,7 +2456,7 @@ mod tests { use super::*; use crate::jiansun::test_support::SettleUi; use super::super::stitch_state::tool_glyph; - use super::super::stitch_timeline::ToolGroupHead; + use super::ToolGroupHead; /// Exercise the real lazy system-font loader until both the actual CJK /// glyph coverage and the font definitions/measurements are stable. @@ -2557,6 +2631,85 @@ mod tests { reply_job(text, 180.0, Color32::WHITE, Color32::BLACK) } + #[test] + fn tool_disclosure_holds_success_then_respects_manual_pins_and_failures() { + let mut state = ToolDisclosure::default(); + state.update(0.0, false, false); + assert!(!state.open); + state.update(0.5, true, false); + assert!(state.open); + state.update(1.0, false, false); + state.update(2.19, false, false); + assert!(state.open); + state.update(2.2, false, false); + assert!(!state.open); + state.update(3.0, false, true); + assert!(state.open); + state.user_pinned = Some(false); + state.update(4.0, true, false); + assert!(!state.open); + assert!(state.finished_at.is_none()); + state.user_pinned = Some(true); + state.update(5.0, false, false); + state.update(7.0, false, false); + assert!(state.open); + } + + #[test] + fn completed_tool_group_schedules_its_deadline_then_stays_idle() { + let ctx = Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + settle_test_cjk_font(&ctx); + let id = egui::Id::unique("tool-completion"); + let frame = |time, active| { + let mut output = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + tool_group(ui, id, "工具调用 · 1/1 已完成", active, false, |ui| { ui.label("读取画布"); }); + }); + let delay = super::super::agent_motion::requested_delay(&output); + output.textures_delta.clear(); + delay + }; + frame(0.0, true); + frame(0.5, true); + frame(1.0, false); + let hold = frame(1.2, false).expect("sleep until the completion deadline"); + assert!(!hold.is_zero() && hold <= std::time::Duration::from_millis(1001), "{hold:?}"); + frame(2.3, false); + frame(2.7, false); + assert_eq!(frame(3.0, false), None); + assert!(!ctx.data(|data| data.get_temp::(id.with("disclosure"))).unwrap().open); + } + + #[test] + fn a_live_final_reply_has_glow_then_settles_while_history_is_immediately_still() { + let ctx = Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + settle_test_cjk_font(&ctx); + let id = egui::Id::unique("discrete-reply"); + let frame = |time, animate| { + let mut output = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + reply_with_arrival(ui, id, "制作结果已经保存,可继续核对主图。", false, animate, false); + }); + let delay = super::super::agent_motion::requested_delay(&output); + output.textures_delta.clear(); + let state = ctx.data(|data| data.get_temp::(id)).unwrap(); + (delay, state) + }; + let (delay, state) = frame(0.0, true); + assert!(delay.is_some()); + assert!(state.reveal_final && state.rest_at > 0.3); + assert!(state.arrivals.windows(2).any(|pair| pair[0] < pair[1])); + assert!(!state.was_streaming && state.caret_exit.is_none()); + frame(0.2, true); + let rested = state.rest_at + 0.1; + assert_eq!(frame(rested, false).0, None); + ctx.data_mut(|data| data.remove::(id)); + let opened = rested + 1.0; + let (delay, history) = frame(opened, false); + assert!(history.rest_at < opened); + assert_eq!(delay, None); + } + #[test] fn response_arrivals_keep_independent_batches_across_markdown_closure() { // 同一批到达的字按每字 15ms 铺开;此前已经显示的字保留自己的到达时间。 From fca2710be5b64c4203dc7f7fdb68440a997be0fc Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Fri, 27 Nov 2026 11:50:34 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E7=BB=86=E5=8C=96=E5=B0=8F=E5=A3=B9?= =?UTF-8?q?=E6=97=B6=E9=97=B4=E6=B5=81=E4=B8=8E=E5=B7=A5=E5=85=B7=E6=B4=BB?= =?UTF-8?q?=E5=8A=A8=E5=91=88=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/detail-photocraft/DESIGN.md | 8 +- .../crates/ui-egui/src/jiansun/agent_panel.rs | 142 +++++----- .../ui-egui/src/jiansun/agent_stream.rs | 111 +++++++- .../ui-egui/src/jiansun/stitch_state.rs | 21 +- .../ui-egui/src/jiansun/stitch_timeline.rs | 52 +++- .../crates/ui-egui/src/jiansun/stitch_ui.rs | 261 ++++++------------ .../crates/ui-egui/src/jiansun/typing_text.rs | 22 +- .../crates/ui-egui/src/theme.rs | 15 +- 8 files changed, 343 insertions(+), 289 deletions(-) diff --git a/apps/detail-photocraft/DESIGN.md b/apps/detail-photocraft/DESIGN.md index 683862cb..d06bf575 100644 --- a/apps/detail-photocraft/DESIGN.md +++ b/apps/detail-photocraft/DESIGN.md @@ -419,11 +419,11 @@ Agent 导入的完全透明页面背景以原生“无填充”表达,保留 **事件行。** 高 24 逻辑点:24 点的图标列内放 14 点图标,随后是 12 点文字,再后是弱化的补充信息,可展开的行末尾带箭头。只有可点击的行回应悬停。行本身不做动画,一轮对话里唯一的等待动画属于状态行。字号只用三档:12 用于行和补充信息,13 用于标题与控件,14 用于回复正文。 -- 思考:只有一行状态,原文不展示;token 数和速度放在悬停说明里,不占行。 +- 思考:运行时图标轻微呼吸,完成后收成一行静态状态。用量和速度有数据才显示在同一行右侧。 - 通知:按类型取图标;等待中用亮色,核查类用告警色,失败用危险色。同一句状态反复记入时,时间线只显示最新一条,更早的相同记录留在对话数据里不再占一行。 -- 工具调用:标题是“工具调用”加已完成数,展开后是一张任务卡,逐行列出图标、名称、状态徽章和真实耗时。进行中的工具组自动展开,成功完成后停留 1.2 秒再收起。失败组保持展开,手动开合优先于自动行为。历史成功组默认收起。耗时按人读的粗细写:1 秒以内写毫秒,10 秒以内保留一位小数,一分钟以内写整秒,再长写几分几秒,统一由 `duration_text` 生成。 +- 工具调用:运行时标题标出当前实际工具,完成时显示结果摘要,失败时标出失败数。展开区用 26 点缩进的无框列表,每行状态图标、工具名、右对齐等宽耗时。进行中自动展开,成功完成后停留 1.2 秒再收起。失败组保持展开,手动开合优先。秒以下用毫秒,如 320ms。连续的思考、工具、通知和图片标题由 1 像素细线相连,图标与正文处断开。 - 回复:正文按到达顺序直接显示。新回复逐字入场,流式转为记录时延续当前字形动画,历史正文直接显示。复制按钮只在鼠标指向这条回复或按钮持有焦点时出现。 -- 图片结果:标题是“生成图片”或“图片来源”加数量;图片按自身比例排列,说明文字统一为左下角白字衬底。 +- 图片结果:标题是“生成图片”或“图片来源”加数量;图片按自身比例排列,说明文字统一为左下角单行白字。真实候选审阅状态在左上角显示语义色圆点和短标签。 - 空对话:还没有任何消息时,时间线顶部用几行说明小壹在这里能做哪三件事、从输入框或一条建议开始;没有打开项目时另给“我的项目”入口。第一条消息出现后即消失,不发送任何请求。 **顶部状态头。** 整套制作期间,状态头固定在对话滚动区上方,向上翻看历史时不动。收起时依次是:标题行(等待指示或时钟、当前步骤、展开钮、停止钮)、图片与文案各有一组独立圆角进度格,子代理字母与阶段按网格排列。进度格保持 5–7 点,空间不足时在对应统计标签右侧换行。展开后追加每个子代理的图位与步骤汇总。标题行在窄栏把位置让给步骤名:侧栏不超过 260 点时不放等待指示和时钟,九个字的步骤名完整显示,等待状态由标题的告警色表达。子代理只有一个写法:汇总行和展开列表用同一个字母,展开列表里的胶囊同宽,等待中没有动画点的胶囊也占同样的宽度,图位名从同一列开始。状态头只有一套进度色:还没有图位格子时用同比例的进度条,已填未验同为琥珀。进度数字显示已上画布的数量,含已显示的首图预览和已写入的文案初稿。蓝格显示已核验,悬停可查看可定位的图片图位。 @@ -466,7 +466,7 @@ Agent 导入的完全透明页面背景以原生“无填充”表达,保留 **品牌动效的定稿参数。** -- 逐字扩散(输入框、用户气泡、回复正文共用 `typing_text.rs`):单字 300ms cubic-out 入场,自下方 4 点升起并从 1.035 倍收拢到原大;相邻两字步进 15ms,同一批到达的字按字素簇铺开,积压时整体压回 650ms。一次到达激起一道柔光,以每字 22ms 向回传、按 exp(−距离/9) 衰减,在流头身后留下约 11 字宽的尾韵;流头另有一团柔光。尚未轮到的字以 12% 的光雾占位,光标不会跑到文字前面。回复里柔光垫在字形下面;输入浮层的文字经光涌透镜绘制,柔光由 `typing_text::paint_glow` 画在玻璃上面、文字光标下面。 +- 逐字扩散(输入框、用户气泡、回复正文共用 `typing_text.rs`):单字 460ms cubic-out 入场,自下方 4 点升起并从 1.035 倍收拢到原大;相邻两字步进 15ms,同一批到达的字按字素簇铺开,积压时整体压回 650ms。一次到达激起一道柔光,以每字 22ms 向回传、按 exp(−距离/9) 衰减,在流头身后留下约 13 字宽的尾韵;流头另有一团柔光。尚未轮到的字以 12% 的光雾占位,光标不会跑到文字前面。回复里柔光垫在字形下面;输入浮层的文字经光涌透镜绘制,柔光由 `typing_text::paint_glow` 画在玻璃上面、文字光标下面。 - 停止:流光、内雾与占位、光球的减速定格统一收敛在 190ms;光球停下时略微变暗。 - 光球档位:待机极柔慢呼吸、输入轻柔响应、运行平稳流动、等待结果慢一档巡视、暂停减速变暗定格。 - 光涌:玻璃光场、流光与 640ms 发送脉冲原样不动,只改了“什么时候申请下一帧”。 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 bf8c3038..b81c1281 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 @@ -79,30 +79,25 @@ fn conversation_settled(workspace: &Workspace, production: bool) -> bool { && !workspace.agent_effects_paused && workspace.error.is_empty() && workspace.stream_reply.is_empty() } -/// Token counts and speed serve the person debugging a run, not someone -/// reading the timeline, so they ride on the row's hover text. -fn thinking_usage(output: &Value) -> (Option, &'static str) { - let mut note = "本次输出用量由模型回传。速度从首段输出开始计算。"; - let Some(tokens) = usage_count(&output["tokens"]).filter(|tokens| *tokens > 0) else { return (None, note) }; +fn thinking_usage(output: &Value, show_speed: bool) -> Option { + let tokens = usage_count(&output["tokens"]).filter(|tokens| *tokens > 0)?; let prefix = if output["estimated"] == true { "≈" } else { "" }; let mut stats = format!("{prefix}{tokens} tokens"); - if let Some(rate) = output["tokensPerSecond"].as_f64().filter(|rate| rate.is_finite() && *rate > 0.0) { + if show_speed && let Some(rate) = output["tokensPerSecond"].as_f64().filter(|rate| rate.is_finite() && *rate > 0.0) { let speed = if rate < 10.0 { format!("{rate:.1}") } else { format!("{rate:.0}") }; stats.push_str(&format!(" · {prefix}{speed} tok/s")); } - if output["estimated"] == true { note = "输出用量暂为估算,模型回传后校准。速度从首段输出开始计算。"; } - (Some(stats), note) + Some(stats) } -fn thinking_ui(ui: &mut Ui, thinking: &Value, turn_running: bool, reduced: bool) { +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, }; - let (stats, note) = thinking_usage(&thinking["output"]); - let hint = stats.map(|stats| format!("{stats}。{note}")); - timeline::thinking_row(ui, ui.next_auto_id().with("thinking"), status, hint.as_deref(), reduced); + let stats = thinking_usage(&thinking["output"], ui.available_width() >= 260.0); + timeline::thinking_row(ui, ui.next_auto_id().with("thinking"), status, stats.as_deref(), reduced) } fn turn_reply_id(conversation_id: Id, user_index: Option) -> Id { @@ -1330,7 +1325,7 @@ impl Workspace { if turn_count == 0 && production { let jobs = self.projected_worker_jobs(); if !jobs.is_empty() { - self.timeline_images(ui, conversation_id.with("worker-jobs"), &jobs.iter().collect::>()); + self.timeline_images(ui, conversation_id.with("worker-jobs"), &jobs.iter().collect::>(), &mut Default::default()); } } self.workflow_card_ui(app, ui); @@ -1734,6 +1729,7 @@ impl Workspace { 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); @@ -1783,14 +1779,16 @@ impl Workspace { for (position, item) in turn.items.into_iter().enumerate() { match item { TurnItem::Thinking(thinking) => { - thinking_ui(ui, thinking, turn_running, self.reduce_motion); + 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 = product.then(|| production_reply_text(text, false)); - timeline::notice_row(ui, ui.next_auto_id().with("notice"), timeline::Notice { + let row = timeline::notice_row(ui, ui.next_auto_id().with("notice"), timeline::Notice { kind: notice_kind(text), text: display.as_deref().unwrap_or(text), hint: None, }, self.reduce_motion); + flow.connect(ui, row.rect); } TurnItem::Tools(tasks) => { let Some((_, first)) = tasks.first() else { continue }; @@ -1806,15 +1804,17 @@ impl Workspace { status: if status == ToolStatus::Started && !turn_running { ToolStatus::Unknown } else { status }, elapsed: elapsed.as_deref() } }).collect(); - timeline::tool_group(ui, id, timeline::ToolGroupHead { + 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()), }, &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); @@ -1858,11 +1858,12 @@ impl Workspace { } 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) { + if let Some(target) = self.timeline_images(ui, conversation_id.with(("image-results", first)), &images, &mut flow) { 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| { @@ -1876,6 +1877,7 @@ impl Workspace { } } 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 { @@ -1884,18 +1886,20 @@ impl Workspace { } 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); + self.timeline_images(ui, conversation_id.with(("worker-jobs", turn.user_index)), &images, &mut flow); } locate } - fn timeline_images(&self, ui: &mut Ui, id: Id, images: &[&Value]) -> Option { + fn timeline_images(&self, ui: &mut Ui, id: Id, images: &[&Value], flow: &mut super::agent_stream::Flow) -> Option { let heading = if images.iter().any(|image| image["kind"] == "template-image") { "图片来源" } else { "生成图片" }; let count = images.len().to_string(); ui.add_space(2.0); - 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)) - .1.into_iter().flatten().last() + 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)); + 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) -> Option { @@ -1939,7 +1943,7 @@ impl Workspace { 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::hover()), + |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) { @@ -1986,22 +1990,24 @@ impl Workspace { } let caption = if page_label.is_empty() { short_label.clone() } else { format!("{page_label} · {short_label}") }; paint_image_caption(&ui.painter_at(rect), rect, &caption); - paint_worker_badge(ui, response.id, rect, value, self.reduce_motion); let review = &self.workflow.production_progress()["candidateReviews"][id]; - if let Some(label) = match review["status"].as_str() { - Some("adopted") => Some("已采纳"), - Some("passed") => Some("验图通过"), - Some("not_selected") => Some("未选用"), - Some("rejected") => Some("已退回"), - Some("pending") => Some("待核查"), + if let Some((status, color)) = match review["status"].as_str() { + Some("adopted") => Some(("已采纳", t.agent_semantic().success)), + Some("passed") => Some(("验图通过", t.agent_semantic().success)), + Some("not_selected") => Some(("未选用", t.text_faint)), + Some("rejected") => Some(("已退回", t.danger)), + Some("pending") => Some(("待核查", t.warning)), _ => None, - } && rect.width() >= 118.0 && rect.height() >= 70.0 { - let badge = Rect::from_min_size(rect.left_top() + vec2(8.0, 36.0), vec2(66.0, 22.0)); - let kind = match review["status"].as_str() { - Some("rejected" | "pending") => super::stitch_ui::BadgeKind::Warning, - _ => super::stitch_ui::BadgeKind::Neutral, - }; - super::stitch_ui::paint_badge(ui, response.id.with("image-review"), badge, kind, label, self.reduce_motion); + } && 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); + } else { + paint_worker_badge(ui, response.id, rect, value, self.reduce_motion); } let expand = (rect.width() >= 42.0 && rect.height() >= 42.0).then(|| image_preview_button(ui, rect, id)); let response = response.on_hover_text(if original { label.clone() } else { format!("定位 {label} · 右键查看候选大图") }); @@ -4212,6 +4218,9 @@ mod tests { 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); @@ -5235,22 +5244,22 @@ mod tests { 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.starts_with("工具调用")).unwrap().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 fold during a provider wait"); - assert!(gap.iter().find(|(text,_)|text.starts_with("工具调用")).unwrap().1.top() < gap.iter().find(|(text,_)|text==&w.stream_reply).unwrap().1.top()); - let header = gap.iter().find(|(text,_)|text.starts_with("工具调用")).unwrap().1.center(); + 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); click(&ctx,w,6.6,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.starts_with("工具调用")).unwrap().1.top() < closed.iter().find(|(text,_)|text==&w.stream_reply).unwrap().1.top()); - let header = closed.iter().find(|(text,_)|text.starts_with("工具调用")).unwrap().1.center(); + 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![]); @@ -5311,8 +5320,8 @@ mod tests { 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("工具调用")); - assert!(top("工具调用") < 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); } @@ -5369,7 +5378,7 @@ mod tests { 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 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()); @@ -5423,9 +5432,9 @@ mod tests { 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")), "token counts stay off the timeline"); - assert_eq!(thinking_usage(&w.messages[1]["output"]).0.as_deref(), Some("≈128 tokens · ≈44 tok/s")); - assert_eq!(thinking_usage(&w.messages[1]["output"]).1, "输出用量暂为估算,模型回传后校准。速度从首段输出开始计算。"); + assert!(running.iter().any(|(text,_,_,_)| text == "≈128 tokens · ≈44 tok/s")); + assert_eq!(thinking_usage(&w.messages[1]["output"], true).as_deref(), Some("≈128 tokens · ≈44 tok/s")); + assert_eq!(thinking_usage(&w.messages[1]["output"], false).as_deref(), Some("≈128 tokens")); assert!(!running.iter().any(|(text,_,_,_)| text == "独立思考原文")); assert!(!running.iter().any(|(text,_,_,_)| text.starts_with("工具调用"))); w.busy = None; @@ -5436,8 +5445,8 @@ mod tests { 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")), "a finished turn keeps its usage on hover"); - assert_eq!(thinking_usage(&w.messages[1]["output"]), (Some("145 tokens · 45 tok/s".to_owned()), "本次输出用量由模型回传。速度从首段输出开始计算。")); + assert!(finished.iter().any(|(text,_,_,_)| text == "145 tokens · 45 tok/s")); + assert_eq!(thinking_usage(&w.messages[1]["output"], true), Some("145 tokens · 45 tok/s".to_owned())); 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), @@ -5539,28 +5548,29 @@ mod tests { 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.3,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.4,id); + let (first, _) = handoff_frame(&ctx,w,0.80,id); let (_,rect,alpha,sections) = first.iter().find(|(text,_,_,_)|text==final_text) .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, meshes) = handoff_frame(&ctx,w,0.5,id); + let (during, meshes) = handoff_frame(&ctx,w,0.90,id); let (_,rect,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)); let samples: Vec<_> = meshes.iter().filter(|vertices| vertices.iter().any(|(pos, alpha)| *alpha > 0 && *alpha < 255 && pos.y >= rect.top() - 6.0 && pos.y <= rect.bottom() + 6.0 && pos.x > rect.left() + 20.0)).collect(); assert!(samples.is_empty(), "the suffix lives in the one shaped glyph layer, without shadow meshes"); assert_eq!(during.iter().filter(|(text,_,_,_)| text==final_text).count(), 1); - let (settled, meshes) = handoff_frame(&ctx,w,0.7,id); + let reveal = super::super::typing_text::ENTER + 2.0 * super::super::typing_text::STEP; + let (settled, meshes) = 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), "suffix settles after 220ms"); + assert!(sections.iter().all(|alpha| *alpha == 255), "the final suffix settles after its glyphs arrive"); assert!(meshes.iter().all(|vertices| !vertices.iter().any(|(pos, alpha)| *alpha > 0 && *alpha < 255 && pos.y >= rect.top() - 6.0 && pos.y <= rect.bottom() + 6.0 && pos.x > rect.left() + 20.0))); } assert!(requests.try_recv().is_err()); @@ -5597,13 +5607,13 @@ mod tests { found }; frame(&mut app,0.0); - let before = frame(&mut app,0.3); + 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.4); + 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"); @@ -5716,9 +5726,9 @@ mod tests { 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.3 秒"); + 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)), - ("耗时 25 毫秒".to_owned(), "耗时 10.0 秒".to_owned(), "耗时 27 秒".to_owned(), "耗时 1 分 01 秒".to_owned())); + ("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}); @@ -7380,7 +7390,7 @@ mod tests { h.render().unwrap().save(path).unwrap(); }; save(&mut h, "collapsed"); - let button = h.get_by_label("工具调用").rect().center(); + let button = h.get_by_label("已完成 2 项操作").rect().center(); h.hover_at(button); h.run_steps(2); for pressed in [true, false] { @@ -7408,8 +7418,10 @@ mod tests { 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() @@ -7428,16 +7440,16 @@ mod tests { h.run_steps(48); save(&mut h, "tool-running"); let w = h.state_mut().jiansun.as_mut().unwrap(); - w.messages[2]["event"]["status"] = json!("completed"); - w.messages[2]["event"]["durationMs"] = json!(320); + 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.run_steps(89); save(&mut h, "tool-completion-hold"); - h.run_steps(38); + h.run_steps(44); save(&mut h, "tool-collapsing"); - h.run_steps(60); + h.run_steps(160); save(&mut h, "tool-folded"); assert!(requests.try_recv().is_err()); } @@ -7773,7 +7785,7 @@ mod tests { }); let mut labels = Vec::new(); for shape in &output.shapes { collect(&shape.shape, &mut labels); } - let heads: Vec<_> = labels.iter().filter(|(s, _)| s=="工具调用").map(|(_, y)| *y).collect(); + 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("原片核对完成,接着制作")); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs index 6baf1a11..04b2ad73 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs @@ -1,6 +1,6 @@ //! Working-state vocabulary for the 小壹 timeline. Every event in the -//! conversation reads as the same quiet row, production progress is a single -//! row of cells, and suggestions are borderless chips. Materials and motion +//! conversation reads as the same quiet row, production progress uses individual +//! cells, and suggestions are borderless chips. Materials and motion //! stay with `stitch_ui` and `agent_motion`; this module fixes only geometry //! and typography so the rows cannot drift apart. Sizes and colours come from //! `theme::agent_scale` and the semantic tokens; nothing here reads copy to decide a state. @@ -29,14 +29,47 @@ pub(super) fn cell_verified(t: &Tokens) -> Color32 { t.agent_semantic().verified /// is about 49pt wide (three dots, a letter, the padding); a waiting one owns /// no dots. The list gives both the same width so their labels share a column. pub(super) const WORKER_BADGE_WIDTH: f32 = 50.0; -/// How much of a folded narration's first line its hover preview carries. +const EVENT_ICON_X: f32 = 12.0; +const EVENT_ICON_CLEARANCE: f32 = 9.0; +const EVENT_LABEL_X: f32 = 26.0; +const EVENT_END_GAP: f32 = 5.0; +const EVENT_CHEVRON_SPACE: f32 = 18.0; +pub(super) const DISCLOSURE_LABEL_SPACE: f32 = EVENT_LABEL_X + EVENT_END_GAP + EVENT_CHEVRON_SPACE; -/// A row's colour only. Rows never animate: the one waiting mark of a turn -/// belongs to the status row, so `Active` just brightens the text. +/// Process rows in the same uninterrupted part of a turn share a quiet rail. +#[derive(Default)] +pub(super) struct Flow(Option); + +impl Flow { + pub(super) fn connect(&mut self, ui: &Ui, current: Rect) { + if let Some(previous) = self.0.replace(current) + && let Some(segment) = flow_segment(previous, current, ui.ctx().pixels_per_point()) + { + let color = Tokens::get(ui.ctx()).agent().card_border; + ui.painter().line_segment(segment, Stroke::new(1.0 / ui.ctx().pixels_per_point(), color)); + } + } + + pub(super) fn break_run(&mut self) { + self.0 = None; + } +} + +fn flow_segment(previous: Rect, current: Rect, scale: f32) -> Option<[egui::Pos2; 2]> { + let x = (((current.left() + EVENT_ICON_X) * scale).floor() + 0.5) / scale; + let top = previous.center().y + EVENT_ICON_CLEARANCE; + let bottom = current.center().y - EVENT_ICON_CLEARANCE; + (bottom > top).then(|| [egui::pos2(x, top), egui::pos2(x, bottom)]) +} + +/// A row's semantic text and icon treatment. #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum EventTone { Quiet, Active, + Working, + Thinking, + Success, Warning, Failure, } @@ -93,21 +126,38 @@ pub(super) fn event_row(ui: &mut Ui, id: Id, row: EventRow<'_>, reduced: bool) - } let tint = match row.tone { EventTone::Quiet => t.text_dim, - EventTone::Active => t.text, + EventTone::Active | EventTone::Working | EventTone::Thinking => t.text, + EventTone::Success => t.text_dim, EventTone::Warning => t.warning, EventTone::Failure => t.danger, }; if ui.is_rect_visible(rect) { let painter = ui.painter_at(rect.intersect(ui.clip_rect())); let middle = rect.center().y; - crate::icons::paint(ui, Rect::from_center_size(egui::pos2(rect.left() + 12.0, middle), Vec2::splat(14.0)), - row.glyph, 14.0, tint); - let mut end = rect.right() - 5.0; + let center = egui::pos2(rect.left() + EVENT_ICON_X, middle); + let icon_rect = Rect::from_center_size(center, Vec2::splat(14.0)); + match row.tone { + EventTone::Working => working_ring(ui, icon_rect, t.text_dim, reduced), + EventTone::Thinking => { + if !reduced { + let time = ui.input(|input| input.time); + let breath = (0.5 + 0.5 * (time * std::f64::consts::TAU / 2.4).sin()) as f32; + painter.circle_filled(center, 9.0, t.text_dim.gamma_multiply(0.035 + 0.075 * breath)); + super::agent_motion::schedule(ui, icon_rect, super::agent_motion::Pace::Idle); + } + crate::icons::paint(ui, icon_rect, row.glyph, 14.0, tint); + } + _ => { + let icon_color = if row.tone == EventTone::Success { t.agent_semantic().success } else { tint }; + crate::icons::paint(ui, icon_rect, row.glyph, 14.0, icon_color); + } + } + let mut end = rect.right() - EVENT_END_GAP; if let RowAction::Expand(open) = row.action { let chevron = if open { "chevron-down" } else { "chevron-right" }; crate::icons::paint(ui, Rect::from_center_size(egui::pos2(end - 6.5, middle), Vec2::splat(13.0)), chevron, 13.0, t.text_dim); - end -= 18.0; + end -= EVENT_CHEVRON_SPACE; } if let Some(meta) = row.meta.filter(|meta| !meta.is_empty()) { let galley = painter.layout_no_wrap(meta.to_owned(), Type::Meta.font_id(), t.text_faint); @@ -116,7 +166,7 @@ pub(super) fn event_row(ui: &mut Ui, id: Id, row: EventRow<'_>, reduced: bool) - painter.galley(egui::pos2(end, top), galley, t.text_faint); end -= 8.0; } - let start = rect.left() + 26.0; + let start = rect.left() + EVENT_LABEL_X; let mut job = egui::text::LayoutJob::simple_singleline(row.text.to_owned(), Type::Meta.font_id(), tint); job.wrap.max_width = (end - start).max(1.0); job.wrap.max_rows = 1; @@ -134,6 +184,20 @@ pub(super) fn event_row(ui: &mut Ui, id: Id, row: EventRow<'_>, reduced: bool) - if interactive { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response } } +pub(super) fn working_ring(ui: &Ui, rect: Rect, tint: Color32, reduced: bool) { + if !ui.is_rect_visible(rect) { return; } + let time = if reduced { 0.0 } else { ui.input(|input| input.time) }; + let phase = (time / 2.4).fract() as f32 * std::f32::consts::TAU; + let painter = ui.painter(); + painter.circle_stroke(rect.center(), 5.0, Stroke::new(1.2, tint.gamma_multiply(0.25))); + let points = (0..=10).map(|step| { + let angle = phase + step as f32 * 0.20; + rect.center() + vec2(angle.cos(), angle.sin()) * 5.0 + }).collect(); + painter.add(egui::Shape::line(points, Stroke::new(1.3, tint))); + if !reduced { super::agent_motion::schedule(ui, rect, super::agent_motion::Pace::Idle); } +} + #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(super) enum Cell { Empty, @@ -302,6 +366,31 @@ pub(super) fn worker_stage(step: &str, review: bool, from_image: bool) -> &'stat #[cfg(test)] mod tests { use super::*; + use crate::jiansun::test_support::SettleUi; + + #[test] + fn timeline_rail_joins_process_rows_and_clears_the_icon_centers() { + let row = |y| Rect::from_min_size(egui::pos2(8.0, y), vec2(200.0, 30.0)); + for scale in [1.0, 1.25, 1.5] { + let [start, end] = flow_segment(row(0.0), row(30.0), scale).unwrap(); + assert_eq!((start.x * scale).fract(), 0.5); + assert_eq!(start.x, end.x); + assert_eq!((start.y, end.y), (24.0, 36.0)); + } + let ctx = egui::Context::default(); + let frame = ctx.settle_ui(egui::RawInput::default(), |ui| { + let mut flow = Flow::default(); + flow.connect(ui, row(0.0)); + flow.connect(ui, row(30.0)); + flow.break_run(); + flow.connect(ui, row(90.0)); + }); + let segments: Vec<_> = frame.shapes.iter().filter_map(|shape| match &shape.shape { + egui::Shape::LineSegment { points, stroke } => Some((points, stroke.width)), + _ => None, + }).collect(); + assert_eq!(segments, vec![(&[egui::pos2(20.5, 24.0), egui::pos2(20.5, 36.0)], 1.0)]); + } #[test] fn event_rows_preserve_active_warning_and_failure_tones() { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs index b2128772..4e91ef17 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs @@ -471,14 +471,17 @@ pub(super) fn tool_glyph(tool: &str) -> &'static str { /// 人读耗时读个大概:一秒以内给毫秒,十秒以内给一位小数,一分钟以内给整秒,再往上给分秒。 pub(super) fn duration_text(ms: u64) -> String { match ms { - 0..=999 => format!("耗时 {ms} 毫秒"), - 1000..=9_999 => format!("耗时 {}.{} 秒", (ms + 50) / 100 / 10, (ms + 50) / 100 % 10), + 0..=999 => format!("{ms}ms"), + 1000..=9_999 => { + let tenths = (ms + 50) / 100; + format!("{}.{}s", tenths / 10, tenths % 10) + } _ => { - let seconds = (ms + 500) / 1000; + let seconds = ms / 1000 + u64::from(ms % 1000 >= 500); if seconds < 60 { - format!("耗时 {seconds} 秒") + format!("{seconds}s") } else { - format!("耗时 {} 分 {:02} 秒", seconds / 60, seconds % 60) + format!("{}m{:02}s", seconds / 60, seconds % 60) } } } @@ -650,9 +653,9 @@ mod tests { assert_eq!(tool_glyph("memory_set"), "type"); assert_eq!(tool_glyph("workflow_propose"), "folder-open"); assert_eq!(tool_glyph("anything-else"), "settings"); - assert_eq!(duration_text(27), "耗时 27 毫秒"); - assert_eq!(duration_text(1300), "耗时 1.3 秒"); - assert_eq!(duration_text(27_400), "耗时 27 秒"); - assert_eq!(duration_text(61_600), "耗时 1 分 02 秒"); + assert_eq!(duration_text(27), "27ms"); + assert_eq!(duration_text(1300), "1.3s"); + assert_eq!(duration_text(27_400), "27s"); + assert_eq!(duration_text(61_600), "1m02s"); } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs index 9c244272..ed572613 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs @@ -37,14 +37,13 @@ impl ThinkingStatus { } } - fn tone(self) -> Tone { - match self { Self::Active => Tone::Active, Self::Interrupted | Self::Done => Tone::Quiet } - } } -pub(super) fn thinking_row(ui: &mut Ui, id: egui::Id, status: ThinkingStatus, usage_hint: Option<&str>, reduced: bool) -> Response { +pub(super) fn thinking_row(ui: &mut Ui, id: egui::Id, status: ThinkingStatus, usage: Option<&str>, reduced: bool) -> Response { agent_stream::event_row(ui, id, EventRow { - glyph: "sparkles", text: status.label(), meta: None, tone: status.tone().into(), hint: usage_hint, action: RowAction::None, + glyph: "sparkles", text: status.label(), meta: usage, + tone: if status == ThinkingStatus::Active { EventTone::Thinking } else { EventTone::Quiet }, + hint: None, action: RowAction::None, }, reduced) } @@ -54,12 +53,45 @@ pub(super) use kit::ToolGroupHead; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct ToolRow<'a> { pub tool: &'a str, pub name: &'a str, pub status: ToolStatus, pub elapsed: Option<&'a str> } -pub(super) fn tool_group(ui: &mut Ui, id: egui::Id, head: ToolGroupHead, rows: &[ToolRow<'_>], reduced: bool) { - kit::tool_group_head(ui, id, "工具调用", Some(&head.count()), head, reduced, |ui| { +fn tool_group_summary(ui: &Ui, head: ToolGroupHead, rows: &[ToolRow<'_>]) -> (String, Option) { + if head.failed > 0 { + return (format!("{} 项操作失败", head.failed), Some(format!("{}/{} 已完成", head.completed, head.total))); + } + if head.active { + let activity = if let Some(row) = rows.iter().rev().find(|row| row.status == ToolStatus::Started) { + format!("正在{}…", row.name) + } else if let Some(row) = rows.iter().find(|row| row.status == ToolStatus::Pending) { + format!("等待 · {}", row.name) + } else { + "正在处理…".to_owned() + }; + if head.completed > 0 { + let summary = format!("已完成 {} 项 · {activity}", head.completed); + let width = ui.painter().layout_no_wrap(summary.clone(), Type::Meta.font_id(), Color32::PLACEHOLDER).size().x; + if width + agent_stream::DISCLOSURE_LABEL_SPACE <= ui.available_width() { + return (summary, None); + } + } + return (activity, None); + } + if head.completed == head.total { + return if let [row] = rows { + (format!("已完成 · {}", row.name), row.elapsed.map(str::to_owned)) + } else { + (format!("已完成 {} 项操作", head.completed), Some(format!("{}/{}", head.completed, head.total))) + }; + } + let stopped = rows.iter().any(|row| row.status == ToolStatus::Stopped); + (if stopped { "工具调用已停止" } else { "工具调用待核查" }.to_owned(), Some(format!("{}/{} 已完成", head.completed, head.total))) +} + +pub(super) fn tool_group(ui: &mut Ui, id: egui::Id, head: ToolGroupHead, rows: &[ToolRow<'_>], reduced: bool) -> Response { + let (label, meta) = tool_group_summary(ui, head, rows); + kit::tool_group_head(ui, id, &label, meta.as_deref(), head, reduced, |ui| { for (index, row) in rows.iter().enumerate() { kit::task_status_row(ui, id.with(("tool", index)), tool_glyph(row.tool), row.name, row.status, row.elapsed, reduced); } - }); + }) } /// 6. 通知:图标与色调取自 `NoticeKind`,失败、待核查、未执行不再共用一个图标。 @@ -736,7 +768,7 @@ mod tests { // 这一组含失败项,默认折叠;测试里先展开,好核对各行。 ui.data_mut(|data| data.insert_temp(id.with("tools").with("open"), true)); tool_group(ui, id.with("tools"), ToolGroupHead { total: 3, completed: 2, failed: 1, active: false }, &[ - ToolRow { tool: "canvas_read", name: "读取画布", status: ToolStatus::Completed, elapsed: Some("耗时 0.4 秒") }, + ToolRow { tool: "canvas_read", name: "读取画布", status: ToolStatus::Completed, elapsed: Some("400ms") }, ToolRow { tool: "generate_slot_image", name: "生成候选图片", status: ToolStatus::Failed, elapsed: None }, ToolRow { tool: "check_image_slots", name: "发起验图", status: ToolStatus::Started, elapsed: None }, ], true); @@ -769,7 +801,7 @@ mod tests { assert_eq!(interaction, 2); assert_eq!(suggestions.len(), 2); let drawn = texts(&output); - for expected in ["给这款边几做一整套详情页", "边几 · 胡桃木", "已深度思考", "工具调用", "2/3 已完成 · 1 项失败", "读取画布", "失败", + for expected in ["给这款边几做一整套详情页", "边几 · 胡桃木", "已深度思考", "1 项操作失败", "2/3 已完成", "读取画布", "主图 4 · 细节特写没生成出来", "有一条对话未确认结果", "整套已经推进到主图这一步。", "生成图片", "添加待审核建议", "执行创作操作", "先不用", "选一个卖点方向", "继续做剩下的 SKU 图"] { assert!(drawn.iter().any(|text| text == expected), "{expected} is drawn: {drawn:?}"); } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs index 54af2e74..100e8331 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs @@ -307,26 +307,11 @@ pub(super) fn ai_loader(ui: &mut Ui, id: egui::Id, running: bool, reduced: bool) /// Only public, allowlisted activity is passed in by the business layer. /// Each group keeps its own disclosure choice as tool states change. The -/// heading is the same quiet row as every other timeline event; only an open -/// group spends a card on its rows. +/// heading is the same quiet row as every other timeline event. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(super) struct ToolGroupHead { pub total: usize, pub completed: usize, pub failed: usize, pub active: bool } -impl ToolGroupHead { - pub(super) fn tone(self) -> Tone { - if self.failed > 0 { Tone::Failure } else if self.active { Tone::Active } else { Tone::Quiet } - } - - pub(super) fn count(self) -> String { - let mut count = format!("{}/{} 已完成", self.completed, self.total); - if self.failed > 0 { - count.push_str(&format!(" · {} 项失败", self.failed)); - } - count - } -} - -/// 工具调用组的外壳:标题行与可折叠的卡片。计数与成败由调用方结构化给出,不从标题文案里拆。 +/// 工具调用组的展开选择与完成后的停留时钟。 #[derive(Clone, Copy, Default)] struct ToolDisclosure { open: bool, @@ -350,14 +335,18 @@ impl ToolDisclosure { } } -pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, count: Option<&str>, head: ToolGroupHead, reduced: bool, body: impl FnOnce(&mut Ui) -> R) { +pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, meta: Option<&str>, head: ToolGroupHead, reduced: bool, body: impl FnOnce(&mut Ui) -> R) -> Response { use super::agent_stream::{EventRow, EventTone, RowAction}; let key = id.with("disclosure"); let now = ui.input(|input| input.time); let mut state = ui.data(|data| data.get_temp::(key)).unwrap_or_default(); state.update(now, head.active, head.failed > 0); + let (glyph, tone) = if head.failed > 0 { ("triangle-alert", EventTone::Failure) } + else if head.active { ("circle-dashed", EventTone::Working) } + else if head.completed == head.total { ("check", EventTone::Success) } + else { ("info", EventTone::Warning) }; let header = super::agent_stream::event_row(ui, id.with("header"), EventRow { - glyph: "settings", text: heading, meta: count, tone: EventTone::from(head.tone()), + glyph, text: heading, meta, tone, hint: None, action: RowAction::Expand(state.open), }, reduced); if header.clicked() { @@ -370,17 +359,13 @@ pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, count ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((finished + ToolDisclosure::HOLD_SECONDS - now).max(0.0))); } morph_surface(ui, id.with("tool-body"), state.open, reduced, |ui| { - ui.horizontal(|ui| { - ui.add_space(space::MD); - surface(ui, SurfaceRole::Task, |ui| { - ui.vertical(|ui| { - ui.set_width(ui.available_width().max(1.0)); - body(ui); - }); - }); + egui::Frame::NONE.inner_margin(egui::Margin { left: 26, top: 2, right: 5, bottom: 4 }).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + body(ui) }); }); ui.data_mut(|data| data.insert_temp(key, state)); + header } /// 旧签名垫片:标题形如"工具调用 · 3/5 已完成 · 1 项失败",成败仍从文案里读。 @@ -389,7 +374,7 @@ pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, count pub(super) fn tool_group(ui: &mut Ui, id: egui::Id, title: &str, active: bool, reduced: bool, body: impl FnOnce(&mut Ui) -> R) { let (heading, count) = title.split_once(" · ").map_or((title, None), |(heading, count)| (heading, Some(count))); let head = ToolGroupHead { active, failed: usize::from(title.contains("失败")), total: 0, completed: 0 }; - tool_group_head(ui, id, heading, count, head, reduced, body) + tool_group_head(ui, id, heading, count, head, reduced, body); } /// A static capacity ring; missing measurements show only the neutral track. @@ -420,51 +405,48 @@ pub(super) fn task_row(ui: &mut Ui, _id: egui::Id, glyph: &str, name: &str, stat /// 一行工具调用:图标、状态徽标与可选的真实耗时。文案、色调与图标都取自 `ToolStatus`。 pub(super) fn task_status_row(ui: &mut Ui, _id: egui::Id, glyph: &str, name: &str, status: ToolStatus, elapsed: Option<&str>, reduced: bool) { let t = Tokens::get(ui.ctx()).agent(); - let state = status.label(); let running = status == ToolStatus::Started; - let text_color = status.tone().color(&t); - let status_galley = ui.painter().layout_no_wrap(state.to_owned(), Type::Meta.font_id(), text_color); - let name_galley = ui.painter().layout_no_wrap(name.to_owned(), Type::Meta.font_id(), t.text); - let timer_height = elapsed.map_or(0.0, |text| ui.painter().layout_no_wrap(text.to_owned(), Type::Meta.font_id(), t.text_dim).size().y.max(12.0)); - let badge_height = status_galley.size().y.max(12.0) + space::SM; - let row_height = badge_height.max(name_galley.size().y).max(timer_height).max(icon::MD); - let row = ui.allocate_ui_with_layout(vec2(ui.available_width(), row_height), egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true), |ui| { - ui.add(crate::icons::image(glyph, icon::MD, t.text_dim)); - ui.label(RichText::new(name).size(Type::Meta.size()).color(t.text)); - let size = vec2(space::SM + icon::SM + space::XS + status_galley.size().x + space::SM, badge_height); - let (rect, response) = ui.allocate_exact_size(size, egui::Sense::empty()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, state)); - ui.painter().rect_filled(rect, radius::CONTROL, t.field); - let color = match status { - ToolStatus::Completed => t.agent_semantic().success, - ToolStatus::Failed => t.danger, - ToolStatus::Stopped => t.warning, - _ => t.text_dim, + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), egui::Sense::empty()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{name} · {}", status.label()))); + if !ui.is_rect_visible(rect) { return; } + let painter = ui.painter_at(rect); + let mid = rect.center().y; + let icon = egui::Rect::from_center_size(egui::pos2(rect.left() + 7.0, mid), vec2(14.0, 14.0)); + if running { + super::agent_stream::working_ring(ui, icon, t.text_dim, reduced); + } else { + let (glyph, tint) = match status { + ToolStatus::Completed => ("check", t.agent_semantic().success), + ToolStatus::Failed => ("triangle-alert", t.danger), + ToolStatus::Stopped => ("triangle-alert", t.warning), + _ => (glyph, t.text_faint), }; - let alpha = if running && !reduced { 0.55 + 0.45 * ((ui.input(|i| i.time) as f32 * std::f32::consts::TAU).sin() * 0.5 + 0.5) } else { 1.0 }; - let image = crate::icons::image(status.glyph(), icon::SM, color.gamma_multiply(alpha)); - let image = if running && !reduced { - image.rotate((ui.input(|i| i.time).rem_euclid(timing::LOADER_PERIOD) / timing::LOADER_PERIOD * std::f64::consts::TAU) as f32, vec2(0.5, 0.5)) - } else { image }; - image.paint_at(ui, egui::Rect::from_center_size(egui::pos2(rect.left() + 14.0, rect.center().y), vec2(icon::SM, icon::SM))); - let text_pos = egui::pos2(rect.left() + 24.0, rect.center().y - status_galley.size().y * 0.5); - ui.painter().galley(text_pos, status_galley.clone(), text_color); - if let Some(elapsed) = elapsed { timer(ui, elapsed); } - }); - if running && !reduced { schedule(ui, row.response.rect, Pace::Full); } -} - -/// A compact, non-interactive timer sourced entirely from the caller's actual -/// upstream duration. Reserving the measured group keeps it on one line. -pub(super) fn timer(ui: &mut Ui, elapsed: &str) { - let t = Tokens::get(ui.ctx()).agent(); - let galley = ui.painter().layout_no_wrap(elapsed.to_owned(), Type::Meta.font_id(), t.text_dim); - let width = galley.size().x + 16.0; - ui.allocate_ui_with_layout(vec2(width, galley.size().y.max(12.0)), egui::Layout::left_to_right(egui::Align::Center), |ui| { - ui.spacing_mut().item_spacing.x = 4.0; - ui.add(crate::icons::image("clock", 12.0, t.text_dim)); - ui.add(egui::Label::new(RichText::new(elapsed).size(Type::Meta.size()).color(t.text_dim)).extend()); - }); + crate::icons::paint(ui, icon, glyph, 14.0, tint); + } + let mut end = rect.right(); + if let Some(elapsed) = elapsed { + let digits = painter.layout_no_wrap(elapsed.to_owned(), crate::theme::mono(Type::Meta.size()), t.text_faint); + end -= digits.size().x; + painter.galley(egui::pos2(end, mid - digits.size().y * 0.5), digits, t.text_faint); + end -= 8.0; + } + let color = if running || status == ToolStatus::Failed { t.text } else { t.text_dim }; + let start = rect.left() + 22.0; + let mut job = egui::text::LayoutJob::default(); + let font_id = Type::Meta.font_id(); + job.append(name, 0.0, egui::TextFormat::simple(font_id.clone(), color)); + if let Some(label) = match status { + ToolStatus::Failed | ToolStatus::Stopped => Some(status.label()), + ToolStatus::Unknown => Some("待核查"), + _ => None, + } { + job.append(" · ", 0.0, egui::TextFormat::simple(font_id.clone(), t.text_faint)); + job.append(label, 0.0, egui::TextFormat::simple(font_id, t.text_faint)); + } + job.wrap.max_width = (end - start).max(1.0); + job.wrap.max_rows = 1; + let line = painter.layout_job(job); + painter.galley(egui::pos2(start, mid - line.size().y * 0.5), line, color); } pub(super) fn disclosure(ui: &mut Ui, id: egui::Id, title: &str, default_open: bool, reduced: bool, body: impl FnOnce(&mut Ui) -> R) -> Response { @@ -656,7 +638,7 @@ pub(super) fn animate_galley( } reveal::light_trail(&mut tokens, now); } - // 入场:单字 300ms cubic-out,自下方 4pt 升起并从 1.035 倍收拢;尚未轮到的字以极淡的光雾占位; + // 入场:单字 460ms cubic-out,自下方 4pt 升起并从 1.035 倍收拢;尚未轮到的字以极淡的光雾占位; // 尾韵里的字被柔光微微托起并染上光的颜色。 let lit = ink.glow().lerp_to_gamma(Color32::WHITE, 0.5); let first_trail_row = tokens.last().map_or(usize::MAX, |token| token.row); @@ -2455,7 +2437,6 @@ pub(super) fn ui_fonts_ready(ui: &Ui) -> bool { mod tests { use super::*; use crate::jiansun::test_support::SettleUi; - use super::super::stitch_state::tool_glyph; use super::ToolGroupHead; /// Exercise the real lazy system-font loader until both the actual CJK @@ -2816,60 +2797,58 @@ mod tests { fn tool_task_row_renders_real_status_and_only_supplied_duration() { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - for (status, elapsed, expected) in [("started", None, "进行中"), ("completed", Some("耗时 1.3 秒"), "已完成"), ("failed", None, "失败"), ("unknown", None, "状态未知")] { + for (status, elapsed, name) in [ + ("started", None, "读取项目规则"), + ("completed", Some("1.3s"), "读取项目规则"), + ("failed", None, "读取项目规则 · 失败"), + ("unknown", None, "读取项目规则 · 待核查"), + ] { let output = ctx.settle_ui(egui::RawInput::default(), |ui| task_row(ui, egui::Id::unique("task"), "settings", "读取项目规则", status, elapsed, true)); let texts: Vec<_> = output.shapes.iter().filter_map(|shape| match &shape.shape { egui::Shape::Text(text) => Some(text.galley.text()), _ => None }).collect(); - assert!(texts.contains(&"读取项目规则") && texts.contains(&expected)); - assert_eq!(texts.iter().any(|text| text.contains("耗时")), elapsed.is_some()); + assert!(texts.contains(&name), "{texts:?}"); + assert_eq!(texts.contains(&"1.3s"), elapsed.is_some()); + assert!(!texts.iter().any(|text| text.contains("耗时") || *text == "已完成")); } } #[test] - fn task_status_badges_are_compact_without_changing_parent_interaction_height() { + fn tool_group_body_and_task_rows_have_no_frames() { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let t = Tokens::get(&ctx).agent(); let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 200.0))), ..Default::default() }, |ui| { - scope_with_motion(ui, false, |ui| { - let interaction_height = ui.spacing().interact_size.y; - task_row(ui, egui::Id::unique("compact-badge"), "check", "读取画布", "completed", Some("耗时 1.3 秒"), false); - assert_eq!(ui.spacing().interact_size.y, interaction_height); + scope_with_motion(ui, true, |ui| { + let head = ToolGroupHead { total: 2, completed: 1, failed: 0, active: true }; + tool_group_head(ui, egui::Id::unique("plain-body"), "正在更新图层…", None, head, true, |ui| { + let top = ui.next_widget_position().y; + task_row(ui, egui::Id::unique("plain-row"), "check", "读取画布", "completed", Some("1.3s"), true); + assert!((ui.min_rect().bottom() - top - 26.0).abs() < 0.5); + }); }); }); - let badges: Vec<_> = output.shapes.iter().filter_map(|shape| match &shape.shape { - egui::Shape::Rect(rect) if rect.fill == t.field => Some(rect.rect), - _ => None, - }).collect(); - assert_eq!(badges.len(), 1); - assert!((20.0..=26.0).contains(&badges[0].height()), "actual status badge: {:?}", badges[0]); + assert!(!output.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Rect(rect) + if rect.fill == t.field || rect.stroke.color == t.card_border))); } #[test] - fn task_status_glyph_centers_match_name_at_multiple_scales_and_widths() { + fn task_name_and_monospace_duration_use_the_same_line_at_all_scales() { for ppp in [1.25, 1.5] { for width in [250.0, 400.0] { let ctx = Context::default(); ctx.set_pixels_per_point(ppp); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 200.0))), ..Default::default() }, |ui| { - task_row(ui, egui::Id::unique("baseline-check"), "search", "读取画布", "completed", Some("耗时 27 毫秒"), true); + task_row(ui, egui::Id::unique("three-columns"), "search", "读取画布", "completed", Some("27ms"), true); }); let find = |wanted| output.shapes.iter().find_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text() == wanted => { - let row = text.galley.rows.first()?; - let glyph = row.glyphs.first()?; - let baseline = text.pos.y + row.pos.y + glyph.pos.y; - Some((baseline, text.galley.mesh_bounds.translate(text.pos.to_vec2()))) - } + egui::Shape::Text(text) if text.galley.text() == wanted => Some(text), _ => None, }).expect("painted task text"); - let (name_baseline, name) = find("读取画布"); - let (status_baseline, status) = find("已完成"); - assert!((name_baseline - status_baseline).abs() <= 1.0 / ppp, "ppp={ppp} width={width}: name baseline={name_baseline}, status baseline={status_baseline}; {name:?} / {status:?}"); - let (elapsed_baseline, elapsed) = find("耗时 27 毫秒"); - if (elapsed_baseline - name_baseline).abs() < 5.0 { - assert!((elapsed_baseline - name_baseline).abs() <= 1.0 / ppp, "ppp={ppp} width={width}: name baseline={name_baseline}, timer baseline={elapsed_baseline}; {name:?} / {elapsed:?}"); - } else { assert!(elapsed.top() >= name.bottom(), "wrapped timer must begin below the first row: {name:?} / {elapsed:?}"); } + let name = find("读取画布"); + let elapsed = find("27ms"); + assert!((elapsed.pos.y + elapsed.galley.size().y / 2.0 - name.pos.y - name.galley.size().y / 2.0).abs() <= 1.0 / ppp); + assert!(elapsed.pos.x > name.pos.x + name.galley.size().x); + assert_eq!(elapsed.galley.job.sections[0].format.font_id, crate::theme::mono(Type::Meta.size())); } } } @@ -2880,10 +2859,10 @@ mod tests { crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(250.0, 200.0))), ..Default::default() }, |ui| { ui.set_width(250.0); - task_row(ui, egui::Id::unique("narrow-duration"), "search", "读取项目规则", "completed", Some("耗时 27 毫秒"), true); + task_row(ui, egui::Id::unique("narrow-duration"), "search", "读取项目规则", "completed", Some("27ms"), true); }); let (clip, text) = output.shapes.iter().find_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text() == "耗时 27 毫秒" => Some((shape.clip_rect, text)), + egui::Shape::Text(text) if text.galley.text() == "27ms" => Some((shape.clip_rect, text)), _ => None, }).expect("actual elapsed label is painted"); assert_eq!(text.galley.rows.len(), 1, "duration must never split between lines"); @@ -3386,7 +3365,7 @@ mod tests { if !ui_fonts_ready(ui) { return; } let t = Tokens::get(ui.ctx()).agent(); ui.painter().rect_filled(ui.max_rect(), 0.0, t.dock); - task_row(ui, egui::Id::unique("task-alignment"), "layers", "读取画布", "completed", Some("耗时 25 毫秒"), true); + task_row(ui, egui::Id::unique("task-alignment"), "layers", "读取画布", "completed", Some("25ms"), true); }); crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); h.run_steps(8); @@ -3595,8 +3574,8 @@ mod tests { file_drop_zone(ui, egui::Id::unique("visual-drop-active"), field_width, Some(pointer), true, reduced); tool_group(ui, egui::Id::unique("visual-task"), "工具调用 · 1/3 已完成", true, reduced, |ui| { task_row(ui, egui::Id::unique("visual-running"), "search", "读取项目规则", "started", None, reduced); - task_row(ui, egui::Id::unique("visual-complete"), "check", "读取画布", "completed", Some("耗时 1.3 秒"), reduced); - task_row(ui, egui::Id::unique("visual-failed"), "triangle-alert", "更新图层", "failed", Some("耗时 400 毫秒"), reduced); + task_row(ui, egui::Id::unique("visual-complete"), "check", "读取画布", "completed", Some("1.3s"), reduced); + task_row(ui, egui::Id::unique("visual-failed"), "triangle-alert", "更新图层", "failed", Some("400ms"), reduced); }); ai_loader(ui, egui::Id::unique("visual-loader"), true, reduced); let (pill, _) = ui.allocate_exact_size(vec2(ui.available_width(), 54.0), egui::Sense::hover()); @@ -4329,13 +4308,10 @@ mod tests { /// 品牌动效的定稿参数都落在 Token 上:改这里就是改观感,别处不许再写字面量。 #[test] fn typing_reveal_and_motion_tokens_hold_the_locked_brand_parameters() { - assert!((reveal::ENTER - 0.300).abs() < 1e-9, "单字入场 300ms cubic-out"); + assert!((reveal::ENTER - 0.460).abs() < 1e-9, "单字入场 460ms cubic-out"); assert!((reveal::STEP - 0.015).abs() < 1e-9, "每字步进 15ms"); - assert!((10..=12).contains(&reveal::TAIL), "尾韵约 10–12 字"); - assert!( - (reveal::ENTER + reveal::STEP * reveal::TAIL as f64) < 0.5, - "原型 460ms 的单字节奏已明显加快:一个字入场、整段尾韵铺完都不到半秒" - ); + assert_eq!(reveal::TAIL, 13); + assert_eq!(reveal::MIST, 0.12); assert!((timing::STOP_SETTLE - 0.190).abs() < 1e-9, "停止减速定格收敛在 180–200ms"); assert_eq!(timing::FRAME_FULL, std::time::Duration::from_millis(16), "发送脉冲、运行、交互满帧"); assert_eq!(timing::FRAME_IDLE, std::time::Duration::from_millis(32), "纯待机降到半帧"); @@ -4352,7 +4328,7 @@ mod tests { assert_eq!(timing::DEEP_AFTER, 15.0); } - /// 回复正文逐字入场时带着柔光:流头一团、身后一条约 11 字的光带;定稿后什么都不画、不申请重绘。 + /// 回复正文逐字入场时带着柔光:流头一团、身后一条约 13 字的光带;定稿后什么都不画、不申请重绘。 #[test] fn streaming_reply_carries_a_head_halo_and_a_tail_band_then_goes_completely_still() { let ctx = Context::default(); @@ -4512,61 +4488,4 @@ mod tests { } } - /// 旧的字符串入参行与新的类型化行读出来完全一样:状态文案、颜色与图标只有一份定义。 - #[test] - fn typed_and_legacy_tool_rows_read_the_same_status() { - let ctx = Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - settle_test_cjk_font(&ctx); - let t = Tokens::get(&ctx).agent(); - let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 120.0))); - let status_color = |output: &egui::FullOutput, label: &str| { - output.shapes.iter().filter_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text() == label => Some(text.galley.job.sections.first().map(|section| section.format.color)), - _ => None, - }).flatten().next() - }; - let mut labels = Vec::new(); - for (legacy, typed) in [ - ("pending", ToolStatus::Pending), ("started", ToolStatus::Started), ("completed", ToolStatus::Completed), - ("failed", ToolStatus::Failed), ("stopped", ToolStatus::Stopped), ("nonsense", ToolStatus::Unknown), - ] { - let legacy_row = ctx.settle_ui(egui::RawInput { screen_rect: screen, ..Default::default() }, |ui| { - scope(ui, |ui| task_row(ui, egui::Id::unique("legacy"), "search", "读取画布", legacy, Some("耗时 27 毫秒"), true)).inner - }); - let typed_row = ctx.settle_ui(egui::RawInput { screen_rect: screen, ..Default::default() }, |ui| { - scope(ui, |ui| task_status_row(ui, egui::Id::unique("typed"), tool_glyph("canvas_read"), "读取画布", typed, Some("耗时 27 毫秒"), true)).inner - }); - assert_eq!(status_color(&legacy_row, typed.label()), Some(typed.tone().color(&t)), "legacy {legacy}"); - assert_eq!(status_color(&typed_row, typed.label()), Some(typed.tone().color(&t)), "typed {legacy}"); - assert!(reply_text_shapes(&typed_row, "读取画布").len() == 1 && reply_text_shapes(&typed_row, "耗时 27 毫秒").len() == 1); - labels.push(typed.label()); - } - assert_eq!(labels, ["等待", "进行中", "已完成", "失败", "已停止", "状态未知"]); - } - - /// 旧的工具组标题垫片与新的类型化标题读出同一行字:计数与失败数只有一处拼法。 - #[test] - fn legacy_tool_group_title_and_typed_head_agree() { - let head = ToolGroupHead { total: 5, completed: 3, failed: 1, active: true }; - assert_eq!(head.count(), "3/5 已完成 · 1 项失败"); - assert_eq!(head.tone(), Tone::Failure, "a failure outranks running for the row's colour"); - assert_eq!(ToolGroupHead { total: 5, completed: 3, failed: 0, active: true }.tone(), Tone::Active); - assert_eq!(ToolGroupHead { total: 5, completed: 5, failed: 0, active: false }.tone(), Tone::Quiet); - let ctx = Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - settle_test_cjk_font(&ctx); - let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 160.0))); - let texts = |title: &str| { - let output = ctx.settle_ui(egui::RawInput { screen_rect: screen, ..Default::default() }, |ui| { - scope(ui, |ui| tool_group(ui, egui::Id::unique(("title", title)), title, true, true, |_| ())); - }); - output.shapes.iter().filter_map(|shape| match &shape.shape { - egui::Shape::Text(text) => Some(text.galley.text().to_owned()), - _ => None, - }).collect::>() - }; - let legacy = texts(&format!("工具调用 · {}", head.count())); - assert!(legacy.iter().any(|text| text == "工具调用") && legacy.iter().any(|text| text == "3/5 已完成 · 1 项失败"), "{legacy:?}"); - } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/typing_text.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/typing_text.rs index 50dde227..808f7621 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/typing_text.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/typing_text.rs @@ -1,7 +1,7 @@ //! 逐字扩散:输入框、用户气泡与 Agent 正文共用的一套入场与柔光算法。 //! -//! 节奏由用户定稿:单字 300ms cubic-out 入场,相邻两字步进 15ms;一次到达激起一道柔光, -//! 以每字 22ms 向回传播、按 exp(-距离/9) 衰减,在流头身后留下约 11 字宽的尾韵,流头另有一团柔光。 +//! 节奏由用户定稿:单字 460ms cubic-out 入场,相邻两字步进 15ms;一次到达激起一道柔光, +//! 以每字 22ms 向回传播、按 exp(-距离/9) 衰减,在流头身后留下约 13 字宽的尾韵,流头另有一团柔光。 //! 尚未轮到的字先以极淡的光雾占位,光标不会跑到文字前面。 //! //! 这里只管到达时间、柔光数学与柔光网格;字形网格的改写在 `stitch_ui::animate_galley`。 @@ -14,7 +14,7 @@ use unicode_segmentation::UnicodeSegmentation; use super::agent_motion::{Pace, schedule}; -/// 单字入场时长:300ms cubic-out。 +/// 单字入场时长:460ms cubic-out。 pub(super) const ENTER: f64 = timing::REVEAL_ENTER; /// 相邻两字的到达步进:15ms。 pub(super) const STEP: f64 = timing::REVEAL_STEP; @@ -79,9 +79,9 @@ pub(super) struct TrailToken { pub glow: f32, } -/// 尾韵窗口:流头向回第 6 个字以内全亮,到第 13 个字减到零,约 11 字宽。 +/// 尾韵窗口:流头向回第 6 个字以内全亮,到第 15 个字减到零,约 13 字宽。 fn window(distance: usize) -> f32 { - let t = ((distance as f32 - 6.0) / 7.0).clamp(0.0, 1.0); + let t = ((distance as f32 - 6.0) / 9.0).clamp(0.0, 1.0); 1.0 - t * t * (3.0 - 2.0 * t) } @@ -369,8 +369,8 @@ mod tests { } #[test] - fn each_character_enters_in_300ms_with_a_15ms_step_and_bounded_span() { - assert!((ENTER - 0.300).abs() < 1e-9 && (STEP - 0.015).abs() < 1e-9 && TAIL == 11); + fn each_character_enters_in_460ms_with_a_15ms_step_and_bounded_span() { + assert!((ENTER - 0.460).abs() < 1e-9 && (STEP - 0.015).abs() < 1e-9 && TAIL == 13); assert_eq!(batch_step(0), 0.0); assert_eq!(batch_step(1), 0.0); assert_eq!(batch_step(40), STEP); @@ -405,15 +405,15 @@ mod tests { } #[test] - fn trail_is_brightest_at_the_head_and_fades_over_about_eleven_characters() { - // 一批字同时到达:流头自己还在升起,身后几个字叠加到最亮,再向回在约 11 字内收束。 + fn trail_is_brightest_at_the_head_and_fades_over_about_thirteen_characters() { + // 一批字同时到达:流头自己还在升起,身后几个字叠加到最亮,再向回在约 13 字内收束。 let mut tokens: Vec<_> = (0..20).map(|index| token(0, 14.0 * index as f32, 0.0)).collect(); light_trail(&mut tokens, 0.138); assert!(tokens[0].glow > 0.5, "the head is lit"); assert!(tokens[1].glow > 0.99); assert!(tokens[1..].windows(2).all(|pair| pair[0].glow >= pair[1].glow), "light fades away from the head"); - assert!(tokens[11].glow > 0.0 && tokens[11].glow < 0.5 * tokens[1].glow, "the tail is still present but half gone at eleven characters"); - assert_eq!(tokens[13].glow, 0.0, "nothing glows beyond the tail window"); + assert!(tokens[13].glow > 0.0 && tokens[13].glow < 0.5 * tokens[1].glow, "the glow tapers at thirteen characters"); + assert_eq!(tokens[15].glow, 0.0, "nothing glows beyond the tail window"); // 逐字到达:最新的字始终是流头,光带跟着它走。`light_trail` 按由新到旧取字,和 `animate_galley` 的收集顺序一致。 let mut typed: Vec<_> = (0..14).map(|index| token(0, 14.0 * index as f32, (13 - index) as f64 * STEP)).collect(); light_trail(&mut typed, 0.138 + 13.0 * STEP); diff --git a/apps/detail-photocraft/crates/ui-egui/src/theme.rs b/apps/detail-photocraft/crates/ui-egui/src/theme.rs index abaa61d8..5930fce3 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/theme.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/theme.rs @@ -1648,7 +1648,7 @@ pub(crate) mod agent_scale { pub(crate) const LG: f32 = 16.0; } - /// 动效时长(秒)。用户定稿的三条:逐字 300ms + 15ms 步进、停止 190ms 收敛、满帧 16ms。 + /// 动效时长(秒)。用户定稿的三条:逐字 460ms + 15ms 步进、停止 190ms 收敛、满帧 16ms。 pub(crate) mod motion { use core::time::Duration; @@ -1682,11 +1682,11 @@ pub(crate) mod agent_scale { /// 光球:一圈 20 秒,呼吸 5.5 秒。 pub(crate) const ORB_LOOP: f64 = 20.0; pub(crate) const ORB_BREATH: f64 = 5.5; - /// 逐字扩散:单字入场 300ms cubic-out,每字步进 15ms,尾韵约 11 字。 - pub(crate) const REVEAL_ENTER: f64 = 0.300; + /// 逐字扩散:单字入场 460ms cubic-out,每字步进 15ms,尾韵约 13 字。 + pub(crate) const REVEAL_ENTER: f64 = 0.460; pub(crate) const REVEAL_STEP: f64 = 0.015; pub(crate) const REVEAL_MAX_SPAN: f64 = 0.650; - pub(crate) const REVEAL_TAIL: usize = 11; + pub(crate) const REVEAL_TAIL: usize = 13; pub(crate) const REVEAL_WAVE: f64 = 0.022; pub(crate) const REVEAL_RISE: f64 = 0.070; pub(crate) const REVEAL_FADE: f64 = 0.430; @@ -1796,7 +1796,7 @@ mod agent_token_tests { } /// 动效时长:对话框与浮层的进退场、表面弹簧、流光周期都保持此前的取值; - /// 用户定稿的三条(逐字 300ms + 15ms、停止 190ms、满帧 16ms)单独钉一遍。 + /// 用户定稿的三条(逐字 460ms + 15ms、停止 190ms、满帧 16ms)单独钉一遍。 #[test] fn agent_motion_tokens_keep_the_dialog_motion_and_pin_the_locked_brand_values() { assert_eq!(motion::NATIVE, 0.22); @@ -1808,9 +1808,8 @@ mod agent_token_tests { assert_eq!((motion::HALO_PERIOD, motion::LOADER_PERIOD), (1.8, 1.2)); assert_eq!((motion::GLOW_SEND, motion::GLOW_SEND_PEAK, motion::GLOW_WAIT_SCALE), (0.640, 0.280, 0.55)); assert_eq!((motion::ORB_LOOP, motion::ORB_BREATH), (20.0, 5.5)); - assert_eq!((motion::REVEAL_ENTER, motion::REVEAL_STEP, motion::REVEAL_MAX_SPAN), (0.300, 0.015, 0.650)); - assert_eq!(motion::REVEAL_TAIL, 11); - assert!((10..=12).contains(&motion::REVEAL_TAIL)); + assert_eq!((motion::REVEAL_ENTER, motion::REVEAL_STEP, motion::REVEAL_MAX_SPAN), (0.460, 0.015, 0.650)); + assert_eq!(motion::REVEAL_TAIL, 13); assert_eq!((motion::REVEAL_WAVE, motion::REVEAL_RISE, motion::REVEAL_FADE), (0.022, 0.070, 0.430)); assert_eq!(motion::REVEAL_SPREAD, 9.0); assert!((0.180..=0.200).contains(&motion::STOP_SETTLE), "停止减速定格收敛在 180–200ms");