diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index a3bc1fe3..dbcd1957 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -420,7 +420,8 @@ export class DetailPiAgent { const output = createAssistantMessageEventStream(); const worker = workers.get(options.sessionId); const workerFields = worker && {slotId:worker.slotId,requestScope:worker.requestScope}; - if (worker?.signal) options = {...options,signal:AbortSignal.any([options.signal,worker.signal].filter(Boolean))}; + const signals = [options.signal, worker?.signal, host.productionSignal].filter(Boolean); + if (signals.length) options = {...options, signal:AbortSignal.any(signals)}; (async () => { let round; const purpose = worker ? 'whole-detail-worker' : host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation'; @@ -858,7 +859,7 @@ export class DetailPiAgent { if (this.canvas.run && !this.canvasEndAttempted) await this.notifyCanvas('contextUsage', this.contextUsage); return this.contextUsage; } - async promptTurn(text, { requiredTool, referenceContent = [], goalContinuation = false } = {}) { + async promptTurn(text, { requiredTool, referenceContent = [], goalContinuation = false, resetProductionGoal = false } = {}) { if (typeof text !== 'string' || !text.trim()) throw Error('请输入本轮要求'); text = redactText(text); const latest = this.firstTurnBrokerInfo ?? (this.broker ? await this.broker.info() : this.info); @@ -912,6 +913,9 @@ export class DetailPiAgent { this.activityScope = activityScope(this.store.identity, this.canvas, begun); try { const production=this.productionGoal; + if (resetProductionGoal && piGoalState(this.manager)) { + await this.session.prompt('/goal clear'); + } if (!production && (await this.canvas.read()).conversationActive===false) { throw Error('当前项目已切换,本轮对话未应用到其他项目'); } @@ -969,6 +973,11 @@ export class DetailPiAgent { return { ...(result?{production:{...result,...(knowledgeVersion?{knowledgeVersion}:null),...(versionNotice?{knowledgeVersionNotice:versionNotice}:null)}}:null), text: textResult, rounds: this.rounds, messages: this.session.messages.length, sessionFile: this.manager.getSessionFile() }; } catch (error) { + if (this.productionSignal?.aborted && this.productionGoal && piGoalState(this.manager)?.status === 'active') { + this.session.clearQueue(); + await this.session.prompt('/goal pause').catch(() => {}); + } + await this.updateContextUsage(null, 'ready').catch(() => {}); await this.display.flush(); await this.nativeUI.stop().catch(() => {}); const generated = this.generatedCandidateReply(); @@ -986,6 +995,7 @@ export class DetailPiAgent { return this.exclusive(async () => { this.rounds = 0; const result = await this.session.compact(); + this.productionSignal?.throwIfAborted(); await atomic(path.join(this.store.dir, 'session.json'), {file:this.manager.getSessionFile()}); return result; }); diff --git a/apps/detail-agent-pi/src/desktop-daemon.mjs b/apps/detail-agent-pi/src/desktop-daemon.mjs index 97aef434..f1fac370 100644 --- a/apps/detail-agent-pi/src/desktop-daemon.mjs +++ b/apps/detail-agent-pi/src/desktop-daemon.mjs @@ -56,7 +56,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out if(config?.productProduction===true && value.documentId===config.documentId && value.project===config.project && value.scope===config.scope && (value.writeEpoch??null)===(config.writeEpoch??null)) { - active.abort(Error('本轮制作已停止,已保留原请求')); + active.abort(new BridgeError('本轮制作已停止,已保留原请求', 'cancelled')); } return; } @@ -105,7 +105,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out const abort = error => { controller.abort(error); for (const [id, task] of waiting) { - if (task.runId !== runId || task.retainOriginal) continue; + if (task.runId !== runId) continue; waiting.delete(id); clearTimeout(task.timer); task.reject(new BridgeError(error.message,error.category ?? 'cancelled',{dispatched:true})); @@ -123,7 +123,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out } const id=++serial; const retainOriginal=action==='pi-image-request' && input.action==='dispatch'; - const task={resolve,reject,runId,retainOriginal,accepted}; + const task={resolve,reject,runId,accepted}; // The local canvas bridge can wait 12 seconds for the UI per queued action. // Keep a separate budget for image dispatch and its original-order recovery. const localCandidate = action === 'pi-image-request' && ['transform','product_reference'].includes(input.action); diff --git a/apps/detail-agent-pi/src/desktop-host.mjs b/apps/detail-agent-pi/src/desktop-host.mjs index 099f4382..76f13cd9 100644 --- a/apps/detail-agent-pi/src/desktop-host.mjs +++ b/apps/detail-agent-pi/src/desktop-host.mjs @@ -202,7 +202,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o host.qaNativeTimeout = command => consumeQaNativeTimeout({scope:info.accountScope, project:config.project, documentId:config.documentId, accountId:host.canvas.identity?.accountId, origin:host.canvas.identity?.origin}, command); signal?.throwIfAborted(); - const result = await host.prompt(config.text, {referenceContent:config.referenceContent,goalContinuation:!!productionGoal&&!config.goalUserEntry}); + const result = await host.prompt(config.text, {referenceContent:config.referenceContent,goalContinuation:!!productionGoal&&!config.goalUserEntry,resetProductionGoal:config.resetProductionGoal===true}); signal?.throwIfAborted(); if (broker.authority?.error) throw broker.authority.error; output = {...result,unknown:false,usage,contextUsage:host.contextUsage, diff --git a/apps/detail-agent-pi/test/conversation.test.mjs b/apps/detail-agent-pi/test/conversation.test.mjs index acc32fd0..d7265043 100644 --- a/apps/detail-agent-pi/test/conversation.test.mjs +++ b/apps/detail-agent-pi/test/conversation.test.mjs @@ -165,7 +165,8 @@ test('a model response arriving after cancellation keeps its receipt and cannot await assert.rejects(first,/停止/); const journal=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(JSON.parse); const finished=journal.find(e=>e.type==='provider_finished'); - assert.equal(finished.stopReason,'toolUse'); + assert.equal(finished.stopReason,'aborted'); + assert.equal(x.host.contextUsage.phase,'ready'); assert.equal(finished.status,'cancelled'); assert.equal(finished.consumption,'discarded_after_cancel'); diff --git a/apps/detail-agent-pi/test/desktop-daemon.test.mjs b/apps/detail-agent-pi/test/desktop-daemon.test.mjs index d13b46c8..f6bee5c5 100644 --- a/apps/detail-agent-pi/test/desktop-daemon.test.mjs +++ b/apps/detail-agent-pi/test/desktop-daemon.test.mjs @@ -370,7 +370,7 @@ test('presentation notifications do not wait for replies and the terminal comman assert.equal(frames.at(-1).type,'complete'); }); -test('cancellation retains the paid image receipt and rejects an old canvas reply or an old pause', async t => { +test('cancellation releases the turn while the host retains the paid image request', async t => { const nextRunId='9a1ba294-f2c4-4e5f-91e0-ef6002f50e23'; const config={productProduction:true,documentId:27,project:'desk',scope:'account-a',writeEpoch:4}; const accepted=[]; @@ -382,9 +382,12 @@ test('cancellation retains the paid image receipt and rejects an old canvas repl return next; } const image=call('pi-image-request',{action:'dispatch',request:{requestId:'original-image'}},()=>accepted.push('image')); - await assert.rejects(call('pi-detail-copy-apply',{}), {category:'cancelled'}); + await Promise.all([ + assert.rejects(call('pi-detail-copy-apply',{}), {category:'cancelled'}), + assert.rejects(image, {category:'cancelled',dispatched:true}), + ]); assert.equal(signal.aborted,true); - return {archived:await image}; + return {stopped:true}; }, }); send({type:'run',runId,config}); @@ -395,11 +398,11 @@ test('cancellation retains the paid image receipt and rejects an old canvas repl send({type:'canvas_result',runId,id:write.id,value:{applied:1}}); await tick(); assert.deepEqual(accepted,['image']); - assert.equal(frames.some(frame=>frame.type==='complete'),false); + assert.deepEqual(frames.at(-1).value,{stopped:true}); const original={requestId:'original-image',status:'complete'}; send({type:'canvas_result',runId,id:image.id,value:original}); await tick(); - assert.deepEqual(frames.at(-1).value,{archived:original}); + assert.deepEqual(frames.at(-1).value,{stopped:true}); send({type:'run',runId:nextRunId,config:{...config,writeEpoch:5}}); await tick(); diff --git a/apps/detail-agent-pi/test/native-wire.test.mjs b/apps/detail-agent-pi/test/native-wire.test.mjs index ba19161a..1bc35eb3 100644 --- a/apps/detail-agent-pi/test/native-wire.test.mjs +++ b/apps/detail-agent-pi/test/native-wire.test.mjs @@ -661,7 +661,7 @@ test('a terminal marker without a completion reason remains unproven and cannot assert.throws(() => auditResponse(sse(broken,'tool_calls'),'openai-chat'),InvalidToolReply); }); -async function compactionFixture({ withCanvas, callBudget = 4, large = false, contextWindow = 64_000, historyInput = large ? 50_000 : 5_000, pendingStep, rateLimit = false } = {}) { +async function compactionFixture({ withCanvas, callBudget = 4, large = false, contextWindow = 64_000, historyInput = large ? 50_000 : 5_000, pendingStep, rateLimit = false, waitForAbort } = {}) { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-')), scope = '9'.repeat(64); const store = await ProjectStore.open(dir, { scope, project: randomUUID() }, { brandId: 'qa', shopId: 'qa', categoryId: 'qa', platform: 'qa', source: 'qa', version: '1', rules: [] }); const manager = SessionManager.create(store.dir, path.join(store.dir, 'sessions')); @@ -678,6 +678,11 @@ async function compactionFixture({ withCanvas, callBudget = 4, large = false, co calls++; const stream = createAssistantMessageEventStream(); const message = { role: 'assistant', api: model.api, provider: model.provider, model: model.id, content: [{ type: 'text', text: 'Summary: original evidence remains archived.' }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 5000, output: 20, cacheRead: 0, cacheWrite: 0, totalTokens: 5020, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } }; + if (waitForAbort) { + options.signal.addEventListener('abort', () => stream.end({...message, content:[], stopReason:'aborted'}), {once:true}); + waitForAbort(); + return stream; + } queueMicrotask(() => { stream.push({ type: 'start', partial: message }); stream.push({ type: 'text_delta', contentIndex: 0, delta: message.content[0].text, partial: message }); stream.push({ type: 'done', reason: 'stop', message }); stream.end(message); }); return stream; } }; @@ -724,6 +729,21 @@ test('compaction with a connected canvas does not call an inactive edit run or s } finally { await x.close(); } }); +test('stopping a production turn aborts an active context compaction', {timeout:3000}, async () => { + const entered = Promise.withResolvers(); + const x = await compactionFixture({waitForAbort:entered.resolve}); + const stop = new AbortController(); + try { + x.host.productionSignal = stop.signal; + const compacting = assert.rejects(x.host.compact()); + await entered.promise; + stop.abort(Error('production stopped')); + await compacting; + assert.equal(x.host.operationActive, false); + assert.equal(x.host.contextUsage.phase, 'ready'); + } finally { await x.close(); } +}); + test('the main session compacts above 150k with production facts and lower summary effort',async()=>{ const x=await compactionFixture({large:true,contextWindow:272_000,historyInput:180_000}); try { diff --git a/apps/detail-agent-pi/test/pi.test.mjs b/apps/detail-agent-pi/test/pi.test.mjs index 8a4cf5b5..0d63b62e 100644 --- a/apps/detail-agent-pi/test/pi.test.mjs +++ b/apps/detail-agent-pi/test/pi.test.mjs @@ -248,7 +248,7 @@ test('Pi pauses after a continuation without tools and resumes on a new user req assert.deepEqual(JSON.parse(defer.content[0].text).availableOutputs,requestedOutputs.slice(1)); } if(calls===3)return tool('open_production_output',detail); - assert.ok(calls<=6,'a text-only continuation must stop further requests'); + assert.ok(calls<=8,'a text-only continuation must stop further requests'); return stream([{type:'text',text:'已汇报进展'}]); }}; const host=await openAgent({store,canvas,transport,documentId,productionGoal:{ @@ -262,12 +262,18 @@ test('Pi pauses after a continuation without tools and resumes on a new user req assert.deepEqual(first.production.pause,{reason:blocker.reason,requiredAction:blocker.requiredAction}); assert.equal(piGoalState(host.manager).status,'paused'); + const previousGoal = piGoalState(host.manager).id; host.productionGoal.drafts=[]; const next=await host.prompt('已补资料,请继续'); assert.equal(calls,6); assert.equal(next.production.stageStatus,'paused'); assert.deepEqual(next.production.pause,{reason:'已汇报进展'}); assert.equal(piGoalState(host.manager).status,'paused'); + + assert.equal(piGoalState(host.manager).id, previousGoal); + await host.prompt('从当前画布开始新一轮', {resetProductionGoal:true}); + assert.ok(calls > 6); + assert.notEqual(piGoalState(host.manager).id, previousGoal); }); test('explicit tools share one Pi transcript and submit each real canvas revision', async t => { 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 dfc29ce2..8e67698a 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs @@ -28,9 +28,9 @@ pub(super) struct Daemon { state: Mutex, pid: u32, } -struct Registry { service: Option>, shutting_down: bool, spawn_count: u64 } +struct Registry { service: Option>, shutting_down: bool, spawn_count: u64, production_pause: Option } impl Registry { - fn new() -> Self { Self { service: None, shutting_down: false, spawn_count: 0 } } + fn new() -> Self { Self { service: None, shutting_down: false, spawn_count: 0, production_pause: None } } fn ensure_start_allowed(&self) -> R<()> { if self.shutting_down { return Err("本机Agent正在关闭,未启动新进程".into()); } Ok(()) @@ -124,6 +124,13 @@ impl Daemon { } } pub(super) fn begin(&self, run: &str, config: &Value) -> Result>, BridgeFailure> { + let mut registry = registry().lock().map_err(|_| "本机Agent状态不可用")?; + if config["productProduction"] == true + && let Some(pause) = registry.production_pause.take() + && ["scope", "project", "documentId", "writeEpoch"].iter().all(|key| pause[*key] == config[*key]) + { + return Err(BridgeFailure::new("cancelled", false, false, "本轮制作已停止,未派发模型")); + } let (sender, receiver) = mpsc::channel(); let sent = { let mut state = self.state.lock().map_err(|_| "本机Agent状态不可用")?; @@ -133,6 +140,7 @@ impl Daemon { state.active = Some((run.to_owned(), sender)); self.send(&json!({"type":"run","runId":run,"config":config})) }; + drop(registry); if let Err(error) = sent { self.fail(); return Err(BridgeFailure::interrupted(error, false)); } Ok(receiver) } @@ -321,10 +329,12 @@ pub(super) fn status() -> Value { pub(super) fn pause_production(doc: u64, project_identity: &str, write_epoch: Option) { 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),"writeEpoch":write_epoch})); + if write_epoch.is_none() { return; } + if let Ok(mut registry) = registry().lock() { + let pause = json!({"type":"production_pause","documentId":doc,"project":project, + "scope":super::hash(account_identity),"writeEpoch":write_epoch}); + if let Some(service) = ®istry.service { let _ = service.send(&pause); } + registry.production_pause = Some(pause); } } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index e08e4fd7..6b9aab87 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -1352,6 +1352,7 @@ impl Backend { v["localId"] = json!(self.locations.get(&id)); let project = self.locations.get(&id).ok_or("项目身份尚未绑定")?; v["contextUsage"] = context_usage::read(self, &dir, project); + v["timeBudgetMinutes"] = json!(self.production_budget_minutes(&dir, project)); let checkpoint = dir.join("production-run.json"); if checkpoint.is_file() { v["productionRun"] = read_json(&checkpoint)?; @@ -1361,6 +1362,12 @@ impl Backend { } Ok(v) } + fn production_budget_minutes(&self, dir: &Path, project: &str) -> u64 { + let settings = dir.join("agent").join(self.scope()).join(project).join("production-settings.json"); + read_json(&settings).ok().and_then(|value| value["timeBudgetMinutes"].as_u64()) + .filter(|minutes| *minutes > 0).unwrap_or(120) + } + fn ensure_current_doc(&self, id: u64) -> R<()> { if self.superseded_docs.lock().map_err(|_| "项目版本状态暂不可用,本机文件已保留")?.contains(&id) { Err("已读取云端新版,旧画布不能继续保存;请打开新版".into()) @@ -1626,7 +1633,7 @@ impl Backend { Ok(self.connection_data(&settings, Some(&available))) } "draft" => self.draft(input["doc"].as_u64().ok_or("项目编号无效")?), - "product-run-checkpoint" | "product-exit-checkpoint" => { + "product-run-checkpoint" | "product-exit-checkpoint" | "product-end-checkpoint" => { let doc = input["doc"].as_u64().ok_or("项目编号无效")?; let checkpoint = &input["checkpoint"]; if checkpoint["active"] == true { @@ -1897,7 +1904,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { for request in rx { if backend.exiting() && !matches!(&request, Request::Save(..) | Request::DeliverProductionBundle(..)) && !matches!(&request, Request::Action(method, _) if matches!(method.as_str(), - "product-run-checkpoint" | "product-exit-checkpoint" | "slot-adopted")) + "product-run-checkpoint" | "product-exit-checkpoint" | "product-end-checkpoint" | "slot-adopted")) { continue; } @@ -2244,8 +2251,8 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { task_backend.agent(&input, recover, &task_events, &task_ctx) } }; - let _ = task_events.send(Event::Json(method, result)); busy.store(false, Ordering::Release); + let _ = task_events.send(Event::Json(method, result)); task_ctx.request_repaint_of(egui::ViewportId::ROOT); }); } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index aabc0620..ae74d1d8 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -3558,6 +3558,21 @@ impl Backend { } } +pub(super) fn export_saved_production_output( + dir: &Path, doc: u64, scope: &str, workspace: &Value, output: &Value, reason: &Value, +) -> R { + let component = output["outputId"].as_str().filter(|id| SUPPORTED_PRODUCTION_OUTPUTS.contains(id)) + .ok_or("制作输出缺失")?; + let variant = uuid(&output["variantId"], "制作款式")?; + let state = load(dir)?; + let key = mapping_key(&variant, component, None); + let native = super::load_draft(dir, &dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"))) + .map_err(|_| "该输出没有已保存的可编辑画布")?; + let input = json!({"workspaceId":workspace,"outputId":component,"variantId":variant, + "complete":true,"deliveryReason":reason}); + export_product_stage_snapshot(dir, doc, &state, &input, scope, Some(&native)) +} + fn export_product_stage(dir: &Path, doc: u64, state: &Value, input: &Value, scope: &str) -> R { export_product_stage_snapshot(dir, doc, state, input, scope, None) } @@ -3797,6 +3812,37 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va return blocked(result); } let journal = production_audit(dir, state, component, &variant_id, scope)?; + if input["deliveryReason"].is_string() { + let mut issues = Vec::new(); + for review in journal["screenReviews"].as_array().into_iter().flatten() { + let Some(page) = review[0].as_u64() else { continue; }; + for issue in review[1]["issues"].as_array().into_iter().flatten() { + if let Some(reason) = issue["issue"].as_str().or_else(|| issue["reason"].as_str()) { + issues.push(json!({"page":page+1,"reason":reason})); + } + } + } + for slot in &missing { + issues.push(json!({"field":slot,"reason":"图位尚未采用图片"})); + } + for field in meta["outputs"].as_array().into_iter().flatten() + .filter(|page| aspects.is_null() || planned_pages.iter().any(|plan| plan["id"] == page["documentId"])) + .flat_map(|page| page["mapping"]["fields"].as_array().into_iter().flatten()) + .filter(|field| field["kind"] == "text") + { + let text = field["nativeLayerId"].as_u64().and_then(|id| native.layer(photocraft_doc::LayerId(id))); + if !text.is_some_and(|layer| matches!(&layer.content, photocraft_doc::LayerContent::Text(text) + if !text.text.trim().is_empty() && field["originalText"].as_str() != Some(text.text.as_str()))) + { + issues.push(json!({"field":field["fieldId"],"reason":"文案格尚未填写"})); + } + } + for issue in &mut issues { + issue["outputId"] = json!(component); + issue["variantId"] = json!(variant_id); + } + result["issues"] = json!(issues); + } let unverified_copy = unverified_export_copy(native, &meta, &journal); if !unverified_copy.is_empty() { result["unverifiedCopy"] = json!(unverified_copy); @@ -6367,8 +6413,17 @@ mod tests { let mut agent_input = input.clone(); agent_input["writeEpoch"] = json!(1); + agent_input["deliveryReason"] = json!("用户手动停止并交付"); + let audit = fixture.dir.join("agent").join("test-account").join(fixture.dir.file_name().unwrap()) + .join("conversation-v1").join(format!("production-detail-{variant}.json")); + fs::create_dir_all(audit.parent().unwrap()).unwrap(); + write_json(&audit, &json!({"binding":json!([state["template"]["contentHash"], variant]).to_string(), + "screenReviews":[[0,{"issues":[{"reason":"标题仍需对齐"}]}]]})).unwrap(); let partial = export_product_stage_snapshot(&fixture.dir, 1, &state, &agent_input, "test-account", Some(&doc)).unwrap(); assert_eq!(partial["missingImages"], json!(["S01-I01"])); + let issues = partial["issues"].as_array().unwrap(); + assert!(issues.iter().any(|row| row["page"] == 1 && row["reason"] == "标题仍需对齐")); + assert!(issues.iter().any(|row| row["field"] == "S01-I01" && row["reason"] == "图位尚未采用图片")); assert_eq!(partial["productionDelivery"]["outputState"], "exported"); assert!(artifact_matches(&partial["files"][0], true)); @@ -6433,6 +6488,13 @@ mod tests { let written = read_json(&receipt_path(&fixture.dir,variant,"detail")).unwrap(); assert_eq!(written["warnings"], ready["warnings"]); assert_eq!(written["blankCopyReasons"][blank_id.to_string()], json!({"field":"S01-T02","reason":"缺少规格时留空"})); + write_json(&fixture.dir.join(FILE), &state).unwrap(); + let stopped = export_saved_production_output(&fixture.dir, 1, "test-account", &state["id"], &input, + &json!("用户手动停止并交付")).unwrap(); + assert!(stopped["generationId"].is_string()); + assert_eq!(stopped["issues"], json!([{"outputId":"detail","variantId":variant, + "field":"S01-T02","reason":"文案格尚未填写"}])); + let mut strict = state.clone(); strict["template"]["productionProfiles"]["detail"] = json!({"schemaVersion":1,"keepTextLayerIds":[]}); let flagged = export_product_stage(&fixture.dir, 1, &strict, &input, "test-account").unwrap(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs index 5b0a7f68..60de1cb1 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs @@ -276,7 +276,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu admitted()?; let dir = project_file::delivery_directory(project, &input["deliveryDir"])?.ok_or("未选择成品目录")?; let delivery_id = input["deliveryId"].as_str().filter(|id| Uuid::parse_str(id).is_ok()).ok_or("本轮交付编号无效")?; - let outputs = input["published"].as_array().filter(|rows| !rows.is_empty()).ok_or("本轮没有已验证成品")?; + let creation = creation::load(project)?; let name = delivery_name(&creation["brief"]); transfer::no_credentials(&json!(name))?; @@ -289,8 +289,8 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu read_json(&target.join("交付清单.json")) .ok() .filter(|saved| saved["deliveryId"] == delivery_id) - .map(|saved| json!({"state":"bundle_saved","path":target,"allOutputsCompleted":saved["allOutputsCompleted"],"counts":saved["counts"], - "missingOutputs":saved["missingOutputs"],"missing":saved["missing"],"knownIssues":saved["knownIssues"],"unverifiedCopy":saved["unverifiedCopy"]})) + .map(|saved| json!({"state":"bundle_saved","path":target,"allOutputsCompleted":saved["allOutputsCompleted"],"completedOutputs":saved["completedOutputs"],"counts":saved["counts"], + "deliveryReason":saved["deliveryReason"],"missingOutputs":saved["missingOutputs"],"missing":saved["missing"],"knownIssues":saved["knownIssues"],"unverifiedCopy":saved["unverifiedCopy"]})) }; // Recover a committed directory if the client lost the completion event. for number in 1.. { @@ -302,6 +302,34 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu return Ok(receipt); } } + let mut input = input.clone(); + if input["deliveryReason"].is_string() { + let mut outputs = input["published"].as_array().cloned().unwrap_or_default(); + let mut issues = input["knownIssues"].as_array().cloned().unwrap_or_default(); + for output in input["remainingOutputs"].as_array().into_iter().flatten() { + admitted()?; + let attempt = super::canvas_workspace::export_saved_production_output( + project, input["doc"].as_u64().ok_or("项目编号无效")?, policy.scope, + &input["workspaceId"], output, &input["deliveryReason"], + ); + let reason = match attempt { + Ok(receipt) if receipt["generationId"].is_string() => { + outputs.push(json!({"outputId":output["outputId"],"variantId":output["variantId"], + "generationId":receipt["generationId"]})); + issues.extend(receipt["issues"].as_array().into_iter().flatten().cloned()); + continue; + } + Ok(_) => "该输出未通过成品导出核验".into(), + Err(error) => error, + }; + issues.push(json!({"outputId":output["outputId"],"variantId":output["variantId"],"reason":reason})); + } + input["published"] = json!(outputs); + input["knownIssues"] = json!(issues); + } + let input = &input; + let outputs = input["published"].as_array() + .filter(|rows| !rows.is_empty() || input["deliveryReason"].is_string()).ok_or("本轮没有已验证成品")?; let stage = tempfile::Builder::new().prefix(".xiaoyi-deliver-tmp-").tempdir_in(&dir).map_err(disk)?; let root = stage.path(); let package_root = root.join("工程文件"); @@ -322,6 +350,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu let mut variant_folders = BTreeMap::new(); let mut seen = HashSet::new(); let mut unverified_copy = Vec::new(); + let mut known_issues = input["knownIssues"].as_array().cloned().unwrap_or_default(); let mut output_evidence = Vec::new(); for output in outputs { admitted()?; @@ -343,6 +372,14 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu unverified_copy.push(json!({"variantId":variant,"outputId":component, "generationId":evidence["generationId"],"fields":fields})); } + if input["deliveryReason"].is_string() { + for (key, reason) in [("missingImages", "图位尚未采用图片"), ("missingVisibleText", "文案格尚未填写")] { + for field in evidence[key].as_array().into_iter().flatten() { + let issue = json!({"outputId":component,"variantId":variant,"field":field,"reason":reason}); + if !known_issues.contains(&issue) { known_issues.push(issue); } + } + } + } output_evidence.push(evidence); } compact_resources(root, &snapshot, &mut package, &mut files)?; @@ -355,7 +392,9 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu let total = input["total"].as_u64().ok_or("本轮计划输出数无效")?; let missing_outputs = total.checked_sub(outputs.len() as u64).ok_or("本轮已导出数量超过计划")?; - let all_outputs_completed = missing_outputs == 0; + let all_outputs_completed = missing_outputs == 0 + && (!input["deliveryReason"].is_string() || known_issues.is_empty()); + let known_issues = if input["deliveryReason"].is_string() { json!(known_issues) } else { input["knownIssues"].clone() }; let mut missing = Vec::new(); if missing_outputs > 0 && let Ok(checkpoint) = read_json(&project.join("production-run.json")) @@ -378,7 +417,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu } let mut manifest = json!({"version":1,"deliveryId":delivery_id,"allOutputsCompleted":all_outputs_completed, "completedOutputs":outputs.len(),"totalOutputs":total,"missingOutputs":missing_outputs,"missing":missing, - "counts":counts,"files":files,"knownIssues":input["knownIssues"],"unverifiedCopy":unverified_copy, + "counts":counts,"files":files,"deliveryReason":input["deliveryReason"],"knownIssues":known_issues,"unverifiedCopy":unverified_copy, "outputEvidence":output_evidence}); if let Some(version) = input["knowledgeVersion"].as_str() { manifest["knowledgeVersion"] = json!(version); @@ -399,9 +438,9 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu match fs::rename(root, &target) { Ok(()) => { let flush = RealFs.sync_dir(&dir).err().map(|error| disk(error)); - return Ok(json!({"state":"bundle_saved","path":target,"allOutputsCompleted":all_outputs_completed, + return Ok(json!({"state":"bundle_saved","path":target,"allOutputsCompleted":all_outputs_completed,"completedOutputs":outputs.len(), "counts":counts,"missingOutputs":missing_outputs,"missing":missing, - "knownIssues":input["knownIssues"],"unverifiedCopy":unverified_copy,"durabilityWarning":flush})); + "deliveryReason":input["deliveryReason"],"knownIssues":known_issues,"unverifiedCopy":unverified_copy,"durabilityWarning":flush})); } Err(_) if target.exists() => continue, Err(error) => return Err(disk(error)), @@ -435,7 +474,11 @@ impl Backend { let scope = self.scope(); let policy = transfer::Policy { chat: false, scope: &scope, project }; pi_runtime::record_export_event(self, doc, input, "export", "deliver_bundle", "running", Value::Null); - let result = deliver_production_bundle(&dir, &policy, input, admitted); + let mut input = input.clone(); + if input["deliveryReason"].is_string() && input["deliveryDir"].is_null() { + input["deliveryDir"] = json!(self.dir().join("deliveries")); + } + let result = deliver_production_bundle(&dir, &policy, &input, admitted); let (status, progress) = match &result { Ok(receipt) => { let status = if receipt["durabilityWarning"].is_string() { "unconfirmed" } else { "completed" }; @@ -443,7 +486,7 @@ impl Backend { } Err(_) => ("failed", Value::Null), }; - pi_runtime::record_export_event(self, doc, input, "export", "deliver_bundle", status, progress); + pi_runtime::record_export_event(self, doc, &input, "export", "deliver_bundle", status, progress); result } } @@ -635,6 +678,20 @@ mod tests { assert_eq!(read_json(&manifest).unwrap()["knowledgeVersion"], version); } + #[test] + fn stop_delivery_lists_known_issues_and_preserves_a_partial_bundle() { + let (_root, project, local, mut input) = fixture(); + input["deliveryReason"] = json!("用户手动停止并交付"); + input["knownIssues"] = json!([{"outputId":"detail","page":2,"reason":"尺寸线待校准"}]); + let policy = transfer::Policy { chat: false, scope: "owner", project: &local }; + let delivered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap(); + let manifest = read_json(&PathBuf::from(delivered["path"].as_str().unwrap()).join("交付清单.json")).unwrap(); + assert_eq!(manifest["deliveryReason"], input["deliveryReason"]); + assert_eq!(manifest["knownIssues"], input["knownIssues"]); + assert_eq!(manifest["completedOutputs"], 3); + assert_eq!(manifest["allOutputsCompleted"], false); + } + #[test] fn locally_published_outputs_form_a_reopenable_verified_bundle_and_keep_older_deliveries() { let (root, project, local, mut input) = fixture(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs index 587e156a..1aa7e2d2 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -652,6 +652,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: else { Some(scope["outputId"].as_str().unwrap_or("detail")) }, "variantId":input["context"]["requestScope"]["variantId"], "goalUserEntry":input["context"]["requestScope"]["goalUserEntry"] == true, + "resetProductionGoal":input["context"]["requestScope"]["resetProductionGoal"] == true, "productProduction":input["context"]["requestScope"]["productProduction"] == true, "pendingOutputs":scope["pendingOutputs"],"productionDrafts":scope["productionDrafts"], "requestedOutputs":scope["requestedOutputs"],"workspaceId":scope["project"]["workspaceId"], @@ -766,6 +767,9 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: // Only the trusted native owner establishes product evidence scope. fields.insert("accountScope".into(), json!(b.scope())); fields.insert("project".into(), json!(project)); + if product_prompt { + fields.insert("timeBudgetMinutes".into(), json!(b.production_budget_minutes(&dir, &project))); + } // The owner forwards the target captured before starting the // child, never a subject supplied by the model or a later click. if input["context"]["requestScope"].is_object() { @@ -793,8 +797,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: let id = value["id"].clone(); let task_events = events.clone(); let task_ctx = ctx.clone(); - let dispatch = v["action"] == "dispatch"; - let worker = std::thread::spawn(move || { + std::thread::spawn(move || { let result = worker.production_image_request(doc, &v, &task_events, &task_ctx, snapshot.as_ref()); let reply = match result { Ok(value) => json!({"value":value}), @@ -802,9 +805,8 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: }; let _ = transport.reply(&run, &id, &reply); }); - // Dispatch archives its own receipt under the original output. - // Waiting for the worker here would delay the production pause. - if !dispatch { workflow_children.workers.push(worker); } + // Candidate operations own their local receipts. The original + // output keeps them even if the Pi turn releases its lease. continue; } if matches!(action, "pi-detail-images" | "pi-detail-archive") { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index c76ef3b7..183540ac 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -1082,6 +1082,8 @@ pub struct Workspace { project_tombstones: Vec, project_list_error: String, pi_run: Option, + production_stop: Value, + production_budget_minutes: u64, pi_ui: pi_ui::State, agent_native: agent_native::State, visual_preview: Option, @@ -1279,7 +1281,8 @@ impl Workspace { return Err("请等待当前操作完成".into()); } let batch_image = delegated && pi_slot_operation && input["detailBatch"] == true; - let scoped_export = method == "slot-product-export" && self.production_can_use_scoped_pending(); + let scoped_export = method == "slot-product-export" && (self.production_can_use_scoped_pending() + || self.production_stop["state"] == "delivering"); if !batch_image && !scoped_export && !slot_action_allowed(&self.template_workflow, self.unknown, method) { return Err(if self.unknown { "原请求待核查,此操作尚未获准;不会重发" @@ -1624,6 +1627,8 @@ impl Workspace { project_tombstones: vec![], project_list_error: String::new(), pi_run: None, + production_stop: json!({"mode":null,"state":"idle","reason":null,"error":null}), + production_budget_minutes: 120, pi_ui: pi_ui::State::default(), agent_native: agent_native::State::default(), visual_preview: None, @@ -1850,6 +1855,8 @@ impl Workspace { state["piReview"] = json!(self.pi_review); state["piUi"] = self.pi_ui_state(); state["piUsage"] = self.pi_usage.clone(); + state["productionStop"] = self.production_stop.clone(); + state["productionBudget"] = self.production_budget_state(); state["contextUsage"] = self.pi_context_usage.clone(); state["creation"] = self.creation.clone(); state["templateWorkflow"] = self.template_workflow.clone(); @@ -2189,7 +2196,8 @@ impl Workspace { self.send("open", pending["target"].clone()); } fn turn_idle(&self) -> bool { - self.busy.is_none() && self.pi_run.is_none() && self.queue.is_empty() && self.pending_image.is_none() + !matches!(self.production_stop["state"].as_str(), Some("stopping" | "delivering")) + && self.busy.is_none() && self.pi_run.is_none() && self.queue.is_empty() && self.pending_image.is_none() && !self.canvas_workspace.adoption_preparing() } @@ -2401,7 +2409,15 @@ impl Workspace { "product":self.creation["brief"],"facts":self.creation["facts"],"sellingPoints":self.creation["sellingPoints"],"plan":self.creation["plan"]}) } pub fn submit(&mut self, app: &PhotocraftApp, text: String) { - if matches!(text.trim().trim_end_matches('。'), + let command = text.trim().trim_end_matches('。'); + if self.production_stop["state"] == "ended" && matches!(command, "一键生成" | "一键制作整套详情页") { + if self.turn_idle() && self.model_ready && self.image_ready && !self.creation_dirty + && !self.resume_saved_production(app) + && let Err(error) = self.slot_action(app, "slot-skeleton", json!({"generateProduct":true})) + { + self.error = error; + } + } else if matches!(command, "继续制作整套" | "继续整套制作" | "一键制作整套详情页" | "继续制作整套详情页") { self.resume_product_production(app); @@ -2417,7 +2433,8 @@ impl Workspace { } fn can_resume_product(&self) -> bool { - (self.has_production_stages() || self.has_paused_production()) + self.production_stop["state"] != "ended" + && (self.has_production_stages() || self.has_paused_production()) && (self.product_production.is_none() || self.has_paused_production()) && self.turn_idle() && (!self.unknown || self.scoped_production_pending()) && self.model_ready && self.image_ready && !self.creation_dirty @@ -2428,6 +2445,10 @@ impl Workspace { } fn resume_product_production_with(&mut self, app: &PhotocraftApp, text: Option) { + if self.production_stop["state"] == "ended" { + self.error = "上一轮目标已结束,请从产品资料开始新一轮制作".into(); + return; + } if !self.has_production_stages() && !self.has_paused_production() { self.error = "当前工程没有待继续的分期制作任务,可从产品资料启动制作".into(); return; @@ -2496,6 +2517,9 @@ impl Workspace { "selectedLayerIds":references.iter().filter_map(|item|item["nativeLayerId"].as_u64()).collect::>() }), }; let mut scope = self.request_scope(active.doc.id.0, subject, &references); + if !production && self.production_stop["state"] == "ended" { + scope["resetProductionGoal"] = json!(true); + } let mut text = text; if production && let Some(run) = self.product_production.as_mut() { self.write_epoch += 1; @@ -2513,6 +2537,7 @@ impl Workspace { let output = output.unwrap_or_default(); scope["outputId"] = output["outputId"].clone(); scope["variantId"] = output["variantId"].clone(); + if run.take_goal_reset() { scope["resetProductionGoal"] = json!(true); } if let Some(goal_user_entry) = run.take_goal_user_entry() { text = goal_user_entry; scope["goalUserEntry"] = json!(true); @@ -2764,6 +2789,12 @@ impl Workspace { self.ready_image = v.get("imageTask").filter(|task| image_ready_for_canvas(task)).cloned(); self.project_context = v["project"].clone(); self.product_checkpoint = v["productionRun"].clone(); + self.production_budget_minutes = v["timeBudgetMinutes"].as_u64().filter(|n| *n > 0).unwrap_or(120); + self.production_stop = match self.product_checkpoint["phase"].as_str() { + Some("ended") => json!({"mode":"end","state":"ended","reason":"用户手动停止目标","error":null}), + Some("paused") => json!({"mode":"pause","state":"paused","reason":self.product_checkpoint["reason"],"error":null}), + _ => json!({"mode":null,"state":"idle","reason":null,"error":null}), + }; for key in ["cloudLink", "syncedRevision", "status"] { if !v[key].is_null() { self.project_context[key] = v[key].clone(); @@ -2922,6 +2953,13 @@ impl Workspace { } return; } + if method == "product-end-checkpoint" { + if self.busy.as_deref() == Some("product-end-checkpoint") { + self.busy = None; + self.production_end_received(result); + } + return; + } if method == "metadata-save" { if let (Some(doc), Err(error)) = (self.metadata_saving.take(), result) { if self.loaded_draft == Some(doc) { self.draft_changed = true; } @@ -2929,6 +2967,18 @@ 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; + } + 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| @@ -3046,6 +3096,12 @@ impl Workspace { } if method == "save" { self.saving = None; + if self.production_stop["state"] == "stopping" && self.production_stop["mode"] == "end" + && let Err(error) = &result + { + self.production_stop["state"] = json!("failed"); + self.production_stop["error"] = json!(error); + } if let (Some(exit), Err(error)) = (&mut self.production_exit, &result) { exit.save_error = Some(error.clone()); } @@ -3787,6 +3843,7 @@ impl Workspace { self.with_product_target(app, |w, app| { let now = Instant::now(); w.production_tick(app); + if let Some(delay) = w.production_budget_delay() { ctx.request_repaint_after(delay); } if let Some(delay) = w.production_retry_delay(now) { ctx.request_repaint_after(delay); } @@ -5127,6 +5184,20 @@ fn action_impl(app: &mut PhotocraftApp, ctx: Option<&egui::Context>, method: &st Err("缺少要求".into()) } } + "production-stop" => { + let reason = match input["mode"].as_str() { + Some("pause") => Ok(("pause", "用户手动暂停")), + Some("end") => Ok(("end", "用户手动停止目标")), + Some("deliver") => Ok(("deliver", "用户手动停止并交付")), + _ => Err("停止方式无效".into()), + }; + reason.and_then(|(mode, reason)| { + if w.product_production.is_none() && w.has_paused_production() { + w.restore_production_checkpoint(app); + } + w.request_production_stop(mode, reason) + }).map(|()| w.production_stop.clone()) + } "handover" => { w.stop_production(); Ok(json!({"queued":w.queue.len()})) @@ -5901,13 +5972,28 @@ mod tests { *call.borrow_mut() = Some((doc, project.into())); })); let owner = w.local_identity("owned-product"); + let epoch = w.product_production.as_ref().and_then(product_production::Run::session_epoch).unwrap(); + w.pi_context_usage = json!({"phase":"running"}); w.stop_production(); assert_eq!(PAUSED.with(|call| call.take()), Some((doc, owner))); assert!(matches!(requests.try_recv().unwrap(), Request::Action(method, input) - if method == "product-run-checkpoint" && input["checkpoint"]["active"] == false)); + if method == "product-run-checkpoint" && input["checkpoint"]["active"] == true && input["checkpoint"]["phase"] == "paused")); assert!(requests.try_recv().is_err()); assert_eq!(app.session.active().unwrap().revision, revision); assert!(w.unknown); + let settled = json!({ + "engine":"pi","doc":doc,"accountId":w.account["id"],"origin":w.origin,"writeEpoch":epoch, + "projectLocalId":"owned-product","contextUsage":{"phase":"ready"},"unknown":false + }); + w.receive_json_event(&mut app, &egui::Context::default(), "agent".into(), Ok(settled)); + w.production_tick(&app); + assert_eq!(w.production_stop["state"], "paused"); + assert_eq!(w.production_stop["mode"], "pause"); + assert_eq!(w.pi_context_usage["phase"], "ready"); + w.submit(&app, "继续制作".into()); + assert!(requests.try_iter().any(|request| matches!(request, Request::Action(method, input) + if method == "agent" && input["context"]["requestScope"]["goalUserEntry"] == true))); + } #[test] fn opening_another_project_reuses_an_unchanged_draft() { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs index db4e75d9..ca92670b 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs @@ -309,6 +309,11 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co if batch { w.agent_native.remember_revision(st); } w.workflow.clear(); w.workflow.bind_identity(input["accountScope"].as_str().unwrap_or(""), input["project"].as_str().unwrap_or(""), st.doc.id.0); + if own_submit && w.pi_request_scope["productProduction"] == true + && let Some(minutes) = input["timeBudgetMinutes"].as_u64().filter(|n| *n > 0) + { + w.production_budget_minutes = minutes; + } w.pi_native = own_submit; w.pi_touched = Instant::now(); w.pi_binding = json!({"accountId":w.account["id"],"origin":w.origin}); 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 a7d2183a..6b481ceb 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 @@ -170,9 +170,10 @@ impl Workspace { { return false; } - let text = "继续整套制作"; + let fresh = self.production_stop["state"] == "ended"; + let text = if fresh { "一键生成" } else { "继续整套制作" }; self.messages.push(json!({"role":"user","text":text})); - self.note("已接续制作,正在核对当前画布和原请求。"); + self.note(if fresh { "正在从当前画布开始新一轮制作。" } else { "已接续制作,正在核对当前画布和原请求。" }); self.agent_effects_paused = false; let mut run = Run::new(doc, project, workspace, stages, Some(text.into()), Phase::AwaitingSave); run.delivery_dir = self.creation_delivery_dir.clone(); @@ -751,6 +752,7 @@ pub(super) struct Run { total: usize, completed: usize, goal_user_entry: Option, + reset_goal: bool, phase: Phase, bound: Option, opening: Option, @@ -764,6 +766,8 @@ pub(super) struct Run { deferred_image_in_flight: Vec, drafts: Vec, started_at: u64, + paused_at: Option, + paused_seconds: u64, delivery_dir: Option, delivery_id: Option, published: Vec, @@ -817,10 +821,10 @@ impl Run { fn new(doc: u64, project: String, workspace: Value, stages: Vec, goal_user_entry: Option, phase: Phase) -> Self { Self { doc, project, workspace, total: stages.len(), requested_outputs: stages.iter().cloned().collect(), stages, completed: 0, - goal_user_entry, bound: None, opening: None, previous_save: Value::Null, session_epoch: None, + 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(), restarted: false, + started_at: production_time(), paused_at: None, 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 } } @@ -848,7 +852,8 @@ fn production_time() -> u64 { impl Run { pub(super) fn elapsed(&self) -> Duration { - Duration::from_secs(production_time().saturating_sub(self.started_at)) + Duration::from_secs(self.paused_at.unwrap_or_else(production_time) + .saturating_sub(self.started_at).saturating_sub(self.paused_seconds)) } pub(super) fn working_output(&self) -> Option { @@ -938,6 +943,10 @@ impl Run { } } + pub(super) fn take_goal_reset(&mut self) -> bool { + std::mem::take(&mut self.reset_goal) + } + pub(super) fn take_goal_user_entry(&mut self) -> Option { self.goal_user_entry.take() } @@ -1003,6 +1012,8 @@ impl Run { impl Workspace { fn begin_prepared_production(&mut self, mut run: Run, blocked: &Value) { + run.reset_goal = self.production_stop["state"] == "ended"; + self.production_stop = json!({"mode":null,"state":"idle","reason":null,"error":null}); for draft in blocked.as_array().into_iter().flatten() { let (Some(stage), Some(reason)) = (Stage::read(draft), draft["reason"].as_str()) else { continue; }; self.note(format!("{}暂无法制作。{reason}。请核对所选模板的原稿与字段映射。", stage.label())); @@ -1019,7 +1030,9 @@ impl Workspace { let mut checkpoint = json!({ "deliveryDir":run.delivery_dir,"deliveryId":run.delivery_id,"published":run.published, "productionDelivery":run.delivery_receipt,"knownIssues":run.finish_receipt["knownIssues"], + "deliveryReason":run.finish_receipt["deliveryReason"], "active":active,"project":project,"workspaceId":run.workspace,"startedAt":run.started_at, + "pausedAt":run.paused_at,"pausedSeconds":run.paused_seconds,"resetGoal":run.reset_goal, "boundOutput":run.working_output(),"outputSelected":run.bound.is_some(), "requestedOutputs":run.requested_outputs(), "total":run.total,"drafts":run.drafts, @@ -1063,7 +1076,11 @@ impl Workspace { let daemon = self.prepare_daemon_exit.as_ref().map(|prepare| prepare()); let composers = self.save_exit_composers(ctx); let delivering = self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle); - let run = if delivering { None } else { self.product_production.take() }; + let ending = self.busy.as_deref() == Some("product-end-checkpoint"); + let run = if delivering { None } else { self.product_production.take().map(|mut run| { + run.paused_at.get_or_insert_with(production_time); + run + }) }; if !delivering { self.with_product_target(app, |w, _| { w.pi_ui_cancel("客户端正在退出"); @@ -1075,7 +1092,13 @@ impl Workspace { self.agent_effects_paused = true; self.product_checkpoint = Value::Null; - let input = run.map(|run| Self::production_checkpoint_request(&run, true)).or_else(|| { + let input = run.map(|run| { + if ending { + json!({"doc":run.doc,"checkpoint":{"active":false,"phase":"ended","project":run.project.rsplit('|').next()}}) + } else { + Self::production_checkpoint_request(&run, true) + } + }).or_else(|| { if delivering { return None; } let (doc, _) = draft?; let identity = self.open_projects.get(&doc)?; @@ -1172,18 +1195,125 @@ impl Workspace { } pub(super) fn stop_production(&mut self) { - if let Some(run) = self.product_production.as_ref() { - if let Some(pause) = self.pause_production_agent { - pause(run.doc, &run.project, run.session_epoch); - } - self.write_production_checkpoint(run, false); + if self.product_production.is_some() { + let _ = self.request_production_stop("pause", "用户手动暂停"); + } else { + self.handover(); + } + } + + pub(super) fn request_production_stop(&mut self, mode: &str, reason: &str) -> Result<(), String> { + if self.production_stop["state"] == "stopping" { + if self.production_stop["mode"] == "pause" && mode != "pause" { + self.production_stop["mode"] = json!(mode); + self.production_stop["reason"] = json!(reason); + } + return Ok(()); + } + let mut run = self.product_production.take().ok_or("当前没有制作任务")?; + if run.phase == Phase::DeliveringBundle { + self.product_production = Some(run); + return Err("当前交付正在进行".into()); + } + if let Some(pause) = self.pause_production_agent { + pause(run.doc, &run.project, run.session_epoch); } - self.product_checkpoint = Value::Null; self.handover(); + run.paused_at.get_or_insert_with(production_time); + run.phase = Phase::Paused(json!({"reason":"用户已停止制作"})); + run.opening = None; + run.finish = None; + run.finish_receipt = Value::Null; + self.product_production = Some(run); + self.production_stop = json!({"mode":mode,"state":"stopping","reason":reason,"error":null}); + self.checkpoint_production(); + Ok(()) + } + + pub(super) fn production_budget_state(&self) -> Value { + json!({"startedAt":self.product_production.as_ref().map(|run| run.started_at), + "budgetMinutes":self.production_budget_minutes, + "elapsedMinutes":self.product_production.as_ref().map_or(0.0, |run| run.elapsed().as_secs_f64() / 60.0)}) + } + + pub(super) fn production_budget_delay(&self) -> Option { + let run = self.product_production.as_ref()?; + if matches!(run.phase, Phase::Paused(_) | Phase::DeliveringBundle) || run.paused_at.is_some() { + return None; + } + Some(Duration::from_secs(self.production_budget_minutes.saturating_add(10).saturating_mul(60).saturating_add(1)) + .saturating_sub(run.elapsed())) + } + + fn settle_production_stop(&mut self, app: &PhotocraftApp) { + 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"); + return; + } + if self.production_stop["mode"] == "end" { + let Some(canvas) = app.session.active() else { return; }; + let doc = canvas.doc.id.0; + if self.persisted_revisions.get(&doc) != Some(&canvas.revision) || self.draft_changed { + if !self.enqueue_project_draft(canvas, true) { + self.production_end_received(Err("本机草稿保存服务已断开".into())); + } + return; + } + let Some(run) = self.product_production.as_ref() else { return; }; + let project = run.project.rsplit('|').next(); + if self.tx.send(Request::Action("product-end-checkpoint".into(), + json!({"doc":run.doc,"checkpoint":{"active":false,"phase":"ended","project":project}}))).is_err() { + self.production_end_received(Err("本机制作记录保存服务已断开".into())); + } else { + self.busy = Some("product-end-checkpoint".into()); + } + return; + } + let Some(run) = self.product_production.as_mut() else { return; }; + run.phase = Phase::Agent; + let mut input = run.bound.as_ref().map(Stage::value).unwrap_or_else(|| json!({})); + input["operationId"] = json!(uuid::Uuid::new_v4().to_string()); + input["scope"] = json!("all"); + input["deliveryReason"] = self.production_stop["reason"].clone(); + if let Some(stage) = run.bound.as_ref() + && let Some(canvas) = app.session.active() + && canvas_workspace::document_scope_matches(&canvas.doc, &self.template_workflow, &stage.output, &stage.variant) + { + input["complete"] = json!(true); + input["canvasRevision"] = json!(app.session.active().map(|state| state.revision)); + } + self.production_stop["state"] = json!("delivering"); + if let Err(error) = self.finish_production(app, &input) { + 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})); + } + self.checkpoint_production(); + } + } + + pub(super) fn production_end_received(&mut self, result: Result) { + match result { + Ok(_) => { + self.product_production = None; + self.product_checkpoint = Value::Null; + self.production_stop["state"] = json!("ended"); + } + Err(error) => { + self.production_stop["state"] = json!("failed"); + self.production_stop["error"] = json!(error); + } + } } pub(super) fn pause_for_authorization(&mut self, category: &Value) { - if let Some(run) = self.product_production.as_ref() { + if let Some(run) = self.product_production.as_mut() { + run.paused_at.get_or_insert_with(production_time); let mut input = Self::production_checkpoint_request(run, false); input["checkpoint"]["phase"] = json!("paused"); input["checkpoint"]["reason"] = category.clone(); @@ -1206,6 +1336,10 @@ impl Workspace { } if let Some(run) = self.product_production.as_mut() { run.goal_user_entry = Some(text.clone()); + if let Some(paused_at) = run.paused_at.take() { + run.paused_seconds += production_time().saturating_sub(paused_at); + } + self.production_stop = json!({"mode":null,"state":"idle","reason":null,"error":null}); run.phase = Phase::AwaitingSave; self.messages.push(json!({"role":"user","text":text})); self.checkpoint_production(); @@ -1215,9 +1349,10 @@ impl Workspace { } } - fn restore_production_checkpoint(&mut self, app: &PhotocraftApp) { + pub(super) fn restore_production_checkpoint(&mut self, app: &PhotocraftApp) { if self.product_checkpoint["active"] != true || self.busy.is_some() || self.saving.is_some() - || self.product_checkpoint["deliveryId"].is_null() && (!self.model_ready || !self.image_ready) + || self.product_checkpoint["deliveryId"].is_null() && self.product_checkpoint["phase"] != "paused" + && (!self.model_ready || !self.image_ready) { return; } let Some(canvas) = app.session.active() else { return; }; let doc = canvas.doc.id.0; @@ -1225,7 +1360,8 @@ impl Workspace { let workspace = self.template_workflow["workspaceId"].clone(); if project != self.local_identity(self.product_checkpoint["project"].as_str().unwrap_or("")) || workspace.is_null() || workspace != self.product_checkpoint["workspaceId"] - || self.persisted_revisions.get(&doc) != Some(&canvas.revision) + || self.product_checkpoint["phase"] != "paused" + && self.persisted_revisions.get(&doc) != Some(&canvas.revision) { return; } let remaining: HashSet<_> = self.template_workflow["productionStages"].as_array() .into_iter().flatten().filter_map(Stage::read).collect(); @@ -1244,6 +1380,7 @@ impl Workspace { } else { Phase::AwaitingSave }; let mut run = Run::new(doc, project, workspace, stages, None, phase); run.bound = bound; + run.reset_goal = checkpoint["resetGoal"] == true; run.started_at = checkpoint["startedAt"].as_u64().or_else(|| { // Checkpoints before startedAt recorded a deadline and used 45 minutes by default. let deadline = checkpoint["deadline"].as_u64()?; @@ -1251,9 +1388,15 @@ impl Workspace { .filter(|minutes| *minutes > 0).unwrap_or(45); Some(deadline.saturating_sub(minutes.saturating_mul(60))) }).unwrap_or(run.started_at); + run.paused_at = checkpoint["pausedAt"].as_u64().or_else(|| paused.then(production_time)); + run.paused_seconds = checkpoint["pausedSeconds"].as_u64().unwrap_or(0); + if !paused && let Some(paused_at) = run.paused_at.take() { + run.paused_seconds += production_time().saturating_sub(paused_at); + } run.delivery_dir = delivery_dir(&checkpoint); run.delivery_id = checkpoint["deliveryId"].as_str().map(str::to_owned); run.finish_receipt["knownIssues"] = checkpoint["knownIssues"].clone(); + run.finish_receipt["deliveryReason"] = checkpoint["deliveryReason"].clone(); run.published = checkpoint["published"].as_array().cloned().unwrap_or_default(); if let Some(requested) = checkpoint["requestedOutputs"].as_array() { run.requested_outputs = requested.iter().filter_map(Stage::read).collect(); @@ -1262,7 +1405,10 @@ impl Workspace { run.total = checkpoint["total"].as_u64().unwrap_or(run.total as u64) as usize; run.completed = run.published.len(); run.restore_deferred_images(&checkpoint); - if run.stages.is_empty() && run.delivery_id.is_some() { + if !paused && (run.stages.is_empty() || run.finish_receipt["deliveryReason"].is_string()) && run.delivery_id.is_some() { + if run.finish_receipt["deliveryReason"].is_string() { + self.production_stop = json!({"mode":"deliver","state":"delivering","reason":run.finish_receipt["deliveryReason"],"error":null}); + } self.finish_production_outputs(run); } else { self.product_production = Some(run); @@ -1510,6 +1656,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()); } self.checkpoint_production(); @@ -1601,12 +1748,25 @@ impl Workspace { if self.product_production.is_none() { self.restore_production_checkpoint(app); } - let Some(run) = self.product_production.as_ref() else { return }; - if !run.current(self, app) { + let current = self.product_production.as_ref().is_some_and(|run| run.current(self, app)); + if !current { self.product_production = None; self.product_export = None; + if matches!(self.production_stop["state"].as_str(), Some("stopping" | "delivering")) { + self.production_stop["state"] = json!("failed"); + self.production_stop["error"] = json!("原制作项目或授权已切换"); + } return; } + if self.production_stop["state"] == "stopping" { + self.settle_production_stop(app); + 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 run.awaiting_canvas_save() || matches!(run.phase, Phase::AgentRetryAt(at) if Instant::now() >= at) { let Some(canvas) = app.session.active() else { return; }; @@ -1633,7 +1793,8 @@ impl Workspace { self.dispatch_production_open(app, &stage); return; } - if self.busy.as_deref() == Some("pi-agent") && self.saving.is_none() && !self.product_view_save_pending() + if (self.busy.as_deref() == Some("pi-agent") || self.production_stop["state"] == "delivering" && self.busy.is_none()) + && self.saving.is_none() && !self.product_view_save_pending() && let Some(input) = self.product_export.take() && let Err(error) = self.slot_action(app, "slot-product-export", input) { self.complete_production_export(json!({"error":error,"files":[]})); @@ -1657,7 +1818,9 @@ impl Workspace { if run.finish.as_ref().is_some_and(|finish| finish["operationId"] == id) { return Ok(json!({"operationId":id,"pending":true})); } - if self.pi_write_blocked || self.busy.as_deref() != Some("pi-agent") || run.phase != Phase::Agent + let stopped = self.production_stop["state"] == "delivering" && input["deliveryReason"].is_string() + && input["deliveryReason"] == self.production_stop["reason"]; + if (!stopped && (self.pi_write_blocked || self.busy.as_deref() != Some("pi-agent"))) || run.phase != Phase::Agent || run.opening.is_some() || run.finish_receipt["finalized"] == true || self.production_write_pending() { return Err("当前画布已有操作或已交接,请查看制作状态".into()); @@ -1689,15 +1852,17 @@ impl Workspace { Some(summary) }); let run = self.product_production.as_mut().ok_or("原制作项目已切换")?; - let mut finish = json!({"operationId":id,"all":all,"issues":input["issues"]}); + let mut finish = json!({"operationId":id,"all":all,"issues":input["issues"],"deliveryReason":stopped.then_some(&input["deliveryReason"])}); if let Some(summary) = summary { finish["progressSummary"] = summary; } run.finish = Some(finish); run.phase = Phase::Export; if export { let mut request = input.clone(); request["workspaceId"] = run.workspace.clone(); - request["writeEpoch"] = self.pi_request_scope["writeEpoch"].clone(); - request["documentKey"] = self.pi_request_scope["documentKey"].clone(); + if !stopped { + request["writeEpoch"] = self.pi_request_scope["writeEpoch"].clone(); + request["documentKey"] = self.pi_request_scope["documentKey"].clone(); + } self.product_export = Some(request); self.production_tick(app); } else { @@ -1712,6 +1877,9 @@ impl Workspace { && run.finish.as_ref().is_some_and(|finish| finish["operationId"] == value["operationId"])) { return; } let Some(run) = self.product_production.as_mut() else { return; }; let Some(stage) = run.bound.clone() else { return; }; + if let Some(finish) = run.finish.as_mut().filter(|finish| finish["deliveryReason"].is_string()) { + finish["issues"] = value["issues"].clone(); + } if let Some(generation) = value["generationId"].as_str() && value["files"].as_array().is_some_and(|files| !files.is_empty()) { run.clear_deferred(&stage); @@ -1758,7 +1926,9 @@ impl Workspace { receipt["published"] = json!(run.published); receipt["drafts"] = json!(run.drafts); receipt["completed"] = json!(run.completed == run.total); - let finalize = finish["all"] == true && run.stages.is_empty() && !receipt["error"].is_string(); + let stopped = finish["deliveryReason"].is_string(); + receipt["deliveryReason"] = finish["deliveryReason"].clone(); + let finalize = finish["all"] == true && (stopped || run.stages.is_empty() && !receipt["error"].is_string()); if finish["all"] == true { let mut pending_reviews = Vec::new(); let mut known_issues = Vec::new(); @@ -1777,6 +1947,23 @@ impl Workspace { pending_reviews.push(row); } } + if stopped { + for page in summary["screensWithOpenIssues"].as_array().into_iter().flatten() { + for issue in page["issues"].as_array().into_iter().flatten() { + let reason = issue["issue"].as_str().or_else(|| issue["reason"].as_str()); + if let Some(reason) = reason { + let row = json!({"outputId":output["outputId"],"variantId":output["variantId"], + "page":page["page"],"reason":reason}); + if !known_issues.contains(&row) { known_issues.push(row); } + } + } + } + for field in summary["unfilledImageSlots"].as_array().into_iter().flatten() { + let row = json!({"outputId":output["outputId"],"variantId":output["variantId"], + "field":field["fieldId"],"reason":"图位尚未采用图片"}); + if !known_issues.contains(&row) { known_issues.push(row); } + } + } for issue in output["issues"].as_array().into_iter().flatten() { let mut row = issue.clone(); if row["outputId"].is_null() { row["outputId"] = output["outputId"].clone(); } @@ -1790,7 +1977,7 @@ impl Workspace { receipt["pendingScreenReviews"] = json!(pending_reviews); receipt["knownIssues"] = json!(known_issues); } - receipt["finalized"] = json!(finalize && (run.delivery_dir.is_none() || run.completed == 0)); + receipt["finalized"] = json!(finalize && !stopped && (run.delivery_dir.is_none() || run.completed == 0)); run.phase = Phase::Agent; if self.pi_run.is_some() { self.busy = Some("pi-agent".into()); } run.finish_receipt = receipt; @@ -1804,7 +1991,7 @@ impl Workspace { } fn finish_production_outputs(&mut self, mut run: Run) { - if run.delivery_dir.is_none() || run.completed == 0 { + if !run.finish_receipt["deliveryReason"].is_string() && (run.delivery_dir.is_none() || run.completed == 0) { self.note_production_summary(run); return; } @@ -1827,7 +2014,7 @@ impl Workspace { "workspaceId":run.workspace,"accountId":self.account["id"],"origin":self.origin, "accountEpoch":self.accepted_account_epoch, "writeEpoch":self.write_epoch,"deliveryDir":run.delivery_dir,"deliveryId":id, - "published":run.published,"knownIssues":run.finish_receipt["knownIssues"],"knowledgeVersion":run.finish_receipt["knowledgeVersion"],"total":run.total,"execution":{"runId":id,"operationId":id,"uiHeartbeat":production_time() * 1000}}); + "published":run.published,"remainingOutputs":run.pending_outputs(),"knownIssues":run.finish_receipt["knownIssues"],"deliveryReason":run.finish_receipt["deliveryReason"],"knowledgeVersion":run.finish_receipt["knowledgeVersion"],"total":run.total,"execution":{"runId":id,"operationId":id,"uiHeartbeat":production_time() * 1000}}); self.write_production_checkpoint(&run, true); if self.tx.send(Request::DeliverProductionBundle(input, cancellation)).is_err() { run.delivery_receipt = json!({"state":"failed","error":"本机交付服务已断开"}); @@ -1856,6 +2043,21 @@ impl Workspace { } fn complete_production_bundle(&mut self, mut run: Run) { + if self.production_stop["state"] == "delivering" { + let delivered = run.delivery_receipt["path"].is_string(); + self.production_stop["state"] = json!(if delivered {"delivered"} else {"failed"}); + self.production_stop["error"] = run.delivery_receipt["error"].clone(); + if let Some(completed) = run.delivery_receipt["completedOutputs"].as_u64() { + run.completed = completed as usize; + } + if !delivered { + run.phase = Phase::Paused(json!({"reason":run.delivery_receipt["error"]})); + run.finish = None; + self.product_production = Some(run); + self.checkpoint_production(); + return; + } + } if run.finish.take().is_some() && self.pi_run.is_some() && self.production_exit.is_none() { run.phase = Phase::Agent; run.finish_receipt["productionDelivery"] = run.delivery_receipt.clone(); @@ -1877,7 +2079,9 @@ impl Workspace { } else { self.write_production_checkpoint(&run, false); } - let mut text = if run.completed == run.total { + let mut text = if run.finish_receipt["deliveryReason"].is_string() && run.completed == run.total { + format!("{},已交付 {} 份当前成果。", run.finish_receipt["deliveryReason"].as_str().unwrap_or_default(), run.total) + } else if run.completed == run.total { format!("整套制作完成 · {} 份可编辑画布与 JPG 已保存", run.total) } else { format!("本轮已交付 {}/{} 份,还有 {} 份待完成。已有编辑已保存。", run.completed, run.total, run.total.saturating_sub(run.completed)) @@ -2437,6 +2641,11 @@ mod tests { assert_eq!(saved["checkpoint"]["startedAt"], run.started_at); assert!(saved["checkpoint"].get("deadline").is_none()); assert!(saved["checkpoint"].get("productionBudgetMinutes").is_none()); + let mut paused = run; + paused.started_at = before - 300; + paused.paused_at = Some(before - 120); + paused.paused_seconds = 60; + assert_eq!(paused.elapsed(), Duration::from_secs(120)); } #[test] @@ -2584,7 +2793,67 @@ mod tests { } #[test] - fn long_running_production_keeps_its_agent_and_pending_outputs() { + fn ending_a_paused_goal_saves_the_canvas_and_starts_a_fresh_goal() { + let (tx, requests) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + requests.try_recv().unwrap(); + w.busy = None; + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":40,"height":50})).unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + let canvas = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + let doc = canvas.id.0; + let project = w.local_identity("project"); + let stage = Stage { output:"detail".into(), variant:"wood".into() }; + w.open_projects.insert(doc, project.clone()); + w.template_workflow = json!({"workspaceId":"workspace","revision":0,"productionStages":[stage.value()]}); + w.product_production = Some(Run::new(doc, project.clone(), json!("workspace"), vec![stage.clone()], + None, Phase::Paused(json!({"reason":"用户手动暂停"})))); + w.production_stop = json!({"mode":"pause","state":"paused","reason":"用户手动暂停","error":null}); + w.model_ready = true; + w.image_ready = true; + app.jiansun = Some(w); + let accepted = super::super::action(&mut app, "production-stop", json!({"mode":"end"})).unwrap(); + assert_eq!(accepted["mode"], "end"); + let mut w = app.jiansun.take().unwrap(); + w.production_tick(&app); + let (saved, saved_revision) = requests.try_iter().find_map(|request| match request { + Request::Save(doc, revision, _) => Some((doc, revision)), + _ => None, + }).expect("ending flushes current edits"); + assert_eq!(saved.id, canvas.id); + assert_eq!(saved_revision, revision); + let ctx = egui::Context::default(); + w.receive_event(&mut app, &ctx, super::super::Event::Saved(doc, revision, json!({"localId":"project"}))); + w.production_tick(&app); + assert!(requests.try_iter().any(|request| matches!(request, + Request::Action(method, input) if method == "product-end-checkpoint" + && input["checkpoint"]["phase"] == "ended" && input["checkpoint"]["active"] == false))); + w.receive_event(&mut app, &ctx, super::super::Event::Json("product-end-checkpoint".into(), Ok(Value::Null))); + assert_eq!(w.production_stop["state"], "ended"); + assert!(!w.has_paused_production()); + assert_eq!(app.session.active().unwrap().doc.id, canvas.id); + assert_eq!(app.session.active().unwrap().revision, revision); + w.submit(&app, "继续制作整套".into()); + assert!(requests.try_recv().is_err()); + + w.submit(&app, "一键生成".into()); + assert!(requests.try_iter().any(|request| matches!(request, + Request::Action(method, input) if method == "slot-skeleton" && input["generateProduct"] == true)), "{}", w.error); + w.busy = None; + w.begin_prepared_production(Run::new(doc, project, json!("workspace"), vec![stage], + Some("一键生成".into()), Phase::AwaitingSave), &Value::Null); + w.production_tick(&app); + assert!(requests.try_iter().any(|request| matches!(request, + Request::Action(method, input) if method == "agent" + && input["context"]["requestScope"]["resetProductionGoal"] == true))); + assert_eq!(w.production_stop["state"], "idle"); + } + + #[test] + fn production_budget_stops_the_turn_and_requests_delivery() { let (tx, requests) = mpsc::channel(); let (_, rx) = mpsc::channel(); let mut w = Workspace::new(tx, rx); @@ -2604,7 +2873,7 @@ mod tests { ]), None, Phase::Agent); run.started_at = production_time() - 5 * 60 * 60; w.product_production = Some(run); - w.pause_production_agent = Some(|_, _, _| panic!("elapsed time must not stop the agent")); + w.pause_production_agent = Some(|_, _, _| {}); w.busy = Some("pi-agent".into()); w.pi_request_scope = json!({"productProduction":true}); w.allow_apply = true; @@ -2612,13 +2881,20 @@ mod tests { w.production_tick(&app); - let run = w.product_production.as_ref().unwrap(); - assert!(run.elapsed() >= Duration::from_secs(5 * 60 * 60)); - assert_eq!(run.stages.len(), 2); - assert_eq!(w.busy.as_deref(), Some("pi-agent")); - assert!(w.allow_apply && w.unknown); - assert!(requests.try_recv().is_err()); - assert!(w.messages.is_empty()); + assert_eq!(w.production_stop["state"], "stopping"); + assert_eq!(w.production_stop["mode"], "deliver"); + assert_eq!(w.production_stop["reason"], "到达时间上限自动交付"); + assert_eq!(w.product_production.as_ref().unwrap().stages.len(), 2); + assert!(!w.allow_apply); + w.busy = None; + w.production_tick(&app); + assert_eq!(w.production_stop["state"], "delivering"); + let input = requests.try_iter().find_map(|request| match request { + Request::DeliverProductionBundle(input, _) => Some(input), + _ => None, + }).expect("budget expiry queues a delivery"); + assert_eq!(input["deliveryReason"], "到达时间上限自动交付"); + assert_eq!(input["remainingOutputs"].as_array().unwrap().len(), 2); } #[test]