保留中断的制作进度并接续完整成品入库
This commit is contained in:
parent
e69f145c35
commit
a3f644cdfa
@ -678,6 +678,8 @@ pub(super) fn status() -> Value {
|
||||
status_from_registry(®istry)
|
||||
}
|
||||
|
||||
pub(super) const TURN_STOP_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
pub(super) fn pause_production(doc: u64, project_identity: &str, write_epoch: Option<u64>) {
|
||||
let Some((account_identity, project)) = project_identity.rsplit_once('|') else { return; };
|
||||
if write_epoch.is_none() { return; }
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
//! Pixel edits for a single candidate. Coordinates are relative to the source
|
||||
//! before editing, and offsets are pixels in the destination frame.
|
||||
use super::{
|
||||
Digest, Path, R, Sha256, Uuid, Value, candidate_available, candidate_pixels, candidate_uses_current_inputs, crop_product_image, definition,
|
||||
generation_references, hash, image_output_component, input_hash, json, local_product_photo, manual_image_source, mapped_slot, material_task_id, new_binding, now, output_uses_variant,
|
||||
product_slot_binding, read_candidate, reserve_candidate, slot_frame, slot_id, template_slots, uuid, write_json,
|
||||
Digest, Path, R, Sha256, Uuid, Value, candidate_available, candidate_pixels, crop_product_image, definition,
|
||||
generation_references, image_output_component, input_hash, json, local_product_photo, manual_image_source, mapped_slot, material_task_id, new_binding, now, output_uses_variant,
|
||||
read_candidate, reserve_candidate, slot_frame, slot_id, template_slots, uuid, variant as product_variant, write_json,
|
||||
};
|
||||
use image::{Rgba, Rgba32FImage, imageops};
|
||||
use photocraft_codecs::{ChannelLayout, Image, SampleType};
|
||||
@ -57,6 +57,25 @@ fn invalid_source(dir: &Path, state: &Value, candidate: &str, target: &str, vari
|
||||
format!("来源候选编号无效:收到「{received}」;sourceCandidateId 应填候选编号。{scope}:{}。跨图位候选可用 list_project_images 查询。", json!(sources))
|
||||
}
|
||||
|
||||
fn crop_source_candidate(dir: &Path, state: &Value, candidate: &str, slot: &str, variant: &str) -> R<Value> {
|
||||
// 编号前缀至少 8 位且在本项目候选中唯一时,按完整编号处理。
|
||||
let prefix = candidate.trim().to_ascii_lowercase();
|
||||
let by_prefix = || {
|
||||
let rows: Vec<&str> = state["candidates"].as_array().into_iter().flatten().filter_map(Value::as_str)
|
||||
.filter(|id| prefix.len() >= 8 && id.starts_with(prefix.as_str())).collect();
|
||||
(rows.len() == 1).then(|| rows[0].to_owned())
|
||||
};
|
||||
let id = uuid(&json!(candidate), "来源候选").ok().or_else(by_prefix)
|
||||
.filter(|id| state["candidates"].as_array().is_some_and(|rows| rows.contains(&json!(id))))
|
||||
.ok_or_else(|| invalid_source(dir, state, candidate, slot, variant))?;
|
||||
let record = read_candidate(dir, &id)?;
|
||||
let source_variant = record["binding"]["variantId"].as_str().ok_or("来源候选缺少花色")?;
|
||||
if !candidate_available(&record) || product_variant(state, source_variant)?["id"] != product_variant(state, variant)?["id"] {
|
||||
return Err("来源候选未完成或不属于当前商品花色".into());
|
||||
}
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
fn source_canvas<'a>(
|
||||
dir: &Path, state: &Value, variant: &str, component: &str, template: &Value,
|
||||
active: Option<&'a super::Document>,
|
||||
@ -215,34 +234,7 @@ pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value, source: O
|
||||
let (bytes, source, reference_index, references, density, manual) = match (manual, candidate, input["referenceIndex"].as_u64()) {
|
||||
(Some((bytes, evidence)), _, _) => (bytes, None, Value::Null, json!([]), 1.0, Some(evidence)),
|
||||
(None, Some(candidate), None) if input["referenceIndex"].is_null() => {
|
||||
// 编号前缀至少 8 位且在本项目候选中唯一时,按完整编号处理。
|
||||
let prefix = candidate.trim().to_ascii_lowercase();
|
||||
let by_prefix = || {
|
||||
let rows: Vec<&str> = state["candidates"].as_array().into_iter().flatten().filter_map(Value::as_str)
|
||||
.filter(|id| prefix.len() >= 8 && id.starts_with(prefix.as_str())).collect();
|
||||
(rows.len() == 1).then(|| rows[0].to_owned())
|
||||
};
|
||||
let id = uuid(&json!(candidate), "来源候选").ok().or_else(by_prefix)
|
||||
.filter(|id| state["candidates"].as_array().is_some_and(|rows| rows.contains(&json!(id))))
|
||||
.ok_or_else(|| invalid_source(dir, &state, candidate, slot, &variant))?;
|
||||
let record = read_candidate(dir, &id)?;
|
||||
let original_binding = &record["binding"];
|
||||
if !candidate_available(&record) || original_binding["variantId"] != variant {
|
||||
return Err("来源候选未完成或不属于当前商品花色".into());
|
||||
}
|
||||
let mut source_state = std::borrow::Cow::Borrowed(&state);
|
||||
if original_binding["templateHash"] != state["template"]["contentHash"] {
|
||||
let structure = hash(&json!([original_binding["templateHash"], state["width"]]).to_string());
|
||||
if !product_slot_binding(&state, original_binding) || original_binding["structureHash"] != structure {
|
||||
return Err("来源候选所用模板或画布宽度已变化".into());
|
||||
}
|
||||
let saved = source_state.to_mut();
|
||||
saved["template"]["contentHash"] = original_binding["templateHash"].clone();
|
||||
saved["structureHash"] = json!(structure);
|
||||
}
|
||||
if !candidate_uses_current_inputs(dir, &source_state, &record, &variant)? {
|
||||
return Err("来源候选的商品资料已变化".into());
|
||||
}
|
||||
let record = crop_source_candidate(dir, &state, candidate, slot, &variant)?;
|
||||
let density = record["canvasTransform"]["resolutionRatio"].as_f64().unwrap_or(1.0).min(1.0);
|
||||
let bytes = candidate_pixels(dir, &record["artifact"])?;
|
||||
let index = record["canvasTransform"]["referenceIndex"].clone();
|
||||
@ -518,6 +510,35 @@ mod tests {
|
||||
assert!(!quality.resolution_sufficient);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_crop_reuses_a_detail_candidate_for_the_same_color_sku() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let color = Uuid::new_v4().to_string();
|
||||
let other = Uuid::new_v4().to_string();
|
||||
let candidate = Uuid::new_v4().to_string();
|
||||
let dimensions = |height| json!({"length":"80","width":"40","height":height,"unit":"cm"});
|
||||
let state = json!({"variants":[{"id":color},{"id":other}],"candidates":[candidate],
|
||||
"activeOutput":"sku_images","productTemplates":{"sku_images":{}},
|
||||
"brief":{"variants":[{"id":color,"name":"原木色"}],
|
||||
"barcodeBindings":{(color.as_str()):["BC-WHEEL","BC-PLAIN"]},
|
||||
"barcodeEntries":[
|
||||
{"barcode":"BC-WHEEL","variantId":color,"colorName":"原木色","specName":"带轮款","dimensions":dimensions("170")},
|
||||
{"barcode":"BC-PLAIN","variantId":color,"colorName":"原木色","specName":"无轮款","dimensions":dimensions("163")}
|
||||
]}});
|
||||
let target = super::super::production_stages(&state).into_iter()
|
||||
.find(|stage| stage["outputId"] == "sku_images" && stage["colorVariantId"] == color).unwrap();
|
||||
let variant = target["variantId"].as_str().unwrap();
|
||||
assert_ne!(variant, color);
|
||||
let record = json!({"version":2,"id":candidate,"phase":"complete","inputHash":"prior-detail-inputs",
|
||||
"binding":{"candidateId":candidate,"taskId":candidate,"variantId":color,"component":"detail",
|
||||
"templateHash":"prior-detail-template","structureHash":"prior-detail-frame"}});
|
||||
let path = super::super::candidate_path(dir.path(), &candidate).unwrap();
|
||||
write_json(&path, &record).unwrap();
|
||||
|
||||
assert_eq!(crop_source_candidate(dir.path(), &state, &candidate, "sku-slot", variant).unwrap(), record);
|
||||
assert!(crop_source_candidate(dir.path(), &state, &candidate, "sku-slot", &other).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closeup_resolution_uses_real_crop_pixels_and_zoom() {
|
||||
let transform: Transform = serde_json::from_value(json!({"crop":[250,250,750,750]})).unwrap();
|
||||
|
||||
@ -497,19 +497,19 @@ pub(super) fn run(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>,
|
||||
reply
|
||||
}
|
||||
};
|
||||
let epoch = &input["context"]["launch"]["writeEpoch"];
|
||||
let value = if epoch.is_u64() {
|
||||
let mut observed = canonical_pi_result(b, value.clone()).unwrap_or_else(|error| {
|
||||
let mut value = value;
|
||||
value["error"] = json!(error);
|
||||
value
|
||||
});
|
||||
let context = &input["context"];
|
||||
let mut observed = canonical_pi_result(b, value.clone()).unwrap_or_else(|error| {
|
||||
let mut value = value;
|
||||
value["error"] = json!(error);
|
||||
value["projectLocalId"] = json!(value["doc"].as_u64().and_then(|doc| b.locations.get(&doc)));
|
||||
value
|
||||
});
|
||||
let epoch = &context["launch"]["writeEpoch"];
|
||||
if epoch.is_u64() {
|
||||
observed["writeEpoch"] = epoch.clone();
|
||||
observed
|
||||
} else {
|
||||
canonical_pi_result(b, value)?
|
||||
};
|
||||
Ok(value)
|
||||
}
|
||||
observed["turnId"] = context["requestScope"]["turnId"].clone();
|
||||
Ok(observed)
|
||||
}
|
||||
|
||||
pub(super) fn record_export_event(
|
||||
@ -611,32 +611,12 @@ fn workflow_receipt(delegation: &Value, result: R<Value>) -> R<Value> {
|
||||
|
||||
#[derive(Default)]
|
||||
struct WorkflowChildren {
|
||||
workers: Vec<mpsc::Receiver<()>>,
|
||||
seen: std::collections::HashSet<String>,
|
||||
}
|
||||
impl WorkflowChildren {
|
||||
fn start(&mut self, b: &Backend, delegation: &Value, scope: (&str, &str, u64), cancellation: Arc<AtomicBool>, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<()> {
|
||||
let (run, project, doc) = scope;
|
||||
let (method, input) = workflow_delegation(delegation, run, &b.origin, &b.auth["account"]["id"], project, doc)?;
|
||||
// A new delegation is issued only after the GUI consumes the previous
|
||||
// terminal event. Join its remaining teardown before opening the next
|
||||
// operation, rather than racing is_finished against event delivery.
|
||||
let batch = input["detailBatch"] == true;
|
||||
let mut index = 0;
|
||||
while index < self.workers.len() {
|
||||
if !batch {
|
||||
self.workers.swap_remove(index).recv().map_err(|_| "原工作流线程异常,结果需核查")?;
|
||||
} else {
|
||||
match self.workers[index].try_recv() {
|
||||
Ok(()) => { self.workers.swap_remove(index); }
|
||||
Err(mpsc::TryRecvError::Disconnected) => {
|
||||
self.workers.swap_remove(index);
|
||||
return Err("原工作流线程异常,结果需核查".into());
|
||||
}
|
||||
Err(mpsc::TryRecvError::Empty) => index += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
let operation = delegation["operationId"].as_str().ok_or("操作身份缺失")?.to_owned();
|
||||
if !self.seen.insert(operation) { return Err("原工作流操作已登记,不会重发".into()); }
|
||||
let mut child_backend = b.clone();
|
||||
@ -644,26 +624,15 @@ impl WorkflowChildren {
|
||||
let child_ctx = ctx.clone();
|
||||
let receipt_identity = delegation.clone();
|
||||
static WORKFLOWS: std::sync::OnceLock<super::reads::ReadPool> = std::sync::OnceLock::new();
|
||||
let (finished, completion) = mpsc::channel();
|
||||
WORKFLOWS.get_or_init(|| super::reads::ReadPool::with_limits(3, 24)).submit(move || {
|
||||
// The existing business dispatcher retains its journals, reference
|
||||
// ownership checks and final single-POST barrier. The parent keeps
|
||||
// the project slot throughout.
|
||||
let result = super::images::with_run_cancellation(cancellation, ||
|
||||
child_backend.slot_action(&method, &input, &child_events, &child_ctx));
|
||||
let _ = child_events.send(Event::Json(method, workflow_receipt(&receipt_identity, result)));
|
||||
child_ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
let _ = finished.send(());
|
||||
}).map_err(|_| "本机工作流队列已满,未派发模型")?;
|
||||
self.workers.push(completion);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for WorkflowChildren {
|
||||
fn drop(&mut self) {
|
||||
for worker in self.workers.drain(..) { let _ = worker.recv(); }
|
||||
}
|
||||
}
|
||||
struct DaemonTurnGuard {
|
||||
daemon: Arc<agent_daemon::Daemon>,
|
||||
run_id: String,
|
||||
@ -846,6 +815,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx:
|
||||
static IMAGE_JOBS: std::sync::OnceLock<super::reads::ReadPool> = std::sync::OnceLock::new();
|
||||
let screen_reader = Arc::new(super::canvas_workspace::ScreenReader::default());
|
||||
let mut late_workflow_replies = Vec::new();
|
||||
let mut stop_deadline = None;
|
||||
let start_workflow = |children: &mut WorkflowChildren, delegation: &Value, run: Option<&str>| {
|
||||
if b.exiting() { return Err("客户端正在退出,未派发工作流".into()); }
|
||||
let start = b.check_dispatch().and_then(|()| run.ok_or_else(|| "原对话尚未连接到当前项目".to_owned()))
|
||||
@ -862,20 +832,18 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx:
|
||||
for delegation in take_late_workflow_delegations(&mut late_workflow_replies) {
|
||||
let _ = start_workflow(&mut workflow_children, &delegation, bound_run.as_deref());
|
||||
}
|
||||
let value = if bound_run.is_none() && late_workflow_replies.is_empty() {
|
||||
receiver.recv_timeout(startup_deadline.saturating_duration_since(std::time::Instant::now()))
|
||||
.map_err(|error| match error {
|
||||
mpsc::RecvTimeoutError::Timeout => BridgeFailure::interrupted("小壹启动会话超时,原请求需核查", true),
|
||||
mpsc::RecvTimeoutError::Disconnected => BridgeFailure::interrupted("小壹的本机连接中断,原请求需核查", true),
|
||||
})??
|
||||
} else if late_workflow_replies.is_empty() {
|
||||
receiver.recv().map_err(|_| BridgeFailure::interrupted("小壹的本机连接中断,原请求需核查", true))??
|
||||
} else {
|
||||
match receiver.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok(value) => value?,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => continue,
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => return Err(BridgeFailure::interrupted("小壹的本机连接中断,原请求需核查", true)),
|
||||
}
|
||||
let now = std::time::Instant::now();
|
||||
if cancellation.load(Ordering::SeqCst)
|
||||
&& now >= *stop_deadline.get_or_insert(now + agent_daemon::TURN_STOP_TIMEOUT) {
|
||||
return Err(BridgeFailure::new("cancelled", false, true, "停止等待超时,在途请求可按原编号核查"));
|
||||
}
|
||||
if bound_run.is_none() && now >= startup_deadline {
|
||||
return Err(BridgeFailure::interrupted("小壹启动会话超时,原请求需核查", true));
|
||||
}
|
||||
let value = match receiver.recv_timeout(Duration::from_millis(250)) {
|
||||
Ok(value) => value?,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => continue,
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => return Err(BridgeFailure::interrupted("小壹的本机连接中断,原请求需核查", true)),
|
||||
};
|
||||
if value["runId"] != daemon_run { return Err("小壹未能核对本次对话".into()); }
|
||||
if value["type"] == "auth_failure" {
|
||||
@ -1175,7 +1143,9 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx:
|
||||
break value["value"].clone();
|
||||
}
|
||||
};
|
||||
drop(workflow_children);
|
||||
for delegation in take_late_workflow_delegations(&mut late_workflow_replies) {
|
||||
let _ = start_workflow(&mut workflow_children, &delegation, bound_run.as_deref());
|
||||
}
|
||||
daemon.end(&daemon_run);
|
||||
turn_guard.complete = true;
|
||||
if b.check_dispatch().is_err() && result["phase"] != "paused" {
|
||||
|
||||
@ -2902,6 +2902,7 @@ impl Workspace {
|
||||
"selectedLayerIds":references.iter().filter_map(|item|item["nativeLayerId"].as_u64()).collect::<std::collections::BTreeSet<_>>() }),
|
||||
};
|
||||
let mut scope = self.request_scope(active.doc.id.0, subject, &references);
|
||||
scope["turnId"] = json!(uuid::Uuid::new_v4());
|
||||
let canvas = product_document_key(&active.doc);
|
||||
if canvas.is_object() {
|
||||
scope["project"]["workspaceId"] = canvas["workspaceId"].clone();
|
||||
@ -3213,8 +3214,9 @@ impl Workspace {
|
||||
|
||||
fn receive_json_agent(&mut self, app: &mut PhotocraftApp, v: Value) {
|
||||
if v["engine"] == "pi" {
|
||||
let production = self.pi_product_production;
|
||||
self.pi_received(app, &v);
|
||||
if self.pi_product_production {
|
||||
if production {
|
||||
self.production_agent_received(app, &v);
|
||||
}
|
||||
return;
|
||||
@ -3485,33 +3487,40 @@ impl Workspace {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if method == "agent" && self.production_stop["state"] == "stopping"
|
||||
&& let Ok(value) = &mut result
|
||||
&& value["writeEpoch"].as_u64().is_some_and(|epoch|
|
||||
self.product_production.as_ref().and_then(product_production::Run::session_epoch) == Some(epoch))
|
||||
{
|
||||
if value["failure"]["category"] == "cancelled" {
|
||||
value["error"] = Value::Null;
|
||||
let mut session_receipt = false;
|
||||
if method == "agent" {
|
||||
if let Ok(value) = &mut result {
|
||||
let stopping = self.production_stop["state"] == "stopping";
|
||||
session_receipt = self.matches_pi_turn(value);
|
||||
let queued_stop = stopping && value["failure"]["category"] == "cancelled"
|
||||
&& value["failure"]["dispatched"] == false && value["writeEpoch"].is_null()
|
||||
&& value["doc"].as_u64() == self.owner_doc
|
||||
&& value["accountId"] == self.account["id"] && value["origin"] == self.origin;
|
||||
if !session_receipt && !queued_stop && (value["turnId"].is_string()
|
||||
|| value["engine"] == "pi" && value["writeEpoch"].is_u64()) {
|
||||
return;
|
||||
}
|
||||
if stopping && (session_receipt || queued_stop) {
|
||||
if value["failure"]["category"] == "cancelled" { value["error"] = Value::Null; }
|
||||
self.pi_received(app, value);
|
||||
self.release_pi_turn();
|
||||
return;
|
||||
}
|
||||
} else if matches!(self.busy.as_deref(), Some("agent" | "pi-agent" | "agent-stopping")) {
|
||||
self.release_pi_turn();
|
||||
}
|
||||
self.pi_received(app, value);
|
||||
if matches!(self.busy.as_deref(), Some("agent" | "pi-agent")) { self.busy = None; }
|
||||
return;
|
||||
}
|
||||
if let Ok(value) = &mut result {
|
||||
let session_receipt = matches!(method.as_str(), "agent" | "agent-stream")
|
||||
&& value["writeEpoch"].as_u64().is_some_and(|epoch|
|
||||
self.product_production.as_ref().and_then(product_production::Run::session_epoch) == Some(epoch))
|
||||
&& self.pi_product_production && !self.pi_write_blocked;
|
||||
if !session_receipt && !self.accepts_production_epoch(&value["writeEpoch"]) {
|
||||
if self.revoked_write_epoch(&value["writeEpoch"])
|
||||
&& (method == "agent" && matches!(self.busy.as_deref(), Some("agent" | "pi-agent"))
|
||||
|| self.busy.as_deref() == Some(method.as_str()) && matches!(method.as_str(), "slot-skeleton" | "slot-product-export"))
|
||||
&& self.busy.as_deref() == Some(method.as_str()) && matches!(method.as_str(), "slot-skeleton" | "slot-product-export")
|
||||
{
|
||||
self.busy = None;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(error) = value["executionError"].as_str() {
|
||||
if method == "agent" { self.release_pi_turn(); }
|
||||
result = Err(error.to_owned());
|
||||
}
|
||||
}
|
||||
@ -3668,7 +3677,7 @@ impl Workspace {
|
||||
}
|
||||
|
||||
fn receive_json_error(&mut self, method: &str, e: String) {
|
||||
if matches!(method, "slot-skeleton" | "slot-product-export" | "agent")
|
||||
if matches!(method, "slot-skeleton" | "slot-product-export")
|
||||
|| method == "save" && (self.pending_slot_apply.is_some()
|
||||
|| self.product_production.as_ref().is_some_and(product_production::Run::awaiting_canvas_save)) {
|
||||
self.product_production = None;
|
||||
@ -5546,9 +5555,10 @@ pub fn product_document_key(doc: &Document) -> Value {
|
||||
}
|
||||
|
||||
pub(crate) fn poll_engine_jobs(app: &mut PhotocraftApp) -> Vec<photocraft_engine::jobs::JobEvent> {
|
||||
let native_job = app.jiansun.as_ref()
|
||||
.and_then(|w| w.pi_run.as_deref().and_then(|run| w.agent_native.pending_job(run)));
|
||||
if let Some(job) = native_job && let Some(mut workspace) = app.jiansun.take() {
|
||||
let native_jobs: Vec<_> = app.jiansun.as_ref()
|
||||
.and_then(|w| w.pi_run.as_deref().map(|run| w.agent_native.pending_jobs(run).collect()))
|
||||
.unwrap_or_default();
|
||||
if !native_jobs.is_empty() && let Some(mut workspace) = app.jiansun.take() {
|
||||
let mut events = Vec::new();
|
||||
if !workspace.authority_active() {
|
||||
workspace.agent_native.cancel();
|
||||
@ -5558,13 +5568,13 @@ pub(crate) fn poll_engine_jobs(app: &mut PhotocraftApp) -> Vec<photocraft_engine
|
||||
events = workspace.with_product_target(app, |w, app| {
|
||||
w.record_manual_layers_from_observer(app);
|
||||
agent_native::settle_jobs(w, app);
|
||||
let events = app.session.poll_jobs_where(|id| id == job);
|
||||
let events = app.session.poll_jobs_where(|id| native_jobs.contains(&id));
|
||||
agent_native::settle_jobs(w, app);
|
||||
events
|
||||
});
|
||||
}
|
||||
app.jiansun = Some(workspace);
|
||||
events.extend(app.session.poll_jobs_where(|id| id != job));
|
||||
events.extend(app.session.poll_jobs_where(|id| !native_jobs.contains(&id)));
|
||||
return events;
|
||||
}
|
||||
app.session.poll_jobs()
|
||||
|
||||
@ -22,6 +22,7 @@ struct OwnedJob {
|
||||
origin: String,
|
||||
project: Value,
|
||||
document: u64,
|
||||
canvas: Value,
|
||||
index: usize,
|
||||
before: u64,
|
||||
target_layers: Vec<u64>,
|
||||
@ -235,7 +236,11 @@ impl State {
|
||||
}
|
||||
|
||||
pub(super) fn pending_job(&self, run: &str) -> Option<JobId> {
|
||||
self.jobs.iter().find(|job| job.run == run && job.terminal.is_none()).map(|job| job.id)
|
||||
self.pending_jobs(run).next()
|
||||
}
|
||||
|
||||
pub(super) fn pending_jobs<'a>(&'a self, run: &'a str) -> impl Iterator<Item = JobId> + 'a {
|
||||
self.jobs.iter().filter(move |job| job.run == run && job.terminal.is_none()).map(|job| job.id)
|
||||
}
|
||||
|
||||
fn make_room(&mut self) -> Result<(), String> {
|
||||
@ -553,6 +558,7 @@ fn register_job(w: &mut Workspace, app: &PhotocraftApp, job: JobId, document: u6
|
||||
if w.agent_native.jobs.iter().any(|record| record.id == job) { return Err("原生任务编号已登记,不会重复派发".into()); }
|
||||
w.agent_native.jobs.push_back(OwnedJob { id:job,run:w.pi_run.clone().ok_or("原生会话已结束")?,account:w.account["id"].clone(),
|
||||
origin:w.origin.clone(),project:w.pi_request_scope["project"]["localId"].clone(),document,
|
||||
canvas:app.session.active().map(|state| super::product_document_key(&state.doc)).unwrap_or_default(),
|
||||
index:app.session.active_index().ok_or("原生任务文档索引不可用")?,before,target_layers,command:command.into(),cancelled:token,terminal:None });
|
||||
Ok(())
|
||||
}
|
||||
@ -620,7 +626,6 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte
|
||||
return Ok(json!({"executed":false,"completed":true,"pending":false,"error":error})),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
if !read && w.agent_native.pending_job(input["run"].as_str().unwrap_or("")).is_some() { return Err("原生任务仍在处理中,请核查原任务,不重复派发".into()); }
|
||||
safe_services(app)?;
|
||||
if !read { w.agent_native.make_room()?; }
|
||||
let (mut scope, token) = if read {
|
||||
@ -638,6 +643,20 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte
|
||||
let target_layers: Vec<_> = native_params["params"]["layer"].as_u64().into_iter()
|
||||
.chain(native_params["params"]["layers"].as_array().into_iter().flatten().filter_map(Value::as_u64))
|
||||
.collect();
|
||||
let mut job_layers = target_layers.clone();
|
||||
if method == "engine.execute" && !read && command != "layer.select" {
|
||||
let state = app.session.active().ok_or("当前画布未打开")?;
|
||||
if job_layers.is_empty() && !command.starts_with("layer.new.") {
|
||||
job_layers.extend(state.selected_layers().into_iter().map(|layer| layer.0));
|
||||
}
|
||||
let canvas = super::product_document_key(&state.doc);
|
||||
if let Some(job) = w.agent_native.jobs.iter().find(|job| job.document == document
|
||||
&& job.run == input["run"] && job.canvas == canvas && job.terminal.is_none()
|
||||
&& job.target_layers.iter().any(|layer| job_layers.contains(layer))) {
|
||||
return Err(BridgeFailure::new("native_target_busy", true, false,
|
||||
format!("同一图层的原生任务 {} 仍在处理中,请核查原任务", job.id.0)));
|
||||
}
|
||||
}
|
||||
let template_policy = if method == "engine.execute" && !read && command != "layer.select"
|
||||
&& w.pi_product_production {
|
||||
let state = app.session.active().ok_or("当前画布未打开")?;
|
||||
@ -723,7 +742,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte
|
||||
if result["pending"] == true {
|
||||
let job = result["job"].as_u64().map(JobId).ok_or_else(|| unknown("原生任务未返回可核查编号".into()))?;
|
||||
let token = token.ok_or_else(|| unknown("读取操作意外启动了原生任务".into()))?;
|
||||
register_job(w, app, job, document, before, &command, target_layers.clone(), token).map_err(unknown)?;
|
||||
register_job(w, app, job, document, before, &command, job_layers, token).map_err(unknown)?;
|
||||
let result = w.agent_native.project_result(result).map_err(unknown)?;
|
||||
let mut value = receipt(w, document, (before, revision), method, &command, &result, true);
|
||||
value["job"] = json!(job.0);
|
||||
@ -735,7 +754,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte
|
||||
}
|
||||
Outcome::AfterJob(job) => {
|
||||
let token = token.ok_or_else(|| unknown("读取操作意外启动了原生任务".into()))?;
|
||||
register_job(w, app, job, document, before, &command, target_layers.clone(), token).map_err(unknown)?;
|
||||
register_job(w, app, job, document, before, &command, job_layers, token).map_err(unknown)?;
|
||||
let result = json!({"job":job.0,"pending":true});
|
||||
let mut value = receipt(w, document, (before, revision), method, &command, &result, true);
|
||||
value["job"] = json!(job.0);
|
||||
@ -796,8 +815,9 @@ pub(super) fn settle_jobs(w: &mut Workspace, app: &PhotocraftApp) -> Vec<Value>
|
||||
let mut applied_here = false;
|
||||
let mut block = false;
|
||||
let production_workspace = super::pi_bridge::production_workspace_active(w);
|
||||
let canvas = super::product_document_key(&active.doc);
|
||||
let target_blocked_jobs: std::collections::HashSet<JobId> = w.agent_native.jobs.iter()
|
||||
.filter(|owned| owned.run == run && owned.terminal.is_none() && owned.document == document)
|
||||
.filter(|owned| owned.run == run && owned.terminal.is_none() && owned.document == document && owned.canvas == canvas)
|
||||
.filter(|owned| owned.target_layers.iter().any(|&id| {
|
||||
w.production_layer_rejection(&active.doc, photocraft_doc::LayerId(id))
|
||||
.is_some_and(|reason| matches!(reason, super::product_production::LayerRejection::UserEdit | super::product_production::LayerRejection::UserLock))
|
||||
@ -857,7 +877,7 @@ pub(super) fn settle_jobs(w: &mut Workspace, app: &PhotocraftApp) -> Vec<Value>
|
||||
// The engine leaves the document unchanged when a job fails (a locked layer,
|
||||
// say) and records no application for it. Report that like a synchronous
|
||||
// command error; only an unverifiable application revokes the run's writes.
|
||||
let failed_unapplied = same && info.state == "failed" && !application.is_object()
|
||||
let failed_unapplied = same && matches!(info.state, "failed" | "cancelled") && !application.is_object()
|
||||
&& info.document.map(|doc| doc.0) == Some(document);
|
||||
if verified {
|
||||
w.expected_revision = revision;
|
||||
@ -2022,6 +2042,30 @@ mod tests {
|
||||
job
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn production_recovery_native_bridge_blocks_only_its_pending_target_layer() {
|
||||
let (mut w, mut app, _) = fixture();
|
||||
let other = app.session.active().unwrap().active_layer.unwrap();
|
||||
app.session.execute("layer.new.layer", json!({"name":"正在处理的图层"})).unwrap();
|
||||
let state = app.session.active().unwrap();
|
||||
let target = state.active_layer.unwrap();
|
||||
w.expected_revision = state.revision;
|
||||
let job = start_owned_worker(&mut w, &mut app);
|
||||
w.agent_native.jobs.back_mut().unwrap().target_layers = vec![target.0];
|
||||
|
||||
assert_eq!(invoke(&mut w, &mut app, "ui.inspect", json!({})).unwrap()["completed"], true);
|
||||
let update = |layer: LayerId| json!({"command":"layer.setProps","params":{"layer":layer.0,"opacity":0.5}});
|
||||
let error = invoke(&mut w, &mut app, "engine.execute", update(target)).unwrap_err();
|
||||
assert!(error.contains(&job.0.to_string()));
|
||||
// Isolate bridge admission while its receipt is still pending and the engine's document lock is gone.
|
||||
assert!(app.session.cancel_job(job));
|
||||
let unrelated = invoke(&mut w, &mut app, "engine.execute", update(other)).unwrap();
|
||||
assert_eq!(unrelated["executed"], true, "{unrelated}");
|
||||
assert_eq!(app.session.active().unwrap().doc.layer(other).unwrap().opacity, 0.5);
|
||||
let _ = app.session.wait_job(job);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn simulate_user_revision(app: &mut PhotocraftApp) {
|
||||
// Simulate a user mutation that bypassed command admission, as UI
|
||||
|
||||
@ -785,9 +785,8 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
}
|
||||
if !input["targetOutput"].is_null() {
|
||||
let target = &input["targetOutput"];
|
||||
if !scoped_read || !production_workspace_active(w)
|
||||
|| !requested_production_output(w, target, &key) {
|
||||
return Err("所选图片不属于本轮制作输出".into());
|
||||
if !scoped_read {
|
||||
return Err("跨画布候选读取仅对当前本机Agent会话开放".into());
|
||||
}
|
||||
return Ok(json!({"projectScope":true,"workspaceId":w.template_workflow["workspaceId"],
|
||||
"outputId":target["outputId"],"variantId":target["variantId"],"slotId":input["slotId"],
|
||||
@ -998,8 +997,6 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
let text = input["text"].as_str().filter(|s| s.len() <= 65000).ok_or("回复无效")?;
|
||||
w.messages.push(json!({"role":"assistant","kind":"reply","text":text,"target":w.pi_request_scope["subject"]}));
|
||||
w.stream_reply.clear();
|
||||
let operation_in_flight = w.pi_run.as_deref().is_some_and(|run| w.workflow.operation_in_flight(run));
|
||||
if operation_in_flight { w.handover(); }
|
||||
if w.busy.as_deref() != Some("slot-append") {
|
||||
w.busy = if w.pi_native { Some("agent".into()) } else { None };
|
||||
}
|
||||
@ -1017,7 +1014,40 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(super) fn matches_pi_turn(&self, value: &Value) -> bool {
|
||||
if value["doc"].as_u64().is_none() || value["doc"].as_u64() != self.owner_doc
|
||||
|| value["accountId"] != self.account["id"] || value["origin"] != self.origin {
|
||||
return false;
|
||||
}
|
||||
if value["turnId"].is_string() {
|
||||
return value["turnId"] == self.pi_request_scope["turnId"];
|
||||
}
|
||||
(self.pi_product_production || self.production_stop["state"] == "stopping")
|
||||
&& value["writeEpoch"].as_u64().is_some_and(|epoch|
|
||||
self.product_production.as_ref().and_then(super::product_production::Run::session_epoch) == Some(epoch))
|
||||
}
|
||||
|
||||
pub(super) fn release_pi_turn(&mut self) {
|
||||
if matches!(self.busy.as_deref(), Some("agent" | "pi-agent" | "agent-stopping")) {
|
||||
self.busy = None;
|
||||
}
|
||||
if self.pi_run.take().is_some() {
|
||||
self.queue.clear();
|
||||
self.recording_edit_owner = None;
|
||||
self.pi_ui_cancel("回合已结束");
|
||||
}
|
||||
self.pi_native = false;
|
||||
self.pi_product_production = false;
|
||||
self.pi_request_scope = Value::Null;
|
||||
self.pi_queued_steering.clear();
|
||||
self.pi_queued_followup.clear();
|
||||
self.agent_presence.finish_run(Instant::now());
|
||||
if self.pi_context_usage.is_object() { self.pi_context_usage["phase"] = json!("ready"); }
|
||||
}
|
||||
|
||||
pub(super) fn pi_received(&mut self, app: &PhotocraftApp, value: &Value) {
|
||||
let owns_turn = self.matches_pi_turn(value);
|
||||
if owns_turn { self.release_pi_turn(); }
|
||||
if value["accountId"] != self.account["id"] || value["origin"] != self.origin || value["doc"].as_u64() != app.session.active().map(|s| s.doc.id.0) {
|
||||
return;
|
||||
}
|
||||
@ -1036,18 +1066,14 @@ impl Workspace {
|
||||
return;
|
||||
}
|
||||
let slot_running = self.busy.as_deref() == Some("slot-append");
|
||||
if self.pi_run.as_deref().is_some_and(|run| self.workflow.operation_in_flight(run)) { self.handover(); }
|
||||
if !slot_running { self.busy = None; }
|
||||
self.pi_queued_steering.clear();
|
||||
self.pi_queued_followup.clear();
|
||||
self.pi_run = None;
|
||||
self.pi_native = false;
|
||||
if !owns_turn { self.release_pi_turn(); }
|
||||
self.unknown = slot_running;
|
||||
let workflow = &value["workflow"];
|
||||
let visible_mapping = app.session.active().and_then(|state| super::canvas_workspace::document_mapping(&state.doc));
|
||||
// A late production receipt can describe a different output on the same tab.
|
||||
// Keep the workflow paired with the visible document.
|
||||
if workflow.is_object() && visible_mapping.as_ref().is_none_or(|mapping|
|
||||
if workflow.is_object() && (!self.pi_write_blocked || self.accepts_production_epoch(&value["writeEpoch"]))
|
||||
&& visible_mapping.as_ref().is_none_or(|mapping|
|
||||
mapping["canvasFirst"] != true || workflow["canvasFirst"] != true
|
||||
|| (mapping["component"] == workflow["outputId"] && mapping["variantId"] == workflow["variantId"]
|
||||
&& mapping["workspaceId"] == workflow["workspaceId"]))
|
||||
@ -1055,8 +1081,8 @@ impl Workspace {
|
||||
self.receive_template_snapshot(workflow, false);
|
||||
// Only the canonical full-project pending summary can release the
|
||||
// dependency barrier; settling Pi cannot resolve another task.
|
||||
self.unknown |= self.template_workflow["pending"].as_bool().unwrap_or(true);
|
||||
}
|
||||
self.unknown |= self.template_workflow["pending"] == true;
|
||||
self.pi_review = value["review"] == true;
|
||||
self.pi_usage = value["usage"].clone();
|
||||
if let Some(usage)=value.get("contextUsage") { self.pi_context_usage=usage.clone(); }
|
||||
@ -1068,10 +1094,6 @@ impl Workspace {
|
||||
if !self.unknown {
|
||||
self.stream_reply.clear();
|
||||
}
|
||||
if !self.unknown {
|
||||
self.pi_request_scope = Value::Null;
|
||||
self.pi_product_production = false;
|
||||
}
|
||||
self.draft_changed = true;
|
||||
}
|
||||
}
|
||||
@ -1185,6 +1207,45 @@ mod tests {
|
||||
assert_eq!(stale.category, "auth_revoked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_recovery_reads_a_project_output_outside_the_current_canvas() {
|
||||
let (mut w, mut app, mut input) = activity_fixture();
|
||||
mount_activity_canvas(&mut w, &mut app, "detail", "chair");
|
||||
w.template_workflow["workspaceId"] = json!("workspace");
|
||||
input["targetOutput"] = json!({"outputId":"sku_images","variantId":"chair"});
|
||||
input["slotId"] = json!("sku-slot");
|
||||
input["candidateId"] = json!("candidate");
|
||||
let target = action_impl(&mut w, &mut app, None, "pi-detail-images", &input, true).unwrap();
|
||||
assert_eq!(target["projectScope"], true);
|
||||
assert_eq!(target["workspaceId"], "workspace");
|
||||
assert_eq!(target["outputId"], "sku_images");
|
||||
assert_eq!(target["slotId"], "sku-slot");
|
||||
assert!(action_impl(&mut w, &mut app, None, "pi-detail-images", &input, false).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_recovery_conversation_receipt_releases_own_lease_before_projection() {
|
||||
let (mut w, app, _) = canonical_fixture();
|
||||
w.pi_request_scope["turnId"] = json!("current-turn");
|
||||
let mut value = canonical_receipt(&w, &app, false);
|
||||
value["turnId"] = json!("current-turn");
|
||||
value["writeEpoch"] = json!(2);
|
||||
w.write_epoch = 4;
|
||||
w.pi_write_blocked = true;
|
||||
value["projectLocalId"] = json!("previous-binding");
|
||||
let original_workflow = w.template_workflow.clone();
|
||||
w.pi_received(&app, &value);
|
||||
assert!(w.busy.is_none());
|
||||
assert_eq!(w.template_workflow, original_workflow);
|
||||
|
||||
w.pi_request_scope["turnId"] = json!("next-turn");
|
||||
value = canonical_receipt(&w, &app, false);
|
||||
value["turnId"] = json!("next-turn");
|
||||
value["workflow"].as_object_mut().unwrap().remove("pending");
|
||||
w.pi_received(&app, &value);
|
||||
assert!(!w.unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_dispatch_carries_optional_worker_and_native_slot_frame() {
|
||||
let (mut w, mut app, mut input) = activity_fixture();
|
||||
|
||||
@ -95,7 +95,9 @@ pub(super) struct Run {
|
||||
delivery_cancellation: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
|
||||
delivery_write_epoch: Option<u64>,
|
||||
all_outputs_completed: bool,
|
||||
restarted: bool,
|
||||
agent_retries: usize,
|
||||
turn_waits: u8,
|
||||
stop_deadline: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
@ -109,7 +111,7 @@ impl Run {
|
||||
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,
|
||||
started_at, paused_at, paused_seconds: 0, agent_retries: 0, turn_waits: 0, stop_deadline: None,
|
||||
delivery_dir: None, delivery_id: None, published: Vec::new(), delivery_receipt: Value::Null,
|
||||
delivery_cancellation: None, delivery_write_epoch: None, all_outputs_completed: false }
|
||||
}
|
||||
@ -305,7 +307,10 @@ impl Run {
|
||||
Phase::AwaitingSave => format!("正在保存{label}画布,保存后自动开始制作"),
|
||||
Phase::Agent if self.bound.is_none() => "正在规划本轮输出".into(),
|
||||
Phase::Agent => format!("正在制作{label}"),
|
||||
Phase::Paused(_) => "已暂停".into(),
|
||||
Phase::Paused(ref pause) => match pause["reason"].as_str() {
|
||||
Some(reason) => format!("已暂停 · {reason}"),
|
||||
None => "已暂停".into(),
|
||||
},
|
||||
Phase::Export => format!("正在保存{label}"),
|
||||
Phase::DeliveringBundle => unreachable!(),
|
||||
Phase::WaitingOriginals { .. } => format!("{label}等待原请求结果,确认后自动继续"),
|
||||
|
||||
@ -3,6 +3,22 @@ use crate::jiansun::{PhotocraftApp, Request, Value, Workspace, json};
|
||||
use crate::jiansun::multi_project_state::ProjectRunVisualStatus;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn verified_bundle(receipt: &Value, delivery_id: Option<&str>) -> bool {
|
||||
let (Some(path), Some(delivery_id)) = (receipt["path"].as_str(), delivery_id) else { return false; };
|
||||
if receipt["state"] != "bundle_saved" || receipt["allOutputsCompleted"] != true { return false; }
|
||||
let root = std::path::Path::new(path);
|
||||
let Ok(bytes) = std::fs::read(root.join("交付清单.json")) else { return false; };
|
||||
let Ok(manifest) = serde_json::from_slice::<Value>(&bytes) else { return false; };
|
||||
manifest["deliveryId"] == delivery_id && manifest["allOutputsCompleted"] == true
|
||||
&& manifest["files"].as_array().is_some_and(|files| !files.is_empty() && files.iter().all(|file| {
|
||||
let Some(path) = file["relativePath"].as_str().map(std::path::Path::new) else { return false; };
|
||||
file["verified"] == true
|
||||
&& path.components().all(|part| matches!(part, std::path::Component::Normal(_)))
|
||||
&& std::fs::File::open(root.join(path)).and_then(|file| file.metadata()).is_ok_and(|meta|
|
||||
meta.is_file() && file["sizeBytes"].as_u64() == Some(meta.len()))
|
||||
}))
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn production_finish_status(&self, id: &str) -> Value {
|
||||
let Some(run) = self.product_production.as_ref() else { return Value::Null; };
|
||||
@ -294,7 +310,10 @@ impl Workspace {
|
||||
} else {
|
||||
run.finish_receipt["error"] = run.delivery_receipt["error"].clone();
|
||||
}
|
||||
if run.finish.take().is_some() && self.pi_run.is_some() && self.production_exit.is_none() {
|
||||
if self.production_exit.is_none()
|
||||
&& (run.finish.take().is_some() && self.pi_run.is_some()
|
||||
|| completed && matches!(self.busy.as_deref(), Some("agent" | "pi-agent" | "slot-append")))
|
||||
{
|
||||
run.phase = Phase::Agent;
|
||||
self.product_production = Some(run);
|
||||
self.checkpoint_production();
|
||||
@ -306,6 +325,8 @@ impl Workspace {
|
||||
pub(super) fn note_production_summary(&mut self, mut run: Run) {
|
||||
let complete = run.delivery_receipt["path"].is_string()
|
||||
&& run.delivery_completed(&run.finish_receipt["knownIssues"]);
|
||||
let upload = self.production_exit.is_none() && self.authority_active() && run.all_outputs_completed
|
||||
&& verified_bundle(&run.delivery_receipt, run.delivery_id.as_deref());
|
||||
let partial = !complete && (!run.published.is_empty() || run.delivery_receipt["path"].is_string());
|
||||
if partial {
|
||||
run.prepare_partial_continuation();
|
||||
@ -365,6 +386,13 @@ impl Workspace {
|
||||
"productionDelivery":receipt,
|
||||
"productionSummary":{"exported":exported,"total":run.total,"drafts":run.drafts,"slotCoverage":coverage}}));
|
||||
self.draft_changed = true;
|
||||
if upload && let Some(&revision) = self.persisted_revisions.get(&run.doc)
|
||||
{
|
||||
// The bundle checkpoint is queued above. Use the same completed
|
||||
// project action as “完结并提交” with the revision already on disk.
|
||||
self.sync_request_meta = self.sync_signature();
|
||||
self.send("project-sync", json!({"doc":run.doc,"revision":revision,"status":"completed"}));
|
||||
}
|
||||
if partial { self.product_production = Some(run); }
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,6 +4,10 @@ use std::collections::HashSet;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const AGENT_RETRY_SECONDS: [u64; 3] = [3, 15, 60];
|
||||
const TURN_WAIT_LIMIT: u8 = 30;
|
||||
const STOP_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn single_project_run_owner(&self) -> Option<u64> {
|
||||
if super::super::multi_project_state::MULTI_PROJECT_CONCURRENCY_ENABLED { return None; }
|
||||
@ -22,7 +26,7 @@ impl Workspace {
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn revoke_production_epoch(&mut self) {
|
||||
if !self.pi_product_production || self.pi_write_blocked { return; }
|
||||
if !self.pi_product_production { return; }
|
||||
self.cancel_deferred_image_recovery();
|
||||
self.write_epoch += 1;
|
||||
self.pi_write_blocked = true;
|
||||
@ -157,7 +161,9 @@ impl Workspace {
|
||||
pause(run.doc, &run.project, run.session_epoch);
|
||||
}
|
||||
self.handover();
|
||||
run.pause(json!({"reason":"用户已停止制作"}));
|
||||
let waiting = Self::production_waiting_originals(&run.phase);
|
||||
run.pause(json!({"reason":"用户已停止制作","waitingOriginals":waiting}));
|
||||
run.stop_deadline = Some(Instant::now() + STOP_TIMEOUT);
|
||||
run.opening = None;
|
||||
run.finish = None;
|
||||
run.finish_receipt = Value::Null;
|
||||
@ -183,12 +189,24 @@ impl Workspace {
|
||||
}
|
||||
|
||||
fn settle_production_stop(&mut self, app: &PhotocraftApp) {
|
||||
if self.product_production.as_ref().and_then(|run| run.stop_deadline)
|
||||
.is_some_and(|deadline| Instant::now() >= deadline) {
|
||||
self.release_pi_turn();
|
||||
if matches!(self.busy.as_deref(),
|
||||
Some("product-end-checkpoint" | "slot-append" | "slot-skeleton" | "slot-product-export")) {
|
||||
self.busy = None;
|
||||
}
|
||||
let reason = "停止等待超时,已暂停制作。在途请求可按原编号核查。";
|
||||
self.pause_production_run(reason);
|
||||
return;
|
||||
}
|
||||
if self.busy.is_some() || self.pi_run.is_some() || self.saving.is_some() || self.metadata_saving.is_some()
|
||||
|| self.product_view_save_pending() || self.production_write_pending() { return; }
|
||||
self.agent_presence.finish_run(Instant::now());
|
||||
if self.pi_context_usage.is_object() { self.pi_context_usage["phase"] = json!("ready"); }
|
||||
if self.production_stop["mode"] == "pause" {
|
||||
self.production_stop["state"] = json!("paused");
|
||||
if let Some(run) = self.product_production.as_mut() { run.stop_deadline = None; }
|
||||
return;
|
||||
}
|
||||
if self.production_stop["mode"] == "end" {
|
||||
@ -316,6 +334,9 @@ impl Workspace {
|
||||
}
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
run.resume_clock();
|
||||
run.agent_retries = 0;
|
||||
run.turn_waits = 0;
|
||||
run.stop_deadline = None;
|
||||
run.goal_user_entry = Some(text.clone());
|
||||
if self.production_stop["state"] == "interrupted" { self.error.clear(); }
|
||||
self.production_stop = json!({"mode":null,"state":"idle","reason":null,"error":null});
|
||||
@ -665,11 +686,7 @@ impl Workspace {
|
||||
if !(self.model_ready && self.image_ready) || self.production_model_problem().is_some() {
|
||||
let reason = self.production_model_problem().unwrap_or_else(||
|
||||
"请配置可用的对话与生图模型".into());
|
||||
let Some(mut run) = self.product_production.take() else { return; };
|
||||
for stage in &run.stages {
|
||||
run.drafts.push(json!({"outputId":stage.output,"variantId":stage.variant,"reason":reason}));
|
||||
}
|
||||
self.note_production_summary(run);
|
||||
self.pause_production_run(&reason);
|
||||
return;
|
||||
}
|
||||
let Some(run) = self.product_production.as_mut() else { return };
|
||||
@ -677,10 +694,11 @@ impl Workspace {
|
||||
run.phase = Phase::Agent;
|
||||
self.agent_effects_paused = false;
|
||||
self.submit_turn(app, "继续本轮制作".into(), true);
|
||||
if self.busy.as_deref() != Some("agent")
|
||||
&& let Some(run) = self.product_production.as_mut()
|
||||
{
|
||||
run.phase = Phase::AgentRetryAt(Instant::now() + Duration::from_secs(3));
|
||||
if self.busy.as_deref() != Some("agent") {
|
||||
let reason = self.error.clone();
|
||||
self.delay_production_turn(&reason);
|
||||
} else if let Some(run) = self.product_production.as_mut() {
|
||||
run.turn_waits = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@ -691,6 +709,9 @@ impl Workspace {
|
||||
|| value["origin"] != self.origin || value["projectLocalId"].as_str().is_none_or(|id| self.local_identity(id) != run.project) {
|
||||
return;
|
||||
}
|
||||
if run.all_outputs_completed {
|
||||
return;
|
||||
}
|
||||
if value["production"]["stageStatus"] == "paused" {
|
||||
let pause = &value["production"]["pause"];
|
||||
let reason = pause["reason"].as_str().unwrap_or_default();
|
||||
@ -711,10 +732,6 @@ impl Workspace {
|
||||
self.note(message);
|
||||
return;
|
||||
}
|
||||
if value["failure"]["category"] == "transport_interrupted" && value["failure"]["retryable"] == true
|
||||
&& self.defer_production_agent(app) {
|
||||
return;
|
||||
}
|
||||
let originals = &value["production"]["originals"];
|
||||
let models = original_ids(originals, "models");
|
||||
let images = original_ids(originals, "images");
|
||||
@ -734,31 +751,49 @@ impl Workspace {
|
||||
self.checkpoint_production();
|
||||
return;
|
||||
}
|
||||
if let Some(reason) = value["error"].as_str().or_else(|| value["failure"]["message"].as_str()) {
|
||||
if retryable_agent_failure(&value["failure"], reason) {
|
||||
self.delay_production_turn(reason);
|
||||
} else {
|
||||
self.pause_production_run(reason);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if value["failure"]["category"] == "cancelled" {
|
||||
self.pause_production_run("制作回合已取消");
|
||||
return;
|
||||
}
|
||||
let Some(mut run) = self.product_production.take() else { return; };
|
||||
let reason = value["error"].as_str().unwrap_or("本轮会话已结束,已保留现有进度");
|
||||
for stage in &run.stages {
|
||||
run.drafts.push(json!({"outputId":stage.output,"variantId":stage.variant,"reason":reason}));
|
||||
run.drafts.push(json!({"outputId":stage.output,"variantId":stage.variant,"reason":"本轮会话已结束,已保留现有进度"}));
|
||||
}
|
||||
self.note_production_summary(run);
|
||||
}
|
||||
|
||||
fn defer_production_agent(&mut self, app: &PhotocraftApp) -> bool {
|
||||
let Some(run) = self.product_production.as_mut() else { return false; };
|
||||
if run.phase != Phase::Agent || run.restarted
|
||||
|| app.session.active().is_none_or(|state| state.doc.id.0 != run.doc)
|
||||
{
|
||||
return false;
|
||||
fn delay_production_turn(&mut self, reason: &str) {
|
||||
let Some(run) = self.product_production.as_mut() else { return; };
|
||||
if let Some(&seconds) = AGENT_RETRY_SECONDS.get(run.agent_retries) {
|
||||
run.agent_retries += 1;
|
||||
run.opening = None;
|
||||
run.phase = Phase::AgentRetryAt(Instant::now() + Duration::from_secs(seconds));
|
||||
self.error.clear();
|
||||
} else {
|
||||
self.pause_production_run(reason);
|
||||
}
|
||||
run.restarted = true;
|
||||
run.phase = Phase::AgentRetryAt(Instant::now() + Duration::from_secs(3));
|
||||
if matches!(self.busy.as_deref(), Some("agent" | "pi-agent")) {
|
||||
self.busy = None;
|
||||
}
|
||||
self.pi_run = None;
|
||||
self.pi_request_scope = Value::Null;
|
||||
self.pi_product_production = false;
|
||||
}
|
||||
|
||||
fn pause_production_run(&mut self, reason: &str) {
|
||||
let Some(run) = self.product_production.as_mut() else { return; };
|
||||
run.opening = None;
|
||||
run.stop_deadline = None;
|
||||
let waiting = Self::production_waiting_originals(&run.phase);
|
||||
run.pause(json!({"reason":reason,"waitingOriginals":waiting}));
|
||||
self.production_stop = json!({"mode":"pause","state":"paused","reason":reason,"error":null});
|
||||
self.pi_write_blocked = true;
|
||||
self.agent_effects_paused = true;
|
||||
self.error.clear();
|
||||
true
|
||||
self.note(format!("制作已暂停。{reason}"));
|
||||
self.checkpoint_production();
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_operation_failed(&mut self, app: &PhotocraftApp, method: &str, reason: &str) -> bool {
|
||||
@ -770,16 +805,18 @@ impl Workspace {
|
||||
return true;
|
||||
}
|
||||
if method == "agent" && run.phase == Phase::Agent {
|
||||
if self.defer_production_agent(app) { return true; }
|
||||
if let Some(run) = self.product_production.take() {
|
||||
self.write_production_checkpoint(&run, true);
|
||||
}
|
||||
if !run.all_outputs_completed { self.pause_production_run(reason); }
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_retry_delay(&self, now: Instant) -> Option<Duration> {
|
||||
match self.product_production.as_ref()?.phase {
|
||||
let run = self.product_production.as_ref()?;
|
||||
if self.production_stop["state"] == "stopping" {
|
||||
return run.stop_deadline.map(|at| at.saturating_duration_since(now));
|
||||
}
|
||||
match run.phase {
|
||||
Phase::AgentRetryAt(at) if at > now => Some(at - now),
|
||||
_ => None,
|
||||
}
|
||||
@ -823,12 +860,19 @@ impl Workspace {
|
||||
self.settle_production_stop(app);
|
||||
return;
|
||||
}
|
||||
let Some(run) = self.product_production.as_ref() else { return; };
|
||||
if run.phase == Phase::DeliveringBundle { return; }
|
||||
if run.phase == Phase::Agent && run.all_outputs_completed {
|
||||
if self.pi_run.is_none() && self.busy.is_none()
|
||||
&& let Some(run) = self.product_production.take() {
|
||||
self.note_production_summary(run);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.production_stop["state"] != "delivering" && self.production_budget_delay() == Some(Duration::ZERO) {
|
||||
let _ = self.request_production_stop("deliver", "到达时间上限自动交付");
|
||||
return;
|
||||
}
|
||||
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;
|
||||
@ -849,16 +893,35 @@ impl Workspace {
|
||||
{
|
||||
self.production_canvas_open_failed(app, "save", "本机保存服务已断开,未绑定所选工作画布");
|
||||
}
|
||||
} else if saved && self.saving.is_none() && self.busy.is_none() && self.pending_slot_apply.is_none() {
|
||||
if self.can_start_production_turn() {
|
||||
self.production_start_session(app);
|
||||
} else if let Some(run) = self.product_production.as_mut() {
|
||||
run.phase = Phase::AgentRetryAt(Instant::now() + Duration::from_secs(1));
|
||||
} else if saved && self.saving.is_none() && self.pending_slot_apply.is_none() && self.can_start_production_turn() {
|
||||
self.production_start_session(app);
|
||||
} else {
|
||||
if !saved && self.saving.is_none() && !self.product_view_save_pending()
|
||||
&& !self.enqueue_project_draft(canvas, !self.draft_changed) {
|
||||
self.pause_production_run("本机保存服务已断开,请重试");
|
||||
return;
|
||||
}
|
||||
let reason = if !saved || self.saving.is_some() || self.product_view_save_pending() {
|
||||
"画布仍在保存"
|
||||
} else if self.pending_slot_apply.is_some() || self.canvas_workspace.adoption_preparing() {
|
||||
"候选采纳仍在处理"
|
||||
} else if self.pending_image.is_some() {
|
||||
"原生图请求仍在处理"
|
||||
} else if self.pi_run.is_some() || self.busy.is_some() {
|
||||
"上一回合仍在收尾"
|
||||
} else if !self.queue.is_empty() {
|
||||
"画布编辑仍在处理"
|
||||
} else {
|
||||
"原请求结果仍待核查"
|
||||
};
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
run.turn_waits += 1;
|
||||
if run.turn_waits >= TURN_WAIT_LIMIT {
|
||||
self.pause_production_run(reason);
|
||||
} else {
|
||||
run.phase = Phase::AgentRetryAt(Instant::now() + Duration::from_secs(1));
|
||||
}
|
||||
}
|
||||
} else if !saved && self.saving.is_none() && !self.product_view_save_pending()
|
||||
&& !self.enqueue_project_draft(canvas, !self.draft_changed)
|
||||
{
|
||||
self.slot_apply_save_failed(app, "本机保存服务已断开,请重试");
|
||||
}
|
||||
return;
|
||||
}
|
||||
@ -877,6 +940,17 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
|
||||
fn retryable_agent_failure(failure: &Value, reason: &str) -> bool {
|
||||
if matches!(failure["category"].as_str(), Some("cancelled" | "auth_revoked" | "scope_changed")) {
|
||||
return false;
|
||||
}
|
||||
failure["retryable"] == true
|
||||
|| matches!(failure["category"].as_str(),
|
||||
Some("transport_interrupted" | "outcome_unknown" | "request_outcome_unknown" | "rate_limited" | "stream_idle_timeout"))
|
||||
|| ["request_outcome_unknown", "stream_idle_timeout", "429", "流式响应空闲超时", "传输中断"]
|
||||
.iter().any(|marker| reason.contains(marker))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@ -936,4 +1010,114 @@ mod tests {
|
||||
assert!(w.error.is_empty(), "resuming must not immediately time out on stale deadline: {}", w.error);
|
||||
assert!(w.product_production.as_ref().is_some_and(|r| r.canvas_save_deadline > Instant::now()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_recovery_retries_three_times_then_retains_the_run_for_resume() {
|
||||
let (mut w, mut app, rx, doc, rev) = test_workspace();
|
||||
w.persisted_revisions.insert(doc, rev);
|
||||
w.product_production = Some(Run::new(doc, w.open_projects[&doc].clone(), json!("workspace"),
|
||||
vec![Stage { output: "detail".into(), variant: "chair".into() }], None, Phase::Agent));
|
||||
for (attempt, error) in ["request_outcome_unknown", "HTTP 429", "模型流式响应空闲超时", "传输中断"].into_iter().enumerate() {
|
||||
let epoch = attempt as u64 + 1;
|
||||
let run = w.product_production.as_mut().unwrap();
|
||||
run.phase = Phase::Agent;
|
||||
run.bind_session_epoch(epoch);
|
||||
w.owner_doc = Some(doc);
|
||||
w.write_epoch = epoch + 2;
|
||||
w.pi_product_production = true;
|
||||
w.pi_write_blocked = true;
|
||||
w.busy = Some("agent".into());
|
||||
let before = Instant::now();
|
||||
let event = json!({"engine":"pi","doc":doc,"accountId":w.account["id"],"origin":w.origin,
|
||||
"projectLocalId":"project","error":error,"writeEpoch":epoch});
|
||||
let ctx = egui::Context::default();
|
||||
if attempt > 0 {
|
||||
let mut late = event.clone();
|
||||
late["writeEpoch"] = json!(epoch - 1);
|
||||
w.receive_json_event(&mut app, &ctx, "agent".into(), Ok(late));
|
||||
assert_eq!(w.busy.as_deref(), Some("agent"));
|
||||
}
|
||||
w.receive_json_event(&mut app, &ctx, "agent".into(), Ok(event));
|
||||
assert!(w.busy.is_none());
|
||||
let run = w.product_production.as_ref().unwrap();
|
||||
assert_eq!(run.stages.len(), 1);
|
||||
if let Some(&seconds) = AGENT_RETRY_SECONDS.get(attempt) {
|
||||
let Phase::AgentRetryAt(at) = run.phase else { panic!("expected backoff"); };
|
||||
assert!(at >= before + Duration::from_secs(seconds));
|
||||
assert!(at <= Instant::now() + Duration::from_secs(seconds));
|
||||
}
|
||||
}
|
||||
assert!(w.has_paused_production());
|
||||
assert_eq!(w.production_stop["reason"], "传输中断");
|
||||
w.resume_paused_production(&app, "继续整套制作".into());
|
||||
assert!(rx.try_iter().any(|request| matches!(request, Request::Action(method, _) if method == "agent")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_recovery_start_wait_and_stop_watchdogs_release_the_owner() {
|
||||
let (mut w, mut app, _rx, doc, rev) = test_workspace();
|
||||
w.persisted_revisions.insert(doc, rev);
|
||||
w.unknown = true;
|
||||
w.product_production = Some(Run::new(doc, w.open_projects[&doc].clone(), json!("workspace"),
|
||||
vec![], None, Phase::AwaitingSave));
|
||||
for _ in 0..TURN_WAIT_LIMIT {
|
||||
w.product_production.as_mut().unwrap().phase = Phase::AgentRetryAt(Instant::now());
|
||||
w.production_tick(&app);
|
||||
}
|
||||
assert_eq!(w.production_stop["reason"], "原请求结果仍待核查");
|
||||
w.product_production.as_mut().unwrap().phase = Phase::Agent;
|
||||
w.busy = Some("pi-agent".into());
|
||||
w.owner_doc = Some(doc);
|
||||
w.request_production_stop("pause", "用户手动暂停").unwrap();
|
||||
w.product_production.as_mut().unwrap().stop_deadline = Some(Instant::now());
|
||||
w.production_tick(&app);
|
||||
assert!(w.busy.is_none());
|
||||
assert!(w.single_project_run_owner().is_none());
|
||||
assert!(w.production_stop["reason"].as_str().unwrap().contains("超时"));
|
||||
|
||||
w.product_production.as_mut().unwrap().phase = Phase::Agent;
|
||||
w.busy = Some("agent".into());
|
||||
w.receive_json_event(&mut app, &egui::Context::default(), "agent".into(), Err("本机连接失败".into()));
|
||||
assert!(w.has_paused_production());
|
||||
assert_eq!(w.production_stop["reason"], "本机连接失败");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_recovery_only_verified_complete_bundles_enqueue_project_sync() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path();
|
||||
let manifest = path.join("交付清单.json");
|
||||
for (complete, file_exists) in [(false, true), (true, false), (true, true)] {
|
||||
let (mut w, _app, requests, doc, rev) = test_workspace();
|
||||
w.persisted_revisions.insert(doc, rev);
|
||||
let mut run = Run::new(doc, w.open_projects[&doc].clone(), json!("workspace"), vec![], None, Phase::DeliveringBundle);
|
||||
run.total = 1;
|
||||
run.published = vec![json!({"outputId":"detail","variantId":"chair","progressSummary":{}})];
|
||||
run.delivery_id = Some("delivery".into());
|
||||
run.delivery_write_epoch = Some(w.write_epoch);
|
||||
w.product_production = Some(run);
|
||||
std::fs::write(&manifest, json!({"deliveryId":"delivery","allOutputsCompleted":complete,
|
||||
"files":[{"relativePath":"成品.jpg","verified":true,"sizeBytes":5}]}).to_string()).unwrap();
|
||||
let file = path.join("成品.jpg");
|
||||
if file_exists {
|
||||
std::fs::write(&file, b"image").unwrap();
|
||||
} else {
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
}
|
||||
let event = json!({"doc":doc,"deliveryId":"delivery","writeEpoch":w.write_epoch,
|
||||
"accountEpoch":w.accepted_account_epoch,"productionDelivery":{
|
||||
"state":"bundle_saved","path":path,"allOutputsCompleted":complete,"completedOutputs":1}});
|
||||
w.production_bundle_received(&event);
|
||||
w.production_bundle_received(&event);
|
||||
let uploads: Vec<_> = requests.try_iter().filter_map(|request| match request {
|
||||
Request::Action(method, value) if method == "project-sync" => Some(value),
|
||||
_ => None,
|
||||
}).collect();
|
||||
if complete && file_exists {
|
||||
assert_eq!(uploads, [json!({"doc":doc,"revision":rev,"status":"completed"})]);
|
||||
} else {
|
||||
assert!(uploads.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -631,6 +631,7 @@ fn delivered_canvas_references_reach_a_new_turn_and_edit_only_the_target_layers(
|
||||
w.observed_doc = Some(doc);
|
||||
w.model_ready = true;
|
||||
w.library = false;
|
||||
w.busy = None;
|
||||
w.canvas_workspace.output = "main_images".into();
|
||||
w.canvas_workspace.variant = "wood".into();
|
||||
w.template_workflow = json!({"canvasFirst":true,"workspaceId":"workspace","outputId":"main_images","variantId":"wood",
|
||||
@ -1142,7 +1143,7 @@ fn paused_production_keeps_originals_and_resumes_with_the_user_message() {
|
||||
assert!(w.agent_effects_paused && w.pi_write_blocked);
|
||||
assert!(w.has_paused_production());
|
||||
let run = w.product_production.as_ref().unwrap();
|
||||
assert_eq!(run.progress_label().as_deref(), Some("已暂停"));
|
||||
assert_eq!(run.progress_label().as_deref(), Some("已暂停 · 缺少资料"));
|
||||
assert_eq!(run.queued_deferred_images().count(), 1);
|
||||
w.production_tick(&app);
|
||||
assert!(requests.try_recv().is_err());
|
||||
@ -1213,7 +1214,7 @@ fn paused_production_reports_saved_user_edits_and_keeps_their_protection() {
|
||||
assert!(w.agent_effects_paused && w.pi_write_blocked);
|
||||
assert!(w.has_paused_production());
|
||||
let run = w.product_production.as_ref().unwrap();
|
||||
assert_eq!(run.progress_label().as_deref(), Some("已暂停"));
|
||||
assert_eq!(run.progress_label().as_deref(), Some("已暂停 · 缺少资料"));
|
||||
assert_eq!(run.queued_deferred_images().count(), 1);
|
||||
w.production_tick(&app);
|
||||
assert!(requests.try_recv().is_err());
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user