抛光小壹制作时间流和窄窗工作台

This commit is contained in:
WuYongJie 2026-11-27 10:46:19 +08:00
parent cb09741133
commit 2a119f4434
8 changed files with 339 additions and 103 deletions

View File

@ -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::<f32>()
+ 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::<f32>() + 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<bool>, wrap: bool) {
fn suggestion_row(&mut self, app: &PhotocraftApp, ui: &mut Ui, key: &str, suggestions: [(&'static str, &'static str); 2], whole_detail: Option<bool>, 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<Preview>, 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);

View File

@ -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)),
)
})

View File

@ -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;

View File

@ -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"];

View File

@ -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::<bool>(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| {

View File

@ -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();

View File

@ -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<Response> {
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<Response> {
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<f32>, 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<V
(count > 0).then(|| format!("{} {count}", stage.label()))
}).collect::<Vec<_>>().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);

View File

@ -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);