修复小壹暂停显示、素材库重连和本地实拍恢复

This commit is contained in:
WuYongJie 2026-12-02 15:31:55 +08:00
parent 5258ad9ca7
commit 66c23c676d
6 changed files with 253 additions and 36 deletions

View File

@ -235,6 +235,13 @@ function originalCandidate(item) {
return item?.state==='unknown'&&(!operation||!item.reason)?item.candidateId:undefined;
}
function isLocalProductOperation(operation) {
// Older ledgers did not store useProductReference. The workflow assigned
// UUIDs to operations, and only real photos reserved one with no candidate ID.
return operation?.intent==='generate_candidate'&&(operation.useProductReference===true||
operation.candidateId===null&&/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/iu.test(operation.operationId));
}
function slotOriginals(item) {
const originals=[];
const candidateId=originalCandidate(item);
@ -270,7 +277,8 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p
const item=readJournal().items[slot.id];
const pendingKey=adopting?'pendingAdoption':'pendingOperation';
const original=item?.[pendingKey];
const archivedCandidate=adopting?undefined:originalCandidate(item);
const local=!adopting&&!item?.heldOriginalId&&isLocalProductOperation(original);
const archivedCandidate=adopting||local?undefined:originalCandidate(item);
signal?.throwIfAborted();
if(archivedCandidate){
const receipt=await detailRecover(slot.id,{projectId:item.heldOriginalProjectId,candidateId:archivedCandidate});
@ -293,14 +301,27 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p
}
if(!original)return {slotId:slot.id,phase:'none'};
const adoption=adopting?{outputId,productVariantId:variantId,slotId:slot.id}:undefined;
const operation=await reconcileWorkflowReceipt(canvas,{...original,adoption});
const operation=await reconcileWorkflowReceipt(canvas,{...original,adoption}).catch(error=>{
if(!local||error.message!=='原操作不存在或不属于当前项目')throw error;
return {phase:'unknown'};
});
signal?.throwIfAborted();
const candidateId=operation.candidateId??original.candidateId;
const receipt=!adoption&&candidateId&&operation.phase==='unknown'
? await detailRecover(slot.id,{candidateId}) : null;
? await detailRecover(slot.id,{candidateId}).catch(error=>{
if(!local||error.message!==`候选 ${candidateId}(canvas-candidate.json):文件缺失`)throw error;
return {id:candidateId,status:'not_executed'};
}) : null;
signal?.throwIfAborted();
const phase=receipt?.id===candidateId&&settledImagePhases.includes(receipt.status)?receipt.status:operation.phase;
const expiry=expiryFields(receipt?.id===candidateId?receipt:operation);
const matchingReceipt=receipt?.id===candidateId?receipt:null;
const localMissing=local&&operation.phase==='unknown'&&(!candidateId||
matchingReceipt&&(matchingReceipt.status==='not_executed'||
matchingReceipt.message===`候选 ${candidateId} 缺少 task.json,原结果仍待核查`));
const phase=localMissing?'not_executed'
:matchingReceipt&&settledImagePhases.includes(matchingReceipt.status)?matchingReceipt.status:operation.phase;
const reason=localMissing?'本地实拍操作没有在途任务或可取回的候选,可以重试'
:matchingReceipt?.message??operation.message;
const expiry=expiryFields(matchingReceipt??operation);
if(settledImagePhases.includes(phase)||phase==='not_executed'){
const applied=phase==='complete'&&adoption;
const decision=original.decision;
@ -308,18 +329,21 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p
if(!sessionPlacement||item.state!=='applied'||item.candidateId!==candidateId)await update(journal=>{
signal?.throwIfAborted();
const record=journal.items[slot.id];
if(local&&record?.pendingOperation?.operationId!==original.operationId)return;
rememberImageExpiry(record,candidateId,expiry);
Object.assign(record,{state:applied?'applied':phase==='complete'?'candidate':phase,candidateId,
Object.assign(record,{state:applied?'applied':phase==='complete'?'candidate':phase,
...(!localMissing?{candidateId}:null),
...(applied&&operation.persistence==='session'?null:{[pendingKey]:null}),
...(local?{reason:reason??null,...(phase==='complete'?{source:'product'}:null)}:null),
...(applied&&!decision?{autoCandidateSetId:null}:null),
...(!adopting?{heldGeneration:false,heldOriginalId:null,heldOriginalProjectId:null}:null)});
if(decision&&applied)(record.autoAdoptions??={})[decision.candidateSetId]={...decision,
state:operation.persistence==='session'?'placed':'adopted',receipt:operation};
if(decision&&phase==='not_executed')(record.autoAdoptions??={})[decision.candidateSetId]={...decision,state:'selected'};
},candidateId?{evidence:[slot.id,candidateId,adopting?'adoption':'candidate',{...operation,phase,...expiry,...decision}]}:undefined);
},candidateId?{evidence:[slot.id,candidateId,adopting?'adoption':'candidate',{...operation,phase,...expiry,...decision,
...(local?{message:reason}:null)}]}:undefined);
if(applied&&!signal?.aborted)onAdopted?.(slot.id,candidateId);
}
const reason=receipt?.id===candidateId?receipt?.message??operation.message:operation.message;
return {slotId:slot.id,phase,candidateId,operationId:original.operationId,reason,...expiry};
};
return async (slot,adopting,signal)=>{
@ -795,7 +819,7 @@ export async function openProductionOperations(host,{target=host.productionConte
let prepared;
const archive=async operation=>{
const candidateId=preparedCandidateId(intent,values,operation);
prepared={...operation,intent,candidateId};
prepared={...operation,intent,candidateId,...(values.useProductReference===true?{useProductReference:true}:null)};
dispatchingImages.set(operation.operationId,undefined);
await save(slot,{[pendingKey]:prepared,...(!adopting?{state:'dispatching'}:null)});
};
@ -819,8 +843,14 @@ export async function openProductionOperations(host,{target=host.productionConte
}
}}));
}catch(error){
if(prepared)await save(slot,{state:scope.original?'unknown':'failed',reason:error.message,
[pendingKey]:scope.original?prepared:null});
if(prepared){
await save(slot,{state:scope.original?'unknown':'failed',reason:error.message,
[pendingKey]:scope.original?prepared:null});
if(scope.original&&isLocalProductOperation(prepared)&&!signal?.aborted){
const recovered=await recoverImage(slot,false,signal);
if(recovered.phase!=='unknown'&&recovered.phase!=='submitted')return recovered;
}
}
throw error;
}
const state=operation.phase==='complete'?(intent==='generate_candidate'?'candidate':'applied'):operation.phase;
@ -831,7 +861,8 @@ export async function openProductionOperations(host,{target=host.productionConte
await update(journal=>{
const item=journal.items[slot.id]??={};
Object.assign(item,{state,candidateId:operation.candidateId??prior?.candidateId,[pendingKey]:pending,
...(intent==='generate_candidate'?{source:values.useProductReference?'product':'generate',prompt:values.instruction}:null),
...(intent==='generate_candidate'?{source:values.useProductReference?'product':'generate',prompt:values.instruction,
...(values.useProductReference===true?{reason:operation.message??null}:null)}:null),
...(state==='applied'?{autoCandidateSetId:null}:null)});
rememberAttempt(item,operation.candidateId);
rememberImageExpiry(item,operation.candidateId,operation);

View File

@ -0,0 +1,108 @@
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { openProductionOperations } from '../src/production-operations.mjs';
import { cleanup } from './cleanup.mjs';
import { productionStore } from './production-store-fixture.mjs';
const slotId='sku-photo';
const target={outputId:'sku_images',variantId:'oak'};
const scope={run:'original-run',documentId:23};
const missingOperation='原操作不存在或不属于当前项目';
async function fixture(t,items={},overrides={}) {
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-real-photo-'));
t.after(()=>cleanup(dir));
const store=productionStore(dir);
const ledger=store.ledger(target.outputId,target.variantId);
if(Object.keys(items).length)ledger.repository.replaceLedger({binding:JSON.stringify(['studio','oak']),items});
const canvas={
...scope,
workflowRead:async()=>({available:true,canvasFirst:true,version:1,outputId:target.outputId,productVariantId:target.variantId,
template:{contentHash:'studio'},totalSlots:1,slots:[{id:slotId,fieldId:'K01',label:'SKU产品图',candidates:[]}]}),
detailCopyFields:async()=>({fields:[]}),
delta:async()=>{},
imageRequest:async action=>{assert.equal(action,'pending');return [];},
...overrides,
};
const actions=await openProductionOperations({store,productionGoal:target,canvas},{
tailWatchClock:{setTimer:()=>({unref(){}}),clearTimer(){}},
});
t.after(()=>actions.close());
return {actions,item:()=>ledger.read()?.items[slotId]};
}
test('an interrupted real-photo request with no native operation settles and can be retried',async t=>{
let submissions=0;
const {actions,item}=await fixture(t,{},{
async workflowExecute({operationId,useProductReference}){
assert.equal(useProductReference,true);
assert.equal(item().pendingOperation.useProductReference,true);
if(++submissions===1)throw Error('画布连接中断');
return {operationId,phase:'submitted'};
},
async workflowPoll(operationId){
return {operationId,phase:'complete',candidateId:'saved-real-photo'};
},
async workflowReconcile(){throw Error(missingOperation);},
});
async function createPhoto(){
assert.equal((await actions.use_product_image({slotId})).phase,'accepted');
return (await actions.await_image_slots({slotIds:[slotId]})).generation[0];
}
const failed=await createPhoto();
assert.equal(failed.phase,'not_executed');
assert.match(failed.reason,/可以重试/u);
assert.equal(item().pendingOperation,null);
assert.equal(item().reason,failed.reason);
assert.equal((await createPhoto()).candidateId,'saved-real-photo');
assert.equal(submissions,2);
});
test('a restarted real-photo operation waits while the native task is live and clears if its candidate is missing',async t=>{
const operationId=randomUUID();
const candidateId=randomUUID();
let phase='submitted';
const {actions,item}=await fixture(t,{[slotId]:{state:'unknown',candidateId:'prior-candidate',pendingOperation:{
...scope,operationId,intent:'generate_candidate',candidateId:null,
}}},{
async workflowReconcile(query){
return {...query,phase,candidateId};
},
async detailRecover(slot,{candidateId:id}){
assert.equal(slot,slotId);
assert.equal(id,candidateId);
throw Error(`候选 ${id}(canvas-candidate.json):文件缺失`);
},
});
assert.equal((await actions.reconcile_image_slots({}))[0].phase,'submitted');
assert.equal(item().pendingOperation.operationId,operationId);
phase='unknown';
const [settled]=await actions.reconcile_image_slots({});
assert.equal(settled.phase,'not_executed');
assert.equal(settled.operationId,operationId);
assert.equal(item().pendingOperation,null);
assert.equal(item().candidateId,'prior-candidate');
assert.equal((await actions.reconcile_image_slots({}))[0].phase,'none');
});
test('a failed local transform leaves the slot free for another transform',async t=>{
let attempts=0;
const {actions,item}=await fixture(t,{},{
async imageRequest(action){
if(action==='pending')return [];
assert.equal(action,'transform');
if(++attempts===1)throw Error('原候选底图不可读取');
return {id:'transformed',status:'complete'};
},
});
const params={slotId,sourceCandidateId:'original',flipX:true};
await assert.rejects(actions.transform_slot_image(params),/原候选底图不可读取/u);
assert.equal(item()?.pendingOperation,undefined);
assert.equal((await actions.reconcile_image_slots({}))[0].phase,'none');
assert.equal((await actions.transform_slot_image(params)).candidateId,'transformed');
assert.equal(item().source,'transform');
});

View File

@ -4451,19 +4451,20 @@ impl Workspace {
"disabled" => ("素材库客户端连接未开放", "重新检查"),
"forbidden" => ("此账户无素材库访问权限", "重新检查"),
_ if self.account.is_null() => ("连接素材库后使用云端项目", "连接素材库"),
_ => ("素材库需要重新授权", "重新连接"),
_ => ("素材库登录已失效,本机草稿已保留。", "重新连接"),
}
}
fn library_notice(&mut self, ui: &mut Ui) {
let t = Tokens::get(ui.ctx()).agent();
ui.horizontal_wrapped(|ui| {
let (label, button) = self.library_notice_labels();
ui.label(RichText::new(label).color(t.text_dim)).on_hover_text(if self.library_message.is_empty() {
let expired = self.library_status == "sign_in_required" && !self.account.is_null();
ui.label(RichText::new(label).color(if expired { t.warning } else { t.text_dim })).on_hover_text(if self.library_message.is_empty() {
"本机作品和未完成的原请求保留,重新授权不会重新生成"
} else {
&self.library_message
});
let action = stitch_ui::action_button(ui, button, stitch_ui::ButtonRole::Secondary, self.busy.is_none());
let action = stitch_ui::action_button(ui, button, stitch_ui::ButtonRole::Secondary, expired || self.busy.is_none());
self.panel_geometry["reconnect"] = agent_panel::rect_value(action.rect);
if action.clicked() {
if matches!(self.library_status.as_str(), "disabled" | "forbidden") {

View File

@ -1331,7 +1331,11 @@ impl Workspace {
});
self.pi_ui_decorations(ui,false);
app.perf.stage.ui_regions.composer += crate::gpu_canvas::now_ms() - composer_start;
if production {
if self.library_status == "sign_in_required" {
Frame::NONE.inner_margin(egui::Margin::symmetric(16, 8))
.show(ui, |ui| self.library_notice(ui));
}
if production || self.product_production.as_ref().is_some_and(|run| run.clock_paused()) {
let head_start = crate::gpu_canvas::now_ms();
self.production_head_ui(app, ui);
app.perf.stage.ui_regions.production_head += crate::gpu_canvas::now_ms() - head_start;
@ -2767,7 +2771,13 @@ impl Workspace {
} else {
GoalBudget::Unreported
};
let state = if self.pi_ui_waiting() { RunState::WaitingUser }
let clock_paused = run.is_some_and(|run| run.clock_paused());
let mut controls = head.view(resume_ready);
if clock_paused && controls.stop == timeline::StopPhase::Idle {
controls.stop = timeline::StopPhase::Paused;
}
let state = if clock_paused { RunState::WaitingResume }
else if self.pi_ui_waiting() { RunState::WaitingUser }
else if waiting { RunState::WaitingResume } else { RunState::Running };
ui.add_space(10.0);
let full = ui.available_rect_before_wrap();
@ -2776,13 +2786,14 @@ impl Workspace {
column.spacing_mut().item_spacing.y = 4.0;
let result = timeline::goal_progress_panel(&mut column, id, GoalProgressPanel {
title, state, budget, pipeline: &pipeline, image_cells: &image_cells, copy_cells: &copy_cells,
workers: &worker_states, roadmap: Some(&stages), controls: run.is_some().then(|| head.view(resume_ready)),
workers: &worker_states, roadmap: Some(&stages), controls: run.is_some().then_some(controls),
}, self.reduce_motion || self.product_view_detached(), |index| {
let row = &image_source[index];
let status = match image_cells[index] { Cell::Verified => "已核验", Cell::Filled => "已上画布", Cell::Preview => "有候选待采纳", Cell::Empty => "待填" };
format!("图片 {} · {} · {status}", index + 1, row["label"].as_str().unwrap_or("图位"))
});
if let GoalBudget::Time { elapsed, .. } = budget
&& !clock_paused
&& !agent_motion::hidden(ui, result.rect)
{
// 首分钟显示秒,之后只在分钟数变化时刷新。
@ -7624,6 +7635,56 @@ mod tests {
assert!(requests.try_recv().is_err());
}
#[test]
fn paused_production_card_shows_a_static_heading_and_elapsed_time() {
use egui_kittest::kittest::Queryable;
let directory = std::env::var_os("PHOTOCRAFT_PAUSED_CARD_QA_OUT").map(std::path::PathBuf::from);
let _gpu = directory.as_ref().map(|_| photocraft_testkit::gpu_lock());
for width in [520.0, 250.0] {
let (mut app, _) = dock_fixture();
let mut w = app.jiansun.take().unwrap();
let doc = app.session.active().unwrap().doc.id.0;
w.open_projects.insert(doc, w.local_identity("project"));
w.template_workflow = json!({"canvasFirst":true,"workspaceId":"ws"});
w.product_checkpoint = json!({"active":true,"phase":"paused","project":"project","workspaceId":"ws",
"startedAt":1_000,"clockSavedAt":1_300});
w.restore_production_checkpoint(&app);
w.agent_effects_paused = true;
w.workflow.set_production_progress(&json!({"heading":"正在制作详情页"}));
let run = w.product_production.as_ref().unwrap();
assert!(run.waiting_to_resume());
assert!(!run.showing_agent_progress());
assert_eq!(run.elapsed(), Duration::from_secs(300));
app.jiansun = Some(w);
let builder = egui_kittest::Harness::builder().with_size(vec2(width, 680.0))
.with_context_setup(|ctx| {
PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium);
crate::cjk_fonts::install_system_provider_for_tests(ctx);
});
let builder = if directory.is_some() { builder.wgpu() } else { builder };
let mut harness = builder.build_ui_state(|ui, app| super::super::agent_dock(app, ui), app);
harness.run_steps(8);
assert!(harness.query_all_by_label("等待恢复 · 已暂停").next().is_some());
assert!(harness.query_all_by_label("正在准备详情页").next().is_none());
assert!(harness.query_all_by_label("正在推进目标").next().is_none());
assert!(harness.query_all_by_label("继续制作").next().is_some());
let w = harness.state_mut().jiansun.as_mut().unwrap();
assert_eq!(w.product_production.as_ref().unwrap().elapsed(), Duration::from_secs(300));
if let Some(directory) = &directory {
harness.render().unwrap().save(directory.join(format!("paused-{width}.png"))).unwrap();
}
let w = harness.state_mut().jiansun.as_mut().unwrap();
w.receive_library_status(&json!({"libraryStatus":"sign_in_required","libraryHttpStatus":401}));
w.product_production = None;
harness.run_steps(8);
assert!(harness.query_all_by_label("重新连接").next().is_some());
if let Some(directory) = &directory {
harness.render().unwrap().save(directory.join(format!("reconnect-{width}.png"))).unwrap();
}
}
}
#[test]
fn reconnect_opens_account_authorization_without_erasing_drafts_or_replaying_a_request() {
let (mut app, requests) = dock_fixture();
@ -7643,8 +7704,8 @@ mod tests {
for _ in 0..2 {
dock_frame(&ctx, &mut app, vec![]);
}
assert!(app.jiansun.as_ref().unwrap().panel_geometry["reconnect"].is_null());
dock_click(&ctx, &mut app, "send");
assert!(app.jiansun.as_ref().unwrap().panel_geometry["reconnect"].is_array());
dock_click(&ctx, &mut app, "reconnect");
let w = app.jiansun.as_ref().unwrap();
assert!(w.config);
assert_eq!(w.login_origin.as_deref(), Some(w.origin.as_str()));

View File

@ -2010,7 +2010,6 @@ mod tests {
let (_, rx) = mpsc::channel();
let mut w = Workspace::new(tx, rx);
let _ = requests.try_recv().unwrap();
let _ = requests.try_recv();
w.busy = None;
w.model_ready = true;
w.account = json!({"id":"scope-owner"});
@ -2141,9 +2140,13 @@ mod tests {
let active_doc = std::sync::Arc::make_mut(&mut session.active_mut().unwrap().doc);
active_doc.layers.push(slot_layer);
active_doc.metadata.text.push(("jiansun.slot-mapping.v1".into(), json!({
"version":1,
"canvasFirst":true,
"workspaceId":"ws-follow-up",
"component":"detail",
"templateId":"tpl-sofa",
"templateVersion":"1",
"templateHash":"hash-1",
"variantId":"oak",
"outputs":[{"documentId":"S01","top":0,"height":1800,"mapping":{"fields":[
{"fieldId":"S01-T01","kind":"text","label":"主标题","nativeLayerId":copy_layer,"originalText":"原标题","templateSample":true},
@ -2165,9 +2168,10 @@ mod tests {
w.observed_doc = Some(doc);
w.loaded_draft = Some(doc);
w.creation_doc = Some(doc);
w.open_projects.insert(doc, "local|project".into());
w.account = json!({"id":"local"});
w.origin = "https://example.test".into();
w.owner_doc = Some(doc);
w.open_projects.insert(doc, w.local_identity("project"));
w.canvas_workspace.output = "detail".into();
w.canvas_workspace.variant = "oak".into();
w.template_workflow = json!({
@ -2181,8 +2185,9 @@ mod tests {
"outputId":"detail",
"variantId":"oak",
"outputs":[{"outputId":"detail","documentId":"S01"}],
"slots":[{"id":"S01-I01","fieldId":"S01-I01","label":"首屏主图","outputId":"detail","variantId":"oak","nativeLayerId":slot_layer_id,"width":800,"height":800,"candidates":[{"id":"cand-1","status":"complete"}]}]
"slots":[{"id":"S01-I01","fieldId":"S01-I01","label":"首屏主图","outputId":"detail","documentId":"S01","variantId":"oak","nativeLayerId":slot_layer_id,"width":800,"height":800,"candidates":[{"id":"cand-1","status":"complete"}]}]
});
assert!(w.canvas_scope_valid(&app));
w.submit_turn(&app, "画布里面还空缺的地方都全部生成完成".into(), false);
let Request::Action(method, submitted) = requests.try_recv().unwrap() else { panic!("expected submit_turn agent action"); };
@ -2202,7 +2207,8 @@ mod tests {
let revision = app.session.active().unwrap().revision;
let applied = action_impl(&mut w, &mut app, None, "pi-detail-copy-apply", &json!({
"run":run,"revision":revision,"matchFields":true,"items":[{"layer":copy_layer,"text":"新标题","expectedText":"原标题"}]
"run":run,"documentId":doc,"revision":revision,"matchFields":true,
"items":[{"layer":copy_layer,"text":"新标题","expectedText":"原标题"}]
}), true).unwrap();
assert_eq!(applied["applied"], 1);

View File

@ -860,11 +860,13 @@ impl PendingExit {
impl Run {
fn new(doc: u64, project: String, workspace: Value, stages: Vec<Stage>,
goal_user_entry: Option<String>, phase: Phase) -> Self {
let started_at = production_time();
let paused_at = matches!(phase, Phase::Paused(_)).then_some(started_at);
Self { doc, project, workspace, total: stages.len(), requested_outputs: stages.iter().cloned().collect(), stages, completed: 0,
goal_user_entry, reset_goal: false, bound: None, opening: None, previous_save: Value::Null, session_epoch: None,
finish: None, finish_receipt: Value::Null, phase, drafts: Vec::new(),
deferred_images: HashMap::new(), deferred_image_due: HashMap::new(), deferred_image_in_flight: Vec::new(),
started_at: production_time(), paused_at: None, paused_seconds: 0, restarted: false,
started_at, paused_at, paused_seconds: 0, restarted: false,
delivery_dir: None, delivery_id: None, published: Vec::new(), delivery_receipt: Value::Null,
delivery_cancellation: None, delivery_write_epoch: None }
}
@ -899,6 +901,15 @@ fn production_time() -> u64 {
}
impl Run {
fn pause(&mut self, reason: Value) {
self.paused_at.get_or_insert_with(production_time);
self.phase = Phase::Paused(reason);
}
pub(super) fn clock_paused(&self) -> bool {
self.paused_at.is_some()
}
pub(super) fn elapsed(&self) -> Duration {
Duration::from_secs(self.paused_at.unwrap_or_else(production_time)
.saturating_sub(self.started_at).saturating_sub(self.paused_seconds))
@ -1021,7 +1032,7 @@ impl Run {
Phase::AwaitingSave => format!("正在保存{label}画布,保存后自动开始制作"),
Phase::Agent if self.bound.is_none() => "正在规划本轮输出".into(),
Phase::Agent => format!("正在制作{label}"),
Phase::Paused(_) => return None,
Phase::Paused(_) => "已暂停".into(),
Phase::Export => format!("正在保存{label}"),
Phase::DeliveringBundle => unreachable!(),
Phase::WaitingOriginals { .. } => format!("{label}等待原请求结果,确认后自动继续"),
@ -1029,7 +1040,7 @@ impl Run {
}
pub(super) fn showing_agent_progress(&self) -> bool {
self.phase == Phase::Agent
self.phase == Phase::Agent && !self.clock_paused()
}
pub(super) fn awaiting_canvas_save(&self) -> bool {
@ -1045,7 +1056,8 @@ impl Run {
}
pub(super) fn waiting_to_resume(&self) -> bool {
self.waiting_for_originals() || matches!(self.phase, Phase::AgentRetryAt(_))
self.clock_paused() || self.waiting_for_originals()
|| matches!(self.phase, Phase::Paused(_) | Phase::AgentRetryAt(_))
}
pub(super) fn canvas_requested(&mut self) {
@ -1281,8 +1293,7 @@ impl Workspace {
pause(run.doc, &run.project, run.session_epoch);
}
self.handover();
run.paused_at.get_or_insert_with(production_time);
run.phase = Phase::Paused(json!({"reason":"用户已停止制作"}));
run.pause(json!({"reason":"用户已停止制作"}));
run.opening = None;
run.finish = None;
run.finish_receipt = Value::Null;
@ -1353,7 +1364,7 @@ impl Workspace {
self.production_stop["state"] = json!("failed");
self.production_stop["error"] = json!(error);
if let Some(run) = self.product_production.as_mut() {
run.phase = Phase::Paused(json!({"reason":error}));
run.pause(json!({"reason":error}));
}
self.checkpoint_production();
}
@ -1749,8 +1760,7 @@ impl Workspace {
if let Some(bound) = run.bound.clone() {
run.defer_images(bound, original_ids(&value["production"]["originals"], "images"));
}
run.paused_at.get_or_insert_with(production_time);
run.phase = Phase::Paused(pause.clone());
run.pause(pause.clone());
}
self.checkpoint_production();
self.pi_write_blocked = true;
@ -2162,7 +2172,7 @@ impl Workspace {
run.completed = completed as usize;
}
if !delivered {
run.phase = Phase::Paused(json!({"reason":run.delivery_receipt["error"]}));
run.pause(json!({"reason":run.delivery_receipt["error"]}));
run.finish = None;
self.product_production = Some(run);
self.checkpoint_production();
@ -2934,7 +2944,7 @@ mod tests {
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(), None);
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());
@ -3006,7 +3016,7 @@ mod tests {
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(), None);
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());