diff --git a/apps/detail-photocraft/DESIGN.md b/apps/detail-photocraft/DESIGN.md index d06bf575..dce515bd 100644 --- a/apps/detail-photocraft/DESIGN.md +++ b/apps/detail-photocraft/DESIGN.md @@ -491,3 +491,24 @@ Agent 导入的完全透明页面背景以原生“无填充”表达,保留 **接入情况。** 已在本批接入生产代码的:语义色与阶梯 Token(库内全部字面量已替换)、`focus_ring`、`task_status_row`、`tool_group_head`、`paint_status_badge`、用户气泡(减少动态已一路透传)、输入浮层的光涌档位、输入框的光球档位与柔光、排版缓存、错误提示的类别驱动(`operation_error.rs`)。 **仍未接入。** 时间流 11 块外壳、目标驾驶舱、等待卡、提示条、停止钮、自适应网格、列表行、独立状态徽标、叠图说明都还没有生产调用方,第 2 批接入;`Hover Highlight`、`Blob Warp` 维持原状。 + +## 多项目并发四层视觉层级(T7B · 2026-12-02) + +为消除多项目并发制作时的「不知道后台有几个项目在跑」「不知道当前视图归属哪款商品」「把当前查看成品误当成正在制作成品」三类核心迷失,客户端新增纯 ViewModel 驱动的四层视觉层级模块 `jiansun/multi_project_ui.rs`: + +1. **第一层|全局后台任务条(Global Task Strip)**:仅在存在活跃/排队/暂停任务时占位,无后台任务为零高度。左侧固定展示并发容量计数(如「进行中 2/2 · 排队 1」);右侧为各项目运行胶囊(24pt 高、`radius::CHIP`),运行态使用冷月青微呼吸点与轻描边,排队态使用空心稳态圆点,暂停/部分交付使用告警色,当前项目标「当前」而不重复放停止钮,非当前运行项目支持快捷暂停。可用宽度低于 `540pt` 时自动收敛为单颗汇总触发器 + `stitch_ui::select_popup` 弹出列表,禁止挤压换行或横向截断。 +2. **第二层|常驻项目身份胶囊(Persistent Project Identity)**:常驻展示当前项目名称与所处环节(「我的项目」「产品资料」「模板画布」),消除顶栏无项目名及资料/画布段切换带来的迷失感;当其他项目正在后台制作而当前项目空闲时,给出温和提示与一键切换入口。 +3. **第三层|「正在查看」与「正在制作」强区分横条(Viewing vs Producing Divergence Strip)**:当 `viewing_differs_from_producing == true` 时显示低噪验证色调信息条(「当前查看:主图 · 后台正制作:详情页」),右侧提供 `Quiet` 一键返回按钮「回到正在制作的详情页」;窄栏(`< 390pt`)自动折行不裁切。 +4. **第四层|右侧驾驶舱与「我的项目」实时态一致性**:右侧停靠栏顶部对接三层上下文头(保持产品资料页协作者钩子不受干扰);`project_browser.rs` 在项目卡片封面左上角区分磁盘静态态与实时运行态(「后台制作中」「排队等待中」「已部分交付·缺项待补」「已暂停」),并在元信息第二行呈现实时产出进度,同时在「我的项目」标题行右侧提供全局设置图标入口直达同一「小壹设置」弹层。 + +## 本机存储设置、两阶段迁移与空间清理(T8 · 2026-12-02) + +新增本机全局存储管理模块 `jiansun/storage_settings_ui.rs`,状态存于机器级全局作用域(切换账号不重置),严格使用 `Tokens::agent()`、`AGENT_SEMANTIC` 与 `agent_scale`: + +1. **「小壹设置」新增「数据存储」卡片**:挂载于 `settings_popup` 中 `client_version_settings` 之后,使用 `stitch_ui::surface_card`;展示当前目录模式(默认目录 / 自定义目录 / 环境变量指定 / 便携模式 / 目录不可用)、自动换行的完整目录路径、异步占用与项目数(未返回前显示「统计中…」绝不伪造 0 GB)、只读锁定说明与操作引导,以及 `Quiet` 按钮「更改目录…」「清理空间」「打开目录」。 +2. **两阶段存储迁移弹窗**:沿用 `client_update_ui.rs` 骨架(`stitch_ui::modal`,宽 `(屏宽 - 64).clamp(340, 520)`,底栏固定 34pt 主/次按钮): + - 选目录与硬校验:展示目标盘剩余空间、禁止符号链接/目录联接/网盘同步目录等硬拦截原因、长路径软警告与迁移须知; + - 阶段 1(在线预拷贝):使用确定性 `stitch_ui::progress_bar_tinted` 展示已拷贝字节 / 总字节与速度,允许点击「后台继续」不阻塞主界面操作; + - 阶段 2(切换与重启):禁止假百分比,使用四步步骤清单(停写冻结核对 → 路径改写与校验 → 原子落指针 → 重启应用),切换期间弹窗不可关闭(无关闭按钮、拦截 Escape); + - 失败/回滚态展示清晰错误与原目录未损说明并提供「重试迁移」;重启后自检通过态展示新目录确认并提供二次确认保护的 `QuietDanger`「释放旧目录」或「稍后保留 7 天兜底」。 +3. **「清理空间」弹窗**:先进入只读扫描态(不修改任何作品),扫描完成后清晰分区展示「无损直接回收(默认勾选,硬链接去重/孤儿回收/残留清理)」与「历史归档清理(默认不勾选,保留策略与风险说明清晰可见)」,底部实时汇总预计释放空间与「开始清理」。 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 111aa394..3181eddb 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 @@ -1,4 +1,9 @@ //! Native collaboration dock. Model execution and credential storage remain outside the UI. +#[path = "multi_project_ui.rs"] +pub(super) mod multi_project_ui; +#[path = "storage_settings_ui.rs"] +pub(super) mod storage_settings_ui; + use super::stitch_timeline as timeline; use super::stitch_state::{NoticeKind, RunState, ToolStatus, WorkerStage}; use timeline::GoalProgressPanel; @@ -1186,6 +1191,7 @@ impl Workspace { ui.set_opacity(ui.opacity()*(1.0-0.18*pulse)); self.agent_body_inner(app,ui); }); + self.storage_modals_ui(ui.ctx()); }); } @@ -1339,6 +1345,10 @@ impl Workspace { Frame::NONE.inner_margin(egui::Margin::symmetric(16, 8)) .show(ui, |ui| self.library_notice(ui)); } + let multi_vm = self.multi_project_view_model(app, ui.ctx()); + if let Some(action) = multi_project_ui::dock_context_header(ui, &multi_vm, self.reduce_motion) { + self.handle_multi_project_action(app, ui.ctx(), action); + } if production || self.product_production.as_ref().is_some_and(|run| run.clock_paused()) { let head_start = crate::gpu_canvas::now_ms(); self.production_head_ui(app, ui); @@ -3879,7 +3889,7 @@ impl Workspace { }); } - fn settings_popup(&mut self, ui: &mut Ui, anchor: &Response) { + pub(super) fn settings_popup(&mut self, ui: &mut Ui, anchor: &Response) { let open = self.model_settings || self.key_settings; let t = Tokens::get(ui.ctx()).agent(); let (visual, transform) = super::stitch_ui::floating_panel_motion(ui.ctx(), anchor.id.with("popup"), anchor, open, self.reduce_motion); @@ -3993,6 +4003,8 @@ impl Workspace { // 有"通知与警告"时补一条分隔线;没有时上面已经是分隔线。 let after_notifications = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc).is_some(); self.client_version_settings(ui, after_notifications); + let after_version = after_notifications || self.client_update.version["version"].is_string(); + self.storage_settings_section(ui, after_version); }); // egui reports the pre-auto-shrink inner rect. Match the // actual vertical viewport used by ScrollArea::end, rather @@ -4019,6 +4031,151 @@ impl Workspace { ui.ctx().request_repaint(); } } + + pub(super) fn multi_project_view_model( + &self, + app: &PhotocraftApp, + ctx: &egui::Context, + ) -> multi_project_ui::MultiProjectViewModel { + if let Some(injected) = multi_project_ui::snapshot(ctx) { + return injected; + } + let section = match self.agent_page(app) { + "brief" => multi_project_ui::WorkspaceSection::Brief, + "canvas" | "professional" => multi_project_ui::WorkspaceSection::Canvas, + _ => multi_project_ui::WorkspaceSection::Projects, + }; + let project_id = self.project_context["localId"] + .as_str() + .or_else(|| self.project_context["id"].as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + let project_title = self.project_context["name"] + .as_str() + .or_else(|| self.creation_brief["name"].as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + let viewing_output_id = self.template_workflow["activeOutputId"] + .as_str() + .or_else(|| self.template_workflow["outputId"].as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + let viewing_output_label = viewing_output_id + .as_deref() + .map(|id| multi_project_ui::output_display_label(id).to_owned()); + let producing_output_id = self + .product_production + .as_ref() + .and_then(|run| run.working_output()) + .and_then(|row| row["outputId"].as_str().map(str::to_owned)); + let producing_output_label = producing_output_id + .as_deref() + .map(|id| multi_project_ui::output_display_label(id).to_owned()); + let viewing_differs_from_producing = matches!( + (&viewing_output_id, &producing_output_id), + (Some(v), Some(p)) if v != p + ); + let mut global_runs = Vec::new(); + if let Some(run) = self.product_production.as_ref() + && let Some(pid) = project_id.clone() + { + let status = if run.clock_paused() { + multi_project_ui::MultiRunStatus::Paused + } else { + multi_project_ui::MultiRunStatus::Running + }; + global_runs.push(multi_project_ui::GlobalRunEntry { + project_id: pid, + project_title: project_title.clone().unwrap_or_else(|| "当前项目".into()), + status, + producing_output_id: producing_output_id.clone().unwrap_or_default(), + producing_output_label: producing_output_label.clone().unwrap_or_default(), + progress_label: run.progress_label().unwrap_or_default(), + elapsed_secs: run.elapsed().as_secs(), + active_slots: self.production_workers().iter().filter(|w| w.active).count(), + has_attention: self.pi_ui_waiting(), + }); + } + multi_project_ui::MultiProjectViewModel { + global_runs, + max_concurrent: 2, + active_project_id: project_id, + active_project_title: project_title, + active_section: section, + viewing_output_id, + viewing_output_label, + producing_output_id, + producing_output_label, + viewing_differs_from_producing, + } + } + + pub(super) fn handle_multi_project_action( + &mut self, + app: &mut PhotocraftApp, + ctx: &egui::Context, + action: multi_project_ui::MultiProjectAction, + ) { + match &action { + multi_project_ui::MultiProjectAction::SwitchToProject(project_id) => { + if let Some(item) = self + .projects + .iter() + .find(|p| p["id"].as_str() == Some(project_id.as_str())) + .cloned() + { + self.handover(); + if let Err(error) = self.request_project_open(app, item) { + self.error = error; + } + } + } + multi_project_ui::MultiProjectAction::PauseProject(_) => { + super::production_controls::queue_action( + ctx, + "production-stop", + super::production_controls::stop_input(timeline::StopMode::Pause), + ); + } + multi_project_ui::MultiProjectAction::ResumeProject(_) => { + self.resume_product_production(app); + } + multi_project_ui::MultiProjectAction::JumpToProducingOutput { .. } => {} + } + multi_project_ui::push_action(ctx, action); + } + + fn storage_settings_section(&mut self, ui: &mut Ui, show_divider: bool) { + let reduced = self.reduce_motion; + let ctx = ui.ctx().clone(); + let (action, modal_opened) = storage_settings_ui::with_machine_state(&ctx, |state| { + let was_open = state.migrate_modal_open || state.cleanup_modal_open; + let action = storage_settings_ui::storage_settings_card(ui, state, reduced, show_divider); + let now_open = state.migrate_modal_open || state.cleanup_modal_open; + (action, !was_open && now_open) + }); + if modal_opened { + self.model_settings = false; + self.key_settings = false; + self.api_key.clear(); + ui.ctx().request_repaint(); + } + if let Some(action) = action { + let (method, payload) = action.to_request(); + let _ = self.tx.send(Request::Action(method.into(), payload)); + } + } + + pub(super) fn storage_modals_ui(&mut self, ctx: &egui::Context) { + let reduced = self.reduce_motion; + let action = storage_settings_ui::with_machine_state(ctx, |state| { + storage_settings_ui::show_storage_modals(ctx, state, reduced) + }); + if let Some(action) = action { + let (method, payload) = action.to_request(); + let _ = self.tx.send(Request::Action(method.into(), payload)); + } + } } /// Experimental, local-acceptance-only opt-in. Until device-loss, resource diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/multi_project_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/multi_project_ui.rs new file mode 100644 index 00000000..04d58605 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/multi_project_ui.rs @@ -0,0 +1,1545 @@ +//! Multi-project concurrency four-layer visual hierarchy. +//! +//! Pure ViewModel + action callback rendering for: +//! - Layer 1: Global background task strip (collapses cleanly under narrow widths). +//! - Layer 2: Persistent project identity capsule (always anchors current project + section). +//! - Layer 3: Viewing-output vs producing-output divergence strip with one-click return. +//! - Layer 4: Right dock header consistency & live runtime badges for project browser cards. + +use super::super::agent_motion::{Pace, schedule}; +use super::super::stitch_state::Tone; +use super::super::stitch_ui::{ + self, BadgeKind, ButtonRole, FocusRing, StatusChipStyle, +}; +use crate::icons; +use crate::theme::agent_scale::{Type, control, icon, motion, radius, space}; +use crate::theme::{AGENT_SEMANTIC, Tokens}; +use egui::{Align, Frame, Id, Layout, Margin, Pos2, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use serde_json::Value; + +/// Narrow breakpoint below which Layer 1 collapses into a single summary trigger + popup. +pub(crate) const NARROW_STRIP_BREAKPOINT: f32 = 540.0; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub(crate) enum MultiRunStatus { + #[default] + Running, + Queued, + Paused, + PartialDelivered, + Completed, + Failed, +} + +impl MultiRunStatus { + #[allow(dead_code, reason = "跨轨契约解析入口,供集成阶段消费后端运行状态")] + pub(crate) fn parse(wire: &str) -> Self { + match wire { + "running" | "active" => Self::Running, + "queued" | "pending" => Self::Queued, + "paused" | "waiting_resume" => Self::Paused, + "partial_delivered" | "partialDelivered" | "partial" => Self::PartialDelivered, + "completed" | "succeeded" | "done" => Self::Completed, + "failed" | "error" => Self::Failed, + _ => Self::Running, + } + } + + pub(crate) fn label(self) -> &'static str { + match self { + Self::Running => "后台制作中", + Self::Queued => "排队等待中", + Self::Paused => "已暂停", + Self::PartialDelivered => "已部分交付·缺项待补", + Self::Completed => "已完成", + Self::Failed => "制作异常", + } + } + + pub(crate) fn short_label(self) -> &'static str { + match self { + Self::Running => "制作中", + Self::Queued => "排队中", + Self::Paused => "已暂停", + Self::PartialDelivered => "部分交付", + Self::Completed => "已完成", + Self::Failed => "异常", + } + } + + pub(crate) fn tone(self) -> Tone { + match self { + Self::Running => Tone::Active, + Self::Queued => Tone::Quiet, + Self::Paused | Self::PartialDelivered => Tone::Warning, + Self::Completed => Tone::Success, + Self::Failed => Tone::Failure, + } + } + + pub(crate) fn badge_kind(self) -> BadgeKind { + match self { + Self::Running => BadgeKind::Running, + Self::Queued => BadgeKind::Neutral, + Self::Paused | Self::PartialDelivered | Self::Failed => BadgeKind::Warning, + Self::Completed => BadgeKind::Adopted, + } + } + + pub(crate) fn is_running(self) -> bool { + self == Self::Running + } + + #[allow(dead_code, reason = "跨轨契约辅助判定,供集成阶段筛选活跃运行")] + pub(crate) fn is_live(self) -> bool { + matches!(self, Self::Running | Self::Queued | Self::Paused | Self::PartialDelivered) + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub(crate) enum WorkspaceSection { + #[default] + Projects, + Brief, + Canvas, +} + +impl WorkspaceSection { + pub(crate) fn label(self) -> &'static str { + match self { + Self::Projects => "我的项目", + Self::Brief => "产品资料", + Self::Canvas => "模板画布", + } + } + + pub(crate) fn glyph(self) -> &'static str { + match self { + Self::Projects => "folder-open", + Self::Brief => "file", + Self::Canvas => "layers", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct GlobalRunEntry { + pub project_id: String, + pub project_title: String, + pub status: MultiRunStatus, + pub producing_output_id: String, + pub producing_output_label: String, + pub progress_label: String, + pub elapsed_secs: u64, + pub active_slots: usize, + pub has_attention: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct MultiProjectViewModel { + pub global_runs: Vec, + pub max_concurrent: usize, + pub active_project_id: Option, + pub active_project_title: Option, + pub active_section: WorkspaceSection, + pub viewing_output_id: Option, + pub viewing_output_label: Option, + pub producing_output_id: Option, + pub producing_output_label: Option, + pub viewing_differs_from_producing: bool, +} + +impl MultiProjectViewModel { + pub(crate) fn running_count(&self) -> usize { + self.global_runs.iter().filter(|run| run.status.is_running()).count() + } + + pub(crate) fn queued_count(&self) -> usize { + self.global_runs.iter().filter(|run| run.status == MultiRunStatus::Queued).count() + } + + pub(crate) fn attention_count(&self) -> usize { + self.global_runs.iter().filter(|run| run.has_attention).count() + } + + pub(crate) fn run_for_project(&self, project_id: &str) -> Option<&GlobalRunEntry> { + self.global_runs.iter().find(|run| run.project_id == project_id) + } + + pub(crate) fn other_active_count(&self) -> usize { + self.global_runs + .iter() + .filter(|run| { + self.active_project_id.as_deref() != Some(run.project_id.as_str()) + && matches!(run.status, MultiRunStatus::Running | MultiRunStatus::Queued) + }) + .count() + } + + #[allow(dead_code, reason = "跨轨契约 JSON 解析入口,供集成阶段同步运行注册表")] + pub(crate) fn from_json(value: &Value) -> Self { + let runs = value["globalRuns"] + .as_array() + .into_iter() + .flatten() + .filter_map(|row| { + let project_id = row["projectId"].as_str()?.to_owned(); + Some(GlobalRunEntry { + project_id, + project_title: row["projectTitle"].as_str().unwrap_or("未命名项目").to_owned(), + status: MultiRunStatus::parse(row["status"].as_str().unwrap_or("running")), + producing_output_id: row["producingOutputId"].as_str().unwrap_or_default().to_owned(), + producing_output_label: row["producingOutputLabel"].as_str().unwrap_or_default().to_owned(), + progress_label: row["progressLabel"].as_str().unwrap_or_default().to_owned(), + elapsed_secs: row["elapsedSecs"].as_u64().unwrap_or(0), + active_slots: row["activeSlots"].as_u64().unwrap_or(0) as usize, + has_attention: row["hasAttention"].as_bool().unwrap_or(false), + }) + }) + .collect(); + let active_section = match value["activeSection"].as_str() { + Some("brief") => WorkspaceSection::Brief, + Some("canvas") => WorkspaceSection::Canvas, + _ => WorkspaceSection::Projects, + }; + Self { + global_runs: runs, + max_concurrent: value["maxConcurrent"].as_u64().unwrap_or(2) as usize, + active_project_id: value["activeProjectId"].as_str().map(str::to_owned), + active_project_title: value["activeProjectTitle"].as_str().map(str::to_owned), + active_section, + viewing_output_id: value["viewingOutputId"].as_str().map(str::to_owned), + viewing_output_label: value["viewingOutputLabel"].as_str().map(str::to_owned), + producing_output_id: value["producingOutputId"].as_str().map(str::to_owned), + producing_output_label: value["producingOutputLabel"].as_str().map(str::to_owned), + viewing_differs_from_producing: value["viewingDiffersFromProducing"].as_bool().unwrap_or(false), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum MultiProjectAction { + SwitchToProject(String), + PauseProject(String), + #[allow(dead_code, reason = "跨轨契约动作,供集成阶段恢复已暂停项目")] + ResumeProject(String), + JumpToProducingOutput { + project_id: String, + output_id: String, + }, +} + +fn snapshot_id() -> Id { + Id::unique("xiaoyi-multi-project-vm") +} + +fn actions_id() -> Id { + Id::unique("xiaoyi-multi-project-actions") +} + +/// Push the live multi-project registry snapshot from the host runtime into the UI context. +#[allow(dead_code, reason = "跨轨契约写入入口,供集成阶段由运行注册表推送状态")] +pub(crate) fn set_snapshot(ctx: &egui::Context, vm: MultiProjectViewModel) { + ctx.data_mut(|data| data.insert_temp(snapshot_id(), vm)); +} + +/// Read the latest injected multi-project snapshot, if present. +pub(crate) fn snapshot(ctx: &egui::Context) -> Option { + ctx.data(|data| data.get_temp::(snapshot_id())) +} + +pub(crate) fn push_action(ctx: &egui::Context, action: MultiProjectAction) { + ctx.data_mut(|data| { + let queue = data.get_temp_mut_or_default::>(actions_id()); + queue.push(action); + }); +} + +#[allow(dead_code, reason = "跨轨契约消费入口,供集成阶段派发多项目交互动作")] +pub(crate) fn drain_actions(ctx: &egui::Context) -> Vec { + ctx.data_mut(|data| { + let queue = data.get_temp_mut_or_default::>(actions_id()); + std::mem::take(queue) + }) +} + +pub(crate) fn format_elapsed(secs: u64) -> String { + if secs < 60 { + format!("{secs}秒") + } else if secs < 3600 { + let mins = secs / 60; + let rem = secs % 60; + if rem == 0 { + format!("{mins}分") + } else { + format!("{mins}分{rem:02}秒") + } + } else { + let hours = secs / 3600; + let mins = (secs % 3600) / 60; + format!("{hours}时{mins:02}分") + } +} + +pub(crate) fn output_display_label(output_id: &str) -> &'static str { + match output_id { + "detail" => "详情页", + "main_images" => "主图", + "sku_images" => "SKU 图", + "main_video" => "主图视频", + "seeding_images" | "seeding_video" => "种草素材", + _ => "成品画布", + } +} + +/// Summary label for Layer 1 capacity counter, e.g. "进行中 2/2 · 排队 1". +pub(crate) fn strip_summary_label(vm: &MultiProjectViewModel) -> String { + let running = vm.running_count(); + let cap = vm.max_concurrent.max(1); + let queued = vm.queued_count(); + let attention = vm.attention_count(); + let mut parts = Vec::with_capacity(3); + parts.push(format!("进行中 {running}/{cap}")); + if queued > 0 { + parts.push(format!("排队 {queued}")); + } + if attention > 0 { + parts.push(format!("待确认 {attention}")); + } + parts.join(" · ") +} + +/// Render Layer 1 + Layer 2 + Layer 3 stacked for full-width workspace headers. +#[allow(dead_code, reason = "跨轨契约组合入口,供顶栏与离屏视觉验收调用")] +pub(crate) fn workspace_top_layers( + ui: &mut Ui, + vm: &MultiProjectViewModel, + reduced: bool, +) -> Option { + let mut action = None; + if !vm.global_runs.is_empty() { + action = action.or_else(|| global_task_strip(ui, vm, reduced)); + ui.add_space(space::XS); + } + if vm.active_project_title.is_some() || vm.active_section != WorkspaceSection::Projects { + action = action.or_else(|| project_identity_bar(ui, vm, reduced)); + } + if vm.viewing_differs_from_producing { + ui.add_space(space::XS); + action = action.or_else(|| viewing_producing_banner(ui, vm, reduced)); + } + action +} + +/// Render Layer 4 right-dock contextual header (compact Layer 1 + Layer 2 + Layer 3) +/// designed specifically for 250–520pt dock widths. +pub(crate) fn dock_context_header( + ui: &mut Ui, + vm: &MultiProjectViewModel, + reduced: bool, +) -> Option { + let has_runs = !vm.global_runs.is_empty(); + let has_identity = vm.active_project_title.is_some(); + let has_divergence = vm.viewing_differs_from_producing; + if !has_runs && !has_identity && !has_divergence { + return None; + } + + let mut action = None; + Frame::NONE + .inner_margin(Margin { + left: space::LG as i8, + right: space::LG as i8, + top: space::MD as i8, + bottom: space::XS as i8, + }) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = space::XS + space::XXS; + if has_runs { + action = action.take().or_else(|| global_task_strip(ui, vm, reduced)); + } + if has_identity { + action = action.take().or_else(|| project_identity_bar(ui, vm, reduced)); + } + if has_divergence { + action = action.take().or_else(|| viewing_producing_banner(ui, vm, reduced)); + } + }); + action +} + +/// Layer 1: Global Background Task Strip. +/// Occupies zero space when `vm.global_runs` is empty. +/// Collapses gracefully into a single summary trigger + popup when width < 540pt. +pub(crate) fn global_task_strip( + ui: &mut Ui, + vm: &MultiProjectViewModel, + reduced: bool, +) -> Option { + if vm.global_runs.is_empty() { + return None; + } + let t = Tokens::get(ui.ctx()).agent(); + let available = ui.available_width(); + let narrow = available < NARROW_STRIP_BREAKPOINT; + let mut action = None; + + let frame = Frame::NONE + .fill(t.card) + .stroke(Stroke::new(1.0, t.card_border)) + .corner_radius(radius::CHIP as u8) + .inner_margin(Margin::symmetric(space::SM as i8, space::XS as i8)); + let inner_width = (available - frame.total_margin().sum().x).max(1.0); + + frame.show(ui, |ui| { + ui.set_width(inner_width); + if narrow { + action = compact_task_strip(ui, vm, reduced); + } else { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(space::SM, space::XS); + paint_capacity_counter(ui, vm, reduced); + stitch_ui::vertical_divider(ui); + for run in &vm.global_runs { + let is_active = vm.active_project_id.as_deref() == Some(run.project_id.as_str()); + if let Some(chosen) = run_capsule(ui, run, is_active, reduced) { + action = Some(chosen); + } + } + }); + } + }); + action +} + +fn compact_task_strip( + ui: &mut Ui, + vm: &MultiProjectViewModel, + reduced: bool, +) -> Option { + let t = Tokens::get(ui.ctx()).agent(); + let summary = strip_summary_label(vm); + let mut action = None; + + let trigger_id = ui.scope_id().with("multi-run-compact-trigger"); + let width = ui.available_width().max(1.0); + let (rect, response) = ui.allocate_exact_size(vec2(width, control::ROW), Sense::click()); + let response = response.on_hover_cursor(egui::CursorIcon::PointingHand); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &summary)); + + if ui.is_rect_visible(rect) { + let painter = ui.painter_at(rect.intersect(ui.clip_rect())); + let fill = if response.is_pointer_button_down_on() { + t.pressed + } else if response.hovered() { + t.hover + } else { + t.field + }; + painter.rect(rect, radius::ROW, fill, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + + let running = vm.running_count() > 0; + let dot_center = pos2(rect.left() + space::MD, rect.center().y); + paint_status_dot(ui, &painter, dot_center, if running { MultiRunStatus::Running } else { MultiRunStatus::Queued }, reduced, rect); + + let text_left = dot_center.x + space::SM; + let chevron_space = icon::MD + space::SM; + let mut job = egui::text::LayoutJob::simple_singleline( + format!("后台任务 · {summary}"), + Type::Meta.semibold(), + t.text, + ); + job.wrap.max_width = (rect.right() - text_left - chevron_space - space::XS).max(1.0); + job.wrap.max_rows = 1; + let galley = painter.layout_job(job); + painter.galley(pos2(text_left, rect.center().y - galley.size().y * 0.5), galley, t.text); + + let chevron_rect = Rect::from_center_size( + pos2(rect.right() - space::MD, rect.center().y), + vec2(icon::MD, icon::MD), + ); + icons::paint(ui, chevron_rect, "chevron-down", icon::MD, t.text_dim); + } + stitch_ui::focus_ring(ui, &response, radius::ROW, FocusRing::Control); + + let popup_width = (ui.ctx().content_rect().width() - space::XL).clamp(240.0, 340.0); + let _ = trigger_id; + stitch_ui::select_popup(ui, &response, popup_width, reduced, |ui| { + ui.spacing_mut().item_spacing.y = space::XS; + for (index, run) in vm.global_runs.iter().enumerate() { + if index > 0 { + stitch_ui::divider(ui); + } + let is_active = vm.active_project_id.as_deref() == Some(run.project_id.as_str()); + if let Some(chosen) = popup_run_row(ui, run, is_active, reduced) { + action = Some(chosen); + ui.close(); + } + } + }); + action +} + +fn popup_run_row( + ui: &mut Ui, + run: &GlobalRunEntry, + is_active: bool, + reduced: bool, +) -> Option { + let t = Tokens::get(ui.ctx()).agent(); + let mut action = None; + ui.horizontal(|ui| { + let can_pause = run.status.is_running() && !is_active; + let pause_space = if can_pause { control::COMPACT + space::XS } else { 0.0 }; + let row_width = (ui.available_width() - pause_space).max(1.0); + let detail = build_run_detail_line(run, is_active); + let title_galley = ui.painter().layout_no_wrap(run.project_title.clone(), Type::Title.semibold(), t.text); + let detail_galley = ui.painter().layout_no_wrap(detail.clone(), Type::Meta.font_id(), t.text_dim); + let row_height = (title_galley.size().y + detail_galley.size().y + space::SM + space::XXS).max(control::COMMAND_ROW); + let (rect, response) = ui.allocate_exact_size(vec2(row_width, row_height), Sense::click()); + let response = response.on_hover_cursor(egui::CursorIcon::PointingHand); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &run.project_title)); + + if ui.is_rect_visible(rect) { + let painter = ui.painter_at(rect.intersect(ui.clip_rect())); + if response.hovered() || is_active { + painter.rect_filled(rect, radius::ROW, if response.hovered() { t.hover } else { t.field }); + } + let dot_pos = pos2(rect.left() + space::SM + space::XXS, rect.top() + space::MD); + paint_status_dot(ui, &painter, dot_pos, run.status, reduced, rect); + let text_x = dot_pos.x + space::SM; + let text_w = (rect.right() - text_x - space::XS).max(1.0); + + let mut t_job = egui::text::LayoutJob::simple_singleline( + run.project_title.clone(), + Type::Title.semibold(), + t.text, + ); + t_job.wrap.max_width = text_w; + t_job.wrap.max_rows = 1; + let tg = painter.layout_job(t_job); + painter.galley(pos2(text_x, rect.top() + space::XS), tg, t.text); + + let mut d_job = egui::text::LayoutJob::simple_singleline( + detail, + Type::Meta.font_id(), + t.text_dim, + ); + d_job.wrap.max_width = text_w; + d_job.wrap.max_rows = 1; + let dg = painter.layout_job(d_job); + painter.galley(pos2(text_x, rect.top() + space::XS + title_galley.size().y + space::XXS), dg, t.text_dim); + } + stitch_ui::focus_ring(ui, &response, radius::ROW, FocusRing::Control); + if response.clicked() { + action = Some(MultiProjectAction::SwitchToProject(run.project_id.clone())); + } + + if can_pause { + let pause = stitch_ui::icon_button(ui, "pause", control::COMPACT, false, "暂停该项目后台制作"); + if pause.clicked() { + action = Some(MultiProjectAction::PauseProject(run.project_id.clone())); + } + } + }); + action +} + +fn build_run_detail_line(run: &GlobalRunEntry, is_active: bool) -> String { + let mut parts = Vec::with_capacity(4); + if is_active { + parts.push("当前项目".to_owned()); + } + parts.push(run.status.short_label().to_owned()); + if !run.producing_output_label.is_empty() { + parts.push(run.producing_output_label.clone()); + } + if !run.progress_label.is_empty() { + parts.push(run.progress_label.clone()); + } + if run.elapsed_secs > 0 && run.status.is_running() { + parts.push(format_elapsed(run.elapsed_secs)); + } + parts.join(" · ") +} + +fn paint_capacity_counter(ui: &mut Ui, vm: &MultiProjectViewModel, reduced: bool) { + let t = Tokens::get(ui.ctx()).agent(); + let label = strip_summary_label(vm); + let running = vm.running_count() > 0; + let galley = ui.painter().layout_no_wrap(label.clone(), Type::Meta.semibold(), t.text); + let width = space::SM + space::SM + space::XS + galley.size().x + space::SM; + let (rect, response) = ui.allocate_exact_size(vec2(width, control::ROW), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &label)); + if ui.is_rect_visible(rect) { + let painter = ui.painter_at(rect.intersect(ui.clip_rect())); + painter.rect_filled(rect, radius::ROW, t.field); + let dot = pos2(rect.left() + space::SM + space::XXS, rect.center().y); + paint_status_dot( + ui, + &painter, + dot, + if running { MultiRunStatus::Running } else { MultiRunStatus::Queued }, + reduced, + rect, + ); + painter.galley( + pos2(dot.x + space::SM, rect.center().y - galley.size().y * 0.5), + galley, + t.text, + ); + } +} + +fn run_capsule( + ui: &mut Ui, + run: &GlobalRunEntry, + is_active: bool, + reduced: bool, +) -> Option { + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + let mut action = None; + + let can_quick_pause = run.status.is_running() && !is_active; + let title_budget = 112.0_f32; + let mut meta_parts = Vec::with_capacity(3); + if !run.producing_output_label.is_empty() { + meta_parts.push(run.producing_output_label.clone()); + } + if !run.progress_label.is_empty() { + meta_parts.push(run.progress_label.clone()); + } else if run.status != MultiRunStatus::Running { + meta_parts.push(run.status.short_label().to_owned()); + } + if run.elapsed_secs > 0 && run.status.is_running() { + meta_parts.push(format_elapsed(run.elapsed_secs)); + } + let meta_text = meta_parts.join(" · "); + + let mut title_job = egui::text::LayoutJob::simple_singleline( + run.project_title.clone(), + Type::Title.font_id(), + t.text, + ); + title_job.wrap.max_width = title_budget; + title_job.wrap.max_rows = 1; + let title_galley = ui.painter().layout_job(title_job); + let meta_galley = ui.painter().layout_no_wrap(meta_text.clone(), Type::Meta.font_id(), t.text_dim); + let active_tag_galley = is_active.then(|| { + ui.painter().layout_no_wrap("当前".to_owned(), Type::Caption.semibold(), semantic.jade) + }); + + let pause_width = if can_quick_pause { 20.0 } else { 0.0 }; + let active_tag_width = active_tag_galley.as_ref().map_or(0.0, |g| g.size().x + space::SM); + let meta_gap = if meta_text.is_empty() { 0.0 } else { space::XS + space::XXS }; + let desired_width = (space::SM + + space::SM + + space::XS + + title_galley.size().x + + meta_gap + + meta_galley.size().x + + active_tag_width + + pause_width + + space::SM) + .min(ui.available_width().max(control::ROW)); + + let id = ui.scope_id().with(("multi-run-capsule", &run.project_id)); + let (rect, response) = ui.allocate_exact_size(vec2(desired_width, control::ROW), Sense::click()); + let response = response.on_hover_cursor(egui::CursorIcon::PointingHand); + + let pause_rect = can_quick_pause.then(|| { + Rect::from_center_size( + pos2(rect.right() - space::SM - 6.0, rect.center().y), + vec2(18.0, 18.0), + ) + }); + let pause_response = pause_rect.map(|r| { + ui.interact(r, id.with("pause"), Sense::click()) + .on_hover_cursor(egui::CursorIcon::PointingHand) + .on_hover_text("暂停该项目制作") + }); + + let tooltip = format!( + "{}\n状态:{}\n正在制作:{}{}{}\n点击切换到此项目", + run.project_title, + run.status.label(), + if run.producing_output_label.is_empty() { "准备中" } else { &run.producing_output_label }, + if run.progress_label.is_empty() { String::new() } else { format!(" · {}", run.progress_label) }, + if run.elapsed_secs > 0 { format!("(已用 {})", format_elapsed(run.elapsed_secs)) } else { String::new() }, + ); + response.widget_info(|| { + egui::WidgetInfo::selected(egui::Role::Button, true, is_active, &run.project_title) + }); + + if ui.is_rect_visible(rect) { + let painter = ui.painter_at(rect.intersect(ui.clip_rect())); + let base_fill = if is_active { + t.field.lerp_to_gamma(semantic.jade, 0.10) + } else { + t.field + }; + let fill = if response.is_pointer_button_down_on() { + t.pressed + } else if response.hovered() { + base_fill.lerp_to_gamma(t.hover, 0.6) + } else { + base_fill + }; + let border = if is_active { + semantic.jade.gamma_multiply(0.65) + } else if run.has_attention { + t.warning.gamma_multiply(0.75) + } else if run.status.is_running() { + t.card_border.lerp_to_gamma(semantic.jade, 0.30) + } else { + t.field_border + }; + painter.rect(rect, radius::CHIP, fill, Stroke::new(1.0, border), StrokeKind::Inside); + + let dot_pos = pos2(rect.left() + space::SM + space::XXS, rect.center().y); + paint_status_dot(ui, &painter, dot_pos, run.status, reduced, rect); + + let mut x = dot_pos.x + space::SM; + let max_x = pause_rect.map_or(rect.right() - space::SM, |r| r.left() - space::XS); + + painter.galley(pos2(x, rect.center().y - title_galley.size().y * 0.5), title_galley.clone(), t.text); + x += title_galley.size().x; + + if !meta_text.is_empty() && x + meta_gap + space::LG < max_x { + x += meta_gap; + let mut m_job = egui::text::LayoutJob::simple_singleline(meta_text, Type::Meta.font_id(), t.text_dim); + m_job.wrap.max_width = (max_x - x - active_tag_width).max(1.0); + m_job.wrap.max_rows = 1; + let mg = painter.layout_job(m_job); + painter.galley(pos2(x, rect.center().y - mg.size().y * 0.5), mg.clone(), t.text_dim); + x += mg.size().x; + } + + if let Some(tag) = active_tag_galley + && x + space::XS + tag.size().x <= max_x + space::XXS + { + painter.galley( + pos2(max_x - tag.size().x, rect.center().y - tag.size().y * 0.5), + tag, + semantic.jade, + ); + } + + if let (Some(r), Some(pr)) = (pause_rect, &pause_response) { + if pr.hovered() { + painter.rect_filled(r, radius::ROW, t.hover); + } + icons::paint(ui, r, "pause", icon::SM, if pr.hovered() { t.text } else { t.text_dim }); + } + } + + stitch_ui::focus_ring(ui, &response, radius::CHIP, FocusRing::Control); + + if let Some(pr) = pause_response + && pr.clicked() + { + return Some(MultiProjectAction::PauseProject(run.project_id.clone())); + } + let clicked = response.clicked(); + response.on_hover_text(tooltip); + if clicked { + action = Some(MultiProjectAction::SwitchToProject(run.project_id.clone())); + } + action +} + +fn paint_status_dot( + ui: &Ui, + painter: &egui::Painter, + center: Pos2, + status: MultiRunStatus, + reduced: bool, + visible_rect: Rect, +) { + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + match status { + MultiRunStatus::Running => { + let now = ui.input(|input| input.time); + let pulse = if reduced { + 0.75 + } else { + 0.45 + 0.55 * ((now * std::f64::consts::TAU / motion::HALO_PERIOD as f64).sin() as f32 * 0.5 + 0.5) + }; + painter.circle_filled(center, 4.5, semantic.jade.gamma_multiply(0.24 * pulse)); + painter.circle_filled(center, 2.8, semantic.jade); + if !reduced { + schedule(ui, visible_rect, Pace::Full); + } + } + MultiRunStatus::Queued => { + painter.circle_stroke(center, 2.8, Stroke::new(1.2, t.text_dim)); + } + MultiRunStatus::Paused | MultiRunStatus::PartialDelivered => { + painter.circle_filled(center, 2.8, t.warning); + } + MultiRunStatus::Completed => { + painter.circle_filled(center, 2.8, semantic.success); + } + MultiRunStatus::Failed => { + painter.circle_filled(center, 2.8, t.danger); + } + } +} + +/// Layer 2: Persistent Project Identity Capsule. +/// Anchors which product project and which section (Projects / Brief / Canvas) is currently open. +pub(crate) fn project_identity_bar( + ui: &mut Ui, + vm: &MultiProjectViewModel, + reduced: bool, +) -> Option { + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + let title = vm.active_project_title.as_deref().unwrap_or("未打开项目"); + let current_run = vm + .active_project_id + .as_deref() + .and_then(|id| vm.run_for_project(id)); + let other_active = vm.other_active_count(); + let mut action = None; + + let available = ui.available_width(); + let frame = Frame::NONE + .fill(t.field) + .stroke(Stroke::new(1.0, t.card_border)) + .corner_radius(radius::CONTROL as u8) + .inner_margin(Margin::symmetric(space::SM as i8 + 2, space::XS as i8 + 1)); + let inner_width = (available - frame.total_margin().sum().x).max(1.0); + + frame.show(ui, |ui| { + ui.set_width(inner_width); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(space::SM, space::XS); + + // Project icon + title + ui.add(icons::image(vm.active_section.glyph(), icon::MD, t.text_dim)); + ui.add( + egui::Label::new(RichText::new(title).font(Type::Title.semibold()).color(t.text)) + .truncate(), + ) + .on_hover_text(title); + + // Section orientation tag (quiet recessed pill) + paint_inline_pill(ui, vm.active_section.label(), t.card, t.card_border, t.text_dim); + + // Current project live state OR subtle other-projects indicator + if let Some(run) = current_run { + let tone_color = match run.status { + MultiRunStatus::Running => semantic.jade, + MultiRunStatus::Paused | MultiRunStatus::PartialDelivered => t.warning, + MultiRunStatus::Failed => t.danger, + MultiRunStatus::Completed => semantic.success, + MultiRunStatus::Queued => t.text_dim, + }; + let status_line = if !run.producing_output_label.is_empty() && !run.progress_label.is_empty() { + format!("{} · {} {}", run.status.short_label(), run.producing_output_label, run.progress_label) + } else if !run.producing_output_label.is_empty() { + format!("{} · {}", run.status.short_label(), run.producing_output_label) + } else { + run.status.label().to_owned() + }; + paint_inline_pill( + ui, + &status_line, + t.card.lerp_to_gamma(tone_color, 0.12), + tone_color.gamma_multiply(0.45), + tone_color, + ); + } else if other_active > 0 { + let first_other = vm.global_runs.iter().find(|run| { + vm.active_project_id.as_deref() != Some(run.project_id.as_str()) + && matches!(run.status, MultiRunStatus::Running | MultiRunStatus::Queued) + }); + let note = format!("另有 {other_active} 个项目后台制作中"); + ui.label(RichText::new(note).font(Type::Meta.font_id()).color(t.text_dim)); + if let Some(other) = first_other + && stitch_ui::action_button(ui, "查看", ButtonRole::Quiet, true).clicked() + { + action = Some(MultiProjectAction::SwitchToProject(other.project_id.clone())); + } + } + }); + }); + let _ = reduced; + action +} + +fn paint_inline_pill(ui: &mut Ui, text: &str, fill: egui::Color32, stroke: egui::Color32, text_color: egui::Color32) { + let galley = ui.painter().layout_no_wrap(text.to_owned(), Type::Meta.font_id(), text_color); + let size = vec2(galley.size().x + space::MD, galley.size().y + space::XS); + let (rect, response) = ui.allocate_exact_size(size, Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, text)); + if ui.is_rect_visible(rect) { + let painter = ui.painter_at(rect.intersect(ui.clip_rect())); + painter.rect(rect, radius::ROW, fill, Stroke::new(1.0, stroke), StrokeKind::Inside); + painter.galley( + pos2(rect.center().x - galley.size().x * 0.5, rect.center().y - galley.size().y * 0.5), + galley, + text_color, + ); + } +} + +/// Layer 3: Viewing-Output vs Producing-Output Strong Distinction Banner. +/// Shown only when `vm.viewing_differs_from_producing == true`. +pub(crate) fn viewing_producing_banner( + ui: &mut Ui, + vm: &MultiProjectViewModel, + reduced: bool, +) -> Option { + if !vm.viewing_differs_from_producing { + return None; + } + let viewing = vm.viewing_output_label.as_deref().filter(|s| !s.is_empty())?; + let producing = vm.producing_output_label.as_deref().filter(|s| !s.is_empty())?; + + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + let mut action = None; + + let available = ui.available_width(); + let frame = Frame::NONE + .fill(t.field.lerp_to_gamma(semantic.verified, 0.12)) + .stroke(Stroke::new(1.0, semantic.verified.gamma_multiply(0.55))) + .corner_radius(radius::CONTROL as u8) + .inner_margin(Margin::symmetric(space::MD as i8, space::SM as i8)); + let inner_width = (available - frame.total_margin().sum().x).max(1.0); + + let response_frame = frame.show(ui, |ui| { + ui.set_width(inner_width); + let jump_label = format!("回到正在制作的{producing}"); + let narrow = inner_width < 410.0; + + if narrow { + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = space::XS; + viewing_producing_copy(ui, viewing, producing, reduced, inner_width < 320.0); + if stitch_ui::action_button(ui, &jump_label, ButtonRole::Quiet, true).clicked() + && let (Some(pid), Some(oid)) = (&vm.active_project_id, &vm.producing_output_id) + { + action = Some(MultiProjectAction::JumpToProducingOutput { + project_id: pid.clone(), + output_id: oid.clone(), + }); + } + }); + } else { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = space::SM; + viewing_producing_copy(ui, viewing, producing, reduced, false); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if stitch_ui::action_button(ui, &jump_label, ButtonRole::Quiet, true).clicked() + && let (Some(pid), Some(oid)) = (&vm.active_project_id, &vm.producing_output_id) + { + action = Some(MultiProjectAction::JumpToProducingOutput { + project_id: pid.clone(), + output_id: oid.clone(), + }); + } + }); + }); + } + }); + let _ = response_frame; + action +} + +fn viewing_producing_copy(ui: &mut Ui, viewing: &str, producing: &str, reduced: bool, stacked: bool) { + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + if stacked { + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = space::XXS; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = space::XS + space::XXS; + ui.add(icons::image("eye", icon::MD, semantic.verified)); + ui.label(RichText::new("当前查看:").font(Type::Meta.font_id()).color(t.text_dim)); + ui.label(RichText::new(viewing).font(Type::Title.semibold()).color(t.text)); + }); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = space::XS + space::XXS; + let (dot_rect, _) = ui.allocate_exact_size(vec2(icon::MD, icon::MD), Sense::hover()); + paint_status_dot(ui, ui.painter(), dot_rect.center(), MultiRunStatus::Running, reduced, dot_rect); + ui.label(RichText::new("后台正制作:").font(Type::Meta.font_id()).color(t.text_dim)); + ui.label(RichText::new(producing).font(Type::Title.semibold()).color(semantic.jade)); + }); + }); + } else { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(space::XS + space::XXS, space::XXS); + ui.add(icons::image("eye", icon::MD, semantic.verified)); + ui.label(RichText::new("当前查看:").font(Type::Meta.font_id()).color(t.text_dim)); + ui.label(RichText::new(viewing).font(Type::Title.semibold()).color(t.text)); + ui.label(RichText::new("·").font(Type::Meta.font_id()).color(t.text_faint)); + + let (dot_rect, _) = ui.allocate_exact_size(vec2(space::SM, icon::MD), Sense::hover()); + paint_status_dot(ui, ui.painter(), dot_rect.center(), MultiRunStatus::Running, reduced, dot_rect); + + ui.label(RichText::new("后台正制作:").font(Type::Meta.font_id()).color(t.text_dim)); + ui.label(RichText::new(producing).font(Type::Title.semibold()).color(semantic.jade)); + }); + } +} + +/// Layer 4 (Project Browser): Paint a live runtime badge on top of a project card cover, +/// visually distinct from static disk draft/completed badges. +pub(crate) fn paint_project_live_badge( + ui: &Ui, + cover_rect: Rect, + run: &GlobalRunEntry, + reduced: bool, +) -> Rect { + let t = Tokens::get(ui.ctx()).agent(); + let label = run.status.label(); + let kind = run.status.badge_kind(); + let text_size = stitch_ui::badge_text_size(control::ROW); + let text_w = ui + .painter() + .layout_no_wrap(label.to_owned(), egui::FontId::proportional(text_size), t.text) + .size() + .x; + let lead = if kind == BadgeKind::Running { 23.0 } else if kind == BadgeKind::Warning || kind == BadgeKind::Adopted { 18.0 } else { 0.0 }; + let max_w = (cover_rect.width() - 56.0).max(48.0); + let width = (text_w + lead + 18.0).clamp(52.0, max_w); + let badge_rect = Rect::from_min_size(cover_rect.min + vec2(10.0, 10.0), vec2(width, control::ROW)); + + let style = if run.status == MultiRunStatus::Completed { + StatusChipStyle::Contrast + } else { + StatusChipStyle::Muted + }; + stitch_ui::paint_status_badge(ui, badge_rect, kind, label, style, reduced); + + // Subtle semantic border ring so runtime badges immediately read as live state vs static disk status. + let ring_color = match run.status { + MultiRunStatus::Running => Some(AGENT_SEMANTIC.jade.gamma_multiply(0.75)), + MultiRunStatus::Paused | MultiRunStatus::PartialDelivered => Some(t.warning.gamma_multiply(0.75)), + MultiRunStatus::Failed => Some(t.danger.gamma_multiply(0.8)), + MultiRunStatus::Queued => Some(t.text_dim.gamma_multiply(0.6)), + MultiRunStatus::Completed => None, + }; + if let Some(color) = ring_color { + let radius = badge_rect.height().min(badge_rect.width()) * 0.5; + ui.painter().rect_stroke(badge_rect, radius, Stroke::new(1.0, color), StrokeKind::Inside); + } + badge_rect +} + +/// Secondary live subtitle shown on a project card metadata row when a live run exists. +pub(crate) fn project_card_live_subtitle(run: &GlobalRunEntry) -> String { + let mut parts = Vec::with_capacity(3); + let prefix = match run.status { + MultiRunStatus::Running => "正在制作", + MultiRunStatus::Queued => "排队等待", + MultiRunStatus::Paused => "已暂停", + MultiRunStatus::PartialDelivered => "部分交付", + MultiRunStatus::Failed => "制作异常", + MultiRunStatus::Completed => "已完成", + }; + if !run.producing_output_label.is_empty() { + parts.push(format!("{prefix} {}", run.producing_output_label)); + } else { + parts.push(prefix.to_owned()); + } + if !run.progress_label.is_empty() { + parts.push(run.progress_label.clone()); + } + if run.elapsed_secs > 0 && run.status.is_running() { + parts.push(format_elapsed(run.elapsed_secs)); + } + parts.join(" · ") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::theme::ThemeKind; + use egui_kittest::Harness; + + pub(crate) fn sample_two_running_one_queued_vm() -> MultiProjectViewModel { + MultiProjectViewModel { + global_runs: vec![ + GlobalRunEntry { + project_id: "proj-chair-a".into(), + project_title: "软包实木餐椅 A01".into(), + status: MultiRunStatus::Running, + producing_output_id: "detail".into(), + producing_output_label: "详情页".into(), + progress_label: "12/49".into(), + elapsed_secs: 372, + active_slots: 3, + has_attention: false, + }, + GlobalRunEntry { + project_id: "proj-sofa-b".into(), + project_title: "意式直排真皮沙发 B08".into(), + status: MultiRunStatus::Running, + producing_output_id: "main_images".into(), + producing_output_label: "主图".into(), + progress_label: "3/5".into(), + elapsed_secs: 185, + active_slots: 2, + has_attention: false, + }, + GlobalRunEntry { + project_id: "proj-table-c".into(), + project_title: "岩板伸缩餐桌 C12".into(), + status: MultiRunStatus::Queued, + producing_output_id: "detail".into(), + producing_output_label: "详情页".into(), + progress_label: "队列第 1 位".into(), + elapsed_secs: 0, + active_slots: 0, + has_attention: false, + }, + ], + max_concurrent: 2, + active_project_id: Some("proj-chair-a".into()), + active_project_title: Some("软包实木餐椅 A01".into()), + active_section: WorkspaceSection::Canvas, + viewing_output_id: Some("main_images".into()), + viewing_output_label: Some("主图".into()), + producing_output_id: Some("detail".into()), + producing_output_label: Some("详情页".into()), + viewing_differs_from_producing: true, + } + } + + #[test] + fn strip_summary_reflects_running_queued_and_attention_counts() { + let mut vm = sample_two_running_one_queued_vm(); + assert_eq!(strip_summary_label(&vm), "进行中 2/2 · 排队 1"); + vm.global_runs[1].has_attention = true; + assert_eq!(strip_summary_label(&vm), "进行中 2/2 · 排队 1 · 待确认 1"); + } + + #[test] + fn elapsed_formatting_covers_seconds_minutes_and_hours() { + assert_eq!(format_elapsed(45), "45秒"); + assert_eq!(format_elapsed(120), "2分"); + assert_eq!(format_elapsed(372), "6分12秒"); + assert_eq!(format_elapsed(3900), "1时05分"); + } + + #[test] + fn viewing_differs_banner_emits_jump_to_producing_action() { + let vm = sample_two_running_one_queued_vm(); + let captured = std::sync::Arc::new(std::sync::Mutex::new(None)); + let captured_clone = captured.clone(); + let mut h = Harness::builder() + .with_size(vec2(720.0, 200.0)) + .with_context_setup(|ctx| { + crate::PhotocraftApp::setup_context(ctx, ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }) + .build_ui(move |ui| { + stitch_ui::scope_with_motion(ui, true, |ui| { + if let Some(act) = workspace_top_layers(ui, &vm, true) { + *captured_clone.lock().unwrap() = Some(act); + } + }); + }); + h.run_steps(2); + let jump_btn = egui_kittest::kittest::Queryable::get_by_label(&h, "回到正在制作的详情页"); + jump_btn.click(); + h.run_steps(2); + assert_eq!( + *captured.lock().unwrap(), + Some(MultiProjectAction::JumpToProducingOutput { + project_id: "proj-chair-a".into(), + output_id: "detail".into(), + }) + ); + } + + #[test] + fn narrow_strip_collapses_into_summary_trigger_without_overflow() { + let vm = sample_two_running_one_queued_vm(); + let mut h = Harness::builder() + .with_size(vec2(340.0, 260.0)) + .with_context_setup(|ctx| { + crate::PhotocraftApp::setup_context(ctx, ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }) + .build_ui(move |ui| { + stitch_ui::scope_with_motion(ui, true, |ui| { + let _ = dock_context_header(ui, &vm, true); + }); + }); + h.run_steps(2); + let trigger = egui_kittest::kittest::Queryable::get_by_label(&h, "进行中 2/2 · 排队 1"); + assert!(trigger.rect().width() <= 340.0); + } + + #[test] + fn module_adheres_to_white_label_and_token_guards() { + let source = include_str!("multi_project_ui.rs").replace("\r\n", "\n"); + let prod = source.split("#[cfg(test)]\nmod tests").next().unwrap_or(""); + for bad in ["egui::Button::", "egui::Separator::", "egui::Spinner::", "egui::Window::", ".button(", ".checkbox(", ".radio(", ".separator(", "Color32::from_"] { + assert!(!prod.contains(bad), "multi_project_ui.rs must not contain {bad}"); + } + for (idx, line) in prod.lines().enumerate() { + let chinese = line.chars().any(|c| ('\u{4e00}'..='\u{9fff}').contains(&c)); + if chinese { + let words: Vec<&str> = line.split(|c: char| !c.is_alphanumeric()).collect(); + assert!( + !line.contains("PhotoCraft") && !line.contains("Pi Agent") && !words.contains(&"Pi"), + "line {} violates white-label guard: {line}", + idx + 1 + ); + } + } + } + + #[test] + #[ignore = "offscreen GPU T7B/T8 visual acceptance; requires PHOTOCRAFT_AGENT_QA_OUT"] + fn t7b_t8_multiproject_and_storage_visual_acceptance() { + use super::super::storage_settings_ui::{ + self, MigrationPhase, OldRootCleanupInfo, StorageUiState, default_switch_steps, + }; + use super::super::super::{PhotocraftApp, Workspace}; + use serde_json::json; + use std::sync::mpsc; + + let _gpu = photocraft_testkit::gpu_lock(); + let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + std::fs::create_dir_all(&directory).unwrap(); + let setup_ctx = |ctx: &egui::Context| { + PhotocraftApp::setup_context(ctx, ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }; + + fn save(directory: &str, name: &str, mut h: Harness<'_, S>) { + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(directory).join(name)).unwrap(); + } + + // 1 & 2 & 3: Four-layer multi-project workspace at 1440x900, 1280x800, and 150% DPI (960x600) + for (filename, w, h_px, ppp) in [ + ("01-multiproject-1440x900.png", 1440.0, 900.0, 1.0), + ("02-multiproject-1280x800.png", 1280.0, 800.0, 1.0), + ("03-multiproject-dpi150-960x600.png", 960.0, 600.0, 1.5), + ] { + let vm = sample_two_running_one_queued_vm(); + let harness = Harness::builder() + .with_size(vec2(w, h_px)) + .with_pixels_per_point(ppp) + .with_context_setup(setup_ctx) + .wgpu() + .build_ui(move |ui| { + let t = Tokens::get(ui.ctx()).agent(); + stitch_ui::scope_with_motion(ui, true, |ui| { + let dock_w = (w * 0.30).clamp(300.0, 420.0); + egui::Panel::right("qa-right-dock") + .resizable(false) + .exact_size(dock_w) + .frame(Frame::NONE.fill(t.dock)) + .show(ui, |ui| { + let _ = dock_context_header(ui, &vm, true); + Frame::NONE.inner_margin(Margin::symmetric(space::LG as i8, space::SM as i8)).show(ui, |ui| { + stitch_ui::divider(ui); + ui.add_space(space::SM); + ui.label(RichText::new("整套制作进行中 · 详情页 12/49").font(Type::Title.semibold()).color(t.text)); + ui.add_space(space::XS); + ui.label(RichText::new("子代理 A 正在生成第 4 屏场景图,B 正在复核第 3 屏文案。你可以随时查看主图或切到其他项目,后台继续推进。").font(Type::Body.font_id()).color(t.text_dim)); + }); + }); + egui::CentralPanel::default() + .frame(Frame::NONE.fill(t.canvas).inner_margin(Margin::same(space::LG as i8))) + .show(ui, |ui| { + let _ = workspace_top_layers(ui, &vm, true); + ui.add_space(space::MD); + Frame::NONE + .fill(t.dock) + .stroke(Stroke::new(1.0, t.card_border)) + .corner_radius(radius::CHIP as u8) + .inner_margin(Margin::same(space::XL as i8)) + .show(ui, |ui| { + ui.set_min_size(vec2(ui.available_width(), (ui.available_height() - space::LG).max(160.0))); + ui.vertical_centered(|ui| { + ui.add_space(space::XL); + ui.label(RichText::new("模板画布预览区 · 当前查看:主图(1/5)").font(Type::Heading.semibold()).color(t.text)); + ui.add_space(space::SM); + ui.label(RichText::new("后台正在静默推进详情页,画布编辑与预览互不干扰。").font(Type::Meta.font_id()).color(t.text_dim)); + }); + }); + }); + }); + }); + save(&directory, filename, harness); + } + + // 4: Narrow dock / top bar collapse check @ 520x900 + { + let vm = sample_two_running_one_queued_vm(); + let harness = Harness::builder() + .with_size(vec2(520.0, 900.0)) + .with_context_setup(setup_ctx) + .wgpu() + .build_ui(move |ui| { + let t = Tokens::get(ui.ctx()).agent(); + stitch_ui::scope_with_motion(ui, true, |ui| { + egui::CentralPanel::default() + .frame(Frame::NONE.fill(t.dock).inner_margin(Margin::same(space::MD as i8))) + .show(ui, |ui| { + ui.label(RichText::new("520pt 窄窗四层自动收敛检验").font(Type::Title.semibold()).color(t.text_dim)); + ui.add_space(space::SM); + let _ = workspace_top_layers(ui, &vm, true); + ui.add_space(space::LG); + stitch_ui::divider(ui); + ui.add_space(space::SM); + ui.label(RichText::new("右侧停靠栏 320pt 极窄宽度模拟").font(Type::Title.semibold()).color(t.text_dim)); + ui.add_space(space::SM); + ui.allocate_ui_with_layout(vec2(320.0, 320.0), Layout::top_down(Align::Min), |ui| { + Frame::NONE.fill(t.canvas).corner_radius(radius::CHIP as u8).show(ui, |ui| { + let _ = dock_context_header(ui, &vm, true); + }); + }); + }); + }); + }); + save(&directory, "04-narrow-dock-520x900.png", harness); + } + + // 5: Ultra-narrow storage cards @ 420x1400 (normal custom + env-override read-only + stats loading) + { + let mut normal = storage_settings_ui::tests_fixture_custom(); + let mut env_ro = storage_settings_ui::tests_fixture_env_override(); + let mut loading = storage_settings_ui::tests_fixture_custom(); + loading.status.stats_ready = false; + loading.status.current_root = r"D:\DesignAssets\XiaoYiProductionWorkspace\LongCompanyFolderName\DataRoot".into(); + loading.status.migration.phase = MigrationPhase::Copying; + loading.status.migration.copied_bytes = 58_840_000_000; + loading.status.migration.total_bytes = 92_234_421_043; + let harness = Harness::builder() + .with_size(vec2(420.0, 1400.0)) + .with_context_setup(setup_ctx) + .wgpu() + .build_ui(move |ui| { + let t = Tokens::get(ui.ctx()).agent(); + stitch_ui::scope_with_motion(ui, true, |ui| { + egui::CentralPanel::default() + .frame(Frame::NONE.fill(t.dock).inner_margin(Margin::same(space::LG as i8))) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = space::MD; + ui.label(RichText::new("场景 A:正常自定义数据目录").font(Type::Title.semibold()).color(t.text_dim)); + let _ = storage_settings_ui::storage_settings_card(ui, &mut normal, true, false); + ui.add_space(space::SM); + ui.label(RichText::new("场景 B:环境变量只读锁定警示").font(Type::Title.semibold()).color(t.text_dim)); + let _ = storage_settings_ui::storage_settings_card(ui, &mut env_ro, true, false); + ui.add_space(space::SM); + ui.label(RichText::new("场景 C:超长路径换行 + 统计中 + 预拷贝中").font(Type::Title.semibold()).color(t.text_dim)); + let _ = storage_settings_ui::storage_settings_card(ui, &mut loading, true, false); + }); + }); + }); + save(&directory, "05-narrow-storage-420x1400.png", harness); + } + + // 6: "我的项目" page with live runtime badges + top-right settings gear @ 1280x800 + { + let (tx, _) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + w.busy = None; + w.reduce_motion = true; + w.library = true; + w.account = json!({"id": "qa", "name": "设计团队"}); + w.projects = vec![ + json!({"id":"proj-chair-a","source":"native","name":"软包实木餐椅 A01","brandName":"原木生活家","productModel":"CY011401","status":"active","updatedLabel":"今天 20:10"}), + json!({"id":"proj-sofa-b","source":"native","name":"意式直排真皮沙发 B08","brandName":"米兰意居","productModel":"SF2088","status":"active","updatedLabel":"今天 19:52"}), + json!({"id":"proj-table-c","source":"native","name":"岩板伸缩餐桌 C12","brandName":"原木生活家","productModel":"TB3312","status":"draft","updatedLabel":"今天 19:40"}), + json!({"id":"proj-bed-d","source":"native","name":"极简悬浮真皮床 D05","brandName":"森屿家居","productModel":"BD5501","status":"active","updatedLabel":"昨天 18:15"}), + json!({"id":"proj-cabinet-e","source":"native","name":"中古黑胡桃餐边柜 E09","brandName":"原木生活家","productModel":"CB9009","status":"active","updatedLabel":"昨天 14:30"}), + json!({"id":"proj-lamp-f","source":"native","name":"包豪斯台灯 F03","brandName":"光影工坊","productModel":"LP0301","status":"completed","updatedLabel":"11-28"}), + ]; + let mut vm = sample_two_running_one_queued_vm(); + vm.active_section = WorkspaceSection::Projects; + vm.global_runs.push(GlobalRunEntry { + project_id: "proj-bed-d".into(), + project_title: "极简悬浮真皮床 D05".into(), + status: MultiRunStatus::PartialDelivered, + producing_output_id: "sku_images".into(), + producing_output_label: "SKU 图".into(), + progress_label: "缺 2 项待补".into(), + elapsed_secs: 0, + active_slots: 0, + has_attention: true, + }); + vm.global_runs.push(GlobalRunEntry { + project_id: "proj-cabinet-e".into(), + project_title: "中古黑胡桃餐边柜 E09".into(), + status: MultiRunStatus::Paused, + producing_output_id: "detail".into(), + producing_output_label: "详情页".into(), + progress_label: "8/24".into(), + elapsed_secs: 0, + active_slots: 0, + has_attention: false, + }); + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let harness = Harness::builder() + .with_size(vec2(1280.0, 800.0)) + .with_context_setup(setup_ctx) + .wgpu() + .build_ui_state( + move |ui, state: &mut Box<(Workspace, PhotocraftApp, MultiProjectViewModel)>| { + let (w, app, vm) = &mut **state; + set_snapshot(ui.ctx(), vm.clone()); + egui::CentralPanel::default().frame(Frame::NONE).show(ui, |ui| { + w.library_ui(app, ui); + }); + }, + Box::new((w, app, vm)), + ); + save(&directory, "06-projects-live-badges-1280x800.png", harness); + } + + // 7: Settings popup containing storage card (normal + env-override side by side) @ 1280x800 + { + let mut s_normal = storage_settings_ui::tests_fixture_custom(); + let mut s_env = storage_settings_ui::tests_fixture_env_override(); + let harness = Harness::builder() + .with_size(vec2(1280.0, 800.0)) + .with_context_setup(setup_ctx) + .wgpu() + .build_ui(move |ui| { + let t = Tokens::get(ui.ctx()).agent(); + stitch_ui::scope_with_motion(ui, true, |ui| { + egui::CentralPanel::default() + .frame(Frame::NONE.fill(t.canvas).inner_margin(Margin::same(space::XL as i8))) + .show(ui, |ui| { + ui.columns(2, |cols| { + let frame = stitch_ui::overlay_frame(cols[0].ctx(), stitch_ui::SurfaceRole::Dialog, 1.0).inner_margin(18); + stitch_ui::material_frame(&mut cols[0], frame, |ui| { + ui.set_width(360.0); + ui.label(RichText::new("小壹设置(自定义存储目录)").font(Type::Body.semibold()).color(t.text)); + ui.add_space(space::SM); + ui.label(RichText::new("当前版本 1.2612.109(提交 f7ad5d1)").font(Type::Title.font_id()).color(t.text)); + ui.label(RichText::new("已是最新版本 · 20:30 检查").font(Type::Meta.font_id()).color(t.text_dim)); + ui.add_space(space::XS); + let _ = storage_settings_ui::storage_settings_card(ui, &mut s_normal, true, true); + }); + let frame2 = stitch_ui::overlay_frame(cols[1].ctx(), stitch_ui::SurfaceRole::Dialog, 1.0).inner_margin(18); + stitch_ui::material_frame(&mut cols[1], frame2, |ui| { + ui.set_width(360.0); + ui.label(RichText::new("小壹设置(环境变量只读锁定)").font(Type::Body.semibold()).color(t.text)); + ui.add_space(space::SM); + ui.label(RichText::new("当前版本 1.2612.109(提交 f7ad5d1)").font(Type::Title.font_id()).color(t.text)); + ui.label(RichText::new("已是最新版本 · 20:30 检查").font(Type::Meta.font_id()).color(t.text_dim)); + ui.add_space(space::XS); + let _ = storage_settings_ui::storage_settings_card(ui, &mut s_env, true, true); + }); + }); + }); + }); + }); + save(&directory, "07-settings-storage-card-1280x800.png", harness); + } + + // 8: Storage Migration Modal states (Stage 1 Progress + Stage 2 Non-Closable Steps + Post-Restart Release + Hard Validation Error) @ 1440x1100 + { + let mut s_validate = storage_settings_ui::tests_fixture_custom(); + s_validate.target_input = r"C:\Users\Designer\OneDrive\XiaoYiData".into(); + s_validate.status.migration.validation_error = Some( + "所选目录位于 OneDrive 同步路径下,包含云端重解析点,为避免工程损坏已拒绝。请改选本机固定硬盘的空目录。".into(), + ); + + let mut s_stage1 = storage_settings_ui::tests_fixture_custom(); + s_stage1.status.migration.phase = MigrationPhase::Copying; + s_stage1.status.migration.copied_bytes = 58_840_000_000; + s_stage1.status.migration.total_bytes = 92_234_421_043; + s_stage1.status.migration.speed_bytes_per_sec = Some(195_000_000); + + let mut s_stage2 = storage_settings_ui::tests_fixture_custom(); + s_stage2.status.migration.phase = MigrationPhase::Switching; + s_stage2.status.migration.switch_steps = default_switch_steps(1); + + let mut s_post = storage_settings_ui::tests_fixture_custom(); + s_post.status.current_root = r"E:\XiaoYiData".into(); + s_post.status.migration.phase = MigrationPhase::Completed; + s_post.status.pending_old_root_cleanup = Some(OldRootCleanupInfo { + old_root: r"D:\XiaoYiWorkspace\Data".into(), + reclaimable_bytes: 92_234_421_043, + grace_days: 7, + verified_project_count: 20, + }); + + let harness = Harness::builder() + .with_size(vec2(1440.0, 1100.0)) + .with_context_setup(setup_ctx) + .wgpu() + .build_ui(move |ui| { + let t = Tokens::get(ui.ctx()).agent(); + stitch_ui::scope_with_motion(ui, true, |ui| { + egui::CentralPanel::default() + .frame(Frame::NONE.fill(t.canvas).inner_margin(Margin::same(space::XL as i8))) + .show(ui, |ui| { + ui.columns(2, |cols| { + storage_settings_ui::render_migrate_preview(&mut cols[0], &mut s_validate, 480.0); + cols[0].add_space(space::LG); + storage_settings_ui::render_migrate_preview(&mut cols[0], &mut s_stage1, 480.0); + + storage_settings_ui::render_migrate_preview(&mut cols[1], &mut s_stage2, 480.0); + cols[1].add_space(space::LG); + storage_settings_ui::render_migrate_preview(&mut cols[1], &mut s_post, 480.0); + }); + }); + }); + }); + save(&directory, "08-migrate-modals-1440x1100.png", harness); + } + + // 9: Cleanup Space Modal (lossless default checked vs archive manual opt-in) @ 1280x800 + { + let mut s_cleanup = storage_settings_ui::tests_fixture_custom(); + s_cleanup.cleanup_modal_open = true; + let harness = Harness::builder() + .with_size(vec2(1280.0, 800.0)) + .with_context_setup(setup_ctx) + .wgpu() + .build_ui_state( + |ui, state: &mut StorageUiState| { + let t = Tokens::get(ui.ctx()).agent(); + stitch_ui::scope_with_motion(ui, true, |ui| { + egui::CentralPanel::default().frame(Frame::NONE.fill(t.canvas)).show(ui, |_| {}); + let _ = storage_settings_ui::show_storage_modals(ui.ctx(), state, true); + }); + }, + s_cleanup, + ); + save(&directory, "09-cleanup-modal-1280x800.png", harness); + } + + // 10: Cleanup Space Modal tall view (showing both lossless + manual archive with risk notes) @ 1280x1000 + { + let mut s_cleanup = storage_settings_ui::tests_fixture_custom(); + s_cleanup.cleanup_modal_open = true; + if let Some(archive) = s_cleanup.scan.items.iter_mut().find(|i| !i.lossless) { + archive.selected = true; + } + let harness = Harness::builder() + .with_size(vec2(1280.0, 1000.0)) + .with_context_setup(setup_ctx) + .wgpu() + .build_ui_state( + |ui, state: &mut StorageUiState| { + let t = Tokens::get(ui.ctx()).agent(); + stitch_ui::scope_with_motion(ui, true, |ui| { + egui::CentralPanel::default().frame(Frame::NONE.fill(t.canvas)).show(ui, |_| {}); + let _ = storage_settings_ui::show_storage_modals(ui.ctx(), state, true); + }); + }, + s_cleanup, + ); + save(&directory, "10-cleanup-modal-full-1280x1000.png", harness); + } + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs index 67a37e4c..10a3a5df 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs @@ -278,12 +278,30 @@ impl Workspace { ui.label(RichText::new("我的项目").size(20.0).strong().color(t.text)); ui.label(RichText::new(self.projects.len().to_string()).size(12.0).color(t.text_dim)); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let settings_btn = stitch_ui::icon_button(ui, "settings", 30.0, self.model_settings, "小壹设置与数据存储"); + if settings_btn.clicked() { + self.model_settings = !self.model_settings; + if self.model_settings { + self.prompt_library.close(); + } else { + self.api_key.clear(); + self.key_settings = false; + } + } + self.settings_popup(ui, &settings_btn); if stitch_ui::icon_button(ui, "rotate-cw", 30.0, false, "刷新项目").clicked() { self.cover_errors.clear(); self.send("projects", json!({})); } }); }); + let multi_vm = self.multi_project_view_model(app, ui.ctx()); + if !multi_vm.global_runs.is_empty() { + ui.add_space(12.0); + if let Some(action) = agent_panel::multi_project_ui::global_task_strip(ui, &multi_vm, self.reduce_motion) { + self.handle_multi_project_action(app, ui.ctx(), action); + } + } ui.add_space(18.0); // The selection belongs to this account and origin, and is only // a view filter: no project status or sync record is modified. @@ -428,6 +446,7 @@ impl Workspace { }); }); self.delete_dialog(app, ui); + self.storage_modals_ui(ui.ctx()); }); if !self.cover_loading.is_empty() { ui.ctx().request_repaint_after(Duration::from_millis(100)); @@ -468,10 +487,22 @@ impl Workspace { } } ui.painter().rect_stroke(shell,16.0,Stroke::new(stroke_width,t.card_border.lerp_to_gamma(t.text_dim,hover*0.65)),egui::StrokeKind::Inside); - let (state, _, _) = badge(item, &t); - let badge_width = if state == "状态未知" { 84.0 } else if state == "进行中" { 54.0 } else { 42.0 }; - let badge_rect = egui::Rect::from_min_size(rect.min+vec2(10.0,10.0),vec2(badge_width,24.0)); - stitch_ui::paint_status_chip(ui, &t, badge_rect, state, if state=="完结" {stitch_ui::StatusChipStyle::Contrast} else {stitch_ui::StatusChipStyle::Muted}); + let live_run = item["id"] + .as_str() + .and_then(|id| { + agent_panel::multi_project_ui::snapshot(ui.ctx()) + .and_then(|vm| vm.run_for_project(id).cloned()) + }); + let (state, badge_rect) = if let Some(run) = &live_run { + let rect = agent_panel::multi_project_ui::paint_project_live_badge(ui, rect, run, self.reduce_motion); + (run.status.label(), rect) + } else { + let (state, _, _) = badge(item, &t); + let badge_width = if state == "状态未知" { 84.0 } else if state == "进行中" { 54.0 } else { 42.0 }; + let badge_rect = egui::Rect::from_min_size(rect.min+vec2(10.0,10.0),vec2(badge_width,24.0)); + stitch_ui::paint_status_chip(ui, &t, badge_rect, state, if state=="完结" {stitch_ui::StatusChipStyle::Contrast} else {stitch_ui::StatusChipStyle::Muted}); + (state, badge_rect) + }; if response.has_focus() {ui.painter().rect_stroke(rect.expand(2.0),18.0,Stroke::new(1.2,t.text),egui::StrokeKind::Outside);} let update = if item["cloudUpdateAvailable"] == true || item["cloudUpdateBlocked"].is_string() { let open = self.open_project_index(app, item["id"].as_str().unwrap_or("")).is_some(); @@ -519,11 +550,21 @@ impl Workspace { else if native { "本机" } else { "云端" }; let updated = item["updatedLabel"].as_str().or_else(|| item["updatedAt"].as_str()?.get(..10)) .unwrap_or("更新时间未知"); - for (offset, text) in [(36.0, format!("{brand} · {model}")), (56.0, format!("{updated} · {status}"))] { + let second_meta = if let Some(run) = &live_run { + agent_panel::multi_project_ui::project_card_live_subtitle(run) + } else { + format!("{updated} · {status}") + }; + let second_color = if let Some(run) = &live_run { + run.status.tone().color(&t) + } else { + t.text_dim + }; + for (offset, text, color) in [(36.0, format!("{brand} · {model}"), t.text_dim), (56.0, second_meta, second_color)] { let line = egui::Rect::from_min_size(pos2(rect.left() + 12.0, rect.bottom() + offset), vec2(width - 24.0, 18.0)); let mut row = ui.new_child(egui::UiBuilder::new().id_salt(("project-meta", offset as u32)) .max_rect(line).layout(Layout::left_to_right(Align::Center))); - row.add(egui::Label::new(RichText::new(&text).size(Type::Meta.size()).color(t.text_dim)).truncate()).on_hover_text(text); + row.add(egui::Label::new(RichText::new(&text).size(Type::Meta.size()).color(color)).truncate()).on_hover_text(text); } let on_menu = ui.input(|i|i.pointer.interact_pos().is_some_and(|p|menu_rect.contains(p))); let opening = menu_open || (response.clicked() && !on_menu && !egui::Popup::is_any_open(ui.ctx())); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/storage_settings_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/storage_settings_ui.rs new file mode 100644 index 00000000..d26e4bb8 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/storage_settings_ui.rs @@ -0,0 +1,1847 @@ +//! Machine-global storage location settings card, two-stage migration modal, +//! and read-only-first storage cleanup modal. +//! +//! State lives in a machine-scoped context slot so switching accounts never +//! resets storage settings or active migration progress. + +use super::super::stitch_ui::{ + self, ButtonRole, FocusRing, OverlayVisual, StatusTone, SurfaceRole, +}; +use crate::icons; +use crate::theme::agent_scale::{Type, control, icon, radius, space}; +use crate::theme::Tokens; +use egui::{Align, Frame, Id, Layout, Margin, Response, RichText, Sense, Stroke, StrokeKind, Ui, vec2}; +use serde_json::{Value, json}; + +/// Machine-global root mode returned by `"storage-status"`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum StorageRootMode { + #[default] + DefaultPlatform, + CustomPointer, + EnvOverride, + Portable, + Unavailable, +} + +impl StorageRootMode { + pub(crate) fn parse(wire: &str) -> Self { + match wire { + "custom" | "pointer" => Self::CustomPointer, + "env" | "override" | "env_override" => Self::EnvOverride, + "portable" => Self::Portable, + "unavailable" => Self::Unavailable, + _ => Self::DefaultPlatform, + } + } + + pub(crate) fn badge_label(self) -> &'static str { + match self { + Self::DefaultPlatform => "默认目录", + Self::CustomPointer => "自定义目录", + Self::EnvOverride => "环境变量指定", + Self::Portable => "便携模式", + Self::Unavailable => "目录不可用", + } + } + + pub(crate) fn is_readonly(self) -> bool { + matches!(self, Self::EnvOverride | Self::Portable) + } +} + +/// Migration state machine phases aligned with `"storage-migrate"`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum MigrationPhase { + #[default] + Idle, + Validating, + Copying, + ReadyToSwitch, + Switching, + Restarting, + Completed, + Failed, + RolledBack, +} + +impl MigrationPhase { + pub(crate) fn parse(wire: &str) -> Self { + match wire { + "validating" => Self::Validating, + "copying" => Self::Copying, + "ready_to_switch" => Self::ReadyToSwitch, + "switching" => Self::Switching, + "restarting" => Self::Restarting, + "completed" => Self::Completed, + "failed" => Self::Failed, + "rolled_back" => Self::RolledBack, + _ => Self::Idle, + } + } + + pub(crate) fn is_non_closable(self) -> bool { + matches!(self, Self::Switching | Self::Restarting) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SwitchStepState { + Pending, + Active, + Done, + Failed, +} + +impl SwitchStepState { + pub(crate) fn parse(wire: &str) -> Self { + match wire { + "done" | "completed" => Self::Done, + "active" | "running" => Self::Active, + "failed" | "error" => Self::Failed, + _ => Self::Pending, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct SwitchStep { + pub id: String, + pub label: String, + pub state: SwitchStepState, +} + +pub(crate) fn default_switch_steps(active_index: usize) -> Vec { + let defs = [ + ("freeze", "停写冻结核对(刷新会话与任务日志)"), + ("rewrite", "路径改写与完整性校验"), + ("pointer", "原子写入新目录指针(保留旧目录)"), + ("restart", "重启应用并完成启动自检"), + ]; + defs.into_iter() + .enumerate() + .map(|(idx, (id, label))| SwitchStep { + id: id.into(), + label: label.into(), + state: if idx < active_index { + SwitchStepState::Done + } else if idx == active_index { + SwitchStepState::Active + } else { + SwitchStepState::Pending + }, + }) + .collect() +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct MigrationStateView { + pub phase: MigrationPhase, + pub target_root: String, + pub target_free_bytes: Option, + pub required_bytes: u64, + pub copied_bytes: u64, + pub total_bytes: u64, + pub speed_bytes_per_sec: Option, + pub validation_error: Option, + pub validation_warnings: Vec, + pub blocking_projects: Vec, + pub switch_steps: Vec, + pub error: Option, + pub rollback_note: Option, +} + +impl MigrationStateView { + pub(crate) fn copy_fraction(&self) -> Option { + if self.total_bytes == 0 { + None + } else { + Some((self.copied_bytes as f64 / self.total_bytes as f64).clamp(0.0, 1.0) as f32) + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct OldRootCleanupInfo { + pub old_root: String, + pub reclaimable_bytes: u64, + pub grace_days: u32, + pub verified_project_count: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct StorageStatusView { + pub current_root: String, + pub mode: StorageRootMode, + pub readonly_reason: Option, + pub stats_ready: bool, + pub total_bytes: u64, + pub project_count: usize, + pub free_bytes: Option, + pub recovery_note: Option, + pub status_text: Option, + pub status_is_warning: bool, + pub status_is_error: bool, + pub migration: MigrationStateView, + pub pending_old_root_cleanup: Option, +} + +impl Default for StorageStatusView { + fn default() -> Self { + Self { + current_root: String::new(), + mode: StorageRootMode::DefaultPlatform, + readonly_reason: None, + stats_ready: false, + total_bytes: 0, + project_count: 0, + free_bytes: None, + recovery_note: Some("异常恢复目录仍保留在本机默认缓存位置,不随迁移移动。".into()), + status_text: None, + status_is_warning: false, + status_is_error: false, + migration: MigrationStateView::default(), + pending_old_root_cleanup: None, + } + } +} + +impl StorageStatusView { + #[allow(dead_code, reason = "跨轨契约 JSON 解析入口,供集成阶段消费 storage-status 回执")] + pub(crate) fn from_json(value: &Value) -> Self { + let mig = &value["migration"]; + let steps = mig["switchSteps"] + .as_array() + .map(|rows| { + rows.iter() + .map(|row| SwitchStep { + id: row["id"].as_str().unwrap_or_default().to_owned(), + label: row["label"].as_str().unwrap_or_default().to_owned(), + state: SwitchStepState::parse(row["state"].as_str().unwrap_or("pending")), + }) + .collect() + }) + .unwrap_or_default(); + let old = value.get("pendingOldRootCleanup").filter(|v| v.is_object()).map(|row| { + OldRootCleanupInfo { + old_root: row["oldRoot"].as_str().unwrap_or_default().to_owned(), + reclaimable_bytes: row["reclaimableBytes"].as_u64().unwrap_or(0), + grace_days: row["graceDays"].as_u64().unwrap_or(7) as u32, + verified_project_count: row["verifiedProjectCount"].as_u64().unwrap_or(0) as usize, + } + }); + Self { + current_root: value["currentRoot"].as_str().unwrap_or_default().to_owned(), + mode: StorageRootMode::parse(value["mode"].as_str().unwrap_or("default")), + readonly_reason: value["readonlyReason"].as_str().filter(|s| !s.is_empty()).map(str::to_owned), + stats_ready: value["statsReady"].as_bool().unwrap_or(false), + total_bytes: value["totalBytes"].as_u64().unwrap_or(0), + project_count: value["projectCount"].as_u64().unwrap_or(0) as usize, + free_bytes: value["freeBytes"].as_u64(), + recovery_note: value["recoveryNote"].as_str().map(str::to_owned), + status_text: value["statusText"].as_str().filter(|s| !s.is_empty()).map(str::to_owned), + status_is_warning: value["statusTone"] == "warning", + status_is_error: value["statusTone"] == "error", + migration: MigrationStateView { + phase: MigrationPhase::parse(mig["phase"].as_str().unwrap_or("idle")), + target_root: mig["targetRoot"].as_str().unwrap_or_default().to_owned(), + target_free_bytes: mig["targetFreeBytes"].as_u64(), + required_bytes: mig["requiredBytes"].as_u64().unwrap_or(0), + copied_bytes: mig["copiedBytes"].as_u64().unwrap_or(0), + total_bytes: mig["totalBytes"].as_u64().unwrap_or(0), + speed_bytes_per_sec: mig["speedBytesPerSec"].as_u64(), + validation_error: mig["validationError"].as_str().filter(|s| !s.is_empty()).map(str::to_owned), + validation_warnings: mig["validationWarnings"] + .as_array() + .into_iter() + .flatten() + .filter_map(|v| v.as_str().map(str::to_owned)) + .collect(), + blocking_projects: mig["blockingProjects"] + .as_array() + .into_iter() + .flatten() + .filter_map(|v| v.as_str().map(str::to_owned)) + .collect(), + switch_steps: steps, + error: mig["error"].as_str().filter(|s| !s.is_empty()).map(str::to_owned), + rollback_note: mig["rollbackNote"].as_str().filter(|s| !s.is_empty()).map(str::to_owned), + }, + pending_old_root_cleanup: old, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct CleanupCategoryItem { + pub id: String, + pub label: String, + pub description: String, + pub bytes: u64, + pub lossless: bool, + pub risk_note: Option, + pub selected: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct CleanupResultView { + pub freed_bytes: u64, + pub message: String, + pub error: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct StorageScanView { + pub scanning: bool, + pub error: Option, + pub items: Vec, + pub cleanup_running: bool, + pub cleanup_result: Option, +} + +impl StorageScanView { + pub(crate) fn selected_bytes(&self) -> u64 { + self.items.iter().filter(|item| item.selected).map(|item| item.bytes).sum() + } + + pub(crate) fn selected_ids(&self) -> Vec { + self.items.iter().filter(|item| item.selected).map(|item| item.id.clone()).collect() + } + + pub(crate) fn lossless_total_bytes(&self) -> u64 { + self.items.iter().filter(|item| item.lossless).map(|item| item.bytes).sum() + } + + pub(crate) fn archive_total_bytes(&self) -> u64 { + self.items.iter().filter(|item| !item.lossless).map(|item| item.bytes).sum() + } + + #[allow(dead_code, reason = "跨轨契约 JSON 解析入口,供集成阶段消费 storage-scan 回执")] + pub(crate) fn from_json(value: &Value) -> Self { + let items = value["categories"] + .as_array() + .into_iter() + .flatten() + .map(|row| { + let lossless = row["lossless"].as_bool().unwrap_or(false); + CleanupCategoryItem { + id: row["id"].as_str().unwrap_or_default().to_owned(), + label: row["label"].as_str().unwrap_or("清理项").to_owned(), + description: row["description"].as_str().unwrap_or_default().to_owned(), + bytes: row["bytes"].as_u64().unwrap_or(0), + lossless, + risk_note: row["riskNote"].as_str().filter(|s| !s.is_empty()).map(str::to_owned), + selected: row["defaultSelected"].as_bool().unwrap_or(lossless), + } + }) + .collect(); + let cleanup_result = value.get("cleanupResult").filter(|v| v.is_object()).map(|row| { + CleanupResultView { + freed_bytes: row["freedBytes"].as_u64().unwrap_or(0), + message: row["message"].as_str().unwrap_or_default().to_owned(), + error: row["error"].as_str().filter(|s| !s.is_empty()).map(str::to_owned), + } + }); + Self { + scanning: value["scanning"].as_bool().unwrap_or(false), + error: value["error"].as_str().filter(|s| !s.is_empty()).map(str::to_owned), + items, + cleanup_running: value["cleanupRunning"].as_bool().unwrap_or(false), + cleanup_result, + } + } +} + +/// Typed storage actions emitted to the host bridge (`"storage-status"`, +/// `"storage-scan"`, `"storage-cleanup"`, `"storage-migrate"`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum StorageAction { + #[allow(dead_code, reason = "跨轨契约动作,供集成阶段显式刷新存储状态")] + RefreshStatus, + OpenCurrentFolder, + PickMigrationTarget, + ValidateTarget(String), + StartCopy(String), + CancelCopy, + ConfirmSwitchAndRestart, + RetryMigration, + ReleaseOldRoot(String), + KeepOldRootForLater, + StartScan, + StartCleanup(Vec), +} + +impl StorageAction { + /// Convert to `(action_name, payload)` matching the T8 host RPC contract. + pub(crate) fn to_request(&self) -> (&'static str, Value) { + match self { + Self::RefreshStatus => ("storage-status", json!({"op": "status"})), + Self::OpenCurrentFolder => ("storage-status", json!({"op": "open-folder"})), + Self::PickMigrationTarget => ("storage-migrate", json!({"op": "pick-folder"})), + Self::ValidateTarget(path) => ("storage-migrate", json!({"op": "validate", "targetRoot": path})), + Self::StartCopy(path) => ("storage-migrate", json!({"op": "start-copy", "targetRoot": path})), + Self::CancelCopy => ("storage-migrate", json!({"op": "cancel"})), + Self::ConfirmSwitchAndRestart => ("storage-migrate", json!({"op": "switch"})), + Self::RetryMigration => ("storage-migrate", json!({"op": "retry"})), + Self::ReleaseOldRoot(old_root) => ("storage-migrate", json!({"op": "release-old-root", "oldRoot": old_root})), + Self::KeepOldRootForLater => ("storage-migrate", json!({"op": "defer-old-root"})), + Self::StartScan => ("storage-scan", json!({"op": "scan"})), + Self::StartCleanup(categories) => ("storage-cleanup", json!({"op": "run", "categories": categories})), + } + } +} + +/// Machine-global UI state (NOT keyed by account or origin!). +#[derive(Clone, Debug, Default)] +pub(crate) struct StorageUiState { + pub status: StorageStatusView, + pub scan: StorageScanView, + pub migrate_modal_open: bool, + pub cleanup_modal_open: bool, + pub target_input: String, + pub confirm_release_armed: bool, +} + +fn machine_state_id() -> Id { + Id::unique("xiaoyi-machine-storage-ui-state") +} + +pub(crate) fn with_machine_state(ctx: &egui::Context, f: impl FnOnce(&mut StorageUiState) -> R) -> R { + let mut state = ctx.data_mut(|data| { + data.get_temp::(machine_state_id()).unwrap_or_default() + }); + let result = f(&mut state); + ctx.data_mut(|data| data.insert_temp(machine_state_id(), state)); + result +} + +#[allow(dead_code, reason = "跨轨契约写入入口,供集成阶段同步 storage-status 状态")] +pub(crate) fn set_status(ctx: &egui::Context, status: StorageStatusView) { + with_machine_state(ctx, |state| { + if state.target_input.is_empty() && !status.migration.target_root.is_empty() { + state.target_input = status.migration.target_root.clone(); + } + if status.migration.phase.is_non_closable() { + state.migrate_modal_open = true; + } + state.status = status; + }); +} + +#[allow(dead_code, reason = "跨轨契约写入入口,供集成阶段同步 storage-scan 状态")] +pub(crate) fn set_scan(ctx: &egui::Context, scan: StorageScanView) { + with_machine_state(ctx, |state| { + state.scan = scan; + }); +} + +pub(crate) fn format_bytes(bytes: u64) -> String { + const KB: f64 = 1024.0; + const MB: f64 = 1024.0 * 1024.0; + const GB: f64 = 1024.0 * 1024.0 * 1024.0; + let b = bytes as f64; + if b >= GB { + let gb = b / GB; + if gb >= 100.0 { format!("{gb:.0} GB") } else { format!("{gb:.1} GB") } + } else if b >= MB { + let mb = b / MB; + if mb >= 100.0 { format!("{mb:.0} MB") } else { format!("{mb:.1} MB") } + } else if b >= KB { + format!("{:.0} KB", b / KB) + } else { + format!("{bytes} B") + } +} + +pub(crate) fn format_speed(bytes_per_sec: u64) -> String { + format!("{}/s", format_bytes(bytes_per_sec)) +} + +/// Render the machine-global "存储" card inside the settings popup, right after +/// client version info and before any bottom preference toggles. +pub(crate) fn storage_settings_card( + ui: &mut Ui, + state: &mut StorageUiState, + reduced: bool, + show_divider: bool, +) -> Option { + if show_divider { + stitch_ui::divider(ui); + } + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + let mut action = None; + + let card_id = Id::unique("xiaoyi-settings-storage-card"); + stitch_ui::surface_card(ui, card_id, true, reduced, |ui| { + ui.spacing_mut().item_spacing = vec2(space::SM, space::SM); + + // Header row: icon + title + mode tag + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = space::XS + space::XXS; + ui.add(icons::image("folder", icon::MD, t.text_dim)); + ui.label(RichText::new("数据存储").font(Type::Title.semibold()).color(t.text)); + let mode_color = match state.status.mode { + StorageRootMode::CustomPointer => semantic.jade, + StorageRootMode::EnvOverride | StorageRootMode::Portable => t.warning, + StorageRootMode::Unavailable => t.danger, + StorageRootMode::DefaultPlatform => t.text_dim, + }; + ui.label( + RichText::new(format!("· {}", state.status.mode.badge_label())) + .font(Type::Meta.font_id()) + .color(mode_color), + ); + }); + + // Current path inside recessed wrap-safe block + let root_text = if state.status.current_root.is_empty() { + "正在读取数据目录…" + } else { + &state.status.current_root + }; + let path_frame = Frame::NONE + .fill(t.field) + .stroke(Stroke::new(1.0, t.field_border)) + .corner_radius(radius::ROW as u8) + .inner_margin(Margin::symmetric(space::SM as i8, space::XS as i8 + 2)); + let path_inner_w = (ui.available_width() - path_frame.total_margin().sum().x).max(1.0); + path_frame.show(ui, |ui| { + ui.set_width(path_inner_w); + ui.add( + egui::Label::new( + RichText::new(root_text) + .font(Type::Meta.font_id()) + .color(if state.status.current_root.is_empty() { t.text_dim } else { t.text }), + ) + .wrap(), + ); + }); + + // Usage & project stats (never fabricate 0 GB before async scan completes) + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = space::XS + space::XXS; + if !state.status.stats_ready { + stitch_ui::ai_loader(ui, card_id.with("stats-loader"), true, reduced); + ui.label(RichText::new("统计中…").font(Type::Meta.font_id()).color(t.text_dim)); + } else { + let mut line = format!( + "已占用 {} · {} 个项目", + format_bytes(state.status.total_bytes), + state.status.project_count + ); + if let Some(free) = state.status.free_bytes { + line.push_str(&format!(" · 磁盘剩余 {}", format_bytes(free))); + } + ui.add(egui::Label::new(RichText::new(line).font(Type::Meta.font_id()).color(t.text_dim)).wrap()); + } + }); + + // Read-only explanation (EnvOverride / Portable) or Unavailable error + if state.status.mode == StorageRootMode::Unavailable { + stitch_ui::status_label( + ui, + state.status.readonly_reason.as_deref().unwrap_or("自定义数据目录暂不可用,请检查对应磁盘连接后重试。"), + StatusTone::Error, + ); + } else if state.status.mode.is_readonly() { + let reason = state.status.readonly_reason.as_deref().unwrap_or( + if state.status.mode == StorageRootMode::EnvOverride { + "当前由启动环境变量锁定目录,无法在设置内迁移;移除该环境变量并重启后可由本机管理。" + } else { + "当前处于便携模式,数据随程序目录存放,暂不支持在设置内迁移。" + }, + ); + stitch_ui::status_label(ui, reason, StatusTone::Warning); + } else if let Some(text) = &state.status.status_text { + let tone = if state.status.status_is_error { + StatusTone::Error + } else if state.status.status_is_warning { + StatusTone::Warning + } else { + StatusTone::Neutral + }; + stitch_ui::status_label(ui, text, tone); + } + + // Live migration inline status banner when copying / ready / post-restart cleanup + match state.status.migration.phase { + MigrationPhase::Copying => { + let pct = state.status.migration.copy_fraction().map_or(0, |f| (f * 100.0).floor() as u32); + ui.horizontal_wrapped(|ui| { + stitch_ui::status_label( + ui, + &format!("后台预拷贝进行中 {pct}%(可继续正常使用)"), + StatusTone::Neutral, + ); + if stitch_ui::action_button(ui, "查看进度", ButtonRole::Quiet, true).clicked() { + state.migrate_modal_open = true; + } + }); + } + MigrationPhase::ReadyToSwitch => { + ui.horizontal_wrapped(|ui| { + stitch_ui::status_label(ui, "预拷贝已完成,等待切换并重启", StatusTone::Warning); + if stitch_ui::action_button(ui, "立即切换", ButtonRole::Quiet, true).clicked() { + state.migrate_modal_open = true; + } + }); + } + _ => {} + } + + if let Some(old) = &state.status.pending_old_root_cleanup { + ui.horizontal_wrapped(|ui| { + stitch_ui::status_label( + ui, + &format!("新目录已生效 · 旧目录可省回 {}", format_bytes(old.reclaimable_bytes)), + StatusTone::Neutral, + ); + if stitch_ui::action_button(ui, "处理旧目录", ButtonRole::Quiet, true).clicked() { + state.migrate_modal_open = true; + } + }); + } + + // Action row (Quiet role, matches Stitch settings density) + let switching = state.status.migration.phase.is_non_closable(); + let can_change = !state.status.mode.is_readonly() && !switching; + let can_cleanup = state.status.mode != StorageRootMode::Unavailable && !switching; + let can_open = !state.status.current_root.is_empty() && state.status.mode != StorageRootMode::Unavailable; + + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(space::MD, space::XS); + let change_label = match state.status.migration.phase { + MigrationPhase::Copying => "迁移进度…", + MigrationPhase::ReadyToSwitch => "切换目录…", + _ => "更改目录…", + }; + let change_btn = stitch_ui::action_button(ui, change_label, ButtonRole::Quiet, can_change); + if change_btn.clicked() { + if state.target_input.is_empty() && !state.status.migration.target_root.is_empty() { + state.target_input = state.status.migration.target_root.clone(); + } + state.migrate_modal_open = true; + } + if !can_change { + change_btn.on_disabled_hover_text("当前目录模式为只读,无法更改存储位置"); + } + + if stitch_ui::action_button(ui, "清理空间", ButtonRole::Quiet, can_cleanup).clicked() { + state.cleanup_modal_open = true; + if state.scan.items.is_empty() && !state.scan.scanning { + state.scan.scanning = true; + action = Some(StorageAction::StartScan); + } + } + + if stitch_ui::action_button(ui, "打开目录", ButtonRole::Quiet, can_open).clicked() { + action = Some(StorageAction::OpenCurrentFolder); + } + }); + + // Machine-global footnote + ui.add( + egui::Label::new( + RichText::new("本机全局设置,切换账号不会重置。") + .font(Type::Caption.font_id()) + .color(t.text_faint), + ) + .wrap(), + ); + }); + + action +} + +/// Render active storage modals (migration modal and/or cleanup modal). +pub(crate) fn show_storage_modals( + ctx: &egui::Context, + state: &mut StorageUiState, + reduced: bool, +) -> Option { + let mut action = None; + if state.migrate_modal_open || state.status.migration.phase.is_non_closable() { + action = action.or_else(|| show_migrate_modal(ctx, state, reduced)); + } + if state.cleanup_modal_open && !state.migrate_modal_open { + action = action.or_else(|| show_cleanup_modal(ctx, state, reduced)); + } + action +} + +fn modal_width(ctx: &egui::Context) -> f32 { + let screen = ctx.content_rect(); + (screen.width() - 64.0) + .clamp(340.0, 520.0) + .min((screen.width() - 2.0 * space::XL).max(1.0)) +} + +/// Migration modal following `client_update_ui.rs` skeleton: +/// `stitch_ui::modal`, width `(screen - 64).clamp(340, 520)`, fixed 34pt footer. +pub(crate) fn show_migrate_modal( + ctx: &egui::Context, + state: &mut StorageUiState, + reduced: bool, +) -> Option { + let non_closable = state.status.migration.phase.is_non_closable(); + let open = state.migrate_modal_open || non_closable; + let id = Id::unique("xiaoyi-storage-migrate-modal"); + let visual = stitch_ui::overlay_transition(ctx, id.with("transition"), open, reduced); + if !visual.render { + return None; + } + + let width = modal_width(ctx); + let margin = stitch_ui::surface_frame(ctx, SurfaceRole::Dialog).total_margin().sum(); + let mut action = None; + let mut close_requested = false; + + let modal = stitch_ui::modal(ctx, id, visual, reduced, |ui| { + ui.set_width((width - margin.x).max(1.0)); + ui.spacing_mut().item_spacing = vec2(space::SM, space::SM); + + let effective_post_restart = state.status.migration.phase == MigrationPhase::Completed + && state.status.pending_old_root_cleanup.is_some(); + + if effective_post_restart { + render_post_restart_release_contents(ui, state, &mut action, &mut close_requested); + } else { + match state.status.migration.phase { + MigrationPhase::Idle | MigrationPhase::Validating => { + render_migrate_select_contents(ui, state, reduced, &mut action, &mut close_requested); + } + MigrationPhase::Copying => { + render_migrate_copying_contents(ui, state, reduced, &mut action, &mut close_requested); + } + MigrationPhase::ReadyToSwitch => { + render_migrate_ready_contents(ui, state, &mut action, &mut close_requested); + } + MigrationPhase::Switching | MigrationPhase::Restarting => { + render_migrate_switching_contents(ui, state, reduced); + } + MigrationPhase::Failed | MigrationPhase::RolledBack => { + render_migrate_failed_contents(ui, state, &mut action, &mut close_requested); + } + MigrationPhase::Completed => { + render_migrate_completed_simple(ui, state, &mut close_requested); + } + } + } + }); + + if !non_closable && visual.interactive { + let escape = modal.is_some_and(|m| { + m.is_top_modal + && !m.any_popup_open + && ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) + }); + if close_requested || escape { + state.migrate_modal_open = false; + state.confirm_release_armed = false; + ctx.request_repaint(); + } + } + action +} + +fn render_migrate_select_contents( + ui: &mut Ui, + state: &mut StorageUiState, + reduced: bool, + action: &mut Option, + close_requested: &mut bool, +) { + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + + if stitch_ui::dialog_heading(ui, "更改数据存储目录") { + *close_requested = true; + } + + // Current root context + let current_text = if state.status.stats_ready { + format!( + "当前目录:{}(需迁移约 {})", + state.status.current_root, + format_bytes(state.status.total_bytes) + ) + } else { + format!("当前目录:{}", state.status.current_root) + }; + ui.add(egui::Label::new(RichText::new(current_text).font(Type::Meta.font_id()).color(t.text_dim)).wrap()); + + // Target directory field + browse button (error detail renders in the full-width callout below, + // keeping this horizontal input row single-line and clean). + ui.label(RichText::new("目标空目录").font(Type::Title.semibold()).color(t.text)); + ui.horizontal(|ui| { + let browse_w = 104.0; + let field_w = (ui.available_width() - browse_w - space::SM).max(120.0); + let validating = state.status.migration.phase == MigrationPhase::Validating; + ui.allocate_ui_with_layout(vec2(field_w, control::DEFAULT), Layout::top_down(Align::Min), |ui| { + stitch_ui::halo_field(ui, Id::unique("storage-target-input"), None, reduced, |ui| { + let edit = stitch_ui::text_input(&mut state.target_input, "例如 D:\\XiaoYiData", false) + .desired_width((field_w - 22.0).max(1.0)); + let resp = ui.add_enabled(!validating, edit); + if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) && !state.target_input.trim().is_empty() { + *action = Some(StorageAction::ValidateTarget(state.target_input.trim().to_owned())); + } + resp + }); + }); + if stitch_ui::action_button(ui, "选择目录…", ButtonRole::Secondary, !validating).clicked() { + *action = Some(StorageAction::PickMigrationTarget); + } + }); + + // Target disk capacity readout + if let Some(free) = state.status.migration.target_free_bytes { + let required = state.status.migration.required_bytes.max(state.status.total_bytes); + let enough = free >= required; + let line = format!( + "目标盘剩余空间 {} · 预计至少需要 {}", + format_bytes(free), + format_bytes(required) + ); + ui.label( + RichText::new(line) + .font(Type::Meta.font_id()) + .color(if enough { semantic.jade } else { t.danger }), + ); + } + + // Hard validation error + if let Some(error) = &state.status.migration.validation_error { + let err_frame = Frame::NONE + .fill(t.field.lerp_to_gamma(t.danger, 0.12)) + .stroke(Stroke::new(1.0, t.danger.gamma_multiply(0.55))) + .corner_radius(radius::CONTROL as u8) + .inner_margin(Margin::same(space::SM as i8 + 2)); + let err_w = (ui.available_width() - err_frame.total_margin().sum().x).max(1.0); + err_frame.show(ui, |ui| { + ui.set_width(err_w); + ui.horizontal_top(|ui| { + ui.add(icons::image("triangle-alert", icon::MD, t.danger)); + ui.add(egui::Label::new(RichText::new(error).font(Type::Meta.font_id()).color(t.text)).wrap()); + }); + }); + } + + // Soft warnings (e.g. path length > 40) + for warning in &state.status.migration.validation_warnings { + stitch_ui::status_label(ui, warning, StatusTone::Warning); + } + + // Precautions (clean typographic list, zero nested cards) + stitch_ui::divider(ui); + ui.label(RichText::new("迁移注意事项").font(Type::Title.semibold()).color(t.text)); + for note in [ + "目标必须为本机固定硬盘的空目录,不支持软链、目录联接(Junction)或 OneDrive 等网盘同步目录。", + "阶段 1 在后台逐文件安全拷贝并校验哈希,期间你可以继续正常使用小壹。", + "阶段 2 切换时将暂停写入、改写工程路径并重启应用;原目录默认保留 7 天,确认无误后再释放。", + ] { + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = space::XS + space::XXS; + ui.label(RichText::new("·").font(Type::Meta.font_id()).color(t.text_faint)); + ui.add(egui::Label::new(RichText::new(note).font(Type::Meta.font_id()).color(t.text_dim)).wrap()); + }); + } + if let Some(recovery_note) = &state.status.recovery_note { + ui.add(egui::Label::new(RichText::new(recovery_note).font(Type::Caption.font_id()).color(t.text_faint)).wrap()); + } + + ui.add_space(space::XS); + let target_trimmed = state.target_input.trim().to_owned(); + let can_start = !target_trimmed.is_empty() + && state.status.migration.validation_error.is_none() + && state.status.migration.phase != MigrationPhase::Validating; + + ui.allocate_ui_with_layout( + vec2(ui.available_width(), control::DEFAULT), + Layout::right_to_left(Align::Center), + |ui| { + if stitch_ui::action_button(ui, "开始预拷贝", ButtonRole::Primary, can_start).clicked() { + *action = Some(StorageAction::StartCopy(target_trimmed)); + } + if stitch_ui::action_button(ui, "取消", ButtonRole::Secondary, true).clicked() { + *close_requested = true; + } + }, + ); +} + +fn render_migrate_copying_contents( + ui: &mut Ui, + state: &StorageUiState, + reduced: bool, + action: &mut Option, + close_requested: &mut bool, +) { + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + let mig = &state.status.migration; + + if stitch_ui::dialog_heading(ui, "正在预拷贝数据(阶段 1 / 2)") { + *close_requested = true; + } + + ui.add( + egui::Label::new( + RichText::new("后台正在逐文件复制并校验完整性,你现在可以关闭此窗口继续使用,拷贝完成后再一键切换。") + .font(Type::Meta.font_id()) + .color(t.text_dim), + ) + .wrap(), + ); + + // Deterministic progress bar + let fraction = mig.copy_fraction(); + let pct_label = fraction.map_or_else(|| "准备中…".into(), |f| format!("{}%", (f * 100.0).floor() as u32)); + ui.horizontal(|ui| { + ui.label( + RichText::new(format!( + "已拷贝 {} / {}({pct_label})", + format_bytes(mig.copied_bytes), + format_bytes(mig.total_bytes) + )) + .font(Type::Title.semibold()) + .color(t.text), + ); + if let Some(speed) = mig.speed_bytes_per_sec { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.label(RichText::new(format_speed(speed)).font(Type::Meta.font_id()).color(semantic.jade)); + }); + } + }); + stitch_ui::progress_bar_tinted( + ui, + Id::unique("storage-migrate-stage1-progress"), + "数据目录预拷贝进度", + fraction, + reduced, + semantic.jade, + ); + + if !mig.target_root.is_empty() { + ui.add( + egui::Label::new( + RichText::new(format!("目标目录:{}", mig.target_root)) + .font(Type::Meta.font_id()) + .color(t.text_dim), + ) + .wrap(), + ); + } + + ui.add_space(space::SM); + ui.allocate_ui_with_layout( + vec2(ui.available_width(), control::DEFAULT), + Layout::right_to_left(Align::Center), + |ui| { + if stitch_ui::action_button(ui, "后台继续", ButtonRole::Primary, true).clicked() { + *close_requested = true; + } + if stitch_ui::action_button(ui, "取消迁移", ButtonRole::QuietDanger, true).clicked() { + *action = Some(StorageAction::CancelCopy); + } + }, + ); +} + +fn render_migrate_ready_contents( + ui: &mut Ui, + state: &StorageUiState, + action: &mut Option, + close_requested: &mut bool, +) { + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + let mig = &state.status.migration; + + if stitch_ui::dialog_heading(ui, "预拷贝已完成,准备切换") { + *close_requested = true; + } + + ui.horizontal_top(|ui| { + ui.add(icons::image("check", icon::LG, semantic.success)); + ui.add( + egui::Label::new( + RichText::new(format!( + "全部数据({})已安全复制到目标目录并核对一致。点击“切换并重启”后将短暂停写、改写工程路径并自动重启。", + format_bytes(mig.total_bytes) + )) + .font(Type::Body.font_id()) + .color(t.text), + ) + .wrap(), + ); + }); + + ui.add( + egui::Label::new( + RichText::new(format!("新目录:{}", mig.target_root)) + .font(Type::Meta.font_id()) + .color(t.text_dim), + ) + .wrap(), + ); + + let blocked = !mig.blocking_projects.is_empty(); + if blocked { + Frame::NONE + .fill(t.field.lerp_to_gamma(t.warning, 0.12)) + .stroke(Stroke::new(1.0, t.warning.gamma_multiply(0.6))) + .corner_radius(radius::CONTROL as u8) + .inner_margin(Margin::same(space::SM as i8 + 2)) + .show(ui, |ui| { + ui.set_min_width((ui.available_width() - space::LG).max(1.0)); + ui.label( + RichText::new("以下项目正在后台制作或存在未保存修改,请先暂停/保存后再切换:") + .font(Type::Meta.semibold()) + .color(t.warning), + ); + for name in &mig.blocking_projects { + ui.label(RichText::new(format!("· {name}")).font(Type::Meta.font_id()).color(t.text)); + } + }); + } + + ui.add_space(space::SM); + ui.allocate_ui_with_layout( + vec2(ui.available_width(), control::DEFAULT), + Layout::right_to_left(Align::Center), + |ui| { + if stitch_ui::action_button(ui, "切换并重启", ButtonRole::Primary, !blocked).clicked() { + *action = Some(StorageAction::ConfirmSwitchAndRestart); + } + if stitch_ui::action_button(ui, "稍后切换", ButtonRole::Secondary, true).clicked() { + *close_requested = true; + } + }, + ); +} + +fn render_migrate_switching_contents(ui: &mut Ui, state: &StorageUiState, reduced: bool) { + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + let restarting = state.status.migration.phase == MigrationPhase::Restarting; + let title = if restarting { + "切换完成,正在重启小壹…" + } else { + "正在切换数据目录(阶段 2 / 2)" + }; + + // Non-closable heading (no close X button!) + ui.label(RichText::new(title).font(Type::TitleLg.semibold()).color(t.text)); + ui.add( + egui::Label::new( + RichText::new("正在执行原子切换,请勿关闭窗口或强行结束进程。旧目录保持原样不会删除。") + .font(Type::Meta.font_id()) + .color(t.warning), + ) + .wrap(), + ); + + stitch_ui::divider(ui); + + // Step checklist — strictly NO fake percentage! + let fallback_steps = default_switch_steps(if restarting { 3 } else { 1 }); + let steps = if state.status.migration.switch_steps.is_empty() { + fallback_steps.as_slice() + } else { + state.status.migration.switch_steps.as_slice() + }; + + for step in steps { + ui.horizontal(|ui| { + ui.set_min_height(control::STANDARD); + ui.spacing_mut().item_spacing.x = space::SM; + let (slot, _) = ui.allocate_exact_size(vec2(22.0, icon::LG), Sense::hover()); + match step.state { + SwitchStepState::Done => { + icons::paint(ui, slot, "check", icon::MD, semantic.success); + ui.add(egui::Label::new(RichText::new(&step.label).font(Type::Title.font_id()).color(t.text_dim)).wrap()); + } + SwitchStepState::Active => { + let mut loader_ui = ui.new_child( + egui::UiBuilder::new() + .max_rect(slot) + .layout(Layout::centered_and_justified(egui::Direction::LeftToRight)), + ); + stitch_ui::ai_loader(&mut loader_ui, Id::unique(("switch-step-loader", &step.id)), true, reduced); + ui.add(egui::Label::new(RichText::new(&step.label).font(Type::Title.semibold()).color(t.text)).wrap()); + } + SwitchStepState::Pending => { + icons::paint(ui, slot, "circle", icon::SM, t.text_faint); + ui.add(egui::Label::new(RichText::new(&step.label).font(Type::Title.font_id()).color(t.text_faint)).wrap()); + } + SwitchStepState::Failed => { + icons::paint(ui, slot, "triangle-alert", icon::MD, t.danger); + ui.add(egui::Label::new(RichText::new(&step.label).font(Type::Title.semibold()).color(t.danger)).wrap()); + } + } + }); + } + + ui.add_space(space::SM); + ui.allocate_ui_with_layout( + vec2(ui.available_width(), control::DEFAULT), + Layout::right_to_left(Align::Center), + |ui| { + let _ = stitch_ui::action_button( + ui, + if restarting { "正在重启…" } else { "切换中,请稍候…" }, + ButtonRole::Secondary, + false, + ); + }, + ); +} + +fn render_migrate_failed_contents( + ui: &mut Ui, + state: &StorageUiState, + action: &mut Option, + close_requested: &mut bool, +) { + let t = Tokens::get(ui.ctx()).agent(); + let rolled_back = state.status.migration.phase == MigrationPhase::RolledBack; + let title = if rolled_back { "已自动回滚到原目录" } else { "目录迁移未完成" }; + + if stitch_ui::dialog_heading(ui, title) { + *close_requested = true; + } + + let reason = state + .status + .migration + .error + .as_deref() + .unwrap_or("迁移过程中发生读写异常,请检查磁盘空间与权限后重试。"); + Frame::NONE + .fill(t.field.lerp_to_gamma(t.danger, 0.12)) + .stroke(Stroke::new(1.0, t.danger.gamma_multiply(0.55))) + .corner_radius(radius::CONTROL as u8) + .inner_margin(Margin::same(space::SM as i8 + 2)) + .show(ui, |ui| { + ui.set_min_width((ui.available_width() - space::LG).max(1.0)); + ui.horizontal_top(|ui| { + ui.add(icons::image("triangle-alert", icon::MD, t.danger)); + ui.add(egui::Label::new(RichText::new(reason).font(Type::Title.font_id()).color(t.text)).wrap()); + }); + }); + + let rollback = state + .status + .migration + .rollback_note + .as_deref() + .unwrap_or("原有数据目录与项目文件均未删除或改动,当前仍安全运行在原目录。"); + ui.add(egui::Label::new(RichText::new(rollback).font(Type::Meta.font_id()).color(t.text_dim)).wrap()); + + ui.add_space(space::SM); + ui.allocate_ui_with_layout( + vec2(ui.available_width(), control::DEFAULT), + Layout::right_to_left(Align::Center), + |ui| { + if stitch_ui::action_button(ui, "重试迁移", ButtonRole::Primary, true).clicked() { + *action = Some(StorageAction::RetryMigration); + } + if stitch_ui::action_button(ui, "关闭", ButtonRole::Secondary, true).clicked() { + *close_requested = true; + } + }, + ); +} + +fn render_post_restart_release_contents( + ui: &mut Ui, + state: &mut StorageUiState, + action: &mut Option, + close_requested: &mut bool, +) { + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + let Some(old) = state.status.pending_old_root_cleanup.clone() else { return }; + + if stitch_ui::dialog_heading(ui, "新数据目录已生效") { + *close_requested = true; + } + + ui.horizontal_top(|ui| { + ui.add(icons::image("check", icon::LG, semantic.success)); + ui.add( + egui::Label::new( + RichText::new(format!( + "重启自检通过:{} 个项目与交付清单均已在新目录正常加载。", + old.verified_project_count + )) + .font(Type::Body.font_id()) + .color(t.text), + ) + .wrap(), + ); + }); + + ui.add( + egui::Label::new( + RichText::new(format!("当前生效目录:{}", state.status.current_root)) + .font(Type::Meta.font_id()) + .color(semantic.jade), + ) + .wrap(), + ); + ui.add( + egui::Label::new( + RichText::new(format!("旧目录备份:{}", old.old_root)) + .font(Type::Meta.font_id()) + .color(t.text_dim), + ) + .wrap(), + ); + + stitch_ui::divider(ui); + ui.add( + egui::Label::new( + RichText::new(format!( + "旧目录当前仍占用 {}。你可以立即释放空间,或先保留 {} 天作为兜底备份。", + format_bytes(old.reclaimable_bytes), + old.grace_days + )) + .font(Type::Meta.font_id()) + .color(t.text_dim), + ) + .wrap(), + ); + + if state.confirm_release_armed { + stitch_ui::status_label( + ui, + "再次点击下方危险按钮将永久删除旧目录副本(保留指向新目录的配置指针)。", + StatusTone::Warning, + ); + } + + ui.add_space(space::SM); + let release_label = if state.confirm_release_armed { + format!("确认永久释放(省回 {})", format_bytes(old.reclaimable_bytes)) + } else { + format!("释放旧目录(省回 {})", format_bytes(old.reclaimable_bytes)) + }; + ui.allocate_ui_with_layout( + vec2(ui.available_width(), control::DEFAULT), + Layout::right_to_left(Align::Center), + |ui| { + if stitch_ui::action_button(ui, &format!("稍后保留 {} 天兜底", old.grace_days), ButtonRole::Primary, true).clicked() { + state.confirm_release_armed = false; + *action = Some(StorageAction::KeepOldRootForLater); + *close_requested = true; + } + if stitch_ui::action_button(ui, &release_label, ButtonRole::QuietDanger, true).clicked() { + if state.confirm_release_armed { + state.confirm_release_armed = false; + *action = Some(StorageAction::ReleaseOldRoot(old.old_root)); + *close_requested = true; + } else { + state.confirm_release_armed = true; + } + } + }, + ); +} + +fn render_migrate_completed_simple( + ui: &mut Ui, + state: &StorageUiState, + close_requested: &mut bool, +) { + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + if stitch_ui::dialog_heading(ui, "数据目录切换完成") { + *close_requested = true; + } + ui.horizontal_top(|ui| { + ui.add(icons::image("check", icon::LG, semantic.success)); + ui.add( + egui::Label::new( + RichText::new(format!("当前已运行在新目录:{}", state.status.current_root)) + .font(Type::Body.font_id()) + .color(t.text), + ) + .wrap(), + ); + }); + ui.add_space(space::SM); + ui.allocate_ui_with_layout( + vec2(ui.available_width(), control::DEFAULT), + Layout::right_to_left(Align::Center), + |ui| { + if stitch_ui::action_button(ui, "完成", ButtonRole::Primary, true).clicked() { + *close_requested = true; + } + }, + ); +} + +/// Cleanup space modal: read-only scan first, then clearly separates +/// "无损直接回收" (default checked) vs "历史归档清理" (manual opt-in with policy explanation). +pub(crate) fn show_cleanup_modal( + ctx: &egui::Context, + state: &mut StorageUiState, + reduced: bool, +) -> Option { + let open = state.cleanup_modal_open; + let id = Id::unique("xiaoyi-storage-cleanup-modal"); + let visual = stitch_ui::overlay_transition(ctx, id.with("transition"), open, reduced); + if !visual.render { + return None; + } + + let width = modal_width(ctx); + let margin = stitch_ui::surface_frame(ctx, SurfaceRole::Dialog).total_margin().sum(); + let screen = ctx.content_rect(); + let mut action = None; + let mut close_requested = false; + let running = state.scan.cleanup_running; + + let modal = stitch_ui::modal(ctx, id, visual, reduced, |ui| { + ui.set_width((width - margin.x).max(1.0)); + ui.spacing_mut().item_spacing = vec2(space::SM, space::SM); + + let heading_closed = ui + .add_enabled_ui(!running, |ui| stitch_ui::dialog_heading(ui, "清理存储空间")) + .inner; + if heading_closed { + close_requested = true; + } + + if state.scan.scanning { + stitch_ui::progress( + ui, + Id::unique("storage-cleanup-scanning"), + "正在只读扫描数据目录(不会修改任何作品文件)…", + None, + reduced, + ); + ui.add_space(space::SM); + ui.allocate_ui_with_layout( + vec2(ui.available_width(), control::DEFAULT), + Layout::right_to_left(Align::Center), + |ui| { + if stitch_ui::action_button(ui, "关闭", ButtonRole::Secondary, true).clicked() { + close_requested = true; + } + }, + ); + return; + } + + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + + if let Some(error) = &state.scan.error { + stitch_ui::status_label(ui, error, StatusTone::Error); + } + if let Some(res) = &state.scan.cleanup_result { + if let Some(err) = &res.error { + stitch_ui::status_label(ui, err, StatusTone::Error); + } else { + ui.horizontal_top(|ui| { + ui.add(icons::image("check", icon::MD, semantic.success)); + ui.add( + egui::Label::new( + RichText::new(if res.message.is_empty() { + format!("已完成清理,共释放 {}", format_bytes(res.freed_bytes)) + } else { + res.message.clone() + }) + .font(Type::Title.font_id()) + .color(semantic.success), + ) + .wrap(), + ); + }); + } + } + + let list_max_h = (screen.height() - 200.0).clamp(200.0, 560.0); + egui::ScrollArea::vertical() + .id_salt("xiaoyi-storage-cleanup-list") + .max_height(list_max_h) + .auto_shrink([false, true]) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = space::XS + space::XXS; + + // Section 1: Lossless direct reclaim (checked by default) + let lossless_total = state.scan.lossless_total_bytes(); + ui.horizontal(|ui| { + ui.label(RichText::new("无损直接回收").font(Type::Title.semibold()).color(t.text)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.label( + RichText::new(format!("共可省 {}", format_bytes(lossless_total))) + .font(Type::Meta.semibold()) + .color(semantic.jade), + ); + }); + }); + ui.add( + egui::Label::new( + RichText::new("默认勾选。通过重建硬链接去重与清理临时残留回收空间,不改动任何项目内容与历史成果。") + .font(Type::Meta.font_id()) + .color(t.text_dim), + ) + .wrap(), + ); + for item in state.scan.items.iter_mut().filter(|i| i.lossless) { + cleanup_category_row(ui, item, !running, reduced); + } + + // Section 2: Archive policy cleanup (manual opt-in) + let has_archive = state.scan.items.iter().any(|i| !i.lossless); + if has_archive { + stitch_ui::divider(ui); + let archive_total = state.scan.archive_total_bytes(); + ui.horizontal(|ui| { + ui.label(RichText::new("历史归档清理").font(Type::Title.semibold()).color(t.text)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.label( + RichText::new(format!("可选再省 {}", format_bytes(archive_total))) + .font(Type::Meta.semibold()) + .color(t.warning), + ); + }); + }); + ui.add( + egui::Label::new( + RichText::new("需手动勾选。按保留策略清理更早的已被取代版本或重存旧格式编辑稿,勾选前请确认风险说明。") + .font(Type::Meta.font_id()) + .color(t.text_dim), + ) + .wrap(), + ); + for item in state.scan.items.iter_mut().filter(|i| !i.lossless) { + cleanup_category_row(ui, item, !running, reduced); + } + } + }); + + if running { + stitch_ui::progress( + ui, + Id::unique("storage-cleanup-running"), + "正在安全回收所选空间…", + None, + reduced, + ); + } + + stitch_ui::divider(ui); + let selected_bytes = state.scan.selected_bytes(); + let selected_ids = state.scan.selected_ids(); + let can_run = !running && !selected_ids.is_empty() && selected_bytes > 0; + + ui.allocate_ui_with_layout( + vec2(ui.available_width(), control::DEFAULT), + Layout::left_to_right(Align::Center), + |ui| { + ui.label( + RichText::new(format!("预计释放 {}", format_bytes(selected_bytes))) + .font(Type::Title.semibold()) + .color(if selected_bytes > 0 { semantic.jade } else { t.text_dim }), + ); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if stitch_ui::action_button( + ui, + if running { "清理中…" } else { "开始清理" }, + ButtonRole::Primary, + can_run, + ) + .clicked() + { + state.scan.cleanup_running = true; + action = Some(StorageAction::StartCleanup(selected_ids)); + } + if stitch_ui::action_button(ui, "关闭", ButtonRole::Secondary, !running).clicked() { + close_requested = true; + } + }); + }, + ); + }); + + if !running && visual.interactive { + let escape = modal.is_some_and(|m| { + m.is_top_modal + && !m.any_popup_open + && ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) + }); + if close_requested || escape { + state.cleanup_modal_open = false; + ctx.request_repaint(); + } + } + action +} + +fn cleanup_category_row(ui: &mut Ui, item: &mut CleanupCategoryItem, enabled: bool, reduced: bool) { + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + let row_id = ui.scope_id().with(("cleanup-cat", &item.id)); + let _ = reduced; + + let frame = Frame::NONE + .fill(if item.selected { t.field.lerp_to_gamma(t.pressed, 0.35) } else { t.field }) + .stroke(Stroke::new( + 1.0, + if item.selected { + if item.lossless { semantic.jade.gamma_multiply(0.55) } else { t.warning.gamma_multiply(0.6) } + } else { + t.field_border + }, + )) + .corner_radius(radius::CONTROL as u8) + .inner_margin(Margin::symmetric(space::SM as i8 + 2, space::XS as i8 + 2)); + let row_inner_w = (ui.available_width() - frame.total_margin().sum().x).max(1.0); + + frame.show(ui, |ui| { + ui.set_width(row_inner_w); + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = space::SM; + + // Accessible check indicator using Stitch-styled click target. + let box_resp = paint_check_box(ui, row_id, item.selected, enabled, item.lossless, &item.label); + if box_resp.clicked() && enabled { + item.selected = !item.selected; + } + + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = space::XXS; + ui.horizontal(|ui| { + ui.label(RichText::new(&item.label).font(Type::Title.font_id()).color(t.text)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.label( + RichText::new(format_bytes(item.bytes)) + .font(Type::Title.semibold()) + .color(if item.lossless { semantic.jade } else { t.warning }), + ); + }); + }); + if !item.description.is_empty() { + ui.add( + egui::Label::new( + RichText::new(&item.description) + .font(Type::Meta.font_id()) + .color(t.text_dim), + ) + .wrap(), + ); + } + if let Some(risk) = &item.risk_note { + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = space::XS; + ui.add(icons::image("info", icon::SM, t.warning)); + ui.add( + egui::Label::new( + RichText::new(risk).font(Type::Caption.font_id()).color(t.warning), + ) + .wrap(), + ); + }); + } + }); + }); + }); +} + +fn paint_check_box( + ui: &mut Ui, + _id: Id, + checked: bool, + enabled: bool, + lossless: bool, + label: &str, +) -> Response { + let t = Tokens::get(ui.ctx()).agent(); + let semantic = t.agent_semantic(); + let (rect, response) = ui.allocate_exact_size(vec2(18.0, 18.0), if enabled { Sense::click() } else { Sense::hover() }); + let response = if enabled { + response.on_hover_cursor(egui::CursorIcon::PointingHand) + } else { + response + }; + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, enabled, checked, label)); + if ui.is_rect_visible(rect) { + let painter = ui.painter_at(rect.intersect(ui.clip_rect())); + let accent = if lossless { semantic.jade } else { t.warning }; + let fill = if checked { + accent.gamma_multiply(if enabled { 0.24 } else { 0.12 }) + } else if response.hovered() && enabled { + t.hover + } else { + t.card + }; + let stroke = if checked { accent } else { t.field_border }; + painter.rect(rect, radius::ROW - 1.0, fill, Stroke::new(1.2, stroke), StrokeKind::Inside); + if checked { + icons::paint(ui, rect, "check", icon::SM, accent); + } + } + stitch_ui::focus_ring(ui, &response, radius::ROW - 1.0, FocusRing::Control); + response +} + +/// Overlay frame helper exposed for external modal rendering checks. +#[cfg(test)] +pub(crate) fn tests_fixture_custom() -> StorageUiState { + tests::sample_custom_storage_state() +} + +#[cfg(test)] +pub(crate) fn tests_fixture_env_override() -> StorageUiState { + tests::sample_env_override_state() +} + +#[cfg(test)] +pub(crate) fn render_migrate_preview(ui: &mut Ui, state: &mut StorageUiState, width: f32) { + let ctx = ui.ctx().clone(); + let frame = stitch_ui::overlay_frame(&ctx, SurfaceRole::Dialog, 1.0); + let visual = OverlayVisual { render: true, interactive: true, opacity: 1.0 }; + stitch_ui::material_frame(ui, frame, |ui| { + stitch_ui::overlay_contents(ui, visual, |ui| { + ui.set_width(width); + ui.spacing_mut().item_spacing = vec2(space::SM, space::SM); + let mut action = None; + let mut close = false; + if state.status.migration.phase == MigrationPhase::Completed + && state.status.pending_old_root_cleanup.is_some() + { + render_post_restart_release_contents(ui, state, &mut action, &mut close); + } else { + match state.status.migration.phase { + MigrationPhase::Idle | MigrationPhase::Validating => { + render_migrate_select_contents(ui, state, true, &mut action, &mut close); + } + MigrationPhase::Copying => { + render_migrate_copying_contents(ui, state, true, &mut action, &mut close); + } + MigrationPhase::ReadyToSwitch => { + render_migrate_ready_contents(ui, state, &mut action, &mut close); + } + MigrationPhase::Switching | MigrationPhase::Restarting => { + render_migrate_switching_contents(ui, state, true); + } + MigrationPhase::Failed | MigrationPhase::RolledBack => { + render_migrate_failed_contents(ui, state, &mut action, &mut close); + } + MigrationPhase::Completed => { + render_migrate_completed_simple(ui, state, &mut close); + } + } + } + }); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::theme::ThemeKind; + use egui_kittest::Harness; + + pub(crate) fn sample_custom_storage_state() -> StorageUiState { + StorageUiState { + status: StorageStatusView { + current_root: r"D:\XiaoYiWorkspace\Data".into(), + mode: StorageRootMode::CustomPointer, + readonly_reason: None, + stats_ready: true, + total_bytes: 92_234_421_043, + project_count: 20, + free_bytes: Some(442_918_502_400), + recovery_note: Some("异常恢复目录仍保留在本机默认缓存位置,不随迁移移动。".into()), + status_text: None, + status_is_warning: false, + status_is_error: false, + migration: MigrationStateView { + phase: MigrationPhase::Idle, + target_root: r"E:\XiaoYiData".into(), + target_free_bytes: Some(512_000_000_000), + required_bytes: 95_000_000_000, + ..Default::default() + }, + pending_old_root_cleanup: None, + }, + scan: sample_scan_view(), + migrate_modal_open: false, + cleanup_modal_open: false, + target_input: r"E:\XiaoYiData".into(), + confirm_release_armed: false, + } + } + + pub(crate) fn sample_env_override_state() -> StorageUiState { + let mut s = sample_custom_storage_state(); + s.status.current_root = r"F:\XiaoYiData".into(); + s.status.mode = StorageRootMode::EnvOverride; + s.status.readonly_reason = Some( + "当前由启动环境变量指定目录,不可在此更改。如需改为小壹托管并迁移目录,请移除该启动环境变量后重启。".into(), + ); + s + } + + pub(crate) fn sample_scan_view() -> StorageScanView { + StorageScanView { + scanning: false, + error: None, + items: vec![ + CleanupCategoryItem { + id: "relink_knowledge".into(), + label: "重连知识包与模板硬链接".into(), + description: "将多个项目间字节完全相同的知识与模板副本合并为硬链接,作品内容不变。".into(), + bytes: 17_072_495_001, + lossless: true, + risk_note: None, + selected: true, + }, + CleanupCategoryItem { + id: "orphan_draft_objects".into(), + label: "回收未被引用的画布孤儿对象".into(), + description: "清理超过 7 天且不再被任何项目检查点引用的历史图像切片。".into(), + bytes: 4_778_151_116, + lossless: true, + risk_note: None, + selected: true, + }, + CleanupCategoryItem { + id: "dedup_same_generations".into(), + label: "去重字节相同的历史成品代".into(), + description: "将与当前代逐字节相同的旧导出文件替换为硬链接。".into(), + bytes: 6_839_735_418, + lossless: true, + risk_note: None, + selected: true, + }, + CleanupCategoryItem { + id: "stale_temp_and_locks".into(), + label: "清理残留下载片段与临时锁文件".into(), + description: "删除已中断超过 7 天的 .part 片段、临时保存文件与已完成任务锁。".into(), + bytes: 1_181_116_006, + lossless: true, + risk_note: None, + selected: true, + }, + CleanupCategoryItem { + id: "prune_old_generations".into(), + label: "清理已被取代的更早成品导出代".into(), + description: "每个成品仅保留当前最新代与上一代,删除更早的历史导出目录。".into(), + bytes: 7_462_505_676, + lossless: false, + risk_note: Some("清理后将无法直接回退到两代以前的旧导出快照,但当前代与上一代完整保留。".into()), + selected: false, + }, + CleanupCategoryItem { + id: "repack_legacy_drafts".into(), + label: "整理旧格式自包含编辑稿".into(), + description: "将早期体积较大的自包含编辑稿按新对象库格式重新保存并去重。".into(), + bytes: 7_945_689_497, + lossless: false, + risk_note: Some("需要逐个重新写入草稿索引,整理期间请勿关闭应用。".into()), + selected: false, + }, + ], + cleanup_running: false, + cleanup_result: None, + } + } + + #[test] + fn machine_global_state_persists_independent_of_accounts() { + let ctx = egui::Context::default(); + let initial = sample_custom_storage_state(); + set_status(&ctx, initial.status.clone()); + let read_back = with_machine_state(&ctx, |s| s.status.current_root.clone()); + assert_eq!(read_back, r"D:\XiaoYiWorkspace\Data"); + } + + #[test] + fn cleanup_defaults_select_only_lossless_categories() { + let scan = sample_scan_view(); + assert_eq!(scan.selected_bytes(), scan.lossless_total_bytes()); + assert!(scan.archive_total_bytes() > 0); + assert_eq!(scan.selected_ids().len(), 4); + } + + #[test] + fn stage2_switching_modal_ignores_escape_and_remains_open() { + let mut state = sample_custom_storage_state(); + state.migrate_modal_open = true; + state.status.migration.phase = MigrationPhase::Switching; + state.status.migration.switch_steps = default_switch_steps(1); + + let mut h = Harness::builder() + .with_size(vec2(800.0, 600.0)) + .with_context_setup(|ctx| { + crate::PhotocraftApp::setup_context(ctx, ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }) + .build_ui_state( + |ui, st: &mut StorageUiState| { + stitch_ui::scope_with_motion(ui, true, |ui| { + let _ = show_storage_modals(ui.ctx(), st, true); + }); + }, + state, + ); + h.run_steps(2); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().migrate_modal_open); + assert!(h.state().status.migration.phase.is_non_closable()); + } + + #[test] + fn storage_card_disables_change_dir_in_env_override_mode() { + let state = sample_env_override_state(); + let mut h = Harness::builder() + .with_size(vec2(380.0, 420.0)) + .with_context_setup(|ctx| { + crate::PhotocraftApp::setup_context(ctx, ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }) + .build_ui_state( + |ui, st: &mut StorageUiState| { + stitch_ui::scope_with_motion(ui, true, |ui| { + let _ = storage_settings_card(ui, st, true, false); + }); + }, + state, + ); + h.run_steps(2); + use egui_kittest::kittest::NodeT; + let btn = egui_kittest::kittest::Queryable::get_by_label(&h, "更改目录…"); + assert!(btn.accesskit_node().is_disabled()); + btn.click(); + h.run_steps(2); + assert!(!h.state().migrate_modal_open); + } + + #[test] + fn module_adheres_to_white_label_and_token_guards() { + let source = include_str!("storage_settings_ui.rs").replace("\r\n", "\n"); + let prod = source.split("#[cfg(test)]\nmod tests").next().unwrap_or(""); + for bad in ["egui::Button::", "egui::Separator::", "egui::Spinner::", "egui::Window::", ".button(", ".checkbox(", ".radio(", ".separator(", "Color32::from_"] { + assert!(!prod.contains(bad), "storage_settings_ui.rs must not contain {bad}"); + } + for (idx, line) in prod.lines().enumerate() { + let chinese = line.chars().any(|c| ('\u{4e00}'..='\u{9fff}').contains(&c)); + if chinese { + let words: Vec<&str> = line.split(|c: char| !c.is_alphanumeric()).collect(); + assert!( + !line.contains("PhotoCraft") && !line.contains("Pi Agent") && !words.contains(&"Pi"), + "line {} violates white-label guard: {line}", + idx + 1 + ); + } + } + } +}