修复小壹重开工程后的原请求核查与继续制作

This commit is contained in:
WuYongJie 2026-11-30 03:24:38 +08:00
parent e219e20896
commit ebc683fb26
4 changed files with 172 additions and 10 deletions

View File

@ -5,7 +5,7 @@ mod template_fidelity;
use super::{json, Path, Value, R, Uuid, PathBuf, hash, original_project_present, read_json, template_slots, Digest, sync, write_json, fs, Sha256, creation, mpsc, Event, template_workflow, now, Document, Backend, production_profile, slot_canvas, Arc};
use photocraft_ui_egui::jiansun::production_facts::{screen_area, screen_fingerprint, screen_overlay_layers};
use photocraft_ui_egui::jiansun::BridgeFailure;
use super::transfer;
use super::{read_json_with_missing, transfer};
use template_slots::candidate_pixels;
#[path = "jiansun_image_transform.rs"]
@ -769,7 +769,9 @@ fn candidate_uses_current_inputs(dir: &Path, state: &Value, record: &Value, vari
Ok(*saved == hash(&old.to_string()))
}
fn read_candidate(dir: &Path, id: &str) -> R<Value> {
let record = read_json(&candidate_path(dir, id)?)?;
let path = candidate_path(dir, id)?;
let record = read_json_with_missing(&path, "文件缺失")
.map_err(|error| format!("候选 {id}({CANDIDATE}):{error}"))?;
if record["version"] != 2
|| record["id"] != id
|| record["binding"]["candidateId"] != id
@ -830,7 +832,11 @@ fn recover_candidate_without_task(dir: &Path, record: &Value) -> R<Value> {
Some("prepared") if record["requestId"].is_null() =>
reconcile_candidate(dir, &json!({"id":record["id"],"slotBinding":record["binding"],
"phase":"prepared","notDispatched":true,"message":"这张图未提交生成,可以重新发起"})),
_ => Ok(pending_candidate(record)),
_ => {
let mut pending = pending_candidate(record);
pending["message"] = json!(format!("候选 {} 缺少 task.json,原结果仍待核查", record["id"]));
Ok(pending)
}
}
}
@ -1249,6 +1255,28 @@ fn candidate_projection_task(dir: &Path, record: &Value) -> R<Option<Value>> {
if task.is_file() { read_json(&task).map(Some) } else { Ok(None) }
}
// A prepared task must be durably replaced by a dispatched task before POST.
// A stale candidate projection alone cannot establish that POST was attempted.
fn settle_prepared_candidate(dir: &Path, record: &Value, task: &Value) -> R<Option<Value>> {
if record["phase"] != "dispatched" || task["phase"] != "prepared"
|| !record["requestId"].is_null() || !task["requestId"].is_null() || !task["upstreamTaskId"].is_null()
{
return Ok(None);
}
let id = uuid(&record["id"], "原候选")?;
let Some(_dispatch) = lock_candidate_dispatch(dir, &id)? else { return Ok(None); };
let Some(mut current) = candidate_projection_task(dir, record)? else { return Ok(None); };
if current["phase"] != "prepared" || !current["requestId"].is_null() || !current["upstreamTaskId"].is_null() {
return Ok(None);
}
if current["id"] != id || current["slotBinding"] != record["binding"] {
return Err(format!("候选 {id} 与原请求 task.json 身份不一致"));
}
current["notDispatched"] = json!(true);
current["message"] = json!("原图片请求未提交");
reconcile_candidate(dir, &current).map(Some)
}
fn candidate_needs_recovery(dir: &Path, record: &Value) -> R<bool> {
if matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
return Ok(false);
@ -2746,6 +2774,33 @@ fn remaining_stages(dir: &Path, state: &Value, brief_revision: &Value, verify_ed
}).collect()
}
fn resumable_stages(dir: &Path, state: &Value, brief_revision: &Value, verify_editable: bool) -> Vec<Value> {
let mut remaining = remaining_stages(dir, state, brief_revision, verify_editable);
let path = dir.join("production-run.json");
if let Ok(checkpoint) = read_json(&path)
&& checkpoint["status"] == "paused_on_exit" && checkpoint["active"] == false
&& checkpoint["workspaceId"] == state["id"]
&& checkpoint["project"].as_str().is_some_and(|id| dir.file_name().is_some_and(|name| name == id))
{
for stage in production_stages(state) {
if remaining.contains(&stage) { continue; }
let output = stage["outputId"].as_str().unwrap_or_default();
let variant = stage["variantId"].as_str().unwrap_or_default();
let published = checkpoint["published"].as_array().into_iter().flatten().find(|row|
row["outputId"] == output && row["variantId"] == variant);
if let Some(row) = published
&& row["issues"].as_array().is_some_and(|issues| !issues.is_empty())
&& row["generationId"].is_string()
&& published_receipt(&receipt_path(dir, variant, output)).is_ok_and(|receipt|
receipt["generationId"] == row["generationId"])
{
remaining.push(stage);
}
}
}
runnable_stages(state, remaining)
}
fn candidate_export_source(dir: &Path, record: &Value) -> Value {
let candidate_id = record["id"].as_str().unwrap_or_default();
let archive = format!("image-jobs/{candidate_id}");
@ -3775,6 +3830,9 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>, read_only: bool) -> R<Valu
dispatched_generations.insert(uuid(&record["id"], "候选")?);
}
if let Some(task) = task {
if !read_only && let Some(settled) = settle_prepared_candidate(dir, record, &task)? {
*record = settled;
}
if !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
if !read_only {
*record = reconcile_candidate(dir, &task)?;
@ -3872,7 +3930,7 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>, read_only: bool) -> R<Valu
"knowledgeVersion":pack["xiaoyi"]["knowledgeVersion"]});
let mut workflow = json!({"canvasFirst":true,"revision":state["revision"],"workspaceId":state["id"],"structureHash":state["structureHash"],"templateId":state["template"]["id"],"templateVersion":state["template"]["version"],"templateHash":state["template"]["contentHash"],"templateName":state["template"]["name"],"template":template,"confirmed":true,"confirmationKind":"template-selection","pending":pending,"recoveryCandidateId":recovery_candidates.first(),"recoveryCandidateIds":recovery_candidates,"activeVariantId":active,"variantId":active,"variants":state["variants"],"outputVariantIds":state["brief"]["outputVariantIds"],"outputId":state["activeOutput"],"outputs":outputs,"slots":slots,"capabilities":{"imageDispatchAllowed":ready&&!pending&&active_color_enabled,"copyDispatchAllowed":ready&&!pending&&active_color_enabled,"localApplyAllowed":ready}});
if state["productTemplates"].is_object() {
workflow["productionStages"] = json!(runnable_stages(&state, remaining_stages(dir, &state, &current["revision"], false)));
workflow["productionStages"] = json!(resumable_stages(dir, &state, &current["revision"], false));
workflow["productionBlocks"] = json!(blocked_production_stages(&state));
workflow["scopedProductionPending"] = json!(scoped_production_pending);
workflow["pendingImageRequests"] = json!(pending_image_requests);
@ -4386,8 +4444,7 @@ impl Backend {
}
let start_product = !browsing && (input["generateProduct"] == true || input["resumeProduct"] == true);
if start_product {
let remaining = remaining_stages(&dir, &state, &creation::load(&dir)?["revision"], true);
let stages = runnable_stages(&state, remaining);
let stages = resumable_stages(&dir, &state, &creation::load(&dir)?["revision"], true);
if stages.is_empty() {
let blocked = blocked_production_stages(&state);
if blocked.is_empty() { return Err("已选成品均已在项目中保存".into()); }
@ -4738,6 +4795,15 @@ impl Backend {
// This enters the existing immutable protocol/key-scoped GET-only recovery path.
let file = dir.join("image-jobs").join(&candidate).join("task.json");
match read_json(&file) {
Ok(mut journal) if journal["phase"] == "prepared" && record["requestId"].is_null()
&& journal["requestId"].is_null() && journal["upstreamTaskId"].is_null() => {
if journal["id"] != candidate || journal["slotBinding"] != record["binding"] {
return Err(format!("候选 {candidate} 与原请求 task.json 身份不一致"));
}
journal["notDispatched"] = json!(true);
journal["message"] = json!("原图片请求未提交");
candidate_result = Some(candidate_receipt(&reconcile_candidate(&dir, &journal)?));
}
Ok(_) => {
let call = self.image_job(None, &json!({"doc":doc,"taskId":candidate,"recoveryBudgetMs":input["recoveryBudgetMs"]}), true, events, ctx);
let journal = read_json(&file)?;
@ -4747,6 +4813,9 @@ impl Backend {
Err(error) => {
if file.try_exists().map_err(|_| error.clone())? { return Err(error); }
let original = recover_candidate_without_task(&dir, &record)?;
if original["phase"] == "unknown" {
operation_error = original["message"].as_str().map(str::to_owned);
}
candidate_result = Some(candidate_receipt(&original));
}
}
@ -6290,6 +6359,14 @@ mod tests {
let pending = || remaining_stages(&fixture.dir, &state, &snapshot["briefRevision"], true)
.iter().any(|stage| stage["outputId"] == "detail" && stage["variantId"] == variant);
assert!(!pending());
write_json(&fixture.dir.join("production-run.json"), &json!({
"active":false,"status":"paused_on_exit","workspaceId":state["id"],"project":fixture.dir.file_name().unwrap().to_str(),
"published":[{"outputId":"detail","variantId":variant,"generationId":snapshot["generationId"],
"issues":[{"field":"S01-I01","reason":"需复核产品图"}]}]
})).unwrap();
assert!(resumable_stages(&fixture.dir, &state, &snapshot["briefRevision"], true)
.contains(&json!({"outputId":"detail","variantId":variant})));
assert!(!pending(), "the published files remain a valid delivery snapshot");
let candidate_path = candidate_path(&fixture.dir, candidate["id"].as_str().unwrap()).unwrap();
let mut retired = candidate.clone();
@ -6785,6 +6862,53 @@ mod tests {
assert_eq!(reconcile_candidate(&dir, &read_json(&file).unwrap()).unwrap()["requestId"], task["requestId"]);
}
#[test]
fn reopen_clears_stale_candidate_dispatches_using_the_original_journals() {
let fixture = fixture();
let dir = &fixture.dir;
let prepared = candidate(dir, "dispatched");
reserve(dir, load(dir).unwrap(), &prepared).unwrap();
let id = prepared["id"].as_str().unwrap();
let journal = json!({"id":id,"slotBinding":prepared["binding"],"phase":"prepared"});
let file = candidate_path(dir, id).unwrap().with_file_name("task.json");
write_json(&file, &journal).unwrap();
let active_dispatch = lock_candidate_dispatch(dir, id).unwrap().unwrap();
assert_eq!(snapshot(dir).unwrap()["recoveryCandidateIds"], json!([id]));
drop(active_dispatch);
assert_eq!(snapshot(dir).unwrap()["pending"], false);
assert_eq!(read_candidate(dir, id).unwrap()["phase"], "failed");
assert_eq!(read_json(&file).unwrap(), journal);
let original = candidate(dir, "unknown");
reserve(dir, load(dir).unwrap(), &original).unwrap();
let original_id = original["id"].as_str().unwrap();
let original_file = candidate_path(dir, original_id).unwrap().with_file_name("task.json");
let mut original_task = json!({"id":original_id,"slotBinding":original["binding"],"phase":"unknown"});
write_json(&original_file, &original_task).unwrap();
let pending = snapshot(dir).unwrap();
assert_eq!(pending["recoveryCandidateIds"], json!([original_id]));
original_task["phase"] = json!("expired");
write_json(&original_file, &original_task).unwrap();
assert_eq!(snapshot(dir).unwrap()["pending"], false);
assert_eq!(snapshot(dir).unwrap()["recoveryCandidateIds"], json!([]));
}
#[test]
fn missing_candidate_records_identify_the_original() {
let fixture = fixture();
let dir = &fixture.dir;
let record = candidate(dir, "unknown");
reserve(dir, load(dir).unwrap(), &record).unwrap();
let id = record["id"].as_str().unwrap();
let missing_task = recover_candidate_without_task(dir, &record).unwrap();
assert_eq!(missing_task["phase"], "unknown");
assert!(missing_task["message"].as_str().unwrap().contains(id));
assert!(missing_task["message"].as_str().unwrap().contains("task.json"));
fs::remove_file(candidate_path(dir, id).unwrap()).unwrap();
let error = snapshot(dir).unwrap_err();
assert!(error.contains(id) && error.contains(CANDIDATE));
}
#[test]
fn interrupted_candidate_before_dispatch_can_be_cleared_without_login_or_network() {
let fixture = fixture();

View File

@ -809,7 +809,7 @@ impl Backend {
let input = &prepared;
let mut c = load(&dir)?;
let mut task = if recover {
let t = read_json(&dir.join("creation-task.json"))?;
let t = read_json_with_missing(&dir.join("creation-task.json"), "未找到原创作请求记录(creation-task.json)")?;
if !matches!(t["phase"].as_str(), Some("unknown" | "received" | "dispatched")) {
return Err("没有需要核查的原创作请求".into());
}

View File

@ -716,6 +716,9 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte
Outcome::Done(value) => {
if value["ok"] != true {
let error = value["error"].as_str().unwrap_or("原生控制未返回成功结果");
if value["ok"] == false && read {
return Err(BridgeFailure::new("native_read_failed", false, false, error));
}
if value["ok"] == false && method == "ui.set" { return Err(error.into()); }
if value["ok"] == false && method == "engine.execute" && !read && revision == before {
return Ok(json!({"dispatched":true,"executed":false,"pending":false,"completed":true,
@ -941,7 +944,7 @@ pub(super) fn reconcile(w: &Workspace, app: &PhotocraftApp, input: &Value) -> Re
let document = input["documentId"].as_u64().filter(|id| *id > 0 && *id <= MAX_INTEGER).ok_or("原项目编号无效")?;
let job = input["job"].as_u64().filter(|id| *id > 0 && *id <= MAX_INTEGER).map(JobId).ok_or("原生任务编号无效")?;
let owned = w.agent_native.jobs.iter().find(|owned| owned.id == job && owned.run == run && owned.document == document)
.ok_or("原生任务记录不可用,原结果仍未知;请保留原编号核查,不重派")?;
.ok_or_else(|| format!("找不到原生任务 {}(回合 {run}),原结果仍待核查", job.0))?;
let active = app.session.active().ok_or("请先打开原项目")?;
if active.doc.id.0 != document || app.session.active_index() != Some(owned.index) || w.owner_doc != Some(document)
|| owned.account != w.account["id"] || owned.origin != w.origin
@ -1826,6 +1829,23 @@ mod tests {
}
}
#[test]
fn missing_shape_is_a_terminal_read_failure_and_a_missing_original_job_stays_unknown() {
let (mut w, mut app, requests) = fixture();
let revision = app.session.active().unwrap().revision;
let mut input = base(&w);
input["revision"] = json!(w.expected_revision);
input["method"] = json!("engine.execute");
input["params"] = json!({"command":"shape.info","params":{"layer":987654}});
let failure = call(&mut w, &mut app, &egui::Context::default(), &input).unwrap_err();
assert_eq!(failure.category, "native_read_failed");
assert!(!failure.dispatched && !failure.retryable);
let error = reconcile(&w, &app, &json!({"run":RUN,"documentId":w.owner_doc,"job":987654})).unwrap_err();
assert!(error.contains("987654") && error.contains(RUN) && error.contains("待核查"));
assert_eq!(app.session.active().unwrap().revision, revision);
assert!(requests.try_recv().is_err() && w.agent_native.last_receipt().is_none());
}
#[test]
fn native_methods_and_ambient_commands_are_closed_and_errors_never_create_success_receipts() {
for (method, params) in [("app.open", json!({"path":"anything"})), ("ui.type", json!({"text":"not allowed"})),

View File

@ -1054,7 +1054,7 @@ impl Workspace {
ui.horizontal(|ui| {
stitch_ui::status_chip(ui, "原请求待核查", stitch_ui::StatusTone::Warning);
if ui.add_enabled_ui(self.busy.is_none(), |ui| stitch_ui::button(ui, "核查原结果", false)).inner.clicked() {
self.creation_submit(app, "creation-recover", json!({}));
self.recover(app);
}
if self.creation["generation"]["screens"].as_object().is_some_and(|m| !m.is_empty())
&& ui.add_enabled_ui(self.busy.is_none(), |ui| stitch_ui::button(ui, "载入已有结果", false)).inner.clicked()
@ -1381,7 +1381,7 @@ impl Workspace {
}
let actions_ready = self.busy.is_none() && !self.unknown;
self.brief_enter_button(app, ui, &template, blocked.is_none(), actions_ready && missing.is_empty());
if self.has_production_stages() {
if self.has_production_stages() || self.has_paused_production() {
let resume = stitch_ui::action_button(ui, "继续整套制作", stitch_ui::ButtonRole::Primary, self.can_resume_product());
self.control_geometry("resume-product", resume.rect);
if resume.clicked() { self.resume_product_production(app); }
@ -3294,6 +3294,24 @@ mod tests {
}
#[test]
fn resumed_project_shows_continue_after_the_originals_settle() {
let (mut w, mut app, _) = brief_fixture();
w.model_ready = true;
w.image_ready = true;
w.unknown = true;
w.product_checkpoint = json!({"active":true,"phase":"paused"});
w.template_workflow = json!({"productionStages":[]});
let ctx = egui::Context::default();
brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]);
assert!(control_rect(&w, "resume-product").is_positive());
assert!(!w.can_resume_product());
w.unknown = false;
brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]);
assert!(control_rect(&w, "resume-product").is_positive());
assert!(w.can_resume_product());
}
#[test]
fn a_scoped_pending_slot_leaves_the_production_resume_button_usable() {
let (mut w, mut app, requests) = brief_fixture();