隔离小壹项目运行状态并校验部分交付

This commit is contained in:
WuYongJie 2026-12-02 21:09:27 +08:00
parent f7ad5d1efc
commit 0ed79ee40a
3 changed files with 1038 additions and 179 deletions

View File

@ -48,6 +48,7 @@ pub mod template_preview;
mod professional_mode;
mod creation;
mod product_production;
mod multi_project_state;
mod production_controls;
mod user_canvas_changes;
pub(crate) use creation::creation_escape_active;
@ -1038,7 +1039,11 @@ pub struct Workspace {
persisted_revisions: HashMap<u64, u64>,
saving: Option<(u64, u64)>,
metadata_saving: Option<u64>,
metadata_save_owners: VecDeque<u64>,
observed_doc: Option<u64>,
project_run_slots: HashMap<String, multi_project_state::ProjectRunSlot>,
project_view_parked: bool,
in_background_project: bool,
project_context: Value,
startup_resume_checked: bool,
onboarding: onboarding::State,
@ -1048,6 +1053,7 @@ pub struct Workspace {
draft_changed: bool,
product_checkpoint: Value,
production_exit: Option<product_production::PendingExit>,
exit_checkpoint_owners: VecDeque<Option<u64>>,
production_exit_state: Option<product_production::ExitState>,
pub exit_admission_closed: Arc<AtomicBool>,
pub prepare_daemon_exit: Option<Box<dyn Fn() -> ExitReceipt>>,
@ -1153,6 +1159,7 @@ pub struct Workspace {
client_update: client_update::ClientUpdate,
client_update_ui: client_update_ui::UpdateUi,
product_production: Option<product_production::Run>,
last_production_summary: Option<(u64, multi_project_state::ProjectRunVisualStatus)>,
product_views: product_production::Views,
product_target_hidden: bool,
write_epoch: u64,
@ -1592,7 +1599,11 @@ impl Workspace {
persisted_revisions: HashMap::new(),
saving: None,
metadata_saving: None,
metadata_save_owners: VecDeque::new(),
observed_doc: None,
project_run_slots: HashMap::new(),
project_view_parked: false,
in_background_project: false,
project_context: json!({}),
startup_resume_checked: false,
onboarding: onboarding::State::default(),
@ -1602,6 +1613,7 @@ impl Workspace {
draft_changed: false,
product_checkpoint: Value::Null,
production_exit: None,
exit_checkpoint_owners: VecDeque::new(),
production_exit_state: None,
exit_admission_closed: Arc::new(AtomicBool::new(false)),
prepare_daemon_exit: None,
@ -1706,6 +1718,7 @@ impl Workspace {
client_update: client_update::ClientUpdate::default(),
client_update_ui: client_update_ui::UpdateUi::default(),
product_production: None,
last_production_summary: None,
product_views: product_production::Views::default(),
product_target_hidden: false,
write_epoch: 0,
@ -2038,12 +2051,21 @@ impl Workspace {
/// The central work area has exactly one destination. A missing document returns to
/// projects rather than leaving an apparently selected, empty canvas behind.
fn show_center(&mut self, view: CenterView, document_open: bool) {
self.cancel_project_open();
if !self.in_background_project { self.cancel_project_open(); }
let material = matches!(view, CenterView::Materials);
let library = matches!(view, CenterView::Projects) || (!document_open && !material);
let creation = document_open && !material && !library;
if (!document_open || self.product_production.is_none())
&& (self.material != material || self.library != library || self.creation_open != creation || (creation && self.creation_step != 3)) {
if !self.in_background_project && (library || material)
&& self.observed_doc.is_some_and(|doc| self.owned_project_key(doc).is_some())
{
self.project_view_parked = true;
} else if !library && !material {
self.project_view_parked = false;
}
if self.observed_doc.and_then(|doc| self.owned_project_key(doc)).is_none()
&& !self.project_view_parked && self.product_production.is_none()
&& (self.material != material || self.library != library || self.creation_open != creation)
{
self.handover();
}
self.material = material;
@ -2073,15 +2095,13 @@ impl Workspace {
}
fn show_creation_step(&mut self, step: usize, document_open: bool) {
self.cancel_project_open();
if !self.in_background_project { self.cancel_project_open(); }
if !document_open {
self.show_center(CenterView::Projects, false);
return;
}
let step = step.min(4);
if self.library || self.material || !self.creation_open || self.creation_step != step {
self.handover();
}
if !self.creation_reads.staged_new_project { self.project_view_parked = false; }
self.set_creation_destination(step);
}
/// A trusted Agent view change is not a human takeover. Callers must still
@ -2160,9 +2180,18 @@ impl Workspace {
app.session.documents().iter().position(|state| self.open_projects.get(&state.doc.id.0)==Some(&identity))
}
fn activate_project_tab(&mut self, app: &mut PhotocraftApp, index: usize) {
self.cancel_project_open();
self.retain_creation_ui_draft(app);
let doc = app.session.documents()[index].doc.id.0;
if self.observed_doc != Some(doc) && self.park_project_projection() {
self.restore_or_read_project(doc);
} else if self.observed_doc != Some(doc) && self.project_view_parked {
self.restore_or_read_project(doc);
}
app.session.set_active(index);
self.show_center(CenterView::Canvas,true);
self.library = false;
self.material = false;
self.project_view_parked = false;
self.creation_open=false;
app.sync_views();
}
@ -2174,6 +2203,9 @@ impl Workspace {
return Ok(());
}
}
if self.product_production.is_some() && input["updateExisting"] != true {
return self.tx.send(Request::Action("open".into(), input)).map_err(|_| "本机项目服务已断开".into());
}
if self.busy.is_some() || self.saving.is_some() || self.pending_project_open.is_some() {
return Err("请等待当前操作保存完成".into());
}
@ -2753,6 +2785,9 @@ impl Workspace {
let scope_changed =
self.account["id"] != v["account"]["id"] || v["origin"].as_str().is_some_and(|origin| origin != self.origin);
if scope_changed {
self.revoke_project_slots(app, ctx, &json!("account_changed"));
self.project_run_slots.clear();
self.project_view_parked = false;
self.feedback = feedback::Feedback::default();
self.workbench = workspace_navigation::Workbench::default();
self.retain_creation_ui_draft(app);
@ -3358,12 +3393,7 @@ impl Workspace {
fn receive_json_success(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, v: Value, live_image_request: bool) {
match method {
"auth-fence" if v["accountId"] == self.account["id"] && v["origin"] == self.origin => {
self.with_product_target(app, |w, app| {
w.pause_for_authorization(&v["category"]);
if let Some(state) = app.session.active().filter(|state| w.loaded_draft == Some(state.doc.id.0)) {
w.save_project_draft(state, ctx);
}
});
self.revoke_project_slots(app, ctx, &v["category"]);
if v["category"] == "auth_revoked" {
self.receive_library_status(&json!({"libraryStatus":"sign_in_required","libraryHttpStatus":401,
"libraryMessage":"授权已失效,制作已暂停;请重新登录"}));
@ -3613,8 +3643,8 @@ impl Workspace {
self.activate_project_tab(app,index);
return;
}
self.handover();
finish_open_busy(&mut self.busy, meta["autoResume"] == true);
self.project_view_parked = false;
self.library = false;
self.material = false;
let file = meta["path"].as_str().map(str::to_owned);
@ -3630,7 +3660,7 @@ impl Workspace {
let mut close = Vec::new();
for (index, old) in app.session.documents().iter().enumerate() {
if old.doc.id != doc.id && superseded.iter().any(|id| id.as_u64() == Some(old.doc.id.0)) {
if old.saved_revision == old.revision {
if old.saved_revision == old.revision && !self.has_project_run_for(old.doc.id.0) {
close.push(index);
} else {
retained_superseded_draft = true;
@ -3681,12 +3711,91 @@ impl Workspace {
}
}
fn restore_or_read_project(&mut self, doc: u64) {
if !self.restore_project_projection(doc) {
self.observed_doc = Some(doc);
let _ = self.tx.send(Request::Action("draft".into(), json!({"doc":doc})));
}
}
fn switch_project_projection(&mut self, app: &PhotocraftApp, ctx: &egui::Context, current: Option<u64>) {
self.persisted_revisions.retain(|id, _| app.session.documents().iter().any(|st| st.doc.id.0 == *id));
self.flush_document_draft(ctx, self.observed_doc, true);
self.retain_creation_ui_draft(app);
self.creation_ui_scope = None;
self.cancel_project_open();
if self.park_project_projection() {
if let Some(id) = current { self.restore_or_read_project(id); }
return;
}
if let Some(id) = current && self.restore_project_projection(id) { return; }
self.handover();
self.user_canvas_changes = Default::default();
self.template_workflow = Value::Null;
self.canvas_workspace = canvas_workspace::State::default();
if self.pending_slot_apply.take().is_some() && self.busy.as_deref() == Some("slot-apply-save") {
self.busy = None;
}
self.preview = None;
self.material_preview_pending = None;
self.observed_doc = current;
self.loaded_draft = None;
self.product_checkpoint = Value::Null;
self.draft_changed = false;
self.messages.clear();
self.stream_reply.clear();
self.error.clear();
self.agent_images.clear();
self.agent_preview_pending.clear();
self.requested_previews.clear();
self.composer.clear();
self.unknown = false;
self.project_context = json!({});
self.creation_doc = None;
self.creation_read_failed = false;
self.creation_dirty = false;
self.creation_brief = creation::empty_brief();
self.creation_selected.clear();
self.creation_direction.clear();
self.creation_plan = json!([]);
self.creation_edit_signature.clear();
self.restored_creation_signature = None;
self.creation_failed_signature.clear();
self.creation_restore_draft = Value::Null;
self.creation = Value::Null;
self.creation_pending = None;
self.creation_run = None;
self.creation_progress.clear();
self.agent_rule = Value::Null;
self.agent_rule_state = Value::Null;
self.agent_categories.clear();
self.legacy_unknown = false;
self.pi_review = false;
self.pi_usage = Value::Null;
self.pi_context_usage = Value::Null;
self.ready_image = None;
self.pending_image = None;
self.unknown_image = false;
self.unknown_image_task = None;
if let Some(id) = current {
let _ = self.tx.send(Request::Action("draft".into(), json!({"doc":id})));
}
}
fn tick_context(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
// Process account/document events first, then invalidate the old read/cache
// scope before the same frame can draw a newly authorized workspace.
if self.professional_child_active(app) { return false; }
self.creation_reads_tick(app);
let current = app.session.active().map(|s| (s.doc.id.0, s.revision));
let current = current.filter(|(doc, _)| !self.project_view_parked
|| self.creation_open && !self.creation_reads.staged_new_project && !self.project_is_parked(*doc));
if current.map(|v| v.0) != self.observed_doc {
self.switch_project_projection(app, ctx, current.map(|v| v.0));
}
if current.is_some() && self.creation_open && !self.creation_reads.staged_new_project {
self.project_view_parked = false;
}
if self.busy.as_deref() == Some("creation-generate") && self.allow_apply {
if current != self.owner_doc.map(|id| (id, self.expected_revision)) {
self.handover();
@ -3712,64 +3821,6 @@ impl Workspace {
self.note("本地 Agent 连接已断开,草稿已保留");
}
self.track_pi_canvas(app);
if self.observed_doc != current.map(|v| v.0) {
self.persisted_revisions.retain(|id, _| app.session.documents().iter().any(|st| st.doc.id.0 == *id));
self.flush_document_draft(ctx, self.observed_doc, true);
self.retain_creation_ui_draft(app);
self.creation_ui_scope = None;
self.cancel_project_open();
self.handover();
self.user_canvas_changes = Default::default();
self.template_workflow = Value::Null;
self.canvas_workspace = canvas_workspace::State::default();
if self.pending_slot_apply.take().is_some() && self.busy.as_deref() == Some("slot-apply-save") {
self.busy = None;
}
self.preview = None;
self.material_preview_pending = None;
self.observed_doc = current.map(|v| v.0);
self.loaded_draft = None;
self.product_checkpoint = Value::Null;
self.draft_changed = false;
self.messages.clear();
self.stream_reply.clear();
self.error.clear();
self.agent_images.clear();
self.agent_preview_pending.clear();
self.requested_previews.clear();
self.composer.clear();
self.unknown = false;
self.project_context = json!({});
self.creation_doc = None;
self.creation_read_failed = false;
self.creation_dirty = false;
self.creation_brief = creation::empty_brief();
self.creation_selected.clear();
self.creation_direction.clear();
self.creation_plan = json!([]);
self.creation_edit_signature.clear();
self.restored_creation_signature = None;
self.creation_failed_signature.clear();
self.creation_restore_draft = Value::Null;
self.creation = Value::Null;
self.creation_pending = None;
self.creation_run = None;
self.creation_progress.clear();
self.agent_rule = Value::Null;
self.agent_rule_state = Value::Null;
self.agent_categories.clear();
self.legacy_unknown = false;
self.pi_review = false;
self.pi_usage = Value::Null;
self.pi_context_usage = Value::Null;
self.ready_image = None;
self.pending_image = None;
self.unknown_image = false;
self.unknown_image_task = None;
if let Some((id, _)) = current {
let _ = self.tx.send(Request::Action("draft".into(), json!({"doc":id})));
}
}
true
}
@ -3896,7 +3947,7 @@ impl Workspace {
|| app.services.app_tray.as_ref().is_some_and(|tray| tray.visible());
let bounds = ctx.content_rect();
let painting = crate::type_tool::in_ui_pass(ctx) && !hidden && bounds.is_finite() && bounds.is_positive();
if hidden && self.pi_run.is_some() {
if hidden && (self.pi_run.is_some() || self.parked_production_active()) {
// Keep the bridge and save receipts moving when Windows suppresses redraw events.
ctx.request_repaint_after(Duration::from_secs(1));
}
@ -3904,6 +3955,15 @@ impl Workspace {
canvas_workspace::observe_canvas_input(ctx);
self.observe_startup_interaction(ctx);
}
if self.production_exit.is_none() && !self.professional_child_active(app) {
let visible_doc = app.session.active().map(|state| state.doc.id.0).filter(|doc|
!self.project_view_parked || self.creation_open && !self.creation_reads.staged_new_project && !self.project_is_parked(*doc));
if visible_doc != self.observed_doc && (self.observed_doc.is_some()
|| visible_doc.is_some_and(|doc| self.project_is_parked(doc)))
{
self.switch_project_projection(app, ctx, visible_doc);
}
}
if self.authority_active() {
self.with_product_target(app, |w, app| {
if let Some((meta, adopted)) = w.poll_canvas_adoption(app, ctx, painting) {
@ -3935,45 +3995,27 @@ impl Workspace {
{
app.remember_original_preview(doc.id, &preview);
}
match event {
Event::Json(method, Ok(value)) if method == "production-deliver-bundle" => {
self.production_bundle_received(&value);
}
Event::Json(method, result) if method == "product-exit-checkpoint" => {
if let Some(exit) = &mut self.production_exit {
exit.checkpoint = Some(result.map(|_| ()));
}
}
Event::SlotCanvas(doc, meta) if meta["productViewId"].is_u64() =>
self.product_view_received(app, doc, meta),
Event::SlotCanvas(doc, meta) if meta["continueProduct"] == true =>
self.continue_product_canvas(app, doc, meta),
Event::Saved(id, revision, ref meta) if self.product_view_saved(app, id, revision, meta) => {}
Event::Json(method, Ok(value)) if method == "slot-product-view" => self.product_view_failed(&value),
Event::Json(method, Ok(value)) if method == "slot-product-view-progress" =>
self.product_view_progressed(app, &value),
Event::Json(method, Ok(value)) if method == "slot-product-view-save" => self.product_view_save_failed(app, &value),
Event::Json(method, Ok(_)) if method == "slot-skeleton" && self.product_stage_waiting_for_view() => {}
event => {
let for_product = match &event {
Event::PiAction(method, _, _) => (self.pi_request_scope["productProduction"] == true
|| self.product_production.is_some()) && !matches!(method.as_str(), "creation-allowed" | "pi-user-canvas-changes"),
Event::SlotAdopt { meta, .. } => meta["detailBatch"] == true,
Event::Saved(..) => true,
Event::Json(method, Ok(value)) if matches!(method.as_str(), "image" | "image-progress") =>
value["productionRun"].is_string(),
Event::Json(method, _) => matches!(method.as_str(),
"save" | "agent" | "agent-stream" | "slot-product-export" | "slot-skeleton"
| "template-progress" | "slot-progress" | "slot-adopt-prep" | "slot-adopted" | "slot-append" | "slot-read"
| "slot-recover"),
_ => false,
};
if for_product {
self.with_product_target(app, |w, app| w.receive_event(app, ctx, event));
} else {
self.receive_event(app, ctx, event);
}
let owner = match &event {
Event::Json(method, _) if method == "product-exit-checkpoint" =>
self.exit_checkpoint_owners.pop_front().flatten(),
Event::Json(method, _) if method == "metadata-save" =>
self.metadata_save_owners.pop_front(),
_ => self.event_project_doc(&event),
};
if let Some(doc) = owner
&& Some(doc) != self.observed_doc && self.project_is_parked(doc)
{
if multi_project_state::foreground_canvas_editing(app, ctx)
&& let Event::PiAction(method, _, reply) = &event
&& multi_project_state::native_canvas_action(method)
{
let _ = reply.send(Err(BridgeFailure::new("revision_conflict", true, false,
"当前画布正在进行手动编辑,请稍后核对原项目再继续")));
} else {
self.with_parked_project(app, doc, |w, app| w.receive_project_event(app, ctx, event));
}
} else {
self.receive_project_event(app, ctx, event);
}
}
if self.production_exit.is_some() {
@ -3982,7 +4024,10 @@ impl Workspace {
}
if self.exit_admission_closed.load(std::sync::atomic::Ordering::Acquire) { return; }
self.client_update.tick(&self.account, &self.origin, &self.tx, ctx, Instant::now());
if !self.tick_context(app, ctx) { return; }
if !self.tick_context(app, ctx) {
self.tick_parked_projects(app, ctx);
return;
}
if self.authority_active() {
self.with_product_target(app, |w, app| {
let current = app.session.active().map(|s| (s.doc.id.0, s.revision));
@ -4033,6 +4078,78 @@ impl Workspace {
});
self.release_settled_product_view();
self.product_view_tick(app, ctx);
self.tick_parked_projects(app, ctx);
}
fn tick_parked_projects(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) {
let editor_busy = multi_project_state::foreground_canvas_editing(app, ctx);
for doc in self.parked_project_docs(app) {
if !editor_busy && self.parked_project_needs_tick(doc) {
self.with_parked_project(app, doc, |w, app| {
if w.draft_changed { w.sync_dirty = true; }
w.with_product_target(app, |w, app| {
if w.authority_active() {
if let Some((meta, adopted)) = w.poll_canvas_adoption(app, ctx, false) {
w.finish_adoption_receipt(app, &meta, adopted);
}
agent_native::settle_jobs(w, app);
let current = app.session.active().map(|state| (state.doc.id.0, state.revision));
w.tick_pending_edits(app, ctx, current);
}
w.production_tick(app);
w.tick_deferred_image_recovery(app, ctx, Instant::now());
w.autosave_project(app, ctx);
w.automatic_image_recovery(app, Instant::now());
});
w.release_settled_product_view();
w.product_view_tick(app, ctx);
});
}
}
if self.parked_production_active() { ctx.request_repaint_after(Duration::from_secs(1)); }
}
fn receive_project_event(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, event: Event) {
match event {
Event::Json(method, Ok(value)) if method == "production-deliver-bundle" => {
self.production_bundle_received(&value);
}
Event::Json(method, result) if method == "product-exit-checkpoint" => {
if let Some(exit) = &mut self.production_exit {
exit.checkpoint = Some(result.map(|_| ()));
}
}
Event::SlotCanvas(doc, meta) if meta["productViewId"].is_u64() =>
self.product_view_received(app, doc, meta),
Event::SlotCanvas(doc, meta) if meta["continueProduct"] == true =>
self.continue_product_canvas(app, doc, meta),
Event::Saved(id, revision, ref meta) if self.product_view_saved(app, id, revision, meta) => {}
Event::Json(method, Ok(value)) if method == "slot-product-view" => self.product_view_failed(&value),
Event::Json(method, Ok(value)) if method == "slot-product-view-progress" =>
self.product_view_progressed(app, &value),
Event::Json(method, Ok(value)) if method == "slot-product-view-save" => self.product_view_save_failed(app, &value),
Event::Json(method, Ok(_)) if method == "slot-skeleton" && self.product_stage_waiting_for_view() => {}
event => {
let for_product = match &event {
Event::PiAction(method, _, _) => (self.pi_request_scope["productProduction"] == true
|| self.product_production.is_some()) && !matches!(method.as_str(), "creation-allowed" | "pi-user-canvas-changes"),
Event::SlotAdopt { meta, .. } => meta["detailBatch"] == true,
Event::Saved(..) => true,
Event::Json(method, Ok(value)) if matches!(method.as_str(), "image" | "image-progress") =>
value["productionRun"].is_string(),
Event::Json(method, _) => matches!(method.as_str(),
"save" | "agent" | "agent-stream" | "slot-product-export" | "slot-skeleton"
| "template-progress" | "slot-progress" | "slot-adopt-prep" | "slot-adopted" | "slot-append" | "slot-read"
| "slot-recover"),
_ => false,
};
if for_product {
self.with_product_target(app, |w, app| w.receive_event(app, ctx, event));
} else {
self.receive_event(app, ctx, event);
}
}
}
}
fn autosave_project(&mut self, app: &PhotocraftApp, ctx: &egui::Context) {
@ -4083,6 +4200,7 @@ impl Workspace {
if submitted {
if metadata_only {
self.metadata_saving = Some(key.0);
self.metadata_save_owners.push_back(key.0);
} else {
self.saving = Some(key);
}
@ -4181,6 +4299,11 @@ impl Workspace {
Event::Json(method, result) => self.receive_json_event(app, ctx, method, result),
Event::Opened(doc, meta) => self.receive_opened(app, ctx, doc, meta),
Event::Saved(id, rev, meta) => {
if meta["accountId"].as_str().is_some_and(|id| self.account["id"].as_str() != Some(id))
|| meta["origin"].as_str().is_some_and(|origin| self.origin != origin)
{
return;
}
if meta["documentKey"].is_object() && app.session.active().is_some_and(|state|
state.doc.id.0 == id && product_document_key(&state.doc) != meta["documentKey"])
{
@ -4191,7 +4314,7 @@ impl Workspace {
}
return;
}
if self.pending_slot_apply.as_ref().is_none_or(|pending| pending["doc"].as_u64() == Some(id)) {
if self.saving == Some((id, rev)) {
self.saving = None;
}
self.saved = Some((id, rev, meta["time"].as_str().unwrap_or("").into()));
@ -4890,17 +5013,26 @@ pub(crate) fn exit_flush_finished(app: &PhotocraftApp) -> bool {
pub(crate) fn cancel_exit(app: &mut PhotocraftApp) {
use std::sync::atomic::Ordering;
let Some(workspace) = app.jiansun.as_mut() else { return };
let Some(mut workspace) = app.jiansun.take() else { return };
if workspace.exit_admission_closed.swap(false, Ordering::AcqRel) {
if let Some(cancel) = workspace.cancel_daemon_exit { cancel(); }
workspace.busy = None;
workspace.pi_run = None;
workspace.pi_native = false;
workspace.pi_request_scope = Value::Null;
for doc in workspace.parked_project_docs(app) {
workspace.with_parked_project(app, doc, |w, _| {
w.busy = None;
w.pi_run = None;
w.pi_request_scope = Value::Null;
w.restore_cancelled_exit();
});
}
workspace.restore_cancelled_exit();
workspace.pi_write_blocked = false;
workspace.agent_effects_paused = false;
}
app.jiansun = Some(workspace);
}
pub(crate) fn background_status(app: &PhotocraftApp) -> Option<String> {
@ -4914,6 +5046,7 @@ impl Workspace {
fn background_status(&self, app: &PhotocraftApp) -> Option<String> {
self.product_production.as_ref().and_then(product_production::Run::progress_label)
.or_else(|| self.parked_production_active().then(|| "后台项目正在处理任务".into()))
.or_else(|| (self.product_start_queued || self.product_export.is_some()
|| self.busy.as_deref() == Some("slot-product-export")).then(|| "正在制作或导出".into()))
.or_else(|| (self.saving.is_some() || self.product_view_save_pending()).then(|| "正在保存小壹工程".into()))

View File

@ -0,0 +1,451 @@
use super::*;
use super::product_production::Run;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum ProjectRunVisualStatus {
Running,
Queued,
Paused,
PartialDelivered,
Completed,
Failed,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct ProjectRunSummary {
pub project_id: String,
pub project_title: String,
pub status: ProjectRunVisualStatus,
pub producing_output_id: Option<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, PartialEq, Eq)]
pub(super) enum WorkspaceSectionKind {
Projects,
Brief,
Canvas,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct MultiProjectUiSnapshot {
pub global_runs: Vec<ProjectRunSummary>,
pub max_concurrent: usize,
pub active_project_id: Option<String>,
pub active_project_title: String,
pub active_section: WorkspaceSectionKind,
pub viewing_output_id: Option<String>,
pub viewing_output_label: String,
pub producing_output_id: Option<String>,
pub producing_output_label: String,
pub viewing_differs_from_producing: bool,
}
// Mount the owning project's state for the existing document-bound commands.
// A single field list keeps parking and restoring symmetric.
macro_rules! project_run_slot {
($($field:ident: $kind:ty = $initial:expr,)*) => {
pub(super) struct ProjectRunSlot {
next_background_tick: Instant,
$($field: $kind,)*
}
impl Default for ProjectRunSlot {
fn default() -> Self {
Self { next_background_tick: Instant::now(), $($field: $initial,)* }
}
}
impl ProjectRunSlot {
fn swap(&mut self, workspace: &mut Workspace) {
$(std::mem::swap(&mut self.$field, &mut workspace.$field);)*
}
}
};
}
project_run_slot! {
agent_effects_paused: bool = false,
pending_candidate_trace: Option<Value> = None,
composer: String = String::new(),
composer_attachments: composer_attachments::State = composer_attachments::State::default(),
composer_references: composer_references::State = composer_references::State::default(),
messages: Vec<Value> = vec![],
error: String = String::new(),
busy: Option<String> = None,
unknown: bool = false,
owner_doc: Option<u64> = None,
expected_revision: u64 = 0,
pi_canvas_basis: Option<Arc<Document>> = None,
user_canvas_changes: user_canvas_changes::UserCanvasChanges = Default::default(),
pi_manual_edit: bool = false,
queue: VecDeque<Edit> = VecDeque::new(),
recording_edit_owner: Option<Value> = None,
next_step: Instant = Instant::now(),
touched: Instant = Instant::now(),
saved: Option<(u64, u64, String)> = None,
saving: Option<(u64, u64)> = None,
metadata_saving: Option<u64> = None,
observed_doc: Option<u64> = None,
project_context: Value = json!({}),
recovery_status: Value = Value::Null,
image_recovery_schedules: HashMap<String, RecoverySchedule> = HashMap::new(),
draft_changed: bool = false,
product_checkpoint: Value = Value::Null,
production_exit: Option<product_production::PendingExit> = None,
production_exit_state: Option<product_production::ExitState> = None,
loaded_draft: Option<u64> = None,
allow_apply: bool = false,
image_mode: String = "chat".into(),
image_progress: String = String::new(),
unknown_image: bool = false,
unknown_image_task: Option<String> = None,
ready_image: Option<Value> = None,
pending_image: Option<Value> = None,
stream_reply: String = String::new(),
agent_images: agent_image_cache::TextureCache<egui::TextureHandle> = agent_image_cache::TextureCache::new(),
agent_preview_pending: std::collections::VecDeque<(serde_json::Value, egui::ColorImage)> = std::collections::VecDeque::new(),
agent_preview_scope: Option<(String, String, Option<u64>)> = None,
requested_previews: std::collections::HashSet<String> = std::collections::HashSet::new(),
pi_run: Option<String> = None,
pi_queued_steering: Vec<String> = Vec::new(),
pi_queued_followup: Vec<String> = Vec::new(),
production_stop: Value = json!({"mode":null,"state":"idle","reason":null,"error":null}),
production_budget_minutes: u64 = 45,
pi_ui: pi_ui::State = pi_ui::State::default(),
agent_native: agent_native::State = agent_native::State::default(),
visual_preview: Option<agent_preview::Preview> = None,
visual_preview_ui: visual_preview_ui::State = visual_preview_ui::State::default(),
pi_write_blocked: bool = false,
pi_touched: Instant = Instant::now(),
pi_binding: Value = Value::Null,
pi_request_scope: Value = Value::Null,
agent_rule: Value = Value::Null,
agent_rule_state: Value = Value::Null,
agent_categories: Vec<Value> = vec![],
legacy_unknown: bool = false,
pi_review: bool = false,
pi_usage: Value = Value::Null,
pi_context_usage: Value = Value::Null,
pi_native: bool = false,
workflow: workflow_bridge::State = workflow_bridge::State::default(),
workflow_waiting: Option<Value> = None,
creation: Value = Value::Null,
creation_brief: Value = creation::empty_brief(),
creation_selected: Vec<String> = vec![],
creation_direction: String = String::new(),
creation_plan: Value = json!([]),
creation_dirty: bool = false,
creation_doc: Option<u64> = None,
creation_read_failed: bool = false,
creation_edit_signature: String = String::new(),
restored_creation_signature: Option<String> = None,
creation_failed_signature: String = String::new(),
creation_submitted_draft: Option<Value> = None,
creation_touched: Instant = Instant::now(),
creation_restore_draft: Value = Value::Null,
creation_ui_scope: Option<CreationUiScope> = None,
creation_width: u32 = 0,
creation_delivery_dir: Option<String> = None,
creation_run: Option<String> = None,
creation_base_revision: u64 = 0,
creation_pending: Option<(Box<Document>, Value)> = None,
creation_progress: String = String::new(),
template_progress: Value = Value::Null,
template_workflow: Value = Value::Null,
product_production: Option<product_production::Run> = None,
last_production_summary: Option<(u64, ProjectRunVisualStatus)> = None,
product_views: product_production::Views = product_production::Views::default(),
write_epoch: u64 = 0,
product_start_queued: bool = false,
product_export: Option<Value> = None,
canvas_workspace: canvas_workspace::State = canvas_workspace::State::default(),
agent_presence: agent_presence::Presence = agent_presence::Presence::default(),
reference_intro_doc: Option<u64> = None,
template_ui: template_slots::UiState = template_slots::UiState::default(),
pending_slot_apply: Option<Value> = None,
listing_read_at: Option<(u64, Instant)> = None,
listing_read_error: Option<String> = None,
sync_dirty: bool = true,
sync_request_meta: String = String::new(),
}
pub(super) fn foreground_canvas_editing(app: &PhotocraftApp, ctx: &egui::Context) -> bool {
app.ui.transform.is_some() || app.ui.text_edit.is_some() || app.ui.type_transform.is_some()
|| app.ui.cam_transform.is_some() || app.ui.symmetry_transform.is_some()
|| app.ui.pen.is_some() || app.ui.crop_rect.is_some() || app.ui.perspective_crop.is_some()
|| !app.ui.polygon.is_empty()
|| ctx.input(|input| input.raw.focused && input.pointer.any_down())
}
pub(super) fn native_canvas_action(method: &str) -> bool {
matches!(method,
"pi-edit" | "pi-native-call" | "pi-native-poll" | "pi-detail-copy-apply" | "pi-detail-images"
| "pi-workflow-execute" | "pi-workflow-poll" | "pi-production-open" | "pi-production-finish")
}
impl Workspace {
pub(super) fn owned_project_key(&self, doc: u64) -> Option<&str> {
self.open_projects.get(&doc)
.filter(|key| key.starts_with(&self.local_identity("")))
.map(String::as_str)
}
pub(super) fn park_project_projection(&mut self) -> bool {
let Some(key) = self.observed_doc.and_then(|doc| self.owned_project_key(doc)).map(str::to_owned) else {
return false;
};
let mut slot = ProjectRunSlot::default();
slot.swap(self);
self.project_run_slots.insert(key, slot);
true
}
pub(super) fn restore_project_projection(&mut self, doc: u64) -> bool {
let Some(key) = self.owned_project_key(doc).map(str::to_owned) else { return false; };
if self.project_run_slots.get(&key).and_then(|slot| slot.observed_doc) != Some(doc) { return false; }
let mut slot = self.project_run_slots.remove(&key).unwrap();
slot.swap(self);
true
}
pub(super) fn parked_project_docs(&self, app: &PhotocraftApp) -> Vec<u64> {
app.session.documents().iter().filter_map(|state| {
let doc = state.doc.id.0;
let key = self.owned_project_key(doc)?;
(self.project_run_slots.get(key)?.observed_doc == Some(doc)).then_some(doc)
}).collect()
}
pub(super) fn with_parked_project<T>(
&mut self, app: &mut PhotocraftApp, doc: u64,
action: impl FnOnce(&mut Self, &mut PhotocraftApp) -> T,
) -> Option<T> {
let key = self.owned_project_key(doc)?.to_owned();
let index = app.session.documents().iter().position(|state| state.doc.id.0 == doc)?;
let visible = app.session.active_index()?;
let mut slot = self.project_run_slots.remove(&key)?;
if slot.observed_doc != Some(doc) {
self.project_run_slots.insert(key, slot);
return None;
}
let navigation = (self.library, self.material, self.creation_open, self.creation_step, self.project_view_parked);
let status = (app.ui.status.clone(), app.ui.status_error);
let paths = (app.ui.selected_path.clone(), app.path_document.clone());
self.in_background_project = true;
slot.swap(self);
(self.library, self.material, self.creation_open) = (false, false, false);
app.session.set_active(index);
let result = action(self, app);
app.session.set_active(visible);
slot.swap(self);
self.in_background_project = false;
(self.library, self.material, self.creation_open, self.creation_step, self.project_view_parked) = navigation;
(app.ui.status, app.ui.status_error) = status;
(app.ui.selected_path, app.path_document) = paths;
self.project_run_slots.insert(key, slot);
Some(result)
}
pub(super) fn event_project_doc(&self, event: &Event) -> Option<u64> {
if let Event::Json(method, Err(_)) = event {
if !matches!(method.as_str(), "agent" | "save" | "product-end-checkpoint"
| "creation-facts" | "creation-points" | "creation-plan" | "creation-generate"
| "creation-recover") && !method.starts_with("slot-") { return None; }
let matches = |busy: Option<&str>, saving| busy == Some(method.as_str())
|| method == "agent" && matches!(busy, Some("pi-agent" | "agent-stopping"))
|| method == "save" && saving;
if matches(self.busy.as_deref(), self.saving.is_some()) { return None; }
let mut owners = self.project_run_slots.iter()
.filter(|(key, slot)| key.starts_with(&self.local_identity(""))
&& matches(slot.busy.as_deref(), slot.saving.is_some()))
.filter_map(|(_, slot)| slot.observed_doc);
let owner = owners.next()?;
return owners.next().is_none().then_some(owner);
}
let data = match event {
Event::Saved(doc, _, _) => return Some(*doc),
Event::SlotCanvas(doc, value) | Event::CreationCanvas(doc, value) => {
return value["doc"].as_u64().or(Some(doc.id.0));
}
Event::PiAction(_, value, _) => value,
Event::SlotAdopt { meta, .. } | Event::SlotPreview(meta, _) => meta,
Event::Preview(meta, _) if meta["purpose"] != "project-cover" => meta,
Event::Json(method, Ok(value)) if matches!(method.as_str(),
"agent" | "agent-stream" | "agent-steer" | "agent-abort" | "agent-clear-queue"
| "save" | "metadata-save" | "draft" | "production-deliver-bundle"
| "image" | "image-progress" | "image-recover" | "template-progress"
| "creation-facts" | "creation-points" | "creation-plan" | "creation-generate"
| "creation-recover" | "creation-stream") || method.starts_with("slot-") => value,
_ => return None,
};
let by_doc = data["documentId"].as_u64().or_else(|| data["doc"].as_u64())
.or_else(|| data["scope"]["documentId"].as_u64());
if by_doc.is_some() { return by_doc; }
let run = data["run"].as_str().or_else(|| data["runId"].as_str());
if let Some(run) = run {
if self.pi_run.as_deref() == Some(run) { return self.observed_doc; }
return self.project_run_slots.values().find_map(|slot|
(slot.pi_run.as_deref() == Some(run)).then_some(slot.observed_doc).flatten());
}
let project = data["projectLocalId"].as_str().or_else(|| data["localId"].as_str())
.or_else(|| data["projectId"].as_str())?;
self.project_run_slots.get(&self.local_identity(project))?.observed_doc
}
pub(super) fn project_is_parked(&self, doc: u64) -> bool {
self.owned_project_key(doc).and_then(|key| self.project_run_slots.get(key))
.is_some_and(|slot| slot.observed_doc == Some(doc))
}
pub(super) fn has_project_run_for(&self, doc: u64) -> bool {
self.product_production.as_ref().is_some_and(|run| run.project_identity().0 == doc)
|| self.project_is_parked(doc) && self.owned_project_key(doc).and_then(|key| self.project_run_slots.get(key))
.is_some_and(|slot| slot.product_production.is_some() || slot.pi_run.is_some())
}
pub(super) fn parked_project_needs_tick(&mut self, doc: u64) -> bool {
let Some(key) = self.owned_project_key(doc).map(str::to_owned) else { return false; };
let Some(slot) = self.project_run_slots.get_mut(&key) else { return false; };
let now = Instant::now();
if now < slot.next_background_tick { return false; }
let pending = slot.pending_image.is_some() || !slot.queue.is_empty() || slot.pending_slot_apply.is_some()
|| slot.canvas_workspace.pending_adoption.is_some() || slot.draft_changed
|| slot.product_start_queued || slot.product_export.is_some() || slot.production_stop["state"] == "stopping"
|| slot.product_production.as_ref().is_some_and(Run::needs_background_tick)
|| slot.pi_run.as_deref().is_some_and(|run| slot.agent_native.pending_job(run).is_some());
if pending {
slot.next_background_tick = now + Duration::from_millis(100);
}
pending
}
pub(super) fn revoke_project_slots(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, category: &Value) {
let revoke = |w: &mut Self, app: &mut PhotocraftApp| {
w.with_product_target(app, |w, app| {
w.pause_for_authorization(category);
if let Some(state) = app.session.active().filter(|state| w.loaded_draft == Some(state.doc.id.0)) {
w.save_project_draft(state, ctx);
}
});
};
for doc in self.parked_project_docs(app) {
self.with_parked_project(app, doc, &revoke);
}
revoke(self, app);
}
pub(super) fn parked_production_active(&self) -> bool {
self.project_run_slots.iter().any(|(key, slot)| key.starts_with(&self.local_identity("")) &&
(slot.pi_run.is_some() || slot.saving.is_some() || slot.pending_slot_apply.is_some() || slot.draft_changed
|| slot.product_start_queued || slot.product_export.is_some() || slot.production_stop["state"] == "stopping"
|| slot.product_production.as_ref().is_some_and(Run::is_active)))
}
pub(super) fn project_title(&self, app: &PhotocraftApp, doc: u64, project: &str, context: &Value) -> String {
context["title"].as_str()
.or_else(|| self.projects.iter().find(|row| row["localId"] == project || row["id"] == project)
.and_then(|row| row["title"].as_str()))
.or_else(|| app.session.documents().iter().find(|state| state.doc.id.0 == doc)
.map(|state| state.doc.name.as_str()))
.unwrap_or(project).to_owned()
}
#[allow(dead_code)] // Consumed by the workspace UI in the integration branch.
pub(super) fn multi_project_ui_snapshot(&self, app: &PhotocraftApp) -> MultiProjectUiSnapshot {
let mut global_runs = Vec::new();
let mut add_run = |run: Option<&Run>, context: &Value, busy: Option<&str>, progress: &Value| {
if let Some(run) = run {
let (doc, project) = run.project_identity();
if self.owned_project_key(doc) == Some(project) && self.authority_active() {
let project_id = project.rsplit('|').next().unwrap_or(project);
global_runs.push(run.ui_summary(project_id, self.project_title(app, doc, project_id, context), busy, progress));
}
}
};
add_run(self.product_production.as_ref(), &self.project_context, self.busy.as_deref(), self.workflow.production_progress());
for slot in self.project_run_slots.values() {
add_run(slot.product_production.as_ref(), &slot.project_context, slot.busy.as_deref(), slot.workflow.production_progress());
}
for (summary, context) in std::iter::once((&self.last_production_summary, &self.project_context))
.chain(self.project_run_slots.values().map(|slot| (&slot.last_production_summary, &slot.project_context)))
{
if let Some((doc, status)) = summary
&& let Some(key) = self.owned_project_key(*doc)
&& self.authority_active()
{
let project_id = key.rsplit('|').next().unwrap_or(key);
if global_runs.iter().any(|run| run.project_id == project_id) { continue; }
global_runs.push(ProjectRunSummary {
project_id: project_id.to_owned(), project_title: self.project_title(app, *doc, project_id, context),
status: status.clone(), producing_output_id: None, producing_output_label: String::new(),
progress_label: if *status == ProjectRunVisualStatus::Completed { "已完成".into() } else { "制作已结束".into() },
elapsed_secs: 0, active_slots: 0, has_attention: *status == ProjectRunVisualStatus::Failed,
});
}
}
global_runs.sort_by(|a, b| a.project_id.cmp(&b.project_id));
let active = app.session.active().map(|state| state.doc.id.0)
.filter(|doc| Some(*doc) == self.observed_doc && !self.library && !self.material);
let active_project_id = active.and_then(|doc| self.owned_project_key(doc))
.and_then(|project| project.rsplit('|').next()).map(str::to_owned);
let active_project_title = active.zip(active_project_id.as_deref())
.map_or_else(String::new, |(doc, project)| self.project_title(app, doc, project, &self.project_context));
let producing = global_runs.iter().find(|run| Some(&run.project_id) == active_project_id.as_ref());
let (viewing_output_id, viewing_output_label) = if active.is_some() && !self.creation_open {
product_production::output_display(&self.template_workflow)
} else { (None, String::new()) };
let producing_output_id = producing.and_then(|run| run.producing_output_id.clone());
let producing_output_label = producing.map_or_else(String::new, |run| run.producing_output_label.clone());
MultiProjectUiSnapshot {
global_runs,
max_concurrent: 1,
active_project_id,
active_project_title,
active_section: if self.library || self.material || active.is_none() { WorkspaceSectionKind::Projects }
else if self.creation_open { WorkspaceSectionKind::Brief } else { WorkspaceSectionKind::Canvas },
viewing_differs_from_producing: viewing_output_id.is_some() && producing_output_id.is_some()
&& viewing_output_id != producing_output_id,
viewing_output_id, viewing_output_label, producing_output_id, producing_output_label,
}
}
#[allow(dead_code)]
pub(super) fn focus_project_by_id(&mut self, app: &mut PhotocraftApp, project_id: &str) {
if !self.authority_active() { return; }
if let Some(index) = self.open_project_index(app, project_id) {
self.activate_project_tab(app, index);
}
}
#[allow(dead_code)]
pub(super) fn pause_project_run(&mut self, app: &mut PhotocraftApp, project_id: &str) {
if !self.authority_active() { return; }
let Some(index) = self.open_project_index(app, project_id) else { return; };
let doc = app.session.documents()[index].doc.id.0;
let pause = |w: &mut Workspace| {
if let Err(error) = w.request_production_stop("pause", "用户手动暂停") { w.error = error; }
};
if self.observed_doc == Some(doc) {
pause(self);
} else {
self.with_parked_project(app, doc, |w, _| pause(w));
}
}
#[allow(dead_code)]
pub(super) fn jump_to_producing_output(&mut self, app: &mut PhotocraftApp) {
let Some(output) = self.product_production.as_ref().and_then(Run::working_output) else { return; };
match self.request_product_view(app, &output) {
Ok(_) => {
self.show_center(CenterView::Canvas, true);
self.creation_open = false;
}
Err(error) => self.error = error,
}
}
}

View File

@ -1,3 +1,4 @@
use super::multi_project_state::{ProjectRunSummary, ProjectRunVisualStatus};
use super::{Document, PhotocraftApp, Request, Value, Workspace, canvas_workspace, json};
use photocraft_doc::LayerId;
use photocraft_engine::DocState;
@ -309,12 +310,15 @@ impl Workspace {
}
pub(super) fn with_product_target<T>(&mut self, app: &mut PhotocraftApp, action: impl FnOnce(&mut Self, &mut PhotocraftApp) -> T) -> T {
let Some(mut worker) = self.product_views.worker.take() else { return action(self, app); };
if !app.session.active().is_some_and(|state| state.doc.id == worker.document.doc.id)
|| self.open_projects.get(&worker.document.doc.id.0).is_none_or(|project| !project.starts_with(&self.local_identity("")))
let Some(worker) = self.product_views.worker.as_ref() else { return action(self, app); };
let doc = worker.document.doc.id;
let Some(project) = self.owned_project_key(doc.0) else { return action(self, app); };
if app.session.active().is_none_or(|state| state.doc.id != doc)
|| self.product_production.as_ref().is_some_and(|run| run.project_identity() != (doc.0, project))
{
return action(self, app);
}
let mut worker = self.product_views.worker.take().unwrap();
// The native tab ID is shared, but its camera belongs to the mounted output.
worker.swap(self, app);
worker.swap_camera(app);
@ -633,14 +637,13 @@ impl Workspace {
let _timing = crate::operation_timer::OperationTimer::new(
"product.switch_view", app.session.active().map(|state| state.doc.as_ref()), true,
);
self.preload_product_outputs(app);
if !self.in_background_project { self.preload_product_outputs(app); }
if self.product_views.saving.is_some() || app.saving() { return; }
if let Some(meta) = self.product_views.waiting_stage.take() {
if self.join_product_view(app, &meta) { return; }
}
let Some(active) = app.session.active() else { self.product_views.clear(); return; };
if self.product_views.worker.as_ref().is_some_and(|worker| worker.document.doc.id != active.doc.id) {
self.product_views.clear();
return;
}
if (self.product_view_detached() || self.product_view_pending())
@ -801,7 +804,6 @@ pub(super) struct Run {
workspace: Value,
stages: Vec<Stage>,
total: usize,
completed: usize,
goal_user_entry: Option<String>,
reset_goal: bool,
phase: Phase,
@ -826,6 +828,7 @@ pub(super) struct Run {
delivery_receipt: Value,
delivery_cancellation: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
delivery_write_epoch: Option<u64>,
all_outputs_completed: bool,
restarted: bool,
}
@ -879,14 +882,14 @@ impl Run {
goal_user_entry: Option<String>, phase: Phase) -> Self {
let started_at = production_time();
let paused_at = matches!(phase, Phase::Paused(_)).then_some(started_at);
Self { doc, project, workspace, total: stages.len(), requested_outputs: stages.iter().cloned().collect(), stages, completed: 0,
Self { doc, project, workspace, total: stages.len(), requested_outputs: stages.iter().cloned().collect(), stages,
goal_user_entry, reset_goal: false, bound: None, opening: None, previous_save: Value::Null, session_epoch: None,
finish: None, finish_receipt: Value::Null, phase, drafts: Vec::new(),
deferred_images: HashMap::new(), deferred_image_due: HashMap::new(), deferred_image_stopped: HashSet::new(),
deferred_image_in_flight: Vec::new(),
started_at, paused_at, paused_seconds: 0, restarted: false,
delivery_dir: None, delivery_id: None, published: Vec::new(), delivery_receipt: Value::Null,
delivery_cancellation: None, delivery_write_epoch: None }
delivery_cancellation: None, delivery_write_epoch: None, all_outputs_completed: false }
}
}
@ -918,7 +921,96 @@ fn production_time() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()
}
fn output_has_no_missing_images(output: &Value) -> bool {
match &output["missingImages"] {
Value::Array(rows) => rows.is_empty(),
Value::Number(count) => count.as_u64() == Some(0),
Value::Null => true,
_ => false,
}
}
fn output_has_passed_reviews(output: &Value) -> bool {
let summary = &output["progressSummary"];
summary.is_object() && ["unfilledImageSlots", "unreviewedScreens", "screensWithOpenIssues"]
.iter().all(|key| summary[*key].as_array().is_none_or(Vec::is_empty))
&& output["issues"].as_array().is_none_or(Vec::is_empty)
}
pub(super) fn output_display(workflow: &Value) -> (Option<String>, String) {
let id = workflow["outputId"].as_str().or_else(|| workflow["component"].as_str());
let label = id.map(|output| Stage { output: output.to_owned(), variant: String::new() }.label().to_owned())
.unwrap_or_default();
(id.map(str::to_owned), label)
}
impl Run {
pub(super) fn project_identity(&self) -> (u64, &str) { (self.doc, &self.project) }
pub(super) fn is_active(&self) -> bool { !matches!(self.phase, Phase::Paused(_)) }
pub(super) fn needs_background_tick(&self) -> bool {
self.is_active() && self.phase != Phase::DeliveringBundle
}
pub(super) fn ui_summary(
&self, project_id: &str, project_title: String, busy: Option<&str>, progress: &Value,
) -> ProjectRunSummary {
let status = if self.finish_receipt["finalized"] == true {
if self.finish_receipt["completed"] == true { ProjectRunVisualStatus::Completed }
else if !self.published.is_empty() { ProjectRunVisualStatus::PartialDelivered }
else { ProjectRunVisualStatus::Failed }
} else if let Phase::Paused(pause) = &self.phase {
if pause["partialDelivered"] == true {
ProjectRunVisualStatus::PartialDelivered
} else { ProjectRunVisualStatus::Paused }
} else if busy.is_none() && matches!(self.phase, Phase::AwaitingSave | Phase::AgentRetryAt(_)) {
ProjectRunVisualStatus::Queued
} else { ProjectRunVisualStatus::Running };
let (producing_output_id, producing_output_label) = self.bound.as_ref().or(self.opening.as_ref())
.map_or((None, String::new()), |stage| (Some(stage.output.clone()), stage.label().to_owned()));
ProjectRunSummary {
project_id: project_id.to_owned(), project_title, producing_output_id, producing_output_label,
active_slots: if status == ProjectRunVisualStatus::Running {
progress["workers"].as_array().into_iter().flatten().filter(|row| row["active"] == true).count()
} else { 0 },
has_attention: matches!(status, ProjectRunVisualStatus::Paused | ProjectRunVisualStatus::PartialDelivered
| ProjectRunVisualStatus::Failed) || self.waiting_for_originals(),
progress_label: match status {
ProjectRunVisualStatus::PartialDelivered => "部分交付".into(),
ProjectRunVisualStatus::Completed => "已完成".into(),
ProjectRunVisualStatus::Failed => "制作已结束".into(),
_ => self.progress_label().unwrap_or_default(),
},
elapsed_secs: self.elapsed().as_secs(),
status,
}
}
fn delivery_completed(&self, known_issues: &Value) -> bool {
self.all_outputs_completed && self.published.len() == self.total
&& self.stages.is_empty() && self.drafts.is_empty()
&& self.published.iter().all(|row| output_has_no_missing_images(row) && output_has_passed_reviews(row))
&& known_issues.as_array().is_none_or(Vec::is_empty)
}
fn prepare_partial_continuation(&mut self) {
for stage in &self.requested_outputs {
if !self.stages.contains(stage) && !self.published.iter().any(|row|
Stage::read(row).as_ref() == Some(stage) && output_has_no_missing_images(row) && output_has_passed_reviews(row))
{
self.stages.push(stage.clone());
}
}
if self.stages.is_empty() {
self.stages.clone_from(&self.requested_outputs);
}
self.delivery_id = None;
self.finish = None;
self.finish_receipt = Value::Null;
self.pause(json!({"reason":"已保存部分成果,可继续补齐制作","partialDelivered":true}));
}
fn pause(&mut self, reason: Value) {
self.paused_at.get_or_insert_with(production_time);
self.phase = Phase::Paused(reason);
@ -1096,7 +1188,7 @@ impl Run {
}
fn current(&self, w: &Workspace, app: &PhotocraftApp) -> bool {
app.session.active().is_some_and(|state| state.doc.id.0 == self.doc)
app.session.documents().iter().any(|state| state.doc.id.0 == self.doc)
&& w.open_projects.get(&self.doc) == Some(&self.project)
&& self.project.starts_with(&w.local_identity(""))
&& w.template_workflow["workspaceId"] == self.workspace
@ -1116,6 +1208,7 @@ impl Workspace {
run.total += run.drafts.len();
self.product_views.user_layers.clear();
self.product_views.editor_basis = None;
self.last_production_summary = None;
self.product_production = Some(run);
self.checkpoint_production();
}
@ -1124,6 +1217,7 @@ impl Workspace {
let project = run.project.rsplit('|').next().unwrap_or_default();
let mut checkpoint = json!({
"deliveryDir":run.delivery_dir,"deliveryId":run.delivery_id,"published":run.published,
"allOutputsCompleted":run.all_outputs_completed,
"productionDelivery":run.delivery_receipt,"knownIssues":run.finish_receipt["knownIssues"],
"deliveryReason":run.finish_receipt["deliveryReason"],
"active":active,"project":project,"workspaceId":run.workspace,"startedAt":run.started_at,
@ -1140,6 +1234,7 @@ impl Workspace {
checkpoint["phase"] = json!("paused");
checkpoint["reason"] = pause["reason"].clone();
checkpoint["requiredAction"] = pause["requiredAction"].clone();
checkpoint["partialDelivered"] = pause["partialDelivered"].clone();
}
let waiting = Self::production_waiting_originals(&run.phase);
if waiting.is_object() {
@ -1177,10 +1272,7 @@ impl Workspace {
pub(super) fn begin_production_exit(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
if self.production_exit.is_some() { return true; }
let draft = self.with_product_target(app, |w, app| app.session.active()
.filter(|state| w.loaded_draft == Some(state.doc.id.0))
.map(|state| (state.doc.id.0, w.draft_changed || w.creation_dirty
|| w.persisted_revisions.get(&state.doc.id.0) != Some(&state.revision))));
let draft = self.exit_draft_target(app);
let dirty_tabs = app.session.documents().iter().any(|state| state.is_dirty()
&& self.open_projects.contains_key(&state.doc.id.0));
if self.exit_admission_closed.load(Ordering::Acquire)
@ -1191,10 +1283,34 @@ impl Workspace {
return false;
}
self.exit_admission_closed.store(true, Ordering::Release);
self.cancel_deferred_image_recovery();
let deadline = Instant::now() + Duration::from_secs(90);
let daemon = self.prepare_daemon_exit.as_ref().map(|prepare| prepare());
let composers = self.save_exit_composers(ctx);
for doc in self.parked_project_docs(app) {
self.with_parked_project(app, doc, |w, app| {
let draft = w.exit_draft_target(app);
w.begin_project_exit(app, deadline, draft, None, None);
});
}
self.begin_project_exit(app, deadline, draft, daemon, composers);
app.ui.status = "正在保存小壹制作进度…".into();
app.ui.status_error = false;
ctx.request_repaint();
true
}
fn exit_draft_target(&mut self, app: &mut PhotocraftApp) -> Option<(u64, bool)> {
self.with_product_target(app, |w, app| app.session.active()
.filter(|state| w.loaded_draft == Some(state.doc.id.0))
.map(|state| (state.doc.id.0, w.draft_changed || w.creation_dirty
|| w.persisted_revisions.get(&state.doc.id.0) != Some(&state.revision))))
}
fn begin_project_exit(
&mut self, app: &mut PhotocraftApp, deadline: Instant, draft: Option<(u64, bool)>,
daemon: Option<super::ExitReceipt>, composers: Option<super::ExitReceipt>,
) {
self.cancel_deferred_image_recovery();
let delivering = self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle);
let ending = self.busy.as_deref() == Some("product-end-checkpoint");
let run = if delivering { None } else { self.product_production.take() };
@ -1224,8 +1340,7 @@ impl Workspace {
self.production_exit_state = Some(ExitState { run, checkpoint: std::mem::take(&mut self.product_checkpoint) });
let checkpoint = if let Some(mut input) = input {
input["checkpoint"]["status"] = json!("paused_on_exit");
self.tx.send(Request::Action("product-exit-checkpoint".into(), input)).err()
.map(|_| Err("本机制作记录保存服务已断开".into()))
self.send_exit_checkpoint(input)
} else { Some(Ok(())) };
self.production_exit = Some(PendingExit {
draft: draft.map(|(id, _)| id),
@ -1236,10 +1351,16 @@ impl Workspace {
save_error: None,
save_requested: false,
});
app.ui.status = "正在保存小壹制作进度…".into();
app.ui.status_error = false;
ctx.request_repaint();
true
}
// The host writes these checkpoints serially and returns untagged acknowledgements.
fn send_exit_checkpoint(&mut self, input: Value) -> Option<Result<(), String>> {
let owner = self.in_background_project.then_some(self.observed_doc).flatten();
if self.tx.send(Request::Action("product-exit-checkpoint".into(), input)).is_err() {
return Some(Err("本机制作记录保存服务已断开".into()));
}
self.exit_checkpoint_owners.push_back(owner);
None
}
pub(super) fn restore_cancelled_exit(&mut self) {
@ -1259,18 +1380,24 @@ impl Workspace {
pub(super) fn advance_production_exit(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) {
let Some(exit) = &self.production_exit else { return };
if self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle) {
return;
}
let remaining = exit.deadline.saturating_duration_since(Instant::now());
let result = if remaining.is_zero() {
Some(Err("退出等待超时,保存结果未确认".to_owned()))
Err("退出等待超时,保存结果未确认".to_owned())
} else {
ctx.request_repaint_after(remaining);
let view = self.flush_exit_view(app);
self.with_product_target(app, Workspace::flush_exit_draft).map(|draft| draft.and(view))
let mut pending = false;
let mut error = None;
for doc in self.parked_project_docs(app) {
match self.with_parked_project(app, doc, Workspace::poll_project_exit).flatten() {
None => pending = true,
Some(Err(reason)) => { error.get_or_insert(reason); }
Some(Ok(())) => {}
}
}
if pending { return; }
let Some(result) = self.poll_project_exit(app) else { return; };
error.map_or(result, Err)
};
let Some(result) = result else { return };
self.production_exit = None;
if let Err(error) = result {
log::warn!("小壹退出前保存未确认:{error}");
@ -1280,6 +1407,14 @@ impl Workspace {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
fn poll_project_exit(&mut self, app: &mut PhotocraftApp) -> Option<Result<(), String>> {
if self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle) {
return None;
}
let view = self.flush_exit_view(app);
self.with_product_target(app, Workspace::flush_exit_draft).map(|draft| draft.and(view))
}
fn flush_exit_view(&mut self, app: &PhotocraftApp) -> Result<(), String> {
// The editable view may be on another output of the same project.
// Preserve its own draft before briefly swapping in the working canvas.
@ -1320,7 +1455,7 @@ impl Workspace {
}
}
}
if self.production_exit.as_ref()?.save_error.is_none() {
if !self.in_background_project && self.production_exit.as_ref()?.save_error.is_none() {
let draft = app.session.documents().iter().find(|state| {
let id = state.doc.id.0;
state.is_dirty() && self.persisted_revisions.get(&id) != Some(&state.revision)
@ -1476,6 +1611,9 @@ impl Workspace {
run.paused_at.get_or_insert_with(production_time);
let waiting = Self::production_waiting_originals(&run.phase);
run.cancel_deferred_image_recovery();
if let Some(cancellation) = run.delivery_cancellation.take() {
cancellation.store(true, Ordering::Release);
}
run.phase = Phase::Paused(json!({"reason":category,"requiredAction":REAUTHORIZE,"waitingOriginals":waiting}));
self.write_production_checkpoint(run, true);
} else if self.product_checkpoint["active"] == true || self.product_checkpoint["phase"] == "paused" {
@ -1576,7 +1714,8 @@ impl Workspace {
.into_iter().flatten().filter_map(Stage::read).collect();
let checkpoint = std::mem::take(&mut self.product_checkpoint);
let mut stages: Vec<_> = checkpoint["stages"].as_array().into_iter().flatten()
.filter_map(Stage::read).filter(|stage| remaining.contains(stage)).collect();
.filter_map(Stage::read)
.filter(|stage| checkpoint["partialDelivered"] == true || remaining.contains(stage)).collect();
if checkpoint["status"] == "paused_on_exit" {
for stage in self.template_workflow["productionStages"].as_array().into_iter().flatten().filter_map(Stage::read) {
if !stages.contains(&stage) && checkpoint["published"].as_array().into_iter().flatten().any(|row|
@ -1594,7 +1733,7 @@ impl Workspace {
&canvas.doc, &self.template_workflow, &stage.output, &stage.variant));
let phase = if paused {
Phase::Paused(json!({"reason":checkpoint["reason"],"requiredAction":checkpoint["requiredAction"],
"waitingOriginals":checkpoint["waitingOriginals"]}))
"waitingOriginals":checkpoint["waitingOriginals"],"partialDelivered":checkpoint["partialDelivered"]}))
} else { Self::production_resume_phase(&checkpoint["waitingOriginals"]) };
let mut run = Run::new(doc, project, workspace, stages, None, phase);
run.bound = bound;
@ -1616,6 +1755,7 @@ impl Workspace {
run.delivery_dir = delivery_dir(&checkpoint);
run.delivery_id = checkpoint["deliveryId"].as_str().map(str::to_owned);
run.delivery_receipt = checkpoint["productionDelivery"].clone();
run.all_outputs_completed = checkpoint["allOutputsCompleted"] == true;
run.finish_receipt["knownIssues"] = checkpoint["knownIssues"].clone();
run.finish_receipt["deliveryReason"] = checkpoint["deliveryReason"].clone();
run.published = checkpoint["published"].as_array().cloned().unwrap_or_default();
@ -1624,7 +1764,6 @@ impl Workspace {
}
run.drafts = checkpoint["drafts"].as_array().cloned().unwrap_or_default();
run.total = checkpoint["total"].as_u64().unwrap_or(run.total as u64) as usize;
run.completed = run.published.len();
run.restore_deferred_images(&checkpoint);
Self::seed_deferred_images(&mut run, &self.template_workflow);
if !paused && run.stages.is_empty() && run.delivery_id.is_none() {
@ -1988,6 +2127,11 @@ impl Workspace {
}
let current = self.product_production.as_ref().is_some_and(|run| run.current(self, app));
if !current {
if self.product_production.as_ref().is_some_and(|run|
app.session.documents().iter().any(|state| state.doc.id.0 == run.doc))
{
return;
}
self.product_production = None;
self.product_export = None;
if matches!(self.production_stop["state"].as_str(), Some("stopping" | "delivering")) {
@ -1996,6 +2140,8 @@ impl Workspace {
}
return;
}
if self.product_production.as_ref().is_none_or(|run|
app.session.active().is_none_or(|state| state.doc.id.0 != run.doc)) { return; }
if self.production_stop["state"] == "stopping" {
self.settle_production_stop(app);
return;
@ -2107,6 +2253,7 @@ impl Workspace {
run.finish = Some(finish);
run.phase = Phase::Export;
if export {
run.all_outputs_completed = false;
let mut request = input.clone();
request["workspaceId"] = run.workspace.clone();
if !stopped {
@ -2130,6 +2277,9 @@ impl Workspace {
if let Some(finish) = run.finish.as_mut().filter(|finish| finish["deliveryReason"].is_string()) {
finish["issues"] = value["issues"].clone();
}
if let Some(complete) = value["allOutputsCompleted"].as_bool() {
run.all_outputs_completed = complete;
}
if let Some(generation) = value["generationId"].as_str()
&& value["files"].as_array().is_some_and(|files| !files.is_empty()) {
run.clear_deferred(&stage);
@ -2139,9 +2289,9 @@ impl Workspace {
run.published.push(json!({"outputId":stage.output,"variantId":stage.variant,
"generationId":generation,"progressSummary":run.finish.as_ref().map(|finish| &finish["progressSummary"]),
"missingImages":value["missingImages"],
"allOutputsCompleted":value["allOutputsCompleted"],
"issues":run.finish.as_ref().map(|finish| &finish["issues"])}));
run.completed = run.published.len();
run.delivery_id = None;
run.delivery_id = None;
} else if value["stageStatus"] == "hard-blocked" {
run.clear_deferred(&stage);
let mut draft = value.clone();
@ -2172,11 +2322,13 @@ impl Workspace {
if let Some(summary) = finish.get("progressSummary") {
receipt["progressSummary"] = summary.clone();
}
receipt["complete"] = json!(receipt["generationId"].is_string());
receipt["complete"] = json!(receipt["generationId"].is_string()
&& run.published.last().is_some_and(output_has_no_missing_images));
receipt["allOutputsCompleted"] = json!(run.all_outputs_completed);
receipt["pendingOutputs"] = run.pending_outputs();
receipt["published"] = json!(run.published);
receipt["drafts"] = json!(run.drafts);
receipt["completed"] = json!(run.completed == run.total);
let stopped = finish["deliveryReason"].is_string();
receipt["deliveryReason"] = finish["deliveryReason"].clone();
let finalize = finish["all"] == true && (stopped || run.stages.is_empty() && !receipt["error"].is_string());
@ -2228,7 +2380,8 @@ impl Workspace {
receipt["pendingScreenReviews"] = json!(pending_reviews);
receipt["knownIssues"] = json!(known_issues);
}
receipt["finalized"] = json!(finalize && !stopped && (run.delivery_dir.is_none() || run.completed == 0));
receipt["completed"] = json!(run.delivery_completed(&receipt["knownIssues"]));
receipt["finalized"] = json!(finalize && !stopped && (run.delivery_dir.is_none() || run.published.is_empty()));
run.phase = Phase::Agent;
if self.pi_run.is_some() { self.busy = Some("pi-agent".into()); }
run.finish_receipt = receipt;
@ -2242,7 +2395,7 @@ impl Workspace {
}
fn finish_production_outputs(&mut self, mut run: Run) {
if !run.finish_receipt["deliveryReason"].is_string() && (run.delivery_dir.is_none() || run.completed == 0) {
if !run.finish_receipt["deliveryReason"].is_string() && (run.delivery_dir.is_none() || run.published.is_empty()) {
self.note_production_summary(run);
return;
}
@ -2251,11 +2404,6 @@ impl Workspace {
self.complete_production_bundle(run);
return;
}
if run.published.len() != run.completed {
run.delivery_receipt = json!({"state":"failed","error":"本轮部分成品缺少已验证的版本记录"});
self.complete_production_bundle(run);
return;
}
let id = run.delivery_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone();
let cancellation = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
run.delivery_cancellation = Some(cancellation.clone());
@ -2298,9 +2446,6 @@ impl Workspace {
let delivered = run.delivery_receipt["path"].is_string();
self.production_stop["state"] = json!(if delivered {"delivered"} else {"failed"});
self.production_stop["error"] = run.delivery_receipt["error"].clone();
if let Some(completed) = run.delivery_receipt["completedOutputs"].as_u64() {
run.completed = completed as usize;
}
if !delivered {
run.pause(json!({"reason":run.delivery_receipt["error"]}));
run.finish = None;
@ -2309,12 +2454,13 @@ impl Workspace {
return;
}
}
let delivered = run.delivery_receipt["path"].is_string();
run.all_outputs_completed = run.delivery_receipt["allOutputsCompleted"] == true;
run.finish_receipt["completed"] = json!(delivered && run.delivery_completed(&run.finish_receipt["knownIssues"]));
if run.finish.take().is_some() && self.pi_run.is_some() && self.production_exit.is_none() {
run.phase = Phase::Agent;
run.finish_receipt["productionDelivery"] = run.delivery_receipt.clone();
let delivered = run.delivery_receipt["path"].is_string();
run.finish_receipt["finalized"] = json!(delivered);
run.finish_receipt["completed"] = json!(delivered && run.completed == run.total);
if !delivered { run.finish_receipt["error"] = run.delivery_receipt["error"].clone(); }
self.product_production = Some(run);
self.checkpoint_production();
@ -2323,12 +2469,22 @@ impl Workspace {
}
}
fn note_production_summary(&mut self, run: Run) {
if let Some(exit) = &mut self.production_exit {
exit.checkpoint = self.tx.send(Request::Action("product-exit-checkpoint".into(), Self::production_checkpoint_request(&run, false)))
.err().map(|_| Err("本机制作记录保存服务已断开".into()));
fn note_production_summary(&mut self, mut run: Run) {
let complete = run.delivery_completed(&run.finish_receipt["knownIssues"]);
let partial = !complete && (!run.published.is_empty() || run.delivery_receipt["path"].is_string());
if partial {
run.prepare_partial_continuation();
}
let status = if complete { ProjectRunVisualStatus::Completed } else if partial {
ProjectRunVisualStatus::PartialDelivered
} else { ProjectRunVisualStatus::Failed };
self.last_production_summary = Some((run.doc, status));
if self.production_exit.is_some() {
let checkpoint = self.send_exit_checkpoint(Self::production_checkpoint_request(&run, partial));
self.production_exit.as_mut().unwrap().checkpoint = checkpoint;
} else {
self.write_production_checkpoint(&run, false);
self.write_production_checkpoint(&run, partial);
}
let mut coverage = [0u64; 3];
for output in run.published.iter().chain(&run.drafts) {
@ -2344,12 +2500,14 @@ impl Workspace {
let coverage = json!({"total":coverage[0],"preview":coverage[1],"empty":coverage[2]});
let mut text = if let Some(label) = slot_coverage_label(&coverage) {
label
} else if run.finish_receipt["deliveryReason"].is_string() && run.completed == run.total {
} else if run.finish_receipt["deliveryReason"].is_string() && complete {
format!("{},已交付 {} 份当前成果。", run.finish_receipt["deliveryReason"].as_str().unwrap_or_default(), run.total)
} else if run.completed == run.total {
} else if complete {
format!("整套制作完成 · {} 份可编辑画布与 JPG 已保存", run.total)
} else if partial {
format!("已保存 {} 份阶段成果,可继续补齐制作。", run.published.len())
} else {
format!("本轮已交付 {}/{} 份,还有 {} 份待完成。已有编辑已保存。", run.completed, run.total, run.total.saturating_sub(run.completed))
"本轮制作已结束,已有编辑已保存。".into()
};
let receipt = &run.delivery_receipt;
if let Some(path) = receipt["path"].as_str() {
@ -2364,8 +2522,9 @@ impl Workspace {
}
self.messages.push(json!({"role":"assistant","kind":"reply","text":text,
"productionDelivery":receipt,
"productionSummary":{"exported":run.completed,"total":run.total,"drafts":run.drafts,"slotCoverage":coverage}}));
"productionSummary":{"exported":receipt["completedOutputs"].as_u64().unwrap_or(run.published.len() as u64),"total":run.total,"drafts":run.drafts,"slotCoverage":coverage}}));
self.draft_changed = true;
if partial { self.product_production = Some(run); }
}
pub(super) fn cancel_deferred_image_recovery(&mut self) {
@ -2715,14 +2874,14 @@ mod tests {
run.published = vec![json!({"outputId":"detail","variantId":"wood","generationId":"export",
"progressSummary":{"unreviewedScreens":[{"page":1,"pageId":"S01"}],
"screensWithOpenIssues":[{"page":2,"name":"规格","issues":[{"issue":"尺寸线悬空"}]}]}})];
run.completed = 1;
run.total = 1;
run.all_outputs_completed = true;
run.finish = Some(json!({"operationId":"first","all":true,"issues":[{"reason":"规格待确认"}]}));
workspace.product_production = Some(run);
workspace.complete_production_export(json!({}));
let delivered = workspace.production_finish_status("first");
assert_eq!(delivered["finalized"], true);
assert_eq!(delivered["completed"], true);
assert_eq!(delivered["completed"], false);
assert_eq!(delivered["pendingScreenReviews"], json!([
{"outputId":"detail","variantId":"wood","page":1,"pageId":"S01","state":"unreviewedScreens"},
{"outputId":"detail","variantId":"wood","page":2,"name":"规格","state":"screensWithOpenIssues",
@ -2731,6 +2890,121 @@ mod tests {
assert_eq!(delivered["knownIssues"], json!([{"reason":"规格待确认"}]));
}
#[test]
fn partial_bundle_preserves_the_directory_and_restores_continuation() {
let (tx, _) = mpsc::channel();
let (_, rx) = mpsc::channel();
let mut w = Workspace::new(tx, rx);
let stage = Stage { output:"detail".into(), variant:"wood".into() };
let mut run = Run::new(1, "project".into(), json!("workspace"), vec![stage.clone()], None, Phase::DeliveringBundle);
run.stages.clear();
run.published.push(json!({"outputId":"detail","variantId":"wood","generationId":"saved-version",
"missingImages":[],"progressSummary":{"unreviewedScreens":[],"screensWithOpenIssues":[]}}));
run.delivery_receipt = json!({"path":"阶段成果","allOutputsCompleted":false,"completedOutputs":1});
w.complete_production_bundle(run);
let run = w.product_production.as_ref().unwrap();
assert!(w.has_paused_production());
assert!(run.stages == [stage]);
assert_eq!(run.published[0]["generationId"], "saved-version");
assert_eq!(run.delivery_receipt["path"], "阶段成果");
assert_eq!(run.ui_summary("project", "项目".into(), None, &Value::Null).status, ProjectRunVisualStatus::PartialDelivered);
assert_eq!(Workspace::production_checkpoint_request(run, true)["checkpoint"]["phase"], "paused");
}
#[test]
fn switching_projects_routes_save_and_stream_and_checkpoints_both_runs_on_exit() {
use super::super::Event;
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"name":"项目甲","width":40,"height":50})).unwrap();
session.execute("file.new", json!({"name":"项目乙","width":40,"height":50})).unwrap();
session.set_active(0);
let mut app = PhotocraftApp::new(session, crate::Services::default());
let first = app.session.documents()[0].doc.id.0;
let second = app.session.documents()[1].doc.id.0;
let (tx, requests) = mpsc::channel();
let (events, rx) = mpsc::channel();
let mut w = Workspace::new(tx, rx);
requests.try_recv().unwrap();
w.account = json!({"id":"owner"});
w.library = false;
w.busy = Some("pi-agent".into());
w.observed_doc = Some(first);
w.loaded_draft = Some(first);
w.owner_doc = Some(first);
w.pi_run = Some("first-run".into());
w.pi_binding = json!({"accountId":"owner","origin":w.origin});
w.pi_native = true;
w.write_epoch = 31;
w.saving = Some((first, 4));
w.template_workflow = json!({"workspaceId":"workspace-a","outputId":"detail","variantId":"wood"});
let stage = Stage { output:"sku_images".into(), variant:"wood".into() };
for (doc, project) in [(first, "a"), (second, "b")] {
w.open_projects.insert(doc, w.local_identity(project));
}
let mut run = Run::new(first, w.local_identity("a"), json!("workspace-a"), vec![stage.clone()], None, Phase::Agent);
run.bound = Some(stage.clone());
w.product_production = Some(run);
let snapshot = w.multi_project_ui_snapshot(&app);
assert!(snapshot.viewing_differs_from_producing);
assert_eq!(snapshot.producing_output_id.as_deref(), Some("sku_images"));
w.focus_project_by_id(&mut app, "b");
assert_eq!(app.session.active().unwrap().doc.id.0, second);
assert!(!w.pi_native);
app.session.execute("layer.new.layer", json!({"name":"乙的手工修改"})).unwrap();
w.template_workflow = json!({"workspaceId":"workspace-b","outputId":"detail","variantId":"wood"});
w.product_production = Some(Run::new(second, w.local_identity("b"), json!("workspace-b"), vec![stage], None, Phase::Agent));
let (reply, result) = mpsc::channel();
events.send(Event::PiAction("pi-delta".into(), json!({"run":"first-run","text":"后台进度"}), reply)).unwrap();
events.send(Event::Saved(first, 4, json!({"localId":"a"}))).unwrap();
let ctx = egui::Context::default();
let _ = ctx.run_logic(&Default::default(), |ctx| w.tick(&mut app, ctx));
assert!(result.try_recv().unwrap().is_ok());
assert_eq!(app.session.active().unwrap().doc.id.0, second);
assert!(w.stream_reply.is_empty());
assert_eq!(w.multi_project_ui_snapshot(&app).global_runs.len(), 2);
w.with_parked_project(&mut app, first, |w, _| {
assert_eq!(w.stream_reply, "后台进度");
assert!(w.pi_native);
assert_eq!(w.write_epoch, 31);
assert_eq!(w.persisted_revisions.get(&first), Some(&4));
assert!(w.saving.is_none() && w.product_production.is_some());
}).unwrap();
app.explicit_exit = true;
let _ = ctx.run_logic(&Default::default(), |ctx| assert!(w.begin_production_exit(&mut app, ctx)));
let checkpoints: HashSet<_> = requests.try_iter().filter_map(|request| match request {
Request::Action(method, input) if method == "product-exit-checkpoint" => {
assert_eq!(input["checkpoint"]["status"], "paused_on_exit");
input["doc"].as_u64()
}
_ => None,
}).collect();
assert_eq!(checkpoints, HashSet::from([first, second]));
}
#[test]
fn an_unrelated_tab_cannot_take_the_hidden_worker() {
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width":40,"height":50})).unwrap();
let worker = session.active().unwrap().clone();
session.execute("file.new", json!({"width":40,"height":50})).unwrap();
let mut app = PhotocraftApp::new(session, crate::Services::default());
let (tx, _) = mpsc::channel();
let (_, rx) = mpsc::channel();
let mut w = Workspace::new(tx, rx);
w.open_projects.insert(worker.doc.id.0, w.local_identity("project"));
w.product_views.worker = Some(Canvas {
document: worker.clone(), workflow: Value::Null, workspace: Default::default(), camera: None,
});
w.with_product_target(&mut app, |w, app| {
assert!(!w.product_target_hidden);
assert_ne!(app.session.active().unwrap().doc.id, worker.doc.id);
});
assert_eq!(w.product_views.worker.as_ref().unwrap().document.doc.id, worker.doc.id);
}
#[test]
fn last_output_dispatches_the_bundle_and_exit_waits_for_its_scoped_receipt() {
let mut session = photocraft_engine::Session::new();
@ -2770,7 +3044,7 @@ mod tests {
assert_eq!(request["deliveryDir"], w.product_production.as_ref().unwrap().delivery_dir.as_deref().unwrap());
assert_eq!(w.product_production.as_ref().unwrap().progress_label().as_deref(), Some("正在保存成品到指定目录"));
let mut receipt = json!({"doc":doc,"deliveryId":request["deliveryId"],"writeEpoch":request["writeEpoch"],
"accountEpoch":1,"productionDelivery":{"state":"bundle_saved","path":request["deliveryDir"],
"accountEpoch":1,"productionDelivery":{"state":"bundle_saved","path":request["deliveryDir"],"allOutputsCompleted":true,
"counts":{"工程文件":4,"PSD":3,"详情页长图":1,"详情页切片":2,"主图":2,"SKU":1}}});
w.production_bundle_received(&receipt);
assert!(w.product_production.is_some(), "old account receipt must be ignored");
@ -2845,12 +3119,13 @@ mod tests {
let mut run = Run::new(doc, project, json!("workspace"), vec![], None, Phase::DeliveringBundle);
run.total = 3;
run.completed = 3;
run.published = ["detail", "main_images", "sku_images"].into_iter().map(|output|
json!({"outputId":output,"variantId":"wood","generationId":output,"progressSummary":{}})).collect();
run.delivery_id = Some("delivered".into());
run.delivery_write_epoch = Some(w.write_epoch);
w.product_production = Some(run);
w.production_bundle_received(&json!({"doc":doc,"deliveryId":"delivered","writeEpoch":w.write_epoch,
"accountEpoch":w.accepted_account_epoch,"productionDelivery":{"state":"bundle_saved","path":"成品"}}));
"accountEpoch":w.accepted_account_epoch,"productionDelivery":{"state":"bundle_saved","path":"成品","allOutputsCompleted":true}}));
assert!(w.product_production.is_none());
assert_eq!(w.messages.last().unwrap()["productionSummary"]["exported"], 3);
assert!(matches!(requests.try_recv().unwrap(), Request::Action(method, input)
@ -3063,7 +3338,7 @@ mod tests {
assert_eq!(w.messages[0]["text"], "主图暂无法制作。字段映射版本不一致。请核对所选模板的原稿与字段映射。");
let mut run = run;
run.stages.clear();
run.completed = 1;
run.published = vec![json!({"outputId":"detail","variantId":"wood","generationId":"result"})];
w.note_production_summary(run);
let summary = &w.messages.last().unwrap()["productionSummary"];
assert_eq!(summary["exported"], 1);
@ -3719,7 +3994,7 @@ mod tests {
let run = w.product_production.as_ref().unwrap();
assert!(run.awaiting_canvas_save());
assert_eq!(run.stages.first().unwrap().output, "main_images");
assert_eq!(run.completed, 0);
assert!(run.published.is_empty());
assert!(matches!(requests.try_recv().unwrap(), Request::Action(method, input)
if method == "product-run-checkpoint" && input["checkpoint"]["deferredImages"] == json!([])));
assert!(requests.try_recv().is_err());