From 9c5ceb09d937068448c8c72caecd4063d098844a Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Wed, 25 Nov 2026 22:46:44 +0800 Subject: [PATCH] fix(xiaoyi): pause production and checkpoint before exit --- apps/detail-agent-pi/src/desktop-daemon.mjs | 17 +- .../test/desktop-daemon.test.mjs | 25 +++ .../photocraft/src/jiansun_agent_daemon.rs | 10 ++ .../apps/photocraft/src/jiansun_backend.rs | 3 +- .../examples/xiaoyi_production_exit.rs | 164 ++++++++++++++++++ .../crates/ui-egui/src/dialogs/discard_ui.rs | 4 + .../crates/ui-egui/src/jiansun.rs | 52 ++++-- .../ui-egui/src/jiansun/product_production.rs | 83 ++++++++- .../crates/ui-egui/src/menus/invoke.rs | 3 + docs/development/xiaoyi/implementation.md | 18 +- 10 files changed, 360 insertions(+), 19 deletions(-) create mode 100644 apps/detail-photocraft/crates/ui-egui/examples/xiaoyi_production_exit.rs diff --git a/apps/detail-agent-pi/src/desktop-daemon.mjs b/apps/detail-agent-pi/src/desktop-daemon.mjs index 0ce813d7..fc804455 100644 --- a/apps/detail-agent-pi/src/desktop-daemon.mjs +++ b/apps/detail-agent-pi/src/desktop-daemon.mjs @@ -30,6 +30,14 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out if(closed)return; let value;try{if(line.length>2*1024*1024)throw Error();value=JSON.parse(line);}catch{send({type:'fatal',error:'本地消息无效;不会重发'});void stop();return;} if(value?.type==='heartbeat') {send({type:'heartbeat_ack',id:value.id,brokerPid:broker?.child?.pid??null});return;} + if(value?.type==='production_pause') { + const config=active?.config; + if(config?.productProduction===true && value.documentId===config.documentId + && value.project===config.project && value.scope===config.scope) { + active.abort(Error('客户端正在退出,已保留原请求')); + } + return; + } if(value?.type==='knowledge_cancel' && uuid.test(value.id||'')) { knowledge.get(value.id)?.abort(Error('已取消模板读取,已下载内容保留')); return; @@ -54,12 +62,11 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out if(active){if(active.runId!==value.runId)failure(value.runId,'已有运行中的任务,未派发');return;} if(seen.has(value.runId)||seen.size>=10000){failure(value.runId,'会话编号已使用或达到上限,未派发');return;} const runId=value.runId, config=structuredClone(value.config); - seen.add(runId);active={runId}; + seen.add(runId); const deadline = config.productProduction === true && Number.isSafeInteger(config.productionDeadline) ? config.productionDeadline * 1000 : null; - const controller = deadline === null ? null : new AbortController(); - const expire = () => { - const error = Error('整套制作已达到时限,已保留当前编辑和原请求'); + const controller = config.productProduction === true ? new AbortController() : null; + const abort = error => { controller.abort(error); for (const [id, task] of waiting) { if (task.runId !== runId) continue; @@ -68,6 +75,8 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out task.reject(error); } }; + active={runId,config,abort}; + const expire = () => abort(Error('整套制作已达到时限,已保留当前编辑和原请求')); const timer = deadline === null ? null : setTimeout(expire, Math.max(0, deadline - Date.now())); const call=(action,input)=>new Promise((resolve,reject)=>{ if(closed||active?.runId!==runId){reject(Error('客户端连接已关闭,原操作需核查'));return;} diff --git a/apps/detail-agent-pi/test/desktop-daemon.test.mjs b/apps/detail-agent-pi/test/desktop-daemon.test.mjs index 9b668365..ca38d5c4 100644 --- a/apps/detail-agent-pi/test/desktop-daemon.test.mjs +++ b/apps/detail-agent-pi/test/desktop-daemon.test.mjs @@ -101,3 +101,28 @@ test('a production deadline aborts a waiting canvas call and retains original re type: 'complete', runId, value: { pending: ['original-1'], unknown: true, reposted: false }, }); }); + +test('client exit pauses the bound production and leaves an original request for recovery', async t => { + let cancelled = false; + const config = { productProduction: true, documentId: 27, project: 'desk', scope: 'account-a' }; + const { frames, send } = daemonFixture(t, { + runSession: async (_, call, _broker, _recovery, signal) => { + await assert.rejects(call('pi-detail-images', { original: 'original-1' }), /正在退出/); + cancelled = signal.aborted; + await assert.rejects(call('pi-detail-images', { original: 'original-1' }), /正在退出/); + return { pending: ['original-1'], unknown: true, reposted: false }; + }, + }); + send({ type: 'run', runId, config }); + await tick(); + send({ ...config, type: 'production_pause', scope: 'account-b' }); + await tick(); + assert.equal(cancelled, false); + send({ ...config, type: 'production_pause' }); + await tick(); + assert.equal(cancelled, true); + assert.equal(frames.filter(frame => frame.type === 'canvas').length, 1); + assert.deepEqual(frames.at(-1), { + type: 'complete', runId, value: { pending: ['original-1'], unknown: true, reposted: false }, + }); +}); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs index 1836ed1e..b016ba90 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs @@ -271,6 +271,16 @@ pub(super) fn status() -> Value { json!({"available":state.alive && state.ready,"pid":service.pid,"brokerPid":state.broker_pid,"spawnCount":registry.spawn_count, "activeRun":state.active.as_ref().map(|(run,_)|run),"heartbeatAgeMs":state.last_ack.map(|at|at.elapsed().as_millis().min(u64::MAX as u128) as u64)}) } + +pub(super) fn pause_production(doc: u64, project_identity: &str) { + let Some((account_identity, project)) = project_identity.rsplit_once('|') else { return; }; + let service = registry().lock().ok().and_then(|registry| registry.service.clone()); + if let Some(service) = service { + let _ = service.send(&json!({"type":"production_pause","documentId":doc,"project":project, + "scope":super::hash(account_identity)})); + } +} + pub(super) fn shutdown() { if let Ok(mut registry) = registry().lock() { registry.mark_shutdown(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 74867608..2fe9502b 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -1370,7 +1370,7 @@ impl Backend { Ok(self.connection_data(&settings, Some(&available))) } "draft" => self.draft(input["doc"].as_u64().ok_or("项目编号无效")?), - "product-run-checkpoint" => { + "product-run-checkpoint" | "product-exit-checkpoint" => { let doc = input["doc"].as_u64().ok_or("项目编号无效")?; self.ensure_owner(doc)?; let checkpoint = &input["checkpoint"]; @@ -1981,6 +1981,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { }); let mut workspace = Workspace::new(tx, results); workspace.draft_flush = Some(Arc::new(move |token, text, primary, secondary, generation| composer_store.flush(token, text, primary, secondary, generation))); + workspace.pause_production_agent = Some(agent_daemon::pause_production); workspace } diff --git a/apps/detail-photocraft/crates/ui-egui/examples/xiaoyi_production_exit.rs b/apps/detail-photocraft/crates/ui-egui/examples/xiaoyi_production_exit.rs new file mode 100644 index 00000000..d521f452 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/examples/xiaoyi_production_exit.rs @@ -0,0 +1,164 @@ +//! Local Windows acceptance of PhotoCraft's exit and restart with a paid-request +//! boundary replaced by a channel. Each process reopens the native file from disk. +#[cfg(target_os = "windows")] +mod windows { + use std::path::{Path, PathBuf}; + use std::sync::{Arc, atomic::{AtomicBool, Ordering::Relaxed}, mpsc}; + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + use photocraft_ui_egui::{PhotocraftApp, Services, jiansun::{Event, Request, Workspace}}; + use serde_json::{Value, json}; + + const PROJECT: &str = "011b9c19-e4ae-4d28-8fcf-5cd529c30a25"; + const ORIGIN: &str = "https://qa.example.test"; + const ACCOUNT: &str = "local-qa"; + const EDIT: &str = "Edit made during the production turn"; + + struct Host { + app: PhotocraftApp, + dispatched: Arc, + mode: String, + dir: PathBuf, + handled: bool, + } + + impl eframe::App for Host { + fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { + if self.dispatched.load(Relaxed) && !self.handled { + self.handled = true; + if self.mode.starts_with("reopen") { + let edited = self.app.session.active().unwrap().doc.layers.iter().any(|layer| layer.name == EDIT); + assert_eq!(edited, self.mode == "reopen-saved"); + println!("reopened native canvas; edit present: {edited}; existing run resumed automatically"); + self.app.jiansun = None; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } else { + self.app.session.execute("layer.new.layer", json!({"name":EDIT})).unwrap(); + std::fs::write(self.dir.join("edited"), b"canvas edit applied").unwrap(); + if self.mode.starts_with("exit") { + photocraft_ui_egui::menus::invoke(&mut self.app, ctx, "file.exit", Value::Null).unwrap(); + } + } + } + eframe::App::logic(&mut self.app, ctx, frame); + if self.mode == "exit-fail" && self.app.jiansun.is_some() + && self.app.ui.status_error && self.app.ui.status.contains("保存未确认") { + assert!(self.app.session.active().unwrap().is_dirty()); + println!("a failed save leaves the document dirty and reports the unconfirmed exit"); + self.app.jiansun = None; + self.app.session.close(self.app.session.active_index().unwrap()); + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } + + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + eframe::App::ui(&mut self.app, ui, frame); + } + } + + fn read(path: &Path) -> Value { + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap() + } + + fn write(path: &Path, value: &Value) { + photocraft_format::atomic_write(path, &serde_json::to_vec(value).unwrap()).unwrap(); + } + + pub fn run(dir: PathBuf, mode: String) { + let canvas = dir.join("canvas.pcraft"); + let journal = dir.join("production-run.json"); + let draft = dir.join("draft.json"); + let stages = json!([{"outputId":"detail","variantId":"satin"},{"outputId":"sku_images","variantId":"matte"}]); + let mapping = json!({"version":1,"canvasFirst":true,"workspaceId":"desk","component":"detail","variantId":"satin", + "templateId":"enterprise","templateVersion":"1","templateHash":"published","outputs":[{"documentId":"desk-page","mapping":{"fields":[]}}]}); + let workflow = json!({"revision":1,"workspaceId":"desk","outputId":"detail","variantId":"satin", + "templateId":"enterprise","templateVersion":"1","templateHash":"published", + "outputs":[{"outputId":"detail","documentId":"desk-page"}], + "productionStages":stages,"scopedProductionPending":true}); + if !mode.starts_with("reopen") { + std::fs::create_dir_all(&dir).unwrap(); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"name":"Production exit QA","width":64,"height":48})).unwrap(); + let doc = Arc::make_mut(&mut session.active_mut().unwrap().doc); + doc.metadata.text.push(("jiansun.slot-mapping.v1".into(), mapping.to_string())); + photocraft_format::PcraftWriter::new().save_path(doc, &canvas, &Default::default()).unwrap(); + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); + write(&journal, &json!({"active":true,"project":PROJECT,"workspaceId":"desk","deadline":now+600, + "stages":stages,"total":2,"drafts":[]})); + write(&draft, &json!({"revision":1})); + } + let mut doc = photocraft_format::load_path(&canvas).unwrap(); + doc.id = photocraft_doc::DocId::fresh(); + let doc_id = doc.id.0; + let options = eframe::NativeOptions { viewport:egui::ViewportBuilder::default().with_inner_size([660.0, 480.0]), ..Default::default() }; + eframe::run_native("PhotoCraft production exit QA", options, Box::new(move |cc| { + let (tx, requests) = mpsc::channel(); + let (events, rx) = mpsc::channel(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + let mut workspace = Workspace::new(tx, rx); + workspace.draft_flush = Some(Arc::new(|_, _, _, _, _| Ok(()))); + app.jiansun = Some(workspace); + let dispatched = Arc::new(AtomicBool::new(false)); + let signal = Arc::clone(&dispatched); + let ctx = cc.egui_ctx.clone(); + let current_mode = mode.clone(); + let evidence = dir.clone(); + events.send(Event::Json("restore".into(), Ok(json!({"account":{"id":ACCOUNT},"origin":ORIGIN, + "modelReady":true,"imageReady":true})))).unwrap(); + events.send(Event::Opened(Box::new(doc), json!({"path":canvas,"localId":PROJECT,"accountId":ACCOUNT, + "origin":ORIGIN,"revision":read(&draft)["revision"]}))).unwrap(); + std::thread::spawn(move || { + let mut writer = photocraft_format::PcraftWriter::new(); + while let Ok(request) = requests.recv() { + let event = match request { + Request::Action(method, _) if method == "draft" => { + let run = read(&journal); + assert_eq!(run["active"], true); + events.send(Event::Json("draft".into(), Ok(json!({"doc":doc_id,"localId":PROJECT,"productionRun":run})))) + .unwrap(); + Event::Json("slot-read".into(), Ok(json!({"doc":doc_id,"accountId":ACCOUNT,"origin":ORIGIN,"workflow":workflow}))) + } + Request::Action(method, input) if method == "agent" => { + assert!(!signal.swap(true, Relaxed)); + assert_eq!(input["context"]["requestScope"]["productionDeadline"], read(&journal)["deadline"]); + println!("loaded active checkpoint; local agent dispatch requested"); + ctx.request_repaint(); + continue; + } + Request::Action(method, input) if method == "product-exit-checkpoint" => { + write(&journal, &input["checkpoint"]); + Event::Json(method, Ok(Value::Null)) + } + Request::Save(..) if current_mode == "exit-fail" => + Event::Json("save".into(), Err("QA: 本机草稿写入失败".into())), + Request::Save(doc, revision, _) if current_mode == "exit" => { + assert!(doc.layers.iter().any(|layer| layer.name == EDIT)); + assert!(evidence.join("edited").is_file()); + // Make the receipt arrive in a later native frame. + std::thread::sleep(Duration::from_millis(300)); + writer.save_path(&doc, &canvas, &Default::default()).unwrap(); + write(&draft, &json!({"revision":revision})); + println!("saved real native canvas at revision {revision}"); + Event::Saved(doc.id.0, revision, json!({"localId":PROJECT,"savedPath":canvas})) + } + Request::Generate(..) => panic!("exit and resume fixture must not send new image requests"), + _ => continue, + }; + if events.send(event).is_err() { break; } + ctx.request_repaint(); + } + }); + Ok(Box::new(Host { app, dispatched, mode, dir, handled:false })) + })).unwrap(); + println!("native window exited"); + } +} + +fn main() { + #[cfg(target_os = "windows")] { + let mut args = std::env::args_os().skip(1); + let mode = args.next().unwrap().into_string().unwrap(); + let dir = args.next().unwrap().into(); + windows::run(dir, mode); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/dialogs/discard_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/dialogs/discard_ui.rs index 41ca4e4a..020856ba 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/dialogs/discard_ui.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/dialogs/discard_ui.rs @@ -125,6 +125,10 @@ pub fn guard_window_close(app: &mut PhotocraftApp, ctx: &egui::Context) { if !ctx.input(|i| i.viewport().close_requested()) { return; } + if crate::jiansun::guard_production_exit(app, ctx) { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + return; + } if !app.allow_close && intercept(app, EXIT, &Value::Null) { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); ctx.send_viewport_cmd(egui::ViewportCommand::Focus); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index cde0ae4c..3bd9871b 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -967,6 +967,8 @@ pub struct Workspace { image_recovery_schedules: HashMap, draft_changed: bool, product_checkpoint: Value, + production_exit: Option, + pub pause_production_agent: Option, loaded_draft: Option, pub draft_flush: Option, composer_drafts: composer_drafts::State, @@ -1442,6 +1444,8 @@ impl Workspace { image_recovery_schedules: HashMap::new(), draft_changed: false, product_checkpoint: Value::Null, + production_exit: None, + pause_production_agent: None, loaded_draft: None, draft_flush: None, composer_drafts: composer_drafts::State::default(), @@ -2754,6 +2758,9 @@ impl Workspace { } if method == "save" { self.saving = None; + if let (Some(exit), Err(error)) = (&mut self.production_exit, &result) { + exit.save_error = Some(error.clone()); + } } match result { Err(e) if method == "agent" && self.defer_production_agent(app, &e) => {} @@ -3327,6 +3334,11 @@ impl Workspace { app.remember_original_preview(doc.id, &preview); } match event { + Event::Json(method, result) if method == "product-exit-checkpoint" => { + if let Some(exit) = &mut self.production_exit { + exit.checkpoint = Some(result.map(|_| ())); + } + } Event::SlotCanvas(doc, meta) if meta["productViewId"].is_u64() => self.product_view_received(app, doc, meta), Event::SlotCanvas(doc, meta) if meta["continueProduct"] == true => @@ -3356,6 +3368,10 @@ impl Workspace { } } } + if self.production_exit.is_some() { + self.advance_production_exit(app, ctx); + return; + } if !self.tick_context(app, ctx) { return; } let current = app.session.active().map(|s| (s.doc.id.0, s.revision)); self.tick_pending_edits(app, ctx, current); @@ -3408,22 +3424,31 @@ impl Workspace { ctx.request_repaint_after(remaining); return; } - let composer_saved = self.flush_document_draft(ctx, Some(key.0), false); - if !composer_saved { self.draft_changed = true; } - let meta = json!({"composer":self.composer,"messages":self.messages,"project":self.project_context,"syncDirty":self.sync_dirty,"creationDraft":self.creation_draft()}); - if self.tx.send(Request::Save(st.doc.clone(), st.revision, meta)).is_ok() { - self.saving = Some(key); - if composer_saved { self.draft_changed = false; } - self.touched = Instant::now(); - } else if !composer_saved { - self.touched = Instant::now(); - } + self.save_project_draft(st, ctx); } } } + fn save_project_draft(&mut self, state: &photocraft_engine::DocState, ctx: &egui::Context) -> bool { + let key = (state.doc.id.0, state.revision); + let composer_saved = self.flush_document_draft(ctx, Some(key.0), false); + if !composer_saved { self.draft_changed = true; } + let meta = json!({"composer":self.composer,"messages":self.messages,"project":self.project_context,"syncDirty":self.sync_dirty,"creationDraft":self.creation_draft()}); + let submitted = self.tx.send(Request::Save(state.doc.clone(), state.revision, meta)).is_ok(); + if submitted { + self.saving = Some(key); + if composer_saved { self.draft_changed = false; } + } + if submitted || !composer_saved { self.touched = Instant::now(); } + submitted + } + fn receive_event(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, event: Event) { match event { Event::PiAction(method, input, reply) => { + if self.production_exit.is_some() { + let _ = reply.send(Err("客户端正在退出,原操作可在重新打开后核查".into())); + return; + } let result = if matches!(method.as_str(), "pi-write-request" | "pi-edit" | "pi-workflow-propose" | "pi-workflow-execute" | "pi-native-call") && !self.enforce_canvas_scope(app) { Err("画布与当前模板或花色不一致,本轮未获画布写入许可".into()) } else if method == "creation-allowed" { @@ -4014,6 +4039,13 @@ pub(crate) fn advance(app: &mut PhotocraftApp, ctx: &egui::Context) { } } +pub(crate) fn guard_production_exit(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + let Some(mut workspace) = app.jiansun.take() else { return false; }; + let waiting = workspace.begin_production_exit(app, ctx); + app.jiansun = Some(workspace); + waiting +} + pub(crate) fn bind_workspace_rendering(app: &PhotocraftApp, ui: &Ui) { if app.jiansun.is_some() { glow_pill::bind(ui, app.gpu_render_state.as_ref()); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs index 7cfc6751..194cabbc 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs @@ -626,6 +626,15 @@ pub(super) struct Run { restarted: bool, } +pub(super) struct PendingExit { + doc: u64, + project: String, + deadline: Instant, + pub(super) checkpoint: Option>, + pub(super) save_error: Option, + save_requested: bool, +} + impl Run { fn new(doc: u64, project: String, workspace: Value, stages: VecDeque, goal_user_entry: Option, phase: Phase) -> Self { @@ -719,15 +728,19 @@ impl Workspace { self.checkpoint_production(); } - fn write_production_checkpoint(&self, run: &Run, active: bool) { - let Some(project) = run.project.rsplit('|').next() else { return; }; + fn production_checkpoint_request(run: &Run, active: bool) -> Value { + let project = run.project.rsplit('|').next().unwrap_or_default(); let checkpoint = json!({ "active":active,"project":project,"workspaceId":run.workspace,"deadline":run.deadline, "total":run.total,"drafts":run.drafts, "stages":run.stages.iter().map(Stage::value).collect::>(), "deferred":run.deferred.iter().map(Stage::value).collect::>() }); - let _ = self.tx.send(Request::Action("product-run-checkpoint".into(), json!({"doc":run.doc,"checkpoint":checkpoint}))); + json!({"doc":run.doc,"checkpoint":checkpoint}) + } + + fn write_production_checkpoint(&self, run: &Run, active: bool) { + let _ = self.tx.send(Request::Action("product-run-checkpoint".into(), Self::production_checkpoint_request(run, active))); } fn checkpoint_production(&self) { @@ -736,6 +749,70 @@ impl Workspace { } } + pub(super) fn begin_production_exit(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + if self.production_exit.is_some() { return true; } + let Some(run) = self.product_production.take() else { return false; }; + if let Some(pause) = self.pause_production_agent { + pause(run.doc, &run.project); + } + self.with_product_target(app, |w, _| { + w.pi_ui_cancel("客户端正在退出"); + w.allow_apply = false; + w.handover(); + }); + self.pending_slot_apply = None; + self.pi_write_blocked = true; + self.agent_effects_paused = true; + self.product_checkpoint = Value::Null; + + let checkpoint = self.tx.send(Request::Action("product-exit-checkpoint".into(), + Self::production_checkpoint_request(&run, true))); + self.production_exit = Some(PendingExit { + doc: run.doc, + project: run.project, + deadline: Instant::now() + Duration::from_secs(90), + checkpoint: checkpoint.err().map(|_| Err("本机制作记录保存服务已断开".into())), + save_error: None, + save_requested: false, + }); + app.ui.status = "正在保存小壹制作进度…".into(); + app.ui.status_error = false; + ctx.request_repaint(); + true + } + + pub(super) fn advance_production_exit(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) { + let result = self.with_product_target(app, |w, app| { + let exit = w.production_exit.as_ref()?; + let remaining = exit.deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { return Some(Err("退出等待超时,保存结果未确认".to_owned())); } + ctx.request_repaint_after(remaining); + if w.saving.is_some() || w.product_view_save_pending() { return None; } + if let Some(error) = &exit.save_error { return Some(Err(error.clone())); } + let Some(state) = app.session.active().filter(|state| state.doc.id.0 == exit.doc + && w.open_projects.get(&exit.doc) == Some(&exit.project) && exit.project.starts_with(&w.local_identity(""))) else { + return Some(Err("制作工程已切换,请核对原工程的草稿".into())); + }; + if w.persisted_revisions.get(&exit.doc) != Some(&state.revision) || w.draft_changed { + if exit.save_requested { return Some(Err("仍有编辑未落盘,请检查保存状态".into())); } + if !w.save_project_draft(state, ctx) { return Some(Err("本机草稿保存服务已断开".into())); } + if let Some(exit) = &mut w.production_exit { + exit.save_requested = true; + } + return None; + } + exit.checkpoint.clone() + }); + let Some(result) = result else { return; }; + self.production_exit = None; + if let Err(error) = result { + log::warn!("小壹退出前保存未确认:{error}"); + app.ui.status = format!("小壹退出前保存未确认。{error}"); + app.ui.status_error = true; + } + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + pub(super) fn stop_production(&mut self) { if let Some(run) = self.product_production.as_ref() { self.write_production_checkpoint(run, false); diff --git a/apps/detail-photocraft/crates/ui-egui/src/menus/invoke.rs b/apps/detail-photocraft/crates/ui-egui/src/menus/invoke.rs index 46cb76c8..5e02d37c 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/menus/invoke.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/menus/invoke.rs @@ -45,6 +45,9 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va { authorize(id, ¶ms)?; } + if id == "file.exit" && crate::jiansun::guard_production_exit(app, ctx) { + return Ok(Value::Null); + } if crate::discard_ui::intercept(app, id, ¶ms) { return Ok(Value::Null); } diff --git a/docs/development/xiaoyi/implementation.md b/docs/development/xiaoyi/implementation.md index c4c8c4f0..313a6430 100644 --- a/docs/development/xiaoyi/implementation.md +++ b/docs/development/xiaoyi/implementation.md @@ -189,7 +189,7 @@ Node 证据为 `04-deadline-node.log`。时限值沿用原有配置。 | 正式原稿排版与重开 | 通过 | 顾家电脑桌正式主图原稿 M04,使用原生模板文字写入入口把两行标题改为一行「桌下宽敞」。保存为可编辑工程并独立重开,文字、首行字符和段落样式吻合。见 `enterprise-copy-evidence.json`、`enterprise-page-copy.pcraft` | | 餐椅本地模板发布包 | 通过本机保存重开 | 用离线发布包中登记的 profile 加载正式餐椅原稿,核对图层数量、画布、参考线、固定文字样式以及旧款宣传层隐藏。18 项原生验收通过,见 `03-05-native-final.log`、`production-typing-pcraft-report.json` | | 电脑桌真实一键制作 | 失败于画布初始化 | 工作树 `bdc372f9` 的新原生构建。隔离新建 SZ012616,录入五张同款实拍,选择顾家电脑桌资源组和一款花色,98K 已连接。点击一次,约 10 秒内观察到退出,详情制作画布未打开,模型调用 0 次,导出 0 份。选中的模型为 GPT‑6.1 Sol 与 GPT Image 2.6 Sunburst。见 `desk-unattended/local-build-manifest.json`、`desk-unattended/dispatch.json`、`desk-unattended/run-evidence.json` | -| 企业资源版本检查 | 已确认阻塞 | 同一资源组的详情组件能解析。主图和 SKU 组件均返回「字段映射与当前原稿版本不符」。绑定组件时客户端把缺失的包交给通用格式检查,界面只显示「模板包格式无效」。需按主图和 SKU 的现行原稿修正正式字段映射并保存新资源版本。只读证据见 `desk-unattended/resource-diagnostics.json` | +| 企业资源版本检查 | 本轮初始化阻塞,后续已修复 | 同一资源组的详情组件能解析。主图和 SKU 组件均返回「字段映射与当前原稿版本不符」,界面只显示「模板包格式无效」。当时的只读证据见 `desk-unattended/resource-diagnostics.json`,正式源文件和修复后的绑定验证见 §7 | | Photoshop 独立兼容、真实推理和跨三类输出交付 | 未执行 | 本轮正式过关范围为 PhotoCraft 独立重开。真实一键调用在发模型请求前停止,因而没有生成或可交付成果 | Node 范围回归 162 项通过,另有采纳本轮超时定向回归 9 项通过。企业发布、五类输出、A/B 双候选、关窗托盘及 SQLite 决策延至后续。 @@ -207,4 +207,20 @@ Node 范围回归 162 项通过,另有采纳本轮超时定向回归 9 项通 原始对照和组件证据在 `audit-corrections/desk-template-repair/`。真实企业资料读取已通过,详情 22 页、主图 5 页、SKU 1 页。资源回归 21 项通过,覆盖局部编号、来源路径错误和摘要错误。 PhotoCraft 用正式文件独立导入了 5 张主图和 1 张 SKU,并按原稿编号、图层名、层级和类型绑定全部 35 个字段。主图首张和 SKU 原稿预览在本机生成并检查。原生回归 3 项与运行状态回归 3 项通过,覆盖组件阻塞、必需交付计数、已有图位审核及到期结算。证据见 `native-components.json`、`native-regression.log`、`ui-regression.log`。本轮验收覆盖正式资源和原稿画布,98K 整套制作另行验证。 + +## 第六批 · 阶段 C,退出制作与重开对账 + +文件菜单和窗口的退出请求共用小壹的制作保存流程。项目暂停新派发,已发请求保留原编号。Pi 守护进程只接受与当前账户、项目、文档一致的暂停信号,并取消本轮等待中的画布调用。客户端用原有项目保存和制作检查点落盘,重开后按同一项目续跑。 + +| 触发条件 | 出口 | 验证 | +| --- | --- | --- | +| 制作已启动,用户显式退出 | 暂停 Pi,保存当前制作检查点和有修改的草稿。收到回执后继续原生退出流程;其他画布仍按原有未保存提示处理 | 通过 Windows 原生窗口和真实文件验证。64 × 48 的两输出、两款式测试工程在回合中编辑,延迟回执后正常退出。新进程读到实际保存的修订 2 和新增图层,自动接续原检查点 | +| 保存失败或 90 秒内未确认 | 记录对应保存问题,交回原生退出流程。已确认版本和原请求可在重开时核对 | 原生窗口注入保存失败回执后,画布保持未保存状态且报告未确认。新进程打开原文件时仍为修订 1。实际磁盘故障和 90 秒超时未实测 | +| 操作系统强制结束进程 | 下次打开实际已保存版本,从持久检查点恢复 | 通过 Windows 进程验证。已应用在内存、未保存的编辑在强制结束后没有出现在重开的文件中,原检查点自动恢复,修订仍为 1 | +| Pi 暂停时有待核查原请求 | 保存原身份并结束当前执行,查询仍走原请求 | 通过本地注入回归。不同账户的信号没有取消当前回合,匹配的退出信号取消了等待,原请求仍保留,后续没有重新提交。含生产、恢复、工作流在内共 167 项通过 | +| 关窗到托盘 | 产品确认后实现和验收 | 待定 | + +证据在 `audit-corrections/exit-recovery/`。Windows 验收通过 `crates/ui-egui/examples/xiaoyi_production_exit.rs` 启动独立原生窗口,使用 PhotoCraft 实际写入和重开 `.pcraft`。模型和后台回执使用本机通道,真实 98K 原请求和三类成品导出未在本批执行。见 `native-probe.log`、`process-evidence.json`、`agent-regression.log`。客户端编译检查和 31 个 crate 的依赖层检查通过。 + +接续阶段 D 的 A20–A22,先将所选企业 Skill 和引用接入 Pi 的版本化资源加载,核对主、子代理读取记录,再处理项目目标和多余的固定轮次限制。