From 66261b2a31e544fa4edb2765dae778772ce7f45d Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Mon, 30 Nov 2026 11:54:12 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E4=B8=8A=E5=B0=8F=E5=A3=B9=E5=9C=A8?= =?UTF-8?q?=E7=BA=BF=E6=9B=B4=E6=96=B0=E7=9A=84=E7=95=8C=E9=9D=A2=EF=BC=88?= =?UTF-8?q?R5-Z67=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 顶栏"账户"左边加更新胶囊,与导航分段同高同圆角:有新版本、需更新、下载进度(底部 2pt 细线)、重启以更新;其余状态不显示 - 点胶囊弹出约 320 宽的浮层:版本与当前版本、更新说明(超过 6 行滚动)、安装包大小;主按钮随状态换成下载更新、进度条、重启并更新,动作返回的错误原样显示在按钮下方 - 小壹设置末尾加版本一栏:当前版本与提交号、检查更新(检查中置灰)、检查结果 - 重启沿用"文件 › 退出"的退出前保存流程,不另加确认框 --- .../crates/ui-egui/src/jiansun.rs | 7 +- .../crates/ui-egui/src/jiansun/agent_panel.rs | 5 + .../ui-egui/src/jiansun/client_update_ui.rs | 707 ++++++++++++++++++ 3 files changed, 718 insertions(+), 1 deletion(-) create mode 100644 apps/detail-photocraft/crates/ui-egui/src/jiansun/client_update_ui.rs diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index 5722d30d..c76ef3b7 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -12,6 +12,7 @@ use std::{ mod account_dialog; mod client_update; +mod client_update_ui; mod agent_image_cache; mod agent_motion; mod glow_pill; @@ -1136,6 +1137,7 @@ pub struct Workspace { template_progress: Value, template_workflow: Value, client_update: client_update::ClientUpdate, + client_update_ui: client_update_ui::UpdateUi, product_production: Option, product_views: product_production::Views, product_target_hidden: bool, @@ -1676,6 +1678,7 @@ impl Workspace { template_progress: Value::Null, template_workflow: Value::Null, client_update: client_update::ClientUpdate::default(), + client_update_ui: client_update_ui::UpdateUi::default(), product_production: None, product_views: product_production::Views::default(), product_target_hidden: false, @@ -4081,7 +4084,7 @@ impl Workspace { } let account_width = 24.0 + self.navigation_account_label().chars() .map(|ch| if ch.is_ascii() { 8.0 } else { 14.0 }) - .sum::(); + .sum::() + self.update_capsule_width(); if app.session.active().is_none() { return account_width + 166.0 + 30.0; } @@ -4117,6 +4120,7 @@ impl Workspace { if stitch_ui::action_button(ui, &account_label, stitch_ui::ButtonRole::Quiet, true).on_hover_text(account_name).clicked() { self.config = true; } + self.update_capsule(app, ui); let projects = self.library || (!document_open && !self.material); let options: Vec<(&str, bool)> = if document_open { vec![("我的项目", true), ("添加素材", true), ("当前画布", true)] } else { vec![("我的项目", true), ("添加素材", true)] }; let selected = if projects { 0 } else if self.material { 1 } else { 2 }; @@ -5476,6 +5480,7 @@ mod tests { ("agent_presence", include_str!("jiansun/agent_presence.rs")), ("typing_text", include_str!("jiansun/typing_text.rs")), ("siri_orb", include_str!("jiansun/siri_orb.rs")), + ("client_update_ui", include_str!("jiansun/client_update_ui.rs")), ]; for (name, source) in library { for (index, line) in source.replace("\r\n", "\n").lines().enumerate() { 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 191add2b..0f725701 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 @@ -3180,6 +3180,8 @@ impl Workspace { if let Some(anchor) = compact_settings_anchor { self.settings_popup(ui, &anchor); } }); } + // 设置浮层里点的"检查更新"在这里派发:浮层本身拿不到 app。 + self.flush_client_update_request(app); let compact_stop_rect = Id::unique("jiansun-composer-compact-stop-rect"); if compact_stop { let compact_center = egui::pos2(surface_rect.right() - 27.0, mini_input.center().y); @@ -3744,6 +3746,9 @@ impl Workspace { self.api_key.clear(); } } + // 有"通知与警告"时补一条分隔线;没有时上面已经是分隔线。 + let after_notifications = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc).is_some(); + self.client_version_settings(ui, after_notifications); }); // egui reports the pre-auto-shrink inner rect. Match the // actual vertical viewport used by ScrollArea::end, rather diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/client_update_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/client_update_ui.rs new file mode 100644 index 00000000..b920737d --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/client_update_ui.rs @@ -0,0 +1,707 @@ +//! 在线更新的界面:顶栏更新胶囊、胶囊浮层、小壹设置里的"版本"一栏。 +//! 状态与动作都在 `client_update`(状态机)里;这里只读 `clientUpdate` 与 `clientVersion`, +//! 按钮只派发 `client-update` 的 check / download / apply,动作返回的错误原样显示。 +use super::stitch_ui::{self, ButtonRole, FocusRing, SurfaceRole}; +use super::{PhotocraftApp, RichText, Tokens, Ui, Value, Workspace, agent_panel, json}; +use crate::theme::agent_scale::{Type, control, radius, space}; +use egui::{Align, Layout, Response, Sense, vec2}; + +/// 与顶栏"我的项目 / 添加素材 / 当前画布"分段轨同高:分段选项高度加上轨的上下内距(各 3)。 +pub(super) const CAPSULE_HEIGHT: f32 = control::MENU_ROW + 6.0; +/// 胶囊左侧圆点的直径。 +const DOT: f32 = 6.0; +/// 浮层外宽(约 320)。 +const POPOVER_WIDTH: f32 = 320.0; +/// 更新说明超过这么多行就在区域内滚动。 +const NOTES_ROWS: f32 = 6.0; + +#[derive(Default)] +pub(super) struct UpdateUi { + /// 最近一次动作的错误:动作名、原文、出错时的更新状态。状态变了就不再显示。 + error: Option<(&'static str, String, Value)>, + /// 设置浮层里点了"检查更新"。设置浮层拿不到 app,由输入框区域随后派发。 + requested: Option<&'static str>, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum CapsuleKind { + Available, + Mandatory, + Downloading(f32), + Ready, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PopoverAction { + Download, + Apply, + Later, +} + +/// 胶囊的文字与样式;idle、checking、up-to-date、error 不显示胶囊。 +pub(super) fn capsule(state: &Value) -> Option<(String, CapsuleKind)> { + let version = state["latest"]["version"].as_str().unwrap_or_default(); + match state["status"].as_str()? { + "available" if state["mandatory"] == true => Some((format!("需更新到 {version}"), CapsuleKind::Mandatory)), + "available" => Some((format!("有新版本 {version}"), CapsuleKind::Available)), + "downloading" => { + let fraction = fraction(state); + Some((format!("下载更新 {}%", percent(fraction)), CapsuleKind::Downloading(fraction))) + } + "ready" => Some(("重启以更新".into(), CapsuleKind::Ready)), + _ => None, + } +} + +fn fraction(state: &Value) -> f32 { + let received = state["progress"]["received"].as_u64().unwrap_or(0); + let total = state["progress"]["total"].as_u64().unwrap_or(0); + if total == 0 { 0.0 } else { (received as f64 / total as f64).clamp(0.0, 1.0) as f32 } +} + +/// 已下载与总字节;宿主还没回报进度时,总量取发布记录里的安装包大小。 +fn download_bytes(state: &Value) -> (u64, u64) { + let progress = &state["progress"]; + let total = progress["total"].as_u64().filter(|total| *total > 0).or_else(|| state["latest"]["file"]["size"].as_u64()); + (progress["received"].as_u64().unwrap_or(0), total.unwrap_or(0)) +} + +fn percent(fraction: f32) -> u32 { + (fraction * 100.0).floor() as u32 +} + +/// 字节数按 MB(1024²)显示:10 MB 以下保留一位小数。 +fn megabytes(bytes: u64) -> String { + let value = bytes as f64 / 1_048_576.0; + if value >= 10.0 || bytes == 0 { format!("{value:.0}") } else { format!("{value:.1}") } +} + +/// 提交号取前 7 位。 +fn short_commit(commit: &str) -> Option<&str> { + commit.get(..7).filter(|short| short.bytes().all(|byte| byte.is_ascii_hexdigit())) +} + +/// `checkedAt` 是宿主写的 UTC RFC 3339 时间;按本机时区显示"时:分"。 +pub(super) fn local_clock(checked_at: &str) -> Option { + let field = |start: usize, end: usize| checked_at.get(start..end).and_then(|text| text.parse::().ok()); + let utc = [field(0, 4)?, field(5, 7)?, field(8, 10)?, field(11, 13)?, field(14, 16)?, field(17, 19)?]; + let in_utc = checked_at.ends_with('Z') || checked_at.ends_with("+00:00"); + let (hour, minute) = in_utc.then(|| to_local(utc)).flatten().unwrap_or((utc[3], utc[4])); + Some(format!("{hour:02}:{minute:02}")) +} + +#[cfg(target_os = "windows")] +fn to_local([year, month, day, hour, minute, second]: [u16; 6]) -> Option<(u16, u16)> { + let universal = winsafe::SYSTEMTIME { wYear: year, wMonth: month, wDay: day, wHour: hour, wMinute: minute, wSecond: second, ..Default::default() }; + winsafe::SystemTimeToTzSpecificLocalTime(None, &universal).ok().map(|local| (local.wHour, local.wMinute)) +} + +#[cfg(not(target_os = "windows"))] +fn to_local(_: [u16; 6]) -> Option<(u16, u16)> { + None +} + +/// 设置栏第二行的状态文字。 +fn settings_status(state: &Value) -> Option { + let version = state["latest"]["version"].as_str().unwrap_or_default(); + match state["status"].as_str()? { + "up-to-date" => Some(match state["checkedAt"].as_str().and_then(local_clock) { + Some(clock) => format!("已是最新版本 · {clock} 检查"), + None => "已是最新版本".into(), + }), + "available" | "downloading" | "ready" => Some(format!("发现新版本 {version}")), + "error" => { + let reason = state["error"].as_str().unwrap_or_default(); + // 检查时状态机会清空 latest;带着 latest 出错的是下载失败。 + Some(if state["latest"].is_null() { format!("检查失败:{reason}") } else { format!("更新失败:{reason}") }) + } + _ => None, + } +} + +impl Workspace { + /// 派发一次 `client-update` 动作;错误原样留给界面显示。 + fn run_client_update(&mut self, app: &PhotocraftApp, op: &'static str) { + self.client_update_ui.error = match self.client_update_action(app, &json!({"op": op})) { + Ok(_) => None, + Err(error) => Some((op, error, self.client_update.state["status"].clone())), + }; + } + + /// 设置浮层记下的"检查更新",在拿得到 app 的位置派发。 + pub(super) fn flush_client_update_request(&mut self, app: &PhotocraftApp) { + if let Some(op) = self.client_update_ui.requested.take() { + self.run_client_update(app, op); + } + } + + /// 仍然有效的动作错误:只在出错后状态没变时显示。 + fn client_update_error(&self, ops: &[&str]) -> Option<&str> { + self.client_update_ui.error.as_ref() + .filter(|(op, _, status)| ops.contains(op) && *status == self.client_update.state["status"]) + .map(|(_, error, _)| error.as_str()) + } + + /// 顶栏胶囊的预估宽度,给顶栏的滚动宽度用。 + pub(super) fn update_capsule_width(&self) -> f32 { + capsule(&self.client_update.state).map_or(0.0, |(label, kind)| { + let text = label.chars().map(|ch| if ch.is_ascii() { 8.0 } else { 14.0 }).sum::(); + let lead = if matches!(kind, CapsuleKind::Available | CapsuleKind::Mandatory) { DOT + 6.0 } else { 0.0 }; + 24.0 + lead + text + space::SM + }) + } + + /// 顶栏更新胶囊:在"账户"按钮左边,点开浮层。没有可显示的更新时什么也不画。 + pub(super) fn update_capsule(&mut self, app: &PhotocraftApp, ui: &mut Ui) { + let id = egui::Id::unique("jiansun-client-update-capsule"); + let Some((label, kind)) = capsule(&self.client_update.state) else { + egui::Popup::close_id(ui.ctx(), id.with("popup")); + return; + }; + let response = paint_capsule(ui, id, &label, kind); + self.navigation_geometry["update"] = agent_panel::rect_value(response.rect); + if response.clicked() { + egui::Popup::toggle_id(ui.ctx(), id.with("popup")); + } + match self.update_popover(ui, &response) { + Some(PopoverAction::Download) => self.run_client_update(app, "download"), + Some(PopoverAction::Apply) => self.run_client_update(app, "apply"), + Some(PopoverAction::Later) => { + egui::Popup::close_id(ui.ctx(), id.with("popup")); + self.client_update_ui.error = None; + } + None => {} + } + } + + /// 锚在胶囊下方的浮层,外观沿用小壹的弹出菜单。 + fn update_popover(&mut self, ui: &Ui, anchor: &Response) -> Option { + let id = anchor.id.with("popup"); + let open = egui::Popup::is_id_open(ui.ctx(), id); + let visual = stitch_ui::overlay_transition(ui.ctx(), id, open, self.reduce_motion); + stitch_ui::anchored_overlay(ui.ctx(), id, anchor, visual); + if !visual.render { + return None; + } + let popup = egui::Popup::from_response(anchor).id(id).kind(egui::PopupKind::Menu) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .align(egui::RectAlign::BOTTOM_END) + .width(POPOVER_WIDTH).style(stitch_ui::scoped_popup_style(ui)) + .frame(egui::Frame::NONE); + let popup = if open { popup.open_memory(None) } else { popup.open(true).interactable(false) }; + let error = self.client_update_error(&["download", "apply"]).map(str::to_owned); + let (state, version, reduced) = (&self.client_update.state, &self.client_update.version, self.reduce_motion); + let shown = popup.show(|ui| { + let frame = stitch_ui::overlay_frame(ui.ctx(), SurfaceRole::Menu, visual.opacity).inner_margin(space::MD as i8); + let mut prepared = frame.begin(ui); + let light = super::agent_motion::reserve_background(&prepared.content_ui); + let view = stitch_ui::overlay_contents(&mut prepared.content_ui, visual, |ui| { + popover_contents(ui, state, version, error.as_deref(), reduced) + }); + let rect = frame.widget_rect(prepared.content_ui.min_rect()); + prepared.end(ui); + let opacity = ui.opacity(); + ui.set_opacity(opacity * visual.opacity); + let t = Tokens::get(ui.ctx()).agent(); + stitch_ui::material_over(ui, id, rect, radius::MENU, 0.0, light, stitch_ui::menu_base(), stitch_ui::menu_rim(t)); + ui.set_opacity(opacity); + view.map(|view| (view.inner, rect)) + }); + let (view, surface) = shown.and_then(|shown| shown.inner)?; + self.navigation_geometry["updatePopover"] = agent_panel::rect_value(surface); + self.navigation_geometry["updateNotes"] = view.notes.map_or(Value::Null, agent_panel::rect_value); + view.action.filter(|_| visual.interactive) + } + + /// 小壹设置末尾的"版本"一栏:当前版本、提交号、检查更新与状态。 + pub(super) fn client_version_settings(&mut self, ui: &mut Ui, divider: bool) { + let Some(version) = self.client_update.version["version"].as_str().map(str::to_owned) else { return }; + if divider { + stitch_ui::divider(ui); + } + let t = Tokens::get(ui.ctx()).agent(); + let status = self.client_update.state["status"].as_str().unwrap_or_default().to_owned(); + let checking = status == "checking"; + let commit = self.client_update.version["commit"].as_str().and_then(short_commit).map(str::to_owned); + let mut clicked = false; + ui.horizontal(|ui| { + ui.label(RichText::new(format!("当前版本 {version}")).size(Type::Title.size()).color(t.text)); + if let Some(commit) = commit { + ui.label(RichText::new(format!("(提交 {commit})")).size(Type::Title.size()).color(t.text_dim)); + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let label = if checking { "检查中…" } else { "检查更新" }; + clicked = stitch_ui::action_button(ui, label, ButtonRole::Quiet, !checking && status != "downloading").clicked(); + }); + }); + if clicked { + self.client_update_ui.requested = Some("check"); + } + let line = self.client_update_error(&["check"]).map(|error| format!("检查失败:{error}")) + .or_else(|| settings_status(&self.client_update.state)); + if let Some(line) = line { + ui.add(egui::Label::new(RichText::new(line).size(Type::Meta.size()).color(t.text_dim)).wrap()); + } + } +} + +/// 画胶囊:与顶栏分段轨同高同圆角,字号同顶栏按钮。 +fn paint_capsule(ui: &mut Ui, id: egui::Id, label: &str, kind: CapsuleKind) -> Response { + let t = Tokens::get(ui.ctx()).agent(); + let (text, rest, hover, pressed) = match kind { + CapsuleKind::Ready => (t.primary_text, t.primary_bg, t.primary_bg.lerp_to_gamma(t.primary_text, 0.07), t.primary_bg.lerp_to_gamma(t.primary_text, 0.15)), + CapsuleKind::Mandatory => (t.warning, t.field, t.hover, t.pressed), + CapsuleKind::Available | CapsuleKind::Downloading(_) => (t.text, t.field, t.hover, t.pressed), + }; + let galley = ui.painter().layout_no_wrap(label.to_owned(), Type::Title.font_id(), text); + // 下载中按最宽的百分比定宽,数字跳动时左边的导航不跟着抖。 + let text_width = if matches!(kind, CapsuleKind::Downloading(_)) { + galley.size().x.max(ui.painter().layout_no_wrap("下载更新 100%".into(), Type::Title.font_id(), text).size().x) + } else { + galley.size().x + }; + let padding = ui.spacing().button_padding.x; + let lead = if matches!(kind, CapsuleKind::Available | CapsuleKind::Mandatory) { DOT + 6.0 } else { 0.0 }; + let (_, rect) = ui.allocate_space(vec2(padding * 2.0 + lead + text_width, CAPSULE_HEIGHT)); + let response = ui.interact(rect, id, Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + if ui.is_rect_visible(rect) { + let painter = ui.painter(); + let fill = if response.is_pointer_button_down_on() { pressed } else if response.hovered() { hover } else { rest }; + painter.rect_filled(rect, radius::CHIP, fill); + let mut x = rect.left() + padding; + if lead > 0.0 { + let dot = if kind == CapsuleKind::Mandatory { t.warning } else { t.accent }; + painter.circle_filled(egui::pos2(x + DOT * 0.5, rect.center().y), DOT * 0.5, dot); + x += lead; + } + painter.galley(egui::pos2(x, rect.center().y - galley.size().y * 0.5), galley, text); + if let CapsuleKind::Downloading(fraction) = kind { + // 2pt 进度细线:左右各让出圆角,避免越出胶囊的弧线。 + let track = egui::Rect::from_min_max(egui::pos2(rect.left() + radius::CHIP, rect.bottom() - 4.0), egui::pos2(rect.right() - radius::CHIP, rect.bottom() - 2.0)); + painter.rect_filled(track, 1.0, t.hover); + let filled = egui::Rect::from_min_size(track.min, vec2(track.width() * fraction, track.height())); + if filled.is_positive() { + painter.rect_filled(filled, 1.0, t.text_dim); + } + } + } + stitch_ui::focus_ring(ui, &response, radius::CHIP, if kind == CapsuleKind::Ready { FocusRing::OnPrimary } else { FocusRing::Control }); + response +} + +struct PopoverView { + action: Option, + notes: Option, +} + +fn popover_contents(ui: &mut Ui, state: &Value, version: &Value, error: Option<&str>, reduced: bool) -> PopoverView { + let t = Tokens::get(ui.ctx()).agent(); + ui.set_width(POPOVER_WIDTH - 2.0 * (space::MD + 1.0)); + ui.spacing_mut().item_spacing = vec2(space::SM, space::SM); + let latest = &state["latest"]; + let meta = |text: String| RichText::new(text).size(Type::Meta.size()).color(t.text_dim); + ui.horizontal(|ui| { + let title = format!("小壹 {}", latest["version"].as_str().unwrap_or_default()); + ui.label(RichText::new(title).size(Type::Subheading.size()).strong().color(t.text)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.label(meta(format!("当前 {}", version["version"].as_str().unwrap_or_default()))); + }); + }); + let notes = latest["notes"].as_str().filter(|notes| !notes.trim().is_empty()).map(|notes| { + let row = ui.painter().layout_no_wrap("小壹".into(), Type::Meta.font_id(), t.text).size().y; + egui::ScrollArea::vertical().id_salt("jiansun-client-update-notes").max_height(row * NOTES_ROWS).auto_shrink([false, true]) + .show(ui, |ui| ui.add(egui::Label::new(RichText::new(notes).size(Type::Meta.size()).color(t.text)).wrap())) + .inner_rect + }); + if let Some(size) = latest["file"]["size"].as_u64() { + ui.label(meta(format!("安装包 {} MB", megabytes(size)))); + } + if state["status"] == "downloading" { + let fraction = fraction(state); + let (received, total) = download_bytes(state); + let text = format!("下载中 {}%({} / {} MB)", percent(fraction), megabytes(received), megabytes(total)); + ui.label(meta(text.clone())); + stitch_ui::progress_bar(ui, ui.scope_id().with("jiansun-client-update-progress"), &text, Some(fraction), reduced); + } + let mut action = None; + ui.allocate_ui_with_layout(vec2(ui.available_width(), control::DEFAULT), Layout::right_to_left(Align::Center), |ui| { + let primary = match state["status"].as_str() { + Some("available") => Some(("下载更新", PopoverAction::Download)), + Some("ready") => Some(("重启并更新", PopoverAction::Apply)), + _ => None, + }; + if let Some((label, choice)) = primary + && stitch_ui::action_button(ui, label, ButtonRole::Primary, true).clicked() + { + action = Some(choice); + } + if stitch_ui::action_button(ui, "稍后", ButtonRole::Secondary, true).clicked() { + action = Some(PopoverAction::Later); + } + }); + if let Some(error) = error { + ui.add(egui::Label::new(RichText::new(error).size(Type::Meta.size()).color(t.warning)).wrap()); + } + PopoverView { action, notes } +} + +#[cfg(test)] +mod tests { + use super::*; + use super::super::Request; + use egui_kittest::{Harness, kittest::{NodeT, Queryable}}; + use std::sync::mpsc; + + const LATEST: &str = "1.1.0"; + + fn latest() -> Value { + json!({"version":LATEST,"channel":"stable","notes":"修复制作中断后无法续传的问题\n优化画布载入速度","file":{"size":159_383_552_u64,"sha256":"a".repeat(64)}}) + } + + fn state(status: &str) -> Value { + json!({"status":status,"latest":latest(),"mandatory":false,"progress":{"received":0,"total":0},"error":null,"checkedAt":null}) + } + + fn workspace() -> (Workspace, mpsc::Receiver) { + let (tx, requests) = mpsc::channel(); + let (_events, rx) = mpsc::channel(); + let mut workspace = Workspace::new(tx, rx); + while requests.try_recv().is_ok() {} + workspace.account = json!({"id":"qa","name":"验收"}); + workspace.busy = None; + workspace.reduce_motion = true; + workspace.configure_client_update(json!({"version":"1.0.0","commit":"7f6686c5943aae0fa7c0b89d0a19ff28c659979d","builtAt":"2026-11-30T02:00:00Z","channel":"stable"}), true, |_| Ok(())); + // 状态机在账户变化时会重置状态:先用一次检查对齐账户范围,再由各用例直接写入状态。 + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert!(workspace.client_update_action(&app, &json!({"op":"check"})).is_ok()); + while requests.try_recv().is_ok() {} + workspace.client_update.state = json!({"status":"idle","latest":null,"mandatory":false,"progress":{"received":0,"total":0},"error":null,"checkedAt":null}); + (workspace, requests) + } + + fn app_with(workspace: Workspace) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.jiansun = Some(workspace); + app + } + + fn toolbar(app: PhotocraftApp, width: f32) -> Harness<'static, PhotocraftApp> { + let mut harness = Harness::builder() + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(vec2(width, 480.0)) + .build_ui_state(|ui, app: &mut PhotocraftApp| { + if stitch_ui::ui_fonts_ready(ui) { crate::panels::options_bar(app, ui); } + }, app); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); + harness.run_steps(4); + harness + } + + /// 通道里发给宿主的 `client-update` 动作,按发送顺序。 + fn update_requests(requests: &mpsc::Receiver) -> Vec { + requests.try_iter().filter_map(|request| match request { + Request::Action(name, input) if name == "client-update" => Some(input), + _ => None, + }).collect() + } + + fn set_state(harness: &mut Harness<'_, PhotocraftApp>, value: Value) { + if let Some(w) = harness.state_mut().jiansun.as_mut() { + w.client_update.state = value; + } + harness.run_steps(3); + } + + const CAPSULES: [&str; 5] = ["有新版本 1.1.0", "需更新到 1.1.0", "下载更新 45%", "重启以更新", "下载更新 0%"]; + + fn capsule_labels(harness: &Harness<'_, PhotocraftApp>) -> Vec<&'static str> { + CAPSULES.into_iter().filter(|label| harness.query_by_label(label).is_some()).collect() + } + + #[test] + fn update_capsule_shows_only_for_available_mandatory_downloading_and_ready() { + let (w, _requests) = workspace(); + let mut harness = toolbar(app_with(w), 1280.0); + for status in ["idle", "checking", "up-to-date", "error"] { + set_state(&mut harness, state(status)); + assert!(capsule_labels(&harness).is_empty(), "{status} has no capsule"); + } + set_state(&mut harness, state("available")); + assert_eq!(capsule_labels(&harness), ["有新版本 1.1.0"]); + let account = harness.get_by_label("账户 · 验收").rect(); + let projects = harness.get_by_label("我的项目").rect(); + let pill = harness.get_by_label("有新版本 1.1.0").rect(); + assert!(pill.right() <= account.left() && pill.left() >= projects.right(), "capsule sits between the navigation and the account"); + assert!((pill.height() - (projects.height() + 6.0)).abs() < 0.5, "capsule matches the segmented rail height: {pill:?} vs {projects:?}"); + assert!((pill.center().y - projects.center().y).abs() < 1.0, "capsule shares the navigation row"); + let mut mandatory = state("available"); + mandatory["mandatory"] = json!(true); + set_state(&mut harness, mandatory); + assert_eq!(capsule_labels(&harness), ["需更新到 1.1.0"]); + let mut downloading = state("downloading"); + downloading["progress"] = json!({"received":72_000_000_u64,"total":159_383_552_u64}); + set_state(&mut harness, downloading); + assert_eq!(capsule_labels(&harness), ["下载更新 45%"]); + set_state(&mut harness, state("ready")); + assert_eq!(capsule_labels(&harness), ["重启以更新"]); + assert_eq!(capsule(&state("ready")).map(|(_, kind)| kind), Some(CapsuleKind::Ready)); + } + + #[test] + fn update_popover_switches_its_primary_action_and_shows_action_errors() { + let (w, requests) = workspace(); + let mut harness = toolbar(app_with(w), 1280.0); + set_state(&mut harness, state("available")); + harness.get_by_label("有新版本 1.1.0").click(); + harness.run_steps(3); + for label in ["小壹 1.1.0", "当前 1.0.0", "安装包 152 MB", "下载更新", "稍后"] { + assert!(harness.query_by_label(label).is_some(), "{label} is in the popover"); + } + let popover = harness.state().jiansun.as_ref().map(|w| w.navigation_geometry["updatePopover"].clone()).unwrap_or_default(); + let width = popover[2].as_f64().unwrap_or_default(); + assert!((300.0..=330.0).contains(&width), "popover is about 320 wide: {width}"); + + harness.get_by_label("下载更新").click(); + harness.run_steps(3); + let sent = update_requests(&requests); + assert_eq!(sent.len(), 1, "one download request: {sent:?}"); + assert_eq!(sent[0]["op"], "download"); + assert!(harness.query_by_label("下载更新").is_none(), "the download button gives way to progress"); + // 文字与进度条共用同一段说明作无障碍名称。 + assert_eq!(harness.query_all_by_label("下载中 0%(0 / 152 MB)").count(), 2); + + if let Some(w) = harness.state_mut().jiansun.as_mut() { + w.client_update.state["progress"] = json!({"received":71_303_168_u64,"total":159_383_552_u64}); + } + harness.run_steps(3); + assert_eq!(harness.query_all_by_label("下载中 44%(68 / 152 MB)").count(), 2); + assert!(harness.query_by_label("下载更新 44%").is_some(), "the capsule follows the same progress"); + + if let Some(w) = harness.state_mut().jiansun.as_mut() { + w.client_update.state = state("ready"); + w.busy = Some("pi-agent".into()); + } + harness.run_steps(3); + harness.get_by_label("重启并更新").click(); + harness.run_steps(3); + assert!(harness.query_by_label("制作结束后再重启更新").is_some(), "the action error is shown verbatim"); + assert!(!harness.state().jiansun.as_ref().is_some_and(|w| w.client_update.restart_requested)); + + if let Some(w) = harness.state_mut().jiansun.as_mut() { w.busy = None; } + harness.get_by_label("重启并更新").click(); + harness.run_steps(3); + assert!(harness.state().jiansun.as_ref().is_some_and(|w| w.client_update.restart_requested), "apply requests the restart"); + assert!(harness.query_by_label("制作结束后再重启更新").is_none(), "a successful action clears the old error"); + + harness.get_by_label("稍后").click(); + harness.run_steps(3); + assert!(harness.query_by_label("重启并更新").is_none(), "later closes the popover"); + assert!(harness.query_by_label("重启以更新").is_some(), "the capsule stays"); + } + + #[test] + fn long_update_notes_scroll_after_six_lines() { + let (w, _requests) = workspace(); + let mut harness = toolbar(app_with(w), 1280.0); + let mut available = state("available"); + available["latest"]["notes"] = json!((1..=12).map(|line| format!("第 {line} 条更新说明")).collect::>().join("\n")); + set_state(&mut harness, available); + harness.get_by_label("有新版本 1.1.0").click(); + harness.run_steps(3); + let notes = harness.state().jiansun.as_ref().map(|w| w.navigation_geometry["updateNotes"].clone()).unwrap_or_default(); + let height = notes[3].as_f64().unwrap_or_default(); + assert!(height > 60.0 && height < 130.0, "notes stop at six rows and scroll: {height}"); + assert!(harness.query_by_label("下载更新").is_some(), "the action stays visible under long notes"); + } + + fn settings(w: Workspace) -> Harness<'static, Workspace> { + let mut harness = Harness::builder() + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(vec2(360.0, 160.0)) + .build_ui_state(|ui, w: &mut Workspace| if stitch_ui::ui_fonts_ready(ui) { w.client_version_settings(ui, true); }, w); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); + harness.run_steps(4); + harness + } + + #[test] + fn version_settings_show_commit_check_button_and_status_lines() { + let (w, requests) = workspace(); + let mut harness = settings(w); + for label in ["当前版本 1.0.0", "(提交 7f6686c)", "检查更新"] { + assert!(harness.query_by_label(label).is_some(), "{label}"); + } + harness.get_by_label("检查更新").click(); + harness.run_steps(2); + assert_eq!(harness.state().client_update_ui.requested, Some("check")); + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + harness.state_mut().flush_client_update_request(&app); + harness.run_steps(2); + let sent = update_requests(&requests); + assert_eq!(sent.len(), 1, "one check request: {sent:?}"); + assert_eq!(sent[0]["op"], "check"); + let checking = harness.get_by_label("检查中…"); + assert!(checking.accesskit_node().is_disabled(), "the check button is greyed out while checking"); + + let checked_at = "2026-11-30T02:32:00+00:00"; + let clock = local_clock(checked_at).unwrap_or_default(); + let mut cases = vec![ + ({ let mut s = state("up-to-date"); s["latest"] = Value::Null; s["checkedAt"] = json!(checked_at); s }, format!("已是最新版本 · {clock} 检查")), + (state("available"), "发现新版本 1.1.0".to_owned()), + ({ let mut s = state("error"); s["latest"] = Value::Null; s["error"] = json!("更新连接失败:无法连接"); s }, "检查失败:更新连接失败:无法连接".to_owned()), + ]; + cases.push(({ let mut s = state("error"); s["error"] = json!("更新包 SHA-256 校验失败"); s }, "更新失败:更新包 SHA-256 校验失败".to_owned())); + for (value, line) in cases { + harness.state_mut().client_update.state = value; + harness.run_steps(2); + assert!(harness.query_by_label(&line).is_some(), "{line}"); + assert!(harness.query_by_label("检查更新").is_some_and(|button| !button.accesskit_node().is_disabled())); + } + } + + #[test] + fn version_settings_show_check_action_errors_and_local_clock() { + let (mut w, _requests) = workspace(); + w.account = Value::Null; + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + w.client_update_ui.requested = Some("check"); + w.flush_client_update_request(&app); + let harness = settings(w); + assert!(harness.query_by_label("检查失败:请先在素材库登录").is_some(), "a refused check is explained in the status line"); + let clock = local_clock("2026-11-30T02:32:00.123456789+00:00").unwrap_or_default(); + assert_eq!(clock.len(), 5); + assert_eq!(local_clock("2026-11-30T10:32:00+08:00").as_deref(), Some("10:32"), "a non-UTC stamp is shown as written"); + assert_eq!(local_clock("bad"), None); + assert_eq!(megabytes(159_383_552), "152"); + assert_eq!(megabytes(5_767_168), "5.5"); + assert_eq!(short_commit("7f6686c5943aae0f"), Some("7f6686c")); + assert_eq!(short_commit("dev"), None); + } + + #[test] + fn version_settings_render_without_applying_texture_deltas() { + let (mut w, _requests) = workspace(); + w.client_update.state = state("available"); + let ctx = egui::Context::default(); + let output = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 160.0))), ..Default::default() }, |ui| w.client_version_settings(ui, false)); + let mut texts = Vec::new(); + fn collect(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, out)), + egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), + _ => {} + } + } + for clipped in &output.shapes { collect(&clipped.shape, &mut texts); } + output.drop_without_applying_deltas(); + assert!(texts.iter().any(|text| text == "发现新版本 1.1.0"), "{texts:?}"); + } + + fn evidence_states() -> Vec<(&'static str, Value, Option<&'static str>)> { + let mut up_to_date = state("up-to-date"); + up_to_date["latest"] = Value::Null; + up_to_date["checkedAt"] = json!("2026-11-30T02:32:00+00:00"); + let mut mandatory = state("available"); + mandatory["mandatory"] = json!(true); + let mut downloading = state("downloading"); + downloading["progress"] = json!({"received":71_303_168_u64,"total":159_383_552_u64}); + let mut long = state("available"); + long["latest"]["notes"] = json!((1..=12).map(|line| format!("第 {line} 条更新说明:修复与优化")).collect::>().join(" +")); + vec![ + ("up-to-date", up_to_date, None), + ("available", state("available"), None), + ("mandatory", mandatory, None), + ("downloading", downloading, None), + ("ready", state("ready"), None), + ("ready-error", state("ready"), Some("制作结束后再重启更新")), + ("long-notes", long, None), + ] + } + + #[test] + #[ignore = "offscreen GPU visual evidence; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn client_update_visual_evidence() { + let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory")); + std::fs::create_dir_all(&directory).unwrap(); + let _guard = photocraft_testkit::gpu_lock(); + for (name, value, error) in evidence_states() { + for open in [false, true] { + let Some((label, _)) = capsule(&value) else { + if open { continue; } + // 不显示胶囊的状态也留一张顶栏图作对照。 + let (mut w, _requests) = workspace(); + w.client_update.state = value.clone(); + save_topbar(&directory, &format!("topbar-{name}"), w, None); + continue; + }; + if !open && matches!(name, "ready-error" | "long-notes") { continue; } + let (mut w, _requests) = workspace(); + w.client_update.state = value.clone(); + if let Some(error) = error { + w.client_update_ui.error = Some(("apply", error.into(), value["status"].clone())); + } + let prefix = if open { "popover" } else { "topbar" }; + save_topbar(&directory, &format!("{prefix}-{name}"), w, open.then_some(label.as_str())); + } + } + let mut checking = state("checking"); + checking["latest"] = Value::Null; + let mut failed = state("error"); + failed["latest"] = Value::Null; + failed["error"] = json!("更新连接失败:无法连接素材库"); + let up_to_date = evidence_states().swap_remove(0).1; + for (name, value) in [("up-to-date", up_to_date), ("available", state("available")), ("checking", checking), ("error", failed)] { + let (mut w, _requests) = workspace(); + w.client_update.state = value; + let mut harness = Harness::builder() + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(vec2(400.0, 170.0)).with_max_steps(64).wgpu() + .build_ui_state(|ui, w: &mut Workspace| { + if !stitch_ui::ui_fonts_ready(ui) { return; } + let t = Tokens::get(ui.ctx()).agent(); + ui.painter().rect_filled(ui.max_rect(), 0.0, t.canvas); + stitch_ui::scope_with_motion(ui, true, |ui| { + ui.add_space(12.0); + // 与小壹设置浮层同一表面:对话框材质、18 内距、同样的标题与分隔线。 + let frame = stitch_ui::surface_frame(ui.ctx(), SurfaceRole::Dialog).inner_margin(18); + stitch_ui::material_frame(ui, frame, |ui| { + ui.set_width(324.0); + ui.spacing_mut().item_spacing = vec2(8.0, 10.0); + ui.label(RichText::new("小壹设置 · 末尾的版本一栏").size(14.0).strong().color(t.text)); + w.client_version_settings(ui, true); + }); + }); + }, w); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); + harness.run_steps(6); + harness.render().unwrap().save(directory.join(format!("settings-{name}.png"))).unwrap(); + } + } + + fn save_topbar(directory: &std::path::Path, name: &str, w: Workspace, click: Option<&str>) { + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + app.sync_views(); + app.jiansun = Some(w); + let height = if click.is_some() { 420.0 } else { 60.0 }; + let mut harness = Harness::builder() + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(vec2(1180.0, height)).with_max_steps(64).wgpu() + .build_ui_state(|ui, app: &mut PhotocraftApp| { + if stitch_ui::ui_fonts_ready(ui) { crate::panels::options_bar(app, ui); } + }, app); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); + harness.run_steps(6); + if let Some(label) = click { + harness.get_by_label(label).click(); + harness.run_steps(6); + } + // 指针移到左下角空白处:截图里不留悬停高亮,也不让指针盖住文字。 + harness.hover_at(egui::pos2(8.0, height - 8.0)); + harness.run_steps(4); + harness.render().unwrap().save(directory.join(format!("{name}.png"))).unwrap(); + } +}