fix(xiaoyi): restrict stable production to one project and settle save waits
This commit is contained in:
parent
7e20c4defa
commit
da1ca87c67
@ -24,6 +24,9 @@ mod agent_panel;
|
||||
mod agent_stream;
|
||||
mod operation_error;
|
||||
mod template_preparation;
|
||||
|
||||
const SAVE_RECEIPT_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
const SINGLE_PROJECT_IN_PROGRESS: &str = "请先完成或暂停当前项目的制作";
|
||||
mod workspace_navigation;
|
||||
mod feedback;
|
||||
pub use feedback::{feedback_payload, sanitize_diagnostic_line};
|
||||
@ -1209,6 +1212,8 @@ pub struct Workspace {
|
||||
reference_intro_doc: Option<u64>,
|
||||
template_ui: template_slots::UiState,
|
||||
pending_slot_apply: Option<Value>,
|
||||
template_save_deadline: Option<Instant>,
|
||||
creation_save_receipts: VecDeque<Option<(CreationUiScope, Instant)>>,
|
||||
sync_confirm: bool,
|
||||
listing_read_at: Option<(u64, Instant)>,
|
||||
listing_read_error: Option<String>,
|
||||
@ -1337,7 +1342,9 @@ impl Workspace {
|
||||
let pi_slot_operation = method == "slot-append" && self.busy.as_deref() == Some("pi-agent")
|
||||
&& self.pi_run.as_deref().is_some_and(|run| self.workflow.operation_in_flight(run));
|
||||
let live_export = method == "slot-product-export" && self.busy.as_deref() == Some("pi-agent");
|
||||
if self.busy.is_some() && !local_adoption && !local_switch && !pi_slot_operation && !live_export {
|
||||
if self.busy.is_some() && !local_adoption
|
||||
&& (!local_switch || self.busy.as_deref() == Some("creation-save"))
|
||||
&& !pi_slot_operation && !live_export {
|
||||
return Err("请等待当前操作完成".into());
|
||||
}
|
||||
let batch_image = delegated && pi_slot_operation && input["detailBatch"] == true;
|
||||
@ -1352,6 +1359,24 @@ impl Workspace {
|
||||
.into());
|
||||
}
|
||||
let st = app.session.active().ok_or("请先打开项目")?;
|
||||
let doc = st.doc.id.0;
|
||||
let first_project_save = method == "slot-skeleton" && st.path.is_none()
|
||||
&& self.creation_doc == Some(doc)
|
||||
&& (self.reference_intro_doc == Some(doc) || self.creation["brief"].is_object())
|
||||
&& (input["brief"].is_object() || input["resumeProduct"] == true && self.has_production_stages())
|
||||
&& !self.open_projects.contains_key(&doc);
|
||||
if method == "slot-skeleton" {
|
||||
if self.single_project_run_owner().is_some_and(|owner| owner != doc) {
|
||||
return Err(SINGLE_PROJECT_IN_PROGRESS.into());
|
||||
}
|
||||
// A draft read can assign a provisional local ID to an imported file.
|
||||
let standalone_file = st.path.as_deref().is_some_and(|path| {
|
||||
!std::path::Path::new(path).extension().is_some_and(|extension| extension.eq_ignore_ascii_case("pcraft"))
|
||||
}) && !self.project_files.contains_key(&doc) && !self.template_workflow["workspaceId"].is_string();
|
||||
if (self.owned_project_key(doc).is_none() || standalone_file) && !first_project_save {
|
||||
return Err("请先打开或新建产品项目,再读取模板".into());
|
||||
}
|
||||
}
|
||||
if matches!(method, "slot-generate" | "slot-append" | "slot-recover") {
|
||||
self.image_progress.clear();
|
||||
}
|
||||
@ -1410,6 +1435,11 @@ impl Workspace {
|
||||
if !already_saved {
|
||||
let meta = json!({"composer":self.composer,"messages":self.messages,"project":self.project_context,"syncDirty":self.sync_dirty,"creationDraft":self.creation_draft()});
|
||||
self.tx.send(Request::Save(st.doc.clone(), st.revision, meta)).map_err(|_| "当前输出无法保存,未切换画布")?;
|
||||
if first_project_save {
|
||||
self.observed_doc = Some(st.doc.id.0);
|
||||
self.loaded_draft = Some(st.doc.id.0);
|
||||
self.project_view_parked = false;
|
||||
}
|
||||
}
|
||||
input["accountId"] = self.account["id"].clone();
|
||||
input["origin"] = json!(self.origin);
|
||||
@ -1434,6 +1464,7 @@ impl Workspace {
|
||||
self.canvas_workspace.scope_switch_in_flight = self.pending_slot_apply.as_ref()
|
||||
.is_some_and(|pending| pending["continueProduct"] != true);
|
||||
self.template_progress = json!({"phase":"save","doc":st.doc.id.0,"accountId":self.account["id"],"origin":self.origin});
|
||||
self.template_save_deadline = (!already_saved).then(|| Instant::now() + SAVE_RECEIPT_TIMEOUT);
|
||||
}
|
||||
self.busy = Some("slot-apply-save".into());
|
||||
if already_saved {
|
||||
@ -1483,7 +1514,12 @@ impl Workspace {
|
||||
let Some(mut pending) = self.pending_slot_apply.take() else { return };
|
||||
let method = pending["dispatchMethod"].as_str().unwrap_or("slot-apply").to_owned();
|
||||
let resume_busy = pending["resumeBusy"].as_str().map(str::to_owned);
|
||||
if method == "slot-skeleton" {
|
||||
self.template_save_deadline = None;
|
||||
self.template_progress = Value::Null;
|
||||
}
|
||||
if !self.accepts_production_epoch(&pending["writeEpoch"]) {
|
||||
self.finish_template_preparation();
|
||||
if self.busy.as_deref() == Some("slot-apply-save") { self.busy = None; }
|
||||
return;
|
||||
}
|
||||
@ -1497,7 +1533,8 @@ impl Workspace {
|
||||
&& (method == "slot-product-export" && self.production_can_use_scoped_pending()
|
||||
|| slot_action_allowed(&self.template_workflow, self.unknown, &method))
|
||||
&& pending["accountId"] == self.account["id"] && pending["origin"] == self.origin
|
||||
&& pending["slotRevision"] == self.template_workflow["revision"]
|
||||
&& pending["slotRevision"].as_u64() == Some(self.template_workflow["revision"].as_u64().unwrap_or(0))
|
||||
&& (method != "slot-skeleton" || self.owned_project_key(id).is_some())
|
||||
&& (method != "slot-skeleton" || pending["draftGuard"] == json!({"brief":self.creation_brief,"width":self.creation_width}))
|
||||
&& (!production_save || self.product_production.is_some())
|
||||
&& ((pending["generateProduct"] != true && pending["resumeProduct"] != true) || self.product_start_queued);
|
||||
@ -1515,8 +1552,7 @@ impl Workspace {
|
||||
self.error = "当前项目或画布已有新变化,本机保存已完成,未切换输出".into();
|
||||
self.canvas_workspace.locate_request = None;
|
||||
if method == "slot-skeleton" {
|
||||
self.canvas_workspace.scope_switch_in_flight = false;
|
||||
self.product_start_queued = false;
|
||||
self.finish_template_preparation();
|
||||
}
|
||||
if live_handoff {
|
||||
self.production_canvas_open_failed(app, &method, "保存期间项目已变化,未切换画布");
|
||||
@ -1538,11 +1574,15 @@ impl Workspace {
|
||||
if live_handoff { self.production_switch_saved(app, revision); }
|
||||
self.busy = resume_busy;
|
||||
if self.tx.send(Request::Action(method, pending)).is_err() {
|
||||
self.finish_template_preparation();
|
||||
self.production_canvas_open_failed(app, "slot-skeleton", "本机服务已停止,原画布已保留");
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
self.send(&method, pending);
|
||||
if method == "slot-skeleton" && self.busy.as_deref() != Some("slot-skeleton") {
|
||||
self.finish_template_preparation();
|
||||
}
|
||||
}
|
||||
if continue_product {
|
||||
if live_handoff || self.busy.as_deref() == Some("slot-skeleton") {
|
||||
@ -1555,7 +1595,7 @@ impl Workspace {
|
||||
|
||||
fn slot_apply_save_failed(&mut self, app: &PhotocraftApp, error: &str) {
|
||||
if self.pending_slot_apply.as_ref().is_some_and(|pending| pending["dispatchMethod"] == "slot-skeleton") {
|
||||
self.template_progress = Value::Null;
|
||||
self.finish_template_preparation();
|
||||
}
|
||||
self.saving = None;
|
||||
if !self.production_canvas_open_failed(app, "save", error)
|
||||
@ -1564,6 +1604,26 @@ impl Workspace {
|
||||
self.receive_json_error("save", error.into());
|
||||
}
|
||||
}
|
||||
fn finish_template_preparation(&mut self) {
|
||||
self.template_save_deadline = None;
|
||||
self.template_progress = Value::Null;
|
||||
self.product_start_queued = false;
|
||||
self.canvas_workspace.scope_switch_in_flight = false;
|
||||
}
|
||||
|
||||
fn cancel_template_save(&mut self) {
|
||||
if self.template_progress["phase"] != "save" { return; }
|
||||
if let Some(pending) = self.pending_slot_apply.take() {
|
||||
// The disk write may still complete. Its receipt must not start template preparation.
|
||||
if self.saving == pending["doc"].as_u64().zip(pending["baseRevision"].as_u64()) {
|
||||
self.saving = None;
|
||||
}
|
||||
if self.busy.as_deref() == Some("slot-apply-save") {
|
||||
self.busy = pending["resumeBusy"].as_str().map(str::to_owned);
|
||||
}
|
||||
}
|
||||
self.finish_template_preparation();
|
||||
}
|
||||
pub fn new(tx: mpsc::Sender<Request>, rx: mpsc::Receiver<Event>) -> Self {
|
||||
let out = Self {
|
||||
tx,
|
||||
@ -1775,6 +1835,8 @@ impl Workspace {
|
||||
reference_intro_doc: None,
|
||||
template_ui: template_slots::UiState::default(),
|
||||
pending_slot_apply: None,
|
||||
template_save_deadline: None,
|
||||
creation_save_receipts: VecDeque::new(),
|
||||
sync_confirm: false,
|
||||
listing_read_at: None,
|
||||
listing_read_error: None,
|
||||
@ -1868,6 +1930,13 @@ impl Workspace {
|
||||
if self.busy.is_some() || (method == "place" && self.material_preview_pending.is_some()) {
|
||||
return;
|
||||
}
|
||||
let creation_scope = if method == "creation-save" {
|
||||
input["doc"].as_u64().map(|doc| CreationUiScope {
|
||||
account: self.account["id"].as_str().unwrap_or_default().into(),
|
||||
origin: self.origin.clone(),
|
||||
doc,
|
||||
})
|
||||
} else { None };
|
||||
if method == "project-delete" {
|
||||
self.delete_error.clear();
|
||||
} else {
|
||||
@ -1880,8 +1949,49 @@ impl Workspace {
|
||||
self.delete_error = "本机服务已停止,请保留作品后重启".into();
|
||||
} else {
|
||||
self.error = "本机服务已停止,请保留作品后重启".into();
|
||||
if method == "creation-save" {
|
||||
self.creation_submitted_draft = None;
|
||||
self.creation_failed_signature = self.creation_edit_signature.clone();
|
||||
}
|
||||
}
|
||||
} else if let Some(scope) = creation_scope {
|
||||
self.creation_save_receipts.push_back(Some((scope, Instant::now() + SAVE_RECEIPT_TIMEOUT)));
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_creation_save(&mut self) {
|
||||
// Keep the place in FIFO order so the late receipt cannot settle a newer save.
|
||||
let Some(request) = self.creation_save_receipts.back_mut() else { return; };
|
||||
if request.take().is_none() { return; }
|
||||
if self.busy.as_deref() == Some("creation-save") { self.busy = None; }
|
||||
self.creation_submitted_draft = None;
|
||||
}
|
||||
|
||||
fn tick_creation_save(&mut self, app: &PhotocraftApp, ctx: &egui::Context) {
|
||||
let Some(Some((scope, deadline))) = self.creation_save_receipts.back() else { return; };
|
||||
if self.current_creation_ui_scope(app).as_ref() != Some(scope) {
|
||||
self.cancel_creation_save();
|
||||
} else if *deadline <= Instant::now() {
|
||||
self.cancel_creation_save();
|
||||
self.receive_json_error("creation-save", "等待保存产品资料超时,修改已保留,请重试".into());
|
||||
} else {
|
||||
ctx.request_repaint_after(deadline.saturating_duration_since(Instant::now()));
|
||||
}
|
||||
}
|
||||
|
||||
fn receive_creation_save(&mut self, app: &PhotocraftApp, result: Result<Value, String>) {
|
||||
let Some(Some((scope, _))) = self.creation_save_receipts.pop_front() else { return; };
|
||||
if self.busy.as_deref() == Some("creation-save") { self.busy = None; }
|
||||
if self.current_creation_ui_scope(app).as_ref() == Some(&scope) {
|
||||
match result {
|
||||
Ok(value) if value["doc"].as_u64() == Some(scope.doc)
|
||||
&& value["accountId"] == scope.account && value["origin"] == scope.origin
|
||||
&& value["creation"].is_object() => self.receive_creation_ui(app, "creation-save", &value),
|
||||
Ok(_) => self.receive_json_error("creation-save", "保存回执与当前项目不一致,修改已保留,请重试".into()),
|
||||
Err(error) => self.receive_json_error("creation-save", error),
|
||||
}
|
||||
}
|
||||
self.creation_submitted_draft = None;
|
||||
}
|
||||
fn send_material_read(&mut self, method: &str, mut input: Value) {
|
||||
if !input.is_object() {
|
||||
@ -2057,6 +2167,7 @@ impl Workspace {
|
||||
}
|
||||
|
||||
fn handover(&mut self) {
|
||||
self.cancel_template_save();
|
||||
self.revoke_production_epoch();
|
||||
if self.product_production.take().is_some() {
|
||||
self.user_canvas_changes = Default::default();
|
||||
@ -2097,6 +2208,10 @@ 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) {
|
||||
if matches!(view, CenterView::Projects | CenterView::Materials) && self.single_project_run_owner().is_some() {
|
||||
self.error = SINGLE_PROJECT_IN_PROGRESS.into();
|
||||
return;
|
||||
}
|
||||
if !self.in_background_project { self.cancel_project_open(); }
|
||||
let material = matches!(view, CenterView::Materials);
|
||||
let library = matches!(view, CenterView::Projects) || (!document_open && !material);
|
||||
@ -2226,12 +2341,21 @@ 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) {
|
||||
let doc = app.session.documents()[index].doc.id.0;
|
||||
if self.single_project_run_owner().is_some_and(|owner| owner != doc) {
|
||||
self.error = SINGLE_PROJECT_IN_PROGRESS.into();
|
||||
return;
|
||||
}
|
||||
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.cancel_template_save();
|
||||
self.cancel_creation_save();
|
||||
}
|
||||
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 {
|
||||
} else if multi_project_state::MULTI_PROJECT_CONCURRENCY_ENABLED
|
||||
&& self.observed_doc != Some(doc) && self.project_view_parked {
|
||||
self.restore_or_read_project(doc);
|
||||
}
|
||||
app.session.set_active(index);
|
||||
@ -2245,11 +2369,18 @@ impl Workspace {
|
||||
if input["updateExisting"] != true {
|
||||
let local=if input["source"]=="native" {input["id"].as_str()} else {input["localId"].as_str()};
|
||||
if let Some(index)=local.and_then(|local|self.open_project_index(app,local)) {
|
||||
if self.single_project_run_owner().is_some_and(|doc| doc != app.session.documents()[index].doc.id.0) {
|
||||
return Err(SINGLE_PROJECT_IN_PROGRESS.into());
|
||||
}
|
||||
self.activate_project_tab(app,index);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if self.product_production.is_some() && input["updateExisting"] != true {
|
||||
if self.single_project_run_owner().is_some() {
|
||||
return Err(SINGLE_PROJECT_IN_PROGRESS.into());
|
||||
}
|
||||
if multi_project_state::MULTI_PROJECT_CONCURRENCY_ENABLED
|
||||
&& 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() {
|
||||
@ -2835,6 +2966,8 @@ 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.cancel_creation_save();
|
||||
self.cancel_template_save();
|
||||
self.revoke_project_slots(app, ctx, &json!("account_changed"));
|
||||
self.project_run_slots.clear();
|
||||
self.project_view_parked = false;
|
||||
@ -3138,6 +3271,23 @@ impl Workspace {
|
||||
}
|
||||
|
||||
fn receive_json_event(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, method: String, mut result: Result<Value, String>) {
|
||||
if method == "creation-save" {
|
||||
self.receive_creation_save(app, result);
|
||||
return;
|
||||
}
|
||||
if method == "save" && let Err(error) = &result
|
||||
&& self.template_progress["phase"] == "save"
|
||||
{
|
||||
self.slot_apply_save_failed(app, error);
|
||||
return;
|
||||
}
|
||||
if method == "slot-skeleton" && self.template_progress.is_object()
|
||||
&& let Ok(value) = &result
|
||||
&& value["doc"].is_u64()
|
||||
&& value["doc"] != self.template_progress["doc"]
|
||||
{
|
||||
return;
|
||||
}
|
||||
match method.as_str() {
|
||||
"desktop-feedback" => { self.feedback_received(result); return; }
|
||||
"workbench-knowledge" => { self.workbench_knowledge_received(result); return; }
|
||||
@ -3246,7 +3396,12 @@ impl Workspace {
|
||||
"template-progress" => { self.receive_template_progress(app, result); return; }
|
||||
"resource-progress" => { self.resource_progress_received(app, result); return; }
|
||||
"knowledge-cancel" => return,
|
||||
"slot-skeleton" => self.template_progress = Value::Null,
|
||||
"slot-skeleton" => {
|
||||
self.template_progress = Value::Null;
|
||||
if !result.as_ref().is_ok_and(|value| value["productionPreparation"] == true) {
|
||||
self.finish_template_preparation();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let mut workflow_envelope = Value::Null;
|
||||
@ -3476,12 +3631,12 @@ impl Workspace {
|
||||
}
|
||||
"slot-product-export" => self.production_export_received(app, &v),
|
||||
"slot-skeleton" if v["productionPreparation"] == true => {
|
||||
let queued = self.product_start_queued;
|
||||
self.finish_template_preparation();
|
||||
let current = app.session.active().filter(|state| v["doc"] == state.doc.id.0);
|
||||
if self.product_start_queued && v["accountId"] == self.account["id"] && v["origin"] == self.origin
|
||||
if queued && v["accountId"] == self.account["id"] && v["origin"] == self.origin
|
||||
&& let Some(state) = current
|
||||
{
|
||||
self.product_start_queued = false;
|
||||
self.canvas_workspace.scope_switch_in_flight = false;
|
||||
if self.library || self.material { return; }
|
||||
if v["baseRevision"] != state.revision
|
||||
|| !template_snapshot_not_older(&self.template_workflow, &v["workflow"])
|
||||
@ -3491,6 +3646,8 @@ impl Workspace {
|
||||
}
|
||||
self.receive_json_slot(app, method, v.clone());
|
||||
self.production_prepared(app, &v);
|
||||
} else if queued {
|
||||
self.error = "模板回执与当前项目不一致,请重新读取".into();
|
||||
}
|
||||
}
|
||||
name if name.starts_with("slot-") => self.receive_json_slot(app, name, v),
|
||||
@ -3798,12 +3955,18 @@ impl Workspace {
|
||||
self.retain_creation_ui_draft(app);
|
||||
self.creation_ui_scope = None;
|
||||
self.cancel_project_open();
|
||||
self.cancel_creation_save();
|
||||
self.cancel_template_save();
|
||||
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();
|
||||
if self.busy.as_deref() == Some("slot-skeleton") {
|
||||
self.busy = None;
|
||||
}
|
||||
self.finish_template_preparation();
|
||||
self.user_canvas_changes = Default::default();
|
||||
self.template_workflow = Value::Null;
|
||||
self.canvas_workspace = canvas_workspace::State::default();
|
||||
@ -4032,6 +4195,14 @@ impl Workspace {
|
||||
self.observe_startup_interaction(ctx);
|
||||
}
|
||||
if self.production_exit.is_none() && !self.professional_child_active(app) {
|
||||
if let Some(owner) = self.single_project_run_owner()
|
||||
&& app.session.active().is_some_and(|state| state.doc.id.0 != owner)
|
||||
&& let Some(index) = app.session.documents().iter().position(|state| state.doc.id.0 == owner)
|
||||
{
|
||||
app.session.set_active(index);
|
||||
app.sync_views();
|
||||
self.error = SINGLE_PROJECT_IN_PROGRESS.into();
|
||||
}
|
||||
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()
|
||||
@ -4094,6 +4265,15 @@ impl Workspace {
|
||||
self.receive_project_event(app, ctx, event);
|
||||
}
|
||||
}
|
||||
if let Some(deadline) = self.template_save_deadline {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
self.slot_apply_save_failed(app, "等待保存产品资料超时,请重试");
|
||||
} else {
|
||||
ctx.request_repaint_after(remaining);
|
||||
}
|
||||
}
|
||||
self.tick_creation_save(app, ctx);
|
||||
if self.production_exit.is_some() {
|
||||
self.advance_production_exit(app, ctx);
|
||||
return;
|
||||
@ -4146,6 +4326,7 @@ impl Workspace {
|
||||
let now = Instant::now();
|
||||
w.production_tick(app);
|
||||
if let Some(delay) = w.production_budget_delay() { ctx.request_repaint_after(delay); }
|
||||
if let Some(delay) = w.production_canvas_save_delay(now) { ctx.request_repaint_after(delay); }
|
||||
if let Some(delay) = w.production_retry_delay(now) {
|
||||
ctx.request_repaint_after(delay);
|
||||
}
|
||||
@ -4379,6 +4560,9 @@ impl Workspace {
|
||||
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)
|
||||
{
|
||||
if self.saving == Some((id, rev)) && self.template_progress["phase"] == "save" {
|
||||
self.slot_apply_save_failed(app, "保存期间项目授权已切换,请重新提交");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if meta["documentKey"].is_object() && app.session.active().is_some_and(|state|
|
||||
@ -4562,7 +4746,9 @@ impl Workspace {
|
||||
self.template_progress["cancelRect"] = agent_panel::rect_value(view.cancel.rect);
|
||||
self.template_progress["progressRect"] = agent_panel::rect_value(view.bar.rect);
|
||||
self.template_progress["surfaceRect"] = agent_panel::rect_value(view.surface);
|
||||
if view.cancel.clicked() && self.tx.send(Request::Action("knowledge-cancel".into(), json!({"jobId":job}))).is_ok() {
|
||||
if view.cancel.clicked() && value["phase"] == "save" {
|
||||
self.slot_apply_save_failed(app, "已取消读取模板,产品资料已保留");
|
||||
} else if view.cancel.clicked() && self.tx.send(Request::Action("knowledge-cancel".into(), json!({"jobId":job}))).is_ok() {
|
||||
if self.product_start_queued || self.product_production.is_some() {
|
||||
self.handover();
|
||||
}
|
||||
@ -5835,6 +6021,124 @@ fn action_impl(app: &mut PhotocraftApp, ctx: Option<&egui::Context>, method: &st
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::jiansun::test_support::SettleUi;
|
||||
|
||||
#[test]
|
||||
fn template_save_rejects_an_unbound_image_and_accepts_a_new_product_project() {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"name":"单张产品图.webp","width":8,"height":8})).unwrap();
|
||||
let mut app = PhotocraftApp::new(session, crate::Services::default());
|
||||
reference_menu_test_workspace(&mut app);
|
||||
let mut w = app.jiansun.take().unwrap();
|
||||
let (tx, requests) = mpsc::channel();
|
||||
w.tx = tx;
|
||||
w.busy = None;
|
||||
w.open_projects.clear();
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
let revision = app.session.active().unwrap().revision;
|
||||
let input = json!({"brief":{},"generateProduct":true});
|
||||
assert!(w.slot_action(&app, "slot-skeleton", input.clone()).unwrap_err().contains("产品项目"));
|
||||
assert!(w.template_progress.is_null());
|
||||
assert!(!w.product_start_queued);
|
||||
assert!(requests.try_recv().is_err());
|
||||
|
||||
app.session.active_mut().unwrap().path = Some("单张产品图.webp".into());
|
||||
w.open_projects.insert(doc, w.local_identity("provisional"));
|
||||
assert!(w.slot_action(&app, "slot-skeleton", input.clone()).unwrap_err().contains("产品项目"));
|
||||
assert!(w.template_progress.is_null());
|
||||
assert!(requests.try_recv().is_err());
|
||||
|
||||
app.session.active_mut().unwrap().path = None;
|
||||
w.open_projects.clear();
|
||||
w.creation_doc = Some(doc);
|
||||
w.reference_intro_doc = Some(doc);
|
||||
w.observed_doc = None;
|
||||
w.slot_action(&app, "slot-skeleton", input).unwrap();
|
||||
assert!(matches!(requests.try_recv(), Ok(Request::Save(..))));
|
||||
w.receive_event(&mut app, &egui::Context::default(), Event::Saved(doc, revision, json!({"localId":"project"})));
|
||||
assert!(matches!(requests.try_recv(), Ok(Request::Action(method, _)) if method == "slot-skeleton"));
|
||||
assert_eq!(w.template_progress["phase"], "metadata");
|
||||
assert_eq!(w.owned_project_key(doc), Some(w.local_identity("project").as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_save_clears_wait_on_cancel_error_timeout_or_tab_switch() {
|
||||
for outcome in ["cancel", "error", "timeout", "switch", "revision"] {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"width":8,"height":8})).unwrap();
|
||||
let mut app = PhotocraftApp::new(session, crate::Services::default());
|
||||
reference_menu_test_workspace(&mut app);
|
||||
let mut w = app.jiansun.take().unwrap();
|
||||
let (tx, requests) = mpsc::channel();
|
||||
w.tx = tx;
|
||||
w.busy = None;
|
||||
w.library = false;
|
||||
let active = app.session.active().unwrap();
|
||||
let (doc, rev) = (active.doc.id.0, active.revision);
|
||||
w.slot_action(&app, "slot-skeleton", json!({"brief":{},"generateProduct":true})).unwrap();
|
||||
assert!(matches!(requests.try_recv(), Ok(Request::Save(..))));
|
||||
let ctx = egui::Context::default();
|
||||
match outcome {
|
||||
"cancel" => w.slot_apply_save_failed(&app, "已取消读取模板,产品资料已保留"),
|
||||
"error" => w.receive_json_event(&mut app, &ctx, "save".into(), Err("磁盘写入失败".into())),
|
||||
"timeout" => {
|
||||
w.template_save_deadline = Some(Instant::now());
|
||||
let _ = ctx.run_logic(&Default::default(), |ctx| w.tick(&mut app, ctx));
|
||||
}
|
||||
"switch" => {
|
||||
app.session.execute("file.new", json!({"width":8,"height":8})).unwrap();
|
||||
let _ = ctx.run_logic(&Default::default(), |ctx| w.tick(&mut app, ctx));
|
||||
}
|
||||
_ => w.slot_apply_saved(&app, doc, rev + 1),
|
||||
}
|
||||
w.slot_apply_saved(&app, doc, rev);
|
||||
assert!(w.template_progress.is_null(), "{outcome}");
|
||||
assert!(w.template_save_deadline.is_none() && w.pending_slot_apply.is_none(), "{outcome}");
|
||||
assert!(!w.product_start_queued && w.product_production.is_none(), "{outcome}");
|
||||
assert!(w.busy.is_none() && w.saving.is_none(), "{outcome}");
|
||||
assert!(!requests.try_iter().any(|request| matches!(request, Request::Action(method, _) if method == "slot-skeleton")), "{outcome}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creation_save_receipts_settle_on_error_mismatch_and_timeout_without_stealing_a_new_save() {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"width":8,"height":8})).unwrap();
|
||||
let mut app = PhotocraftApp::new(session, crate::Services::default());
|
||||
reference_menu_test_workspace(&mut app);
|
||||
let mut w = app.jiansun.take().unwrap();
|
||||
let (tx, requests) = mpsc::channel();
|
||||
w.tx = tx;
|
||||
w.busy = None;
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
let ctx = egui::Context::default();
|
||||
let send_save = |w: &mut Workspace| {
|
||||
w.send("creation-save", json!({"doc":doc}));
|
||||
assert!(matches!(requests.try_recv(), Ok(Request::Action(method, _)) if method == "creation-save"));
|
||||
};
|
||||
send_save(&mut w);
|
||||
w.receive_json_event(&mut app, &ctx, "creation-save".into(), Err("磁盘写入失败".into()));
|
||||
assert!(w.busy.is_none());
|
||||
assert_eq!(w.error, "磁盘写入失败");
|
||||
send_save(&mut w);
|
||||
w.receive_json_event(&mut app, &ctx, "creation-save".into(), Ok(json!({"doc":doc+1})));
|
||||
assert!(w.busy.is_none());
|
||||
assert!(w.error.contains("保存回执"));
|
||||
|
||||
send_save(&mut w);
|
||||
w.creation_save_receipts.back_mut().unwrap().as_mut().unwrap().1 = Instant::now();
|
||||
w.tick_creation_save(&app, &ctx);
|
||||
assert!(w.busy.is_none());
|
||||
assert!(w.error.contains("超时"));
|
||||
send_save(&mut w);
|
||||
w.receive_json_event(&mut app, &ctx, "creation-save".into(), Err("旧请求失败".into()));
|
||||
assert_eq!(w.busy.as_deref(), Some("creation-save"));
|
||||
let receipt = json!({"accountId":w.account["id"],"origin":w.origin,"doc":doc,
|
||||
"creation":{"brief":{"name":"已保存的资料"}}});
|
||||
w.receive_json_event(&mut app, &ctx, "creation-save".into(), Ok(receipt));
|
||||
assert!(w.busy.is_none());
|
||||
assert_eq!(w.creation_brief["name"], "已保存的资料");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_ui_callers_use_shared_stitch_controls() {
|
||||
let files = [
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
use super::*;
|
||||
use super::product_production::Run;
|
||||
|
||||
pub(super) const MULTI_PROJECT_CONCURRENCY_ENABLED: bool = false;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) enum ProjectRunVisualStatus {
|
||||
Running,
|
||||
@ -168,6 +170,7 @@ project_run_slot! {
|
||||
reference_intro_doc: Option<u64> = None,
|
||||
template_ui: template_slots::UiState = template_slots::UiState::default(),
|
||||
pending_slot_apply: Option<Value> = None,
|
||||
template_save_deadline: Option<Instant> = None,
|
||||
listing_read_at: Option<(u64, Instant)> = None,
|
||||
listing_read_error: Option<String> = None,
|
||||
sync_dirty: bool = true,
|
||||
@ -196,6 +199,7 @@ impl Workspace {
|
||||
}
|
||||
|
||||
pub(super) fn park_project_projection(&mut self) -> bool {
|
||||
if !MULTI_PROJECT_CONCURRENCY_ENABLED { return false; }
|
||||
let Some(key) = self.observed_doc.and_then(|doc| self.owned_project_key(doc)).map(str::to_owned) else {
|
||||
return false;
|
||||
};
|
||||
@ -206,6 +210,7 @@ impl Workspace {
|
||||
}
|
||||
|
||||
pub(super) fn restore_project_projection(&mut self, doc: u64) -> bool {
|
||||
if !MULTI_PROJECT_CONCURRENCY_ENABLED { return false; }
|
||||
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();
|
||||
@ -214,6 +219,7 @@ impl Workspace {
|
||||
}
|
||||
|
||||
pub(super) fn parked_project_docs(&self, app: &PhotocraftApp) -> Vec<u64> {
|
||||
if !MULTI_PROJECT_CONCURRENCY_ENABLED { return Vec::new(); }
|
||||
app.session.documents().iter().filter_map(|state| {
|
||||
let doc = state.doc.id.0;
|
||||
let key = self.owned_project_key(doc)?;
|
||||
@ -225,6 +231,7 @@ impl Workspace {
|
||||
&mut self, app: &mut PhotocraftApp, doc: u64,
|
||||
action: impl FnOnce(&mut Self, &mut PhotocraftApp) -> T,
|
||||
) -> Option<T> {
|
||||
if !MULTI_PROJECT_CONCURRENCY_ENABLED { return None; }
|
||||
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()?;
|
||||
@ -252,6 +259,7 @@ impl Workspace {
|
||||
}
|
||||
|
||||
pub(super) fn event_project_doc(&self, event: &Event) -> Option<u64> {
|
||||
if !MULTI_PROJECT_CONCURRENCY_ENABLED { return None; }
|
||||
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"
|
||||
@ -298,7 +306,7 @@ impl Workspace {
|
||||
}
|
||||
|
||||
pub(super) fn project_is_parked(&self, doc: u64) -> bool {
|
||||
self.owned_project_key(doc).and_then(|key| self.project_run_slots.get(key))
|
||||
MULTI_PROJECT_CONCURRENCY_ENABLED && self.owned_project_key(doc).and_then(|key| self.project_run_slots.get(key))
|
||||
.is_some_and(|slot| slot.observed_doc == Some(doc))
|
||||
}
|
||||
|
||||
@ -340,7 +348,7 @@ impl Workspace {
|
||||
}
|
||||
|
||||
pub(super) fn parked_production_active(&self) -> bool {
|
||||
self.project_run_slots.iter().any(|(key, slot)| key.starts_with(&self.local_identity("")) &&
|
||||
MULTI_PROJECT_CONCURRENCY_ENABLED && 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)))
|
||||
@ -366,28 +374,30 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
};
|
||||
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,
|
||||
});
|
||||
if MULTI_PROJECT_CONCURRENCY_ENABLED {
|
||||
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));
|
||||
}
|
||||
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))
|
||||
@ -402,7 +412,8 @@ impl Workspace {
|
||||
let producing_output_label = producing.map_or_else(String::new, |run| run.producing_output_label.clone());
|
||||
MultiProjectUiSnapshot {
|
||||
global_runs,
|
||||
max_concurrent: if std::env::var("JIANSUN_PARALLEL_PROJECTS").as_deref() == Ok("3") { 3 } else { 2 },
|
||||
max_concurrent: if !MULTI_PROJECT_CONCURRENCY_ENABLED { 1 }
|
||||
else if std::env::var("JIANSUN_PARALLEL_PROJECTS").as_deref() == Ok("3") { 3 } else { 2 },
|
||||
active_project_id,
|
||||
active_project_title,
|
||||
active_section: if self.library || self.material || active.is_none() { WorkspaceSectionKind::Projects }
|
||||
@ -456,3 +467,29 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stable_snapshot_omits_project_run_badges_but_keeps_project_identity() {
|
||||
if MULTI_PROJECT_CONCURRENCY_ENABLED { return; }
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"name":"当前项目","width":8,"height":8})).unwrap();
|
||||
let mut app = PhotocraftApp::new(session, crate::Services::default());
|
||||
super::super::reference_menu_test_workspace(&mut app);
|
||||
let mut workspace = app.jiansun.take().unwrap();
|
||||
workspace.library = false;
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
workspace.last_production_summary = Some((doc, ProjectRunVisualStatus::Completed));
|
||||
|
||||
let snapshot = workspace.multi_project_ui_snapshot(&app);
|
||||
assert_eq!(snapshot.max_concurrent, 1);
|
||||
assert!(snapshot.global_runs.is_empty());
|
||||
assert!(!snapshot.viewing_differs_from_producing);
|
||||
assert_eq!(snapshot.active_project_id.as_deref(), Some("menu-project"));
|
||||
assert!(!workspace.park_project_projection());
|
||||
assert!(workspace.project_run_slots.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@ -155,6 +155,13 @@ impl LayerRejection {
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(super) fn single_project_run_owner(&self) -> Option<u64> {
|
||||
if super::multi_project_state::MULTI_PROJECT_CONCURRENCY_ENABLED { return None; }
|
||||
self.product_production.as_ref()
|
||||
.filter(|run| run.is_active() || self.production_stop["state"] == "stopping")
|
||||
.map(|run| run.doc)
|
||||
}
|
||||
|
||||
pub(super) fn accepts_production_epoch(&self, epoch: &Value) -> bool {
|
||||
epoch.is_null() || epoch.as_u64() == Some(self.write_epoch)
|
||||
}
|
||||
@ -173,6 +180,7 @@ impl Workspace {
|
||||
pub(super) fn resume_saved_production(&mut self, app: &PhotocraftApp) -> bool {
|
||||
let Some(canvas) = app.session.active() else { return false };
|
||||
let doc = canvas.doc.id.0;
|
||||
if self.single_project_run_owner().is_some_and(|owner| owner != doc) { return false; }
|
||||
let Some(project) = self.open_projects.get(&doc).cloned() else { return false };
|
||||
let Some(stages) = self.template_workflow["productionStages"].as_array()
|
||||
.and_then(|rows| rows.iter().map(Stage::read).collect::<Option<Vec<_>>>()) else { return false };
|
||||
@ -829,6 +837,7 @@ pub(super) struct Run {
|
||||
goal_user_entry: Option<String>,
|
||||
reset_goal: bool,
|
||||
phase: Phase,
|
||||
canvas_save_deadline: Instant,
|
||||
bound: Option<Stage>,
|
||||
opening: Option<Stage>,
|
||||
previous_save: Value,
|
||||
@ -907,6 +916,7 @@ impl Run {
|
||||
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(),
|
||||
canvas_save_deadline: Instant::now() + super::SAVE_RECEIPT_TIMEOUT,
|
||||
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,
|
||||
@ -1183,6 +1193,11 @@ impl Run {
|
||||
self.phase == Phase::AwaitingSave
|
||||
}
|
||||
|
||||
fn await_canvas_save(&mut self) {
|
||||
self.phase = Phase::AwaitingSave;
|
||||
self.canvas_save_deadline = Instant::now() + super::SAVE_RECEIPT_TIMEOUT;
|
||||
}
|
||||
|
||||
pub(super) fn waiting_for_originals(&self) -> bool {
|
||||
matches!(self.phase, Phase::WaitingOriginals { .. })
|
||||
}
|
||||
@ -1391,7 +1406,7 @@ impl Workspace {
|
||||
self.product_checkpoint = snapshot.checkpoint;
|
||||
if let Some(mut run) = snapshot.run {
|
||||
if !matches!(run.phase, Phase::Paused(_) | Phase::WaitingOriginals { .. }) {
|
||||
run.phase = Phase::AwaitingSave;
|
||||
run.await_canvas_save();
|
||||
run.opening = None;
|
||||
run.finish = None;
|
||||
}
|
||||
@ -1789,7 +1804,7 @@ impl Workspace {
|
||||
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() {
|
||||
run.phase = Phase::AwaitingSave;
|
||||
run.await_canvas_save();
|
||||
self.write_production_checkpoint(&run, false);
|
||||
self.production_stop = json!({"mode":null,"state":"idle","reason":null,"error":null});
|
||||
if self.error == WAITING_MODELS { self.error.clear(); }
|
||||
@ -1822,7 +1837,11 @@ impl Workspace {
|
||||
pub(super) fn production_prepared(&mut self, app: &PhotocraftApp, meta: &Value) {
|
||||
if meta["productionPreparation"] == true {
|
||||
let Some(doc) = meta["doc"].as_u64() else { return };
|
||||
let Some(project) = self.open_projects.get(&doc).cloned() else {
|
||||
if self.single_project_run_owner().is_some_and(|owner| owner != doc) {
|
||||
self.error = super::SINGLE_PROJECT_IN_PROGRESS.into();
|
||||
return;
|
||||
}
|
||||
let Some(project) = self.owned_project_key(doc).map(str::to_owned) else {
|
||||
self.error = "项目尚未完成首次保存".into();
|
||||
return;
|
||||
};
|
||||
@ -1854,7 +1873,7 @@ impl Workspace {
|
||||
self.busy = None;
|
||||
}
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
run.phase = Phase::AwaitingSave;
|
||||
run.await_canvas_save();
|
||||
}
|
||||
self.production_tick(app);
|
||||
}
|
||||
@ -1997,6 +2016,7 @@ impl Workspace {
|
||||
run.phase = Phase::Agent;
|
||||
}
|
||||
self.pending_slot_apply = None;
|
||||
self.finish_template_preparation();
|
||||
self.busy = Some("pi-agent".into());
|
||||
self.canvas_workspace.scope_switch_in_flight = false;
|
||||
self.error = reason.into();
|
||||
@ -2143,6 +2163,11 @@ impl Workspace {
|
||||
run.awaiting_canvas_save() || matches!(run.phase, Phase::AgentRetryAt(at) if Instant::now() >= at))
|
||||
}
|
||||
|
||||
pub(super) fn production_canvas_save_delay(&self, now: Instant) -> Option<Duration> {
|
||||
self.product_production.as_ref().filter(|run| run.awaiting_canvas_save())
|
||||
.map(|run| run.canvas_save_deadline.saturating_duration_since(now))
|
||||
}
|
||||
|
||||
pub(super) fn production_tick(&mut self, app: &PhotocraftApp) {
|
||||
if self.product_production.is_none() {
|
||||
self.restore_production_checkpoint(app);
|
||||
@ -2150,10 +2175,13 @@ 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))
|
||||
!run.awaiting_canvas_save() && app.session.documents().iter().any(|state| state.doc.id.0 == run.doc))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if self.product_production.as_ref().is_some_and(Run::awaiting_canvas_save) {
|
||||
self.slot_apply_save_failed(app, "原制作项目已切换,请重新打开项目后继续");
|
||||
}
|
||||
self.product_production = None;
|
||||
self.product_export = None;
|
||||
if matches!(self.production_stop["state"].as_str(), Some("stopping" | "delivering")) {
|
||||
@ -2174,6 +2202,10 @@ impl Workspace {
|
||||
}
|
||||
let Some(run) = self.product_production.as_ref() else { return; };
|
||||
if run.phase == Phase::DeliveringBundle { return; }
|
||||
if self.production_canvas_save_delay(Instant::now()) == Some(Duration::ZERO) {
|
||||
self.slot_apply_save_failed(app, "等待制作画布保存超时,请重试");
|
||||
return;
|
||||
}
|
||||
if self.production_start_waiting() {
|
||||
let Some(canvas) = app.session.active() else { return; };
|
||||
let saved = self.persisted_revisions.get(&run.doc) == Some(&canvas.revision);
|
||||
@ -2691,7 +2723,7 @@ impl Workspace {
|
||||
if let Some(id) = terminal_image { images.retain(|pending| pending != id); }
|
||||
if goal.as_deref().map_or_else(|| models.len() + images.len() < count, has_result) {
|
||||
if let Some(stage) = &stage && let Some(id) = terminal_image { run.settle_deferred_image(stage, id); }
|
||||
run.phase = Phase::AwaitingSave;
|
||||
run.await_canvas_save();
|
||||
self.checkpoint_production();
|
||||
} else if stage.as_ref().zip(terminal_image).is_some_and(|(stage,id)| run.settle_deferred_image(stage, id)) {
|
||||
self.checkpoint_production();
|
||||
@ -2936,6 +2968,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn switching_projects_routes_save_and_stream_and_checkpoints_both_runs_on_exit() {
|
||||
if !super::super::multi_project_state::MULTI_PROJECT_CONCURRENCY_ENABLED { return; }
|
||||
use super::super::Event;
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"name":"项目甲","width":40,"height":50})).unwrap();
|
||||
@ -3041,6 +3074,23 @@ mod tests {
|
||||
|
||||
let ctx = egui::Context::default();
|
||||
let vm_before = w.multi_project_view_model(&app, &ctx);
|
||||
if !super::super::multi_project_state::MULTI_PROJECT_CONCURRENCY_ENABLED {
|
||||
assert_eq!(vm_before.max_concurrent, 1);
|
||||
assert!(vm_before.global_runs.is_empty());
|
||||
assert!(!vm_before.viewing_differs_from_producing);
|
||||
assert!(!w.park_project_projection());
|
||||
assert!(!w.restore_project_projection(first));
|
||||
assert!(w.project_run_slots.is_empty());
|
||||
assert!(w.request_project_open(&mut app, json!({"source":"native","id":"proj-b"})).is_err());
|
||||
assert_eq!(app.session.active().unwrap().doc.id.0, first);
|
||||
app.session.set_active(1);
|
||||
assert!(w.slot_action(&app, "slot-skeleton", json!({"resumeProduct":true})).is_err());
|
||||
assert_eq!(w.product_production.as_ref().unwrap().doc, first);
|
||||
let _ = ctx.run_logic(&Default::default(), |ctx| w.tick(&mut app, ctx));
|
||||
assert_eq!(app.session.active().unwrap().doc.id.0, first);
|
||||
assert!(w.project_run_slots.is_empty());
|
||||
return;
|
||||
}
|
||||
assert!(vm_before.max_concurrent >= 2);
|
||||
assert_eq!(vm_before.global_runs.len(), 1);
|
||||
assert_eq!(vm_before.active_project_id.as_deref(), Some("proj-a"));
|
||||
@ -3809,6 +3859,33 @@ mod tests {
|
||||
assert_eq!(input["remainingOutputs"].as_array().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_canvas_save_timeout_releases_the_run_without_starting_a_turn() {
|
||||
let (tx, requests) = mpsc::channel();
|
||||
let (_, rx) = mpsc::channel();
|
||||
let mut w = Workspace::new(tx, rx);
|
||||
requests.try_recv().unwrap();
|
||||
w.busy = None;
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"width":40,"height":50})).unwrap();
|
||||
let app = PhotocraftApp::new(session, crate::Services::default());
|
||||
let canvas = app.session.active().unwrap();
|
||||
let doc = canvas.doc.id.0;
|
||||
let project = w.local_identity("project");
|
||||
w.open_projects.insert(doc, project.clone());
|
||||
w.template_workflow = json!({"workspaceId":"workspace"});
|
||||
let mut run = Run::new(doc, project, json!("workspace"), vec![], None, Phase::AwaitingSave);
|
||||
run.canvas_save_deadline = Instant::now();
|
||||
w.product_production = Some(run);
|
||||
w.saving = Some((doc, canvas.revision));
|
||||
|
||||
w.production_tick(&app);
|
||||
|
||||
assert!(w.product_production.is_none() && w.saving.is_none());
|
||||
assert!(w.error.contains("超时"));
|
||||
assert!(requests.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_autosave_waits_twenty_seconds_but_canvas_boundary_saves_immediately() {
|
||||
let (tx, requests) = mpsc::channel();
|
||||
|
||||
@ -48,7 +48,8 @@ pub(super) fn show(ui: &mut Ui, value: &Value, reduced: bool) -> View {
|
||||
ui.allocate_response(egui::Vec2::ZERO, egui::Sense::empty())
|
||||
} else {
|
||||
stitch_ui::action_button(ui, if viewing.is_some() {"留在当前页"} else {"取消读取"},
|
||||
stitch_ui::ButtonRole::Secondary, viewing.is_some() || value["cancelling"] != true && value["jobId"].is_string())
|
||||
stitch_ui::ButtonRole::Secondary, viewing.is_some() || value["phase"] == "save"
|
||||
|| value["cancelling"] != true && value["jobId"].is_string())
|
||||
};
|
||||
ui.add(egui::Label::new(&label).truncate()).on_hover_text(&label);
|
||||
cancel
|
||||
@ -85,11 +86,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn template_progress_bar_and_cancel_fit_narrow_and_wide_windows() {
|
||||
for width in [320.0, 1100.0] {
|
||||
for (width, value) in [320.0, 1100.0].into_iter().flat_map(|width| [
|
||||
(width, json!({"phase":"save"})),
|
||||
(width, json!({"phase":"waiting","completed":0,"fileCount":9,"jobId":"job"})),
|
||||
]) {
|
||||
let ctx = egui::Context::default();
|
||||
let input = egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,egui::vec2(width,720.0))),..Default::default() };
|
||||
ctx.run_ui(input, |ui| {
|
||||
let view = show(ui,&json!({"phase":"waiting","completed":0,"fileCount":9,"jobId":"job"}),true);
|
||||
let view = show(ui, &value, true);
|
||||
assert!(view.surface.width() <= width);
|
||||
assert!(view.surface.contains_rect(view.bar.rect));
|
||||
assert!(view.surface.contains_rect(view.cancel.rect));
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user