fix(xiaoyi): 修复首次设置输入与交付确认

This commit is contained in:
WuYongJie 2026-12-05 10:22:47 +08:00
parent 210ebede70
commit c6189f5b84
7 changed files with 332 additions and 66 deletions

View File

@ -713,6 +713,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
})),
inbox: None,
open_url: Some(Box::new(open_external_url)),
open_folder: Some(Box::new(open_local_folder)),
beep: Some(platform_beep),
// This distribution is a complete, customized client plus its Pi runtime.
// Upstream PhotoCraft releases do not contain that runtime and must not
@ -866,6 +867,9 @@ pub(crate) fn open_external_url(url: &str) -> Result<(), String> {
/// Open a local directory in the OS file manager without spawning PowerShell.
pub(crate) fn open_local_folder(path: &Path) -> Result<(), String> {
if !path.is_absolute() || !path.is_dir() {
return Err("文件夹不存在或暂时无法访问".into());
}
#[cfg(target_os = "windows")]
{
use winsafe::prelude::Handle as _;

View File

@ -1490,7 +1490,7 @@ impl Workspace {
});
agent_motion::message_repaint(ui, response.response.rect, stream_enter);
}
self.production_outcome_ui(ui, production);
self.production_outcome_ui(ui, production, &app.services);
if turn_count == 0 && production {
let jobs = self.projected_worker_jobs();
if !jobs.is_empty() {
@ -1756,19 +1756,35 @@ impl Workspace {
self.panel_geometry["processingLightMode"] = json!("inactive");
}
fn production_outcome_ui(&self, ui: &mut Ui, production: bool) {
fn production_outcome_ui(&mut self, ui: &mut Ui, production: bool, services: &crate::Services) {
use timeline::RunOutcome;
if production {
return;
}
let receipt = self.messages.iter().rev().take_while(|row| row["role"] != "user")
.find(|row| row["productionSummary"].is_object());
let summary = receipt.map(|row| &row["productionSummary"]);
let delivery_error = receipt.and_then(|row| row["productionDelivery"]["error"].as_str());
let checkpoint = &self.product_checkpoint;
let restored_partial = receipt.is_none() && checkpoint["phase"] == "paused";
let delivery = receipt.map(|row| &row["productionDelivery"])
.or_else(|| restored_partial.then_some(&checkpoint["productionDelivery"]));
let delivery_error = delivery.and_then(|data| data["error"].as_str());
let completed = summary.and_then(|summary| summary["exported"].as_u64().zip(summary["total"].as_u64()));
let coverage = summary.and_then(|summary| super::product_production::slot_coverage_label(&summary["slotCoverage"]));
let completion = completed.map(|(done, total)| format!("已交付 {done}/{total} 份"));
let saved_delivery = delivery.filter(|data| data["state"] == "bundle_saved");
let receipt_path = saved_delivery.and_then(|data| data["path"].as_str());
let delivery_path = receipt_path
.or_else(|| (restored_partial && saved_delivery.is_some()).then(|| checkpoint["deliveryDir"].as_str()).flatten())
.filter(|path| {
let folder = std::path::Path::new(path);
folder.is_absolute() && folder.join("交付清单.json").is_file()
});
let complete = completed.filter(|&(done, total)| total > 0 && done == total
&& coverage.is_none() && saved_delivery.is_some_and(|data| data["allOutputsCompleted"] == true))
.zip(receipt_path.and(delivery_path));
let delivery_summary;
let producing = self.pi_request_scope["productProduction"] == true;
let outcome = if production {
None
} else if producing && self.agent_effects_paused {
let outcome = if producing && self.agent_effects_paused {
Some(RunOutcome::Stopped { request_kept: self.pending() || self.unknown })
} else if producing && self.result_needs_check() {
Some(RunOutcome::NeedsCheck)
@ -1776,11 +1792,23 @@ impl Workspace {
None
} else if let Some(error) = delivery_error {
Some(RunOutcome::Failed { category: super::stitch_state::ErrorCategory::classify(error) })
} else if let Some(((done, total), path)) = complete {
delivery_summary = format!("已交付 {done}/{total} 份");
Some(RunOutcome::Completed { summary: &delivery_summary, path })
} else if let Some(path) = delivery_path {
delivery_summary = if let Some(coverage) = &coverage {
format!("已保存阶段成果 · {coverage}")
} else if let Some((done, total)) = completed {
format!("已保存阶段成果 · {done}/{total} 份")
} else {
"已保存阶段成果".into()
};
Some(RunOutcome::PartialDelivery { summary: &delivery_summary, path })
} else if let Some(coverage) = coverage.as_deref() {
Some(RunOutcome::Waiting { reason: coverage })
} else if let Some((done, total)) = completed {
Some(if done == total {
RunOutcome::Completed { summary: completion.as_deref().unwrap_or_default() }
} else if completed.is_some() {
Some(if completed.is_some_and(|(done, total)| total > 0 && done == total) {
RunOutcome::Waiting { reason: "成品交付尚未确认" }
} else if self.production_stop["state"] != "ended" && self.has_production_stages() {
RunOutcome::Waiting { reason: "还有输出待完成,可继续制作整套" }
} else {
@ -1789,7 +1817,18 @@ impl Workspace {
} else {
None
};
if let Some(outcome) = outcome { timeline::run_outcome_card(ui, outcome, None, |_| {}); }
let mut folder_failed = false;
if let Some(outcome) = outcome {
timeline::run_outcome_card(ui, outcome, None, |_| {
if let Some(path) = delivery_path {
folder_failed = services.open_folder.as_ref()
.is_none_or(|open| open(std::path::Path::new(path)).is_err());
}
});
}
if folder_failed {
self.error = "无法打开文件夹,请检查目录是否仍可访问".into();
}
}
fn workflow_card_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
@ -3316,7 +3355,7 @@ impl Workspace {
}
self.composer_attachment_menu_item(app, ui);
if super::stitch_ui::command_menu_item(ui, "folder-open", "常用提示词", true).clicked() {
self.model_settings = false; self.key_settings = false; self.api_key.clear();
self.close_model_settings();
self.prompt_library.toggle(&self.account, &self.origin, &self.tx); ui.close();
}
if ultra {
@ -3372,17 +3411,15 @@ impl Workspace {
self.panel_geometry["settings"] = rect_value(response.rect);
if response.clicked() {
if self.model_settings {
self.model_settings = false;
self.api_key.clear();
self.key_settings = false;
self.close_model_settings();
} else {
self.open_model_settings();
}
}
self.settings_popup(ui, &response);
self.model_settings_popup(ui, &response);
}
});
if let Some(anchor) = compact_settings_anchor { self.settings_popup(ui, &anchor); }
if let Some(anchor) = compact_settings_anchor { self.model_settings_popup(ui, &anchor); }
});
}
if send_clicked || (shortcut && (can || connect)) {
@ -3794,10 +3831,10 @@ impl Workspace {
});
}
pub(super) fn model_key_editor(&mut self, ui: &mut Ui, open: bool, focus: bool) {
pub(super) fn model_key_editor(&mut self, ui: &mut Ui, scope: &str, open: bool, focus: bool) {
let enabled = open && self.busy.is_none() && !self.account.is_null();
ui.add_enabled_ui(enabled, |ui| {
let key_id = ui.make_persistent_id(("personal-key", &self.origin, self.account["id"].as_str().unwrap_or_default()));
let key_id = ui.make_persistent_id((scope, "personal-key", &self.origin, self.account["id"].as_str().unwrap_or_default()));
let input = super::stitch_ui::halo_field(ui, key_id.with("field"), None, self.reduce_motion, |ui| ui.add(
super::stitch_ui::text_input(
&mut self.api_key,
@ -3937,6 +3974,21 @@ impl Workspace {
}
}
fn clear_settings_key_draft(&mut self) {
if !self.onboarding.is_open() {
self.api_key.clear();
}
}
pub(super) fn close_model_settings(&mut self) {
if self.model_settings || self.key_settings {
self.model_settings = false;
self.key_settings = false;
self.clear_settings_key_draft();
self.xiaoyi_key.clear();
}
}
pub(super) fn workspace_settings_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui, corner: egui::Pos2) {
// The brief's buttons disappear when the models are ready. Anchor the
// popup and its exit animation to the workspace instead.
@ -3946,17 +3998,21 @@ impl Workspace {
ui.make_persistent_id("workspace-settings-anchor"),
Sense::hover(),
);
let mounted = ui.ctx().read_response(egui::Popup::default_response_id(&anchor)).is_some();
if self.model_settings || self.key_settings || mounted {
self.settings_popup(ui, &anchor);
}
self.model_settings_popup(ui, &anchor);
self.flush_client_update_request(app);
if self.notifications_ui(ui) {
self.show_center(super::CenterView::Canvas, app.session.active().is_some());
}
}
pub(super) fn settings_popup(&mut self, ui: &mut Ui, anchor: &Response) {
pub(super) fn model_settings_popup(&mut self, ui: &mut Ui, anchor: &Response) {
let retained = ui.ctx().read_response(egui::Popup::default_response_id(anchor)).is_some();
if self.model_settings || self.key_settings || retained {
self.settings_popup(ui, anchor);
}
}
fn settings_popup(&mut self, ui: &mut Ui, anchor: &Response) {
// The dock layout can change mid-pass. A mounted popup claims the pass
// so another host cannot draw a second copy during the handoff.
let host = Id::unique(("jiansun-settings-host", ui.ctx().viewport_id()));
@ -3965,16 +4021,16 @@ impl Workspace {
return;
}
let open = self.model_settings || self.key_settings;
let open_id = host.with("open");
let was_open = ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::<bool>(open_id), open));
if was_open && !open {
self.clear_settings_key_draft();
self.xiaoyi_key.clear();
}
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);
self.panel_geometry["settingsMotion"] = json!({"opacity":visual.opacity,"scale":transform.scaling,"interactive":visual.interactive});
ui.ctx().data_mut(|data| data.insert_temp(Id::unique("jiansun-settings-retained"), visual.render));
// The logical popup closes immediately, but its visual shell stays
// mounted through the exit. Secrets never stay in the retained shell.
if !open {
self.api_key.clear();
self.xiaoyi_key.clear();
}
if !visual.render {
return;
}
@ -4004,9 +4060,7 @@ impl Workspace {
ui.label(RichText::new("小壹设置").size(14.0).strong().color(t.text));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if super::stitch_ui::icon_button(ui, "x", 26.0, false, "关闭模型设置").clicked() {
self.model_settings = false;
self.key_settings = false;
self.api_key.clear();
self.close_model_settings();
}
});
});
@ -4048,12 +4102,14 @@ impl Workspace {
{
self.key_settings = !self.key_settings;
if !self.key_settings {
self.api_key.clear();
self.clear_settings_key_draft();
}
}
});
super::stitch_ui::morph_surface(ui, ui.scope_id().with("key-reveal"), self.key_settings, self.reduce_motion, |ui| {
self.model_key_editor(ui, self.key_settings, false);
if !self.onboarding.is_open() {
self.model_key_editor(ui, "settings", self.key_settings, false);
}
});
super::stitch_ui::divider(ui);
self.knowledge_settings(ui);
@ -4070,9 +4126,7 @@ impl Workspace {
self.panel_geometry["notificationsButton"] = rect_value(notifications.rect);
if notifications.clicked() {
ui.ctx().data_mut(|data| data.get_temp_mut_or_default::<AgentNotifications>(id).open = true);
self.model_settings = false;
self.key_settings = false;
self.api_key.clear();
self.close_model_settings();
}
}
// 有"通知与警告"时补一条分隔线;没有时上面已经是分隔线。
@ -4100,9 +4154,7 @@ impl Workspace {
}
});
if open && !popup_visible && !nested_open {
self.model_settings = false;
self.key_settings = false;
self.api_key.clear();
self.close_model_settings();
ui.ctx().request_repaint();
}
}
@ -4240,9 +4292,7 @@ impl Workspace {
(action, !was_open && now_open)
});
if modal_opened {
self.model_settings = false;
self.key_settings = false;
self.api_key.clear();
self.close_model_settings();
ui.ctx().request_repaint();
}
if let Some(action) = action {
@ -4519,6 +4569,100 @@ mod tests {
use super::*;
use egui::pos2;
#[test]
fn production_delivery_card_opens_the_actual_saved_directory() {
use egui_kittest::{Harness, kittest::Queryable};
let root = tempfile::tempdir().unwrap();
let folder = root.path().join("成品");
std::fs::create_dir(&folder).unwrap();
std::fs::write(folder.join("交付清单.json"), b"{}").unwrap();
let path = folder.to_str().unwrap();
for (done, full, label) in [(3, true, "打开交付文件夹"), (1, false, "打开导出文件夹")] {
let (mut app, requests) = dock_fixture();
let (opened, paths) = mpsc::channel();
app.services.open_folder = Some(Box::new(move |path| {
opened.send(path.to_owned()).unwrap();
Ok(())
}));
let workspace = app.jiansun.as_mut().unwrap();
workspace.product_checkpoint = json!({"deliveryDir": root.path().join("预设目录")});
workspace.messages.push(json!({
"role":"assistant",
"productionSummary":{"exported":done,"total":3},
"productionDelivery":{"state":"bundle_saved","path":path,"allOutputsCompleted":full}
}));
let mut harness = Harness::builder().with_size(vec2(760.0, 380.0))
.with_context_setup(crate::cjk_fonts::install_system_provider_for_tests)
.build_ui_state(|ui, app: &mut PhotocraftApp| {
app.jiansun.as_mut().unwrap().production_outcome_ui(ui, false, &app.services);
}, app);
harness.run_steps(3);
harness.get_by_label(path);
harness.get_by_label(label).click();
harness.run_steps(2);
assert_eq!(paths.try_recv().unwrap(), folder);
assert!(paths.try_recv().is_err());
assert!(requests.try_recv().is_err());
}
}
#[test]
fn paused_production_can_open_the_saved_partial_delivery_from_its_checkpoint() {
use egui_kittest::{Harness, kittest::Queryable};
let folder = tempfile::tempdir().unwrap();
std::fs::write(folder.path().join("交付清单.json"), b"{}").unwrap();
let (mut app, _) = dock_fixture();
let (opened, paths) = mpsc::channel();
app.services.open_folder = Some(Box::new(move |path| {
opened.send(path.to_owned()).unwrap();
Ok(())
}));
app.jiansun.as_mut().unwrap().product_checkpoint = json!({
"phase":"paused",
"partialDelivered":true,
"deliveryDir":folder.path(),
"productionDelivery":{"state":"bundle_saved","allOutputsCompleted":false}
});
let mut harness = Harness::builder().with_size(vec2(760.0, 380.0))
.with_context_setup(crate::cjk_fonts::install_system_provider_for_tests)
.build_ui_state(|ui, app: &mut PhotocraftApp| {
app.jiansun.as_mut().unwrap().production_outcome_ui(ui, false, &app.services);
}, app);
harness.run_steps(3);
harness.get_by_label(folder.path().to_str().unwrap());
harness.get_by_label("打开导出文件夹").click();
harness.run_steps(2);
assert_eq!(paths.try_recv().unwrap(), folder.path());
assert!(harness.query_by_label("打开交付文件夹").is_none());
}
#[test]
fn production_counts_alone_do_not_confirm_delivery() {
use egui_kittest::{Harness, kittest::Queryable};
let folder = tempfile::tempdir().unwrap();
let (app, _) = dock_fixture();
let mut harness = Harness::builder().with_size(vec2(760.0, 380.0))
.with_context_setup(crate::cjk_fonts::install_system_provider_for_tests)
.build_ui_state(|ui, app: &mut PhotocraftApp| {
app.jiansun.as_mut().unwrap().production_outcome_ui(ui, false, &app.services);
}, app);
for path in [Value::Null, json!(folder.path().join("已移走")), json!(folder.path())] {
let workspace = harness.state_mut().jiansun.as_mut().unwrap();
workspace.messages = vec![json!({
"role":"assistant",
"productionSummary":{"exported":3,"total":3},
"productionDelivery":{"state":"bundle_saved","allOutputsCompleted":true,"path":path}
})];
harness.run_steps(2);
harness.get_by_label("成品交付尚未确认");
assert!(harness.query_by_label("整套制作已完成 · 已交付 3/3 份").is_none());
assert!(harness.query_by_label("打开交付文件夹").is_none());
}
}
#[test]
fn asset_dock_open_folder_requests_the_current_project() {
let (mut workspace, app, requests, _, _) = super::super::canvas_workspace::tests::native_fixture();

View File

@ -39,8 +39,10 @@ impl Workspace {
}
fn dismiss_onboarding(&mut self, ctx: &Context) {
if self.onboarding.is_open() {
self.api_key.clear();
}
self.onboarding = State::Dismissed;
self.api_key.clear();
ctx.data_mut(|data| data.insert_persisted(preference_id(), true));
}
@ -86,7 +88,7 @@ impl Workspace {
} else {
false
};
self.model_key_editor(ui, true, focus);
self.model_key_editor(ui, "onboarding", true, focus);
if self.busy.as_deref() == Some("configure") {
stitch_ui::status_label(ui, "正在校验 Key…", stitch_ui::StatusTone::Neutral);
}
@ -130,7 +132,7 @@ mod tests {
use super::*;
use crate::PhotocraftApp;
use super::super::Request;
use egui_kittest::{Harness, kittest::Queryable};
use egui_kittest::{Harness, kittest::{NodeT, Queryable}};
use serde_json::{Value, json};
use std::sync::mpsc;
@ -184,7 +186,7 @@ mod tests {
}
#[test]
fn login_focuses_the_shared_key_editor_and_saved_key_finishes_the_guide() {
fn onboarding_key_survives_closed_settings_and_can_be_saved() {
let evidence = std::env::var_os("PHOTOCRAFT_ONBOARDING_QA_OUT");
for width in [760.0, 1180.0] {
let (tx, requests) = mpsc::channel();
@ -195,15 +197,18 @@ mod tests {
let builder = Harness::builder().with_size(egui::vec2(width, 620.0))
.with_context_setup(setup_context);
let builder = if evidence.is_some() { builder.wgpu() } else { builder };
let mut harness = builder.build_ui_state(|ui, workspace: &mut Workspace| {
let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
let mut harness = builder.build_ui_state(|ui, (workspace, app): &mut (Workspace, PhotocraftApp)| {
workspace.begin_onboarding(ui.ctx());
if workspace.onboarding.is_open() { workspace.onboarding_dialog(ui); }
}, workspace);
workspace.library_ui(app, ui);
}, (workspace, app));
harness.run_steps(3);
assert!(harness.state().0.project_geometry["tiles"].is_array());
if let Some(directory) = &evidence {
harness.render().unwrap().save(std::path::Path::new(directory).join(format!("onboarding-login-{width}.png"))).unwrap();
}
let workspace = harness.state_mut();
let workspace = &mut harness.state_mut().0;
workspace.account = json!({"id":"test"});
workspace.models = vec![json!({"id":"test-model","key":"test-model"})];
workspace.model = "test-model".into();
@ -214,13 +219,34 @@ mod tests {
if let Some(directory) = &evidence {
harness.render().unwrap().save(std::path::Path::new(directory).join(format!("onboarding-key-{width}.png"))).unwrap();
}
harness.state_mut().api_key = "offline-test-key".into();
harness.run_steps(1);
let pasted = "sk-test-paste-123456";
assert!(harness.get_by_label("保存连接").accesskit_node().is_disabled());
harness.event(egui::Event::Paste(pasted.into()));
harness.run_steps(3);
assert_eq!(harness.state().0.api_key, pasted);
assert!(!harness.get_by_label("保存连接").accesskit_node().is_disabled());
harness.event(egui::Event::Text("a".into()));
harness.run_steps(2);
assert_eq!(harness.state().0.api_key, format!("{pasted}a"));
for (key, modifiers) in [
(egui::Key::A, egui::Modifiers::COMMAND),
(egui::Key::Backspace, egui::Modifiers::NONE),
] {
harness.event(egui::Event::Key {
key, physical_key: None, pressed: true, repeat: false, modifiers,
});
}
harness.run_steps(2);
assert!(harness.state().0.api_key.is_empty());
assert!(harness.get_by_label("保存连接").accesskit_node().is_disabled());
harness.event(egui::Event::Paste(pasted.into()));
harness.run_steps(2);
harness.get_by_label("保存连接").click();
harness.run_steps(2);
assert!(matches!(requests.try_recv(), Ok(Request::Action(method, value))
if method == "configure" && value["key"] == "offline-test-key" && value["model"] == "test-model"));
let workspace = harness.state_mut();
if method == "configure" && value["key"] == pasted && value["model"] == "test-model"));
let workspace = &mut harness.state_mut().0;
workspace.busy = None;
workspace.key_saved = true;
harness.run_steps(3);
@ -228,7 +254,7 @@ mod tests {
harness.get_by_label("已保存");
harness.get_by_label("开始使用小壹").click();
harness.run_steps(2);
assert!(!harness.state().onboarding.is_open());
assert!(!harness.state().0.onboarding.is_open());
}
}
}

View File

@ -317,16 +317,13 @@ impl Workspace {
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();
self.maybe_check_update_on_settings_open();
self.close_model_settings();
} else {
self.api_key.clear();
self.key_settings = false;
self.open_model_settings();
}
}
self.settings_popup(ui, &settings_btn);
self.model_settings_popup(ui, &settings_btn);
self.flush_client_update_request(app);
if stitch_ui::icon_button(ui, "rotate-cw", 30.0, false, "刷新项目").clicked() {
self.cover_errors.clear();

View File

@ -225,7 +225,8 @@ pub(super) enum RunOutcome<'a> {
Stopped { request_kept: bool },
NeedsCheck,
Failed { category: ErrorCategory },
Completed { summary: &'a str },
Completed { summary: &'a str, path: &'a str },
PartialDelivery { summary: &'a str, path: &'a str },
Waiting { reason: &'a str },
}
@ -236,7 +237,7 @@ impl RunOutcome<'_> {
Self::NeedsCheck => RunState::NeedsCheck,
Self::Failed { .. } => RunState::Failed,
Self::Completed { .. } => RunState::Completed,
Self::Waiting { .. } => RunState::WaitingResume,
Self::Waiting { .. } | Self::PartialDelivery { .. } => RunState::WaitingResume,
}
}
@ -246,7 +247,8 @@ impl RunOutcome<'_> {
Self::Stopped { request_kept: false } => "已停止本地自动操作".to_owned(),
Self::NeedsCheck => "原请求结果待核查".to_owned(),
Self::Failed { category } => category.title("这次操作没有完成").to_owned(),
Self::Completed { summary } => format!("已完成 · {summary}"),
Self::Completed { summary, .. } => format!("整套制作已完成 · {summary}"),
Self::PartialDelivery { summary, .. } => summary.to_owned(),
Self::Waiting { reason } => reason.to_owned(),
}
}
@ -261,6 +263,11 @@ impl RunOutcome<'_> {
pub(super) fn run_outcome_card(ui: &mut Ui, outcome: RunOutcome<'_>, action: Option<&str>, on_action: impl FnOnce(&mut Ui)) -> Response {
let state = outcome.state();
let title = outcome.title();
match outcome {
RunOutcome::Completed { path, .. } => return kit::delivery_card(ui, &title, path, true, on_action),
RunOutcome::PartialDelivery { path, .. } => return kit::delivery_card(ui, &title, path, false, on_action),
_ => {}
}
let response = inline_notice(ui, state.glyph(), state.tone(), &title, |ui| {
if let Some(action) = action
&& kit::action_button(ui, action, kit::ButtonRole::Secondary, true).clicked()
@ -1197,12 +1204,37 @@ mod tests {
assert!(drawn.iter().any(|text| text == "目标已在画布上改动"), "the reason is shown");
}
#[test]
fn completed_delivery_renders_its_path_and_dispatches_one_click() {
use egui_kittest::{Harness, kittest::Queryable};
let path = "/交付/作品";
for width in [205.0, 520.0] {
let mut harness = Harness::builder().with_size(vec2(width, 300.0))
.with_context_setup(fonts)
.build_ui_state(|ui, opened: &mut usize| {
kit::scope(ui, |ui| {
run_outcome_card(ui, RunOutcome::Completed { summary: "已交付 3/3 份", path },
None, |_| *opened += 1);
});
}, 0);
harness.run_steps(3);
harness.get_by_label("整套制作已完成 · 已交付 3/3 份");
harness.get_by_label(path);
let button = harness.get_by_label("打开交付文件夹");
assert!(button.rect().right() <= width);
button.click();
harness.run_steps(2);
assert_eq!(*harness.state(), 1);
}
}
#[test]
fn run_outcomes_never_read_the_same_and_only_failures_carry_a_reason() {
let all = [
RunOutcome::Stopped { request_kept: true }, RunOutcome::Stopped { request_kept: false }, RunOutcome::NeedsCheck,
RunOutcome::Failed { category: ErrorCategory::CanvasOperationFailed },
RunOutcome::Completed { summary: "文案 20/20 · 主图 5/5" }, RunOutcome::Waiting { reason: "正在等子代理回执" },
RunOutcome::Completed { summary: "文案 20/20 · 主图 5/5", path: "/交付/作品" }, RunOutcome::Waiting { reason: "正在等子代理回执" },
];
let titles: std::collections::HashSet<_> = all.iter().map(|outcome| outcome.title()).collect();
assert_eq!(titles.len(), all.len(), "no two outcomes read the same");

View File

@ -1645,6 +1645,66 @@ pub(super) fn action_button(ui: &mut Ui, label: &str, role: ButtonRole, enabled:
action_button_height(ui, label, role, enabled, control::DEFAULT)
}
pub(super) fn delivery_card(
ui: &mut Ui,
title: &str,
path: &str,
completed: bool,
open: impl FnOnce(&mut Ui),
) -> Response {
let t = Tokens::get(ui.ctx()).agent();
let success = AGENT_SEMANTIC.success;
let mut frame = surface_frame(ui.ctx(), SurfaceRole::Task).inner_margin(space::MD as i8);
if completed {
frame = frame
.fill(success.gamma_multiply(0.13))
.stroke(Stroke::new(1.0, success.gamma_multiply(0.62)))
.shadow(egui::epaint::Shadow {
offset: [0, 0],
blur: 10,
spread: 0,
color: success.gamma_multiply(0.19),
});
}
frame.show(ui, |ui| {
ui.spacing_mut().item_spacing = vec2(space::SM, space::XS);
let contents = |ui: &mut Ui| {
ui.horizontal_top(|ui| {
let (glyph, color) = if completed { ("check", t.primary_text) } else { ("folder-open", t.text_dim) };
let (badge, _) = ui.allocate_exact_size(Vec2::splat(icon::LG), egui::Sense::hover());
if completed {
ui.painter().circle_filled(badge.center(), badge.width() * 0.5, success);
}
crate::icons::image(glyph, icon::SM, color).paint_at(ui, badge.shrink((icon::LG - icon::SM) * 0.5));
ui.vertical(|ui| {
ui.add(egui::Label::new(RichText::new(title).font(Type::Subheading.semibold()).color(t.text)).wrap());
let path_label = RichText::new(path).font(Type::Meta.font_id()).color(t.text_dim);
ui.add(egui::Label::new(path_label).truncate().show_tooltip_when_elided(false)).on_hover_text(path);
});
});
};
let label = if completed { "打开交付文件夹" } else { "打开导出文件夹" };
let role = if completed { ButtonRole::Primary } else { ButtonRole::Secondary };
let button_width = ui.painter().layout_no_wrap(label.to_owned(), Type::Title.font_id(), t.text).size().x
+ ui.spacing().button_padding.x * 2.0;
let action = |ui: &mut Ui| {
if action_button(ui, label, role, true).clicked() {
open(ui);
}
};
let width = ui.available_width();
if width >= button_width + icon::LG * 6.0 {
ui.allocate_ui_with_layout(vec2(width, 0.0), egui::Layout::right_to_left(egui::Align::Center), |ui| {
action(ui);
ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::top_down(egui::Align::Min), contents);
});
} else {
contents(ui);
ui.allocate_ui_with_layout(vec2(width, 0.0), egui::Layout::right_to_left(egui::Align::Center), action);
}
}).response
}
pub(super) fn action_button_height(ui: &mut Ui, label: &str, role: ButtonRole, enabled: bool, height: f32) -> Response {
let t = Tokens::get(ui.ctx()).agent();
let material_slot=super::agent_motion::reserve_background(ui);

View File

@ -239,6 +239,7 @@ pub type AutomationCommandFn = Box<dyn Fn(&str, &Value) -> Result<(), String>>;
/// Open a URL in the system browser (native) — reliable cross-platform, unlike `ctx.open_url`.
pub type OpenUrlFn = Box<dyn Fn(&str) -> Result<(), String>>;
pub type OpenFolderFn = Box<dyn Fn(&std::path::Path) -> Result<(), String>>;
pub type EncodePngFn = Box<dyn Fn(u32, u32, &[u8]) -> Result<Vec<u8>, String>>;
@ -424,6 +425,8 @@ pub struct Services {
pub encode_png: Option<EncodePngFn>,
/// Open a URL in the system browser (native). Falls back to `ctx.open_url` (web) when unset.
pub open_url: Option<OpenUrlFn>,
/// Open a local directory in the system file manager.
pub open_folder: Option<OpenFolderFn>,
/// Preferences ▸ General ▸ Beep When Done: the platform's default beep, played when a
/// background job finishes successfully. `None` in the web build (and in tests).
pub beep: Option<fn()>,