Merge first saved canvas binding and native cancellation

This commit is contained in:
WuYongJie 2026-11-26 17:36:22 +08:00
commit 28b07ebfee
7 changed files with 163 additions and 52 deletions

View File

@ -58,7 +58,7 @@ references是用户提交时冻结的本轮引用;component为pixelMask或vect
只确认已执行的修改。工具失败要说明。生图和画布操作结果未确认时,只核查原编号。`;
const PRODUCTION_SYSTEM = `你是小壹的制作 Agent。先读本项目适用的企业 Skill,并按它及模板在 PhotoCraft 制作和复核。由你决定要做什么、顺序、并行和返工。
用 plan_production 读取本轮输出和工作画布。尚未绑定时,用 open_production_output 打开本轮所选画布。用户查看的页面和制作画布独立。
用 plan_production 读取本轮输出和工作画布。尚未绑定时,单独调用 open_production_output 打开所选画布,收到已保存的绑定回执后再查询 native_catalog 或调用画布工具。打开失败时按回执处理,可重新打开或选择另一待制作输出。用户查看的页面和制作画布独立。
企业 Skill 中的命令行编修可在当前画布用等价的 PhotoCraft 原生命令完成。用已有产品资料写买家看得懂的文案,检查实际画面的图文对应、品牌元素和旧商品信息。
复核后提交当前修订。PhotoCraft 按实际导出回执交接下一项。生图或画布操作结果未确认时按原编号核查。用简短中文说明实际进展。`;

View File

@ -35,7 +35,7 @@ const preparationArgs={
const dispatchArgs={requestId:text,expectedRevision:rev,expectedHash:text};
export const productionOperationTools = [
['open_production_output','打开本轮待制作的工作画布,返回已保存画布的绑定回执。用 plan_production 获取输出和花色。',obj({outputId:text,variantId:text})],
['open_production_output','打开本轮待制作的工作画布,返回已保存画布的绑定回执。用 plan_production 获取输出和花色。请单独调用,收到绑定回执后再查询原生命令或操作画布。',obj({outputId:text,variantId:text})],
['plan_production','读取当前商品规格与备注、模板、图位和本轮其它待处理输出。按 slotIds 读取指定图位的规则和要求。模板规则从项目 Skill 及其引用读取。调用图位工具时优先使用 pictures 中的 fieldId。',obj({slotIds:optional(ids)})],
['read_production_knowledge','读取已选模板的固定版本规则,按回执的 nextOffset 翻页。',obj({fileId:text,offset:optional(page)})],
['read_copy_fields','读取画布文字格、当前文案和修订号。指定 pageId 或 fieldId 时一并读取该范围的模板样稿与发布要求,供撰写和复核。',obj({

View File

@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { BridgeError } from './bridge-error.mjs';
export function canvasReplyTimedOut(error) {
return error?.category === 'transport_interrupted';
@ -10,29 +11,42 @@ export class StdioCanvas {
durableGenerationIds = true;
constructor(call, documentId) { this.call = call; this.documentId = documentId; }
action(action, input = {}) { return this.call(action, { ...input, run: this.run, documentId: this.documentId }); }
async #observe(action, input = {}) {
async #observe(action, input = {}, signal) {
const {run,documentId}=this;
const deadline=Date.now()+120_000;
for(;;){
signal?.throwIfAborted();
if(this.run!==run||this.documentId!==documentId)throw Error('原回合已结束,未继续查询');
try { return await this.call(action,{...input,run,documentId}); }
catch(error) {
if(!canvasReplyTimedOut(error)||Date.now()>=deadline)throw error;
await delay(500);
await delay(500,undefined,{signal});
}
}
}
async begin(text) { this.run = randomUUID(); return this.action('pi-begin', { text, ...(this.identity || {}) }); }
read() { return this.#observe('pi-state'); }
async openProductionOutput({outputId,variantId},signal) {
let status=await this.action('pi-production-open',{outputId,variantId});
signal?.throwIfAborted();
let status;
try {
status=await this.action('pi-production-open',{outputId,variantId});
} catch(error) {
if (!canvasReplyTimedOut(error)) throw error;
status=await this.#observe('pi-state',{},signal);
}
while(status.openingProductionCanvas) {
await delay(500,undefined,{signal});
status=await this.read();
status=await this.#observe('pi-state',{},signal);
}
signal?.throwIfAborted();
const binding=status.productionCanvas;
if(binding?.outputId!==outputId || binding.variantId!==variantId) {
throw Error(status.error || 'PhotoCraft 未绑定或保存所选画布');
if (status.conversationActive === false) {
throw new BridgeError('制作项目已切换,原画布操作已保留','scope_changed');
}
throw new BridgeError(status.error || '所选画布尚未绑定,请重新打开本轮工作画布',
'production_canvas_open_failed',{retryable:true});
}
return binding;
}

View File

@ -235,6 +235,7 @@ test('Pi loads the Skill and opens a project-selected output with the same sessi
const template={id:'fixture',version:'3',enterprise:true,resourceSetId:'published'};
const instruction='先准备画册,再制作详情页。';
const bindings=[];
const catalogs=[];
const x=await setup((payload,n)=>{
const call=(name,args)=>sse({tool_calls:[{index:0,id:'binding-'+n,type:'function',
function:{name,arguments:JSON.stringify(args)}}]},'tool_calls');
@ -251,16 +252,30 @@ test('Pi loads the Skill and opens a project-selected output with the same sessi
if(n===2)return call('plan_production',{});
if(n===3){
assert.match(JSON.stringify(payload.messages),new RegExp(instruction,'u'));
return call('open_production_output',outputs[1]);
return call('native_catalog',{id:'layer.setProps'});
}
if(n===4){
assert.match(JSON.stringify(payload.messages),/production_canvas_pending/u);
return call('open_production_output',outputs[1]);
}
if(n===5){
assert.match(JSON.stringify(payload.messages),/gallery.*revision/u);
return call('native_catalog',{id:'layer.setProps'});
}
if(n===6){
assert.match(JSON.stringify(payload.messages),/requiresRevisionLease/u);
return call('finish_production',{revision:1});
}
return sse({content:'已核对画册。'},'stop');
},undefined,{outputs,template,callBudget:6,canvas:{
},undefined,{outputs,template,callBudget:8,canvas:{
workflowRead(){assert.fail('selection should not require a mapped canvas');},
requestWrite(){assert.fail('selection should not ask for canvas write access');},
nativeCatalog:async({id})=>{
catalogs.push(id);
if(!bindings.length)throw new BridgeError('请先打开工作画布','production_canvas_pending',{retryable:true});
return {revision:1,items:[{id,requiresRevisionLease:true}]};
},
nativeCall(){assert.fail('catalog discovery should not dispatch an edit');},
openProductionOutput:async args=>{
bindings.push(args);
return {...args,revision:1,pendingOutputs:[outputs[0]]};
@ -276,9 +291,10 @@ test('Pi loads the Skill and opens a project-selected output with the same sessi
};
const response=await x.host.prompt('制作本轮所选输出');
assert.deepEqual(bindings,[outputs[1]]);
assert.deepEqual(catalogs,['layer.setProps','layer.setProps']);
assert.equal(response.production.outputId,'gallery');
assert.equal(response.production.complete,true);
assert.equal(x.requests.length,4);
assert.equal(x.requests.length,6);
assert.ok(x.host.manager.getBranch().some(row=>row.customType==='pi-goal'&&row.data.goal.status==='active'));
}finally{await x.close();}
});
@ -630,6 +646,39 @@ test('a canvas can complete more than 20 edits and cancellation stops waiting',a
assert.equal(dispatched,22);
});
test('first canvas save failure leaves the original run usable; a lost open ACK is observed without replay', async () => {
const target={outputId:'detail',variantId:'wood'};
const dispatched=[];
let attempts=0, binding;
const canvas=new StdioCanvas(async(action,input)=>{
if(action==='pi-begin')return {};
assert.equal(input.run,canvas.run);
assert.equal(input.documentId,1);
if(action==='pi-production-open'){
dispatched.push({outputId:input.outputId,variantId:input.variantId});
if(++attempts===1)return {openingProductionCanvas:true};
throw new BridgeError('画布未确认操作','transport_interrupted',{retryable:true,dispatched:true});
}
if(action==='pi-native-catalog'){
if(!binding)throw new BridgeError('请先打开工作画布','production_canvas_pending',{retryable:true});
return {revision:binding.revision};
}
assert.equal(action,'pi-state');
if(attempts===1)return {conversationActive:true,error:'当前草稿保存失败'};
binding={...target,revision:2,pendingOutputs:[]};
return {conversationActive:true,productionCanvas:binding};
},1);
await canvas.begin('制作详情页');
const first=canvas.openProductionOutput(target);
await Promise.all([
assert.rejects(first,{category:'production_canvas_open_failed',message:'当前草稿保存失败',retryable:true}),
assert.rejects(canvas.nativeCatalog(),{category:'production_canvas_pending',dispatched:false}),
]);
assert.deepEqual(await canvas.openProductionOutput(target),binding);
assert.deepEqual(await canvas.nativeCatalog(),{revision:2});
assert.deepEqual(dispatched,[target,target]);
});
test('canvas search keeps the screen and keyword when a layer argument is also present',()=>{
assert.deepEqual(canvasReadQuery({layer:999,screen:'第二屏',screenId:41,filter:'材质',maxDepth:0,mode:'layers',offset:0}),
{screenId:41,filter:'材质',mode:'layers',offset:0});

View File

@ -3044,6 +3044,11 @@ impl Workspace {
})
.map(|state| state.doc.id);
let Some(active_doc) = active_doc else {
if meta["continueProduct"] == true
&& self.production_canvas_open_failed(app, "slot-skeleton", "打开期间画布已修改,请重新打开所选工作画布")
{
return;
}
if meta["canvasFirst"] == true
&& meta["accountId"] == self.account["id"]
&& meta["origin"] == self.origin
@ -3095,8 +3100,11 @@ impl Workspace {
}
}
Err(e) => {
self.product_production = None;
self.error = e.to_string();
let reason = e.to_string();
if meta["continueProduct"] != true || !self.production_canvas_open_failed(app, "slot-skeleton", &reason) {
self.product_production = None;
self.error = reason;
}
}
}
}
@ -4339,7 +4347,7 @@ mod agent_daemon_control_tests {
#[test]
fn continuing_a_stopped_product_uses_the_original_three_output_pipeline() {
for typed in [false, true] {
for (typed, output) in [(false, "detail"), (true, "sku_images")] {
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width":32,"height":32,"name":"已暂停的商品"})).unwrap();
let mut app = PhotocraftApp::new(session, crate::Services::default());
@ -4395,7 +4403,15 @@ mod agent_daemon_control_tests {
let ctx = egui::Context::default();
pi_bridge::private_action_in_ui(&mut w, &mut app, &ctx, "pi-begin",
&json!({"run":run,"documentId":doc,"text":"继续整套制作"})).unwrap();
let requested = json!({"run":run,"documentId":doc,"outputId":"sku_images","variantId":"wood"});
let catalog_input = json!({"run":run,"documentId":doc,"id":"layer.setProps"});
let pending_catalog = |w: &mut Workspace, app: &mut PhotocraftApp| {
let error = pi_bridge::private_action_in_ui(w, app, &ctx, "pi-native-catalog", &catalog_input).unwrap_err();
assert_eq!(error.category, "production_canvas_pending");
assert!(error.retryable && !error.dispatched);
assert!(!w.agent_native.cancelled(run) && !w.agent_effects_paused);
};
pending_catalog(&mut w, &mut app);
let requested = json!({"run":run,"documentId":doc,"outputId":output,"variantId":"wood"});
let mut other = requested.clone();
other["variantId"] = json!("another-product");
assert!(pi_bridge::private_action_in_ui(&mut w, &mut app, &ctx, "pi-production-open", &other).is_err());
@ -4404,45 +4420,61 @@ mod agent_daemon_control_tests {
assert!(receipt["productionCanvas"].is_null());
assert_eq!(w.pi_run.as_deref(), Some(run));
assert!(matches!(requests.try_recv().unwrap(), Request::Save(..)));
pending_catalog(&mut w, &mut app);
w.receive_json_event(&mut app, &ctx, "save".into(), Err("当前草稿保存失败".into()));
let failed = pi_bridge::private_action_in_ui(&mut w, &mut app, &ctx, "pi-state", &requested).unwrap();
assert_eq!(failed["openingProductionCanvas"], false);
assert_eq!(failed["error"], "当前草稿保存失败");
pending_catalog(&mut w, &mut app);
let retry = pi_bridge::private_action_in_ui(&mut w, &mut app, &ctx, "pi-production-open", &requested).unwrap();
assert_eq!(retry["openingProductionCanvas"], true);
assert!(matches!(requests.try_recv().unwrap(), Request::Save(..)));
w.saving = None;
w.slot_apply_saved(&app, doc, revision);
assert!(matches!(requests.try_recv().unwrap(), Request::Action(method, input)
if method == "slot-skeleton" && input["outputId"] == "sku_images"
if method == "slot-skeleton" && input["outputId"] == output
&& input["variantId"] == "wood" && input["continueProduct"] == true));
pending_catalog(&mut w, &mut app);
let mut opened = (*app.session.active().unwrap().doc).clone();
let pages = json!([{"documentId":"page","mapping":{"fields":[]}}]);
let mapping = json!({"version":1,"canvasFirst":true,"workspaceId":"product",
"component":"sku_images","variantId":"wood","templateId":"fixture",
"templateVersion":"1","templateHash":"fixture-hash",
"outputs":[{"documentId":"sku-01","mapping":{"fields":[]}}]});
"component":output,"variantId":"wood","templateId":"fixture",
"templateVersion":"1","templateHash":"fixture-hash","outputs":pages});
opened.metadata.text.push(("jiansun.slot-mapping.v1".into(), mapping.to_string()));
let mut workflow = w.template_workflow.clone();
for (key, value) in [("outputId",json!("sku_images")),("templateId",json!("fixture")),
("templateVersion",json!("1")),("templateHash",json!("fixture-hash"))] {
for (key, value) in [("outputId",json!(output)),("templateId",json!("fixture")),
("templateVersion",json!("1")),("templateHash",json!("fixture-hash")),("revision",json!(3)),
("outputs",json!([{"outputId":output,"documentId":"page"}]))] {
workflow[key] = value;
}
workflow["outputs"] = json!([{"outputId":"sku_images","documentId":"sku-01"}]);
w.continue_product_canvas(&mut app, Box::new(opened), json!({
"doc":doc,"baseRevision":revision,"workspaceId":"product","accountId":w.account["id"],
"origin":w.origin,"outputId":"sku_images","variantId":"wood",
"origin":w.origin,"outputId":output,"variantId":"wood",
"canvasFirst":true,"continueProduct":true,"workflow":workflow
}));
assert!(!w.product_view_detached(), "the first mapped canvas replaces the placeholder");
w.with_product_target(&mut app, |w, app| {
assert!(w.production_canvas_receipt(app).is_null(), "wait for the real save receipt");
let rev = app.session.active().unwrap().revision;
assert!(rev > revision);
w.receive_event(app, &ctx, Event::Saved(doc, rev, Value::Null));
w.production_tick(app);
assert_eq!(w.production_canvas_receipt(app)["outputId"], "sku_images");
assert_eq!(w.production_canvas_receipt(app)["revision"], rev);
assert_eq!(w.pi_run.as_deref(), Some(run));
});
assert!(!w.product_view_detached(), "a placeholder is not a second editable view");
assert!(w.production_canvas_receipt(&app).is_null(), "wait for the real save receipt");
pending_catalog(&mut w, &mut app);
let rev = app.session.active().unwrap().revision;
assert!(rev > revision);
w.receive_event(&mut app, &ctx, Event::Saved(doc, rev, Value::Null));
w.production_tick(&app);
assert_eq!(w.production_canvas_receipt(&app)["outputId"], output);
assert_eq!(w.production_canvas_receipt(&app)["revision"], rev);
assert!(w.enforce_canvas_scope(&app));
assert!(!w.agent_native.cancelled(run));
let catalog = pi_bridge::private_action_in_ui(&mut w, &mut app, &ctx, "pi-native-catalog", &catalog_input).unwrap();
assert_eq!(catalog["items"][0]["id"], "layer.setProps");
assert_eq!(catalog["revision"], rev);
assert_eq!(w.pi_run.as_deref(), Some(run));
assert!(!w.agent_native.cancelled(run) && !w.agent_effects_paused);
assert!(w.product_production.is_some());
assert!(matches!(requests.try_recv().unwrap(), Request::Action(method, input)
if method == "product-run-checkpoint" && input["checkpoint"]["outputSelected"] == true));
assert!(requests.try_recv().is_err(), "the bound canvas stays in the original Pi turn");
w.stop_production();
assert!(w.agent_native.cancelled(run) && w.agent_effects_paused);
let error = pi_bridge::private_action_in_ui(&mut w, &mut app, &ctx, "pi-native-catalog", &catalog_input).unwrap_err();
assert_eq!(error.message, "当前制作会话已取消");
}
}

View File

@ -569,6 +569,8 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
Ok(json!({"fieldId":field,"templateHash":mapping["templateHash"],"component":mapping["component"],
"documentId":mapping["outputId"],"variantId":mapping["variantId"]}))
}
"pi-native-catalog" if w.production_canvas_unbound(app) => Err(BridgeFailure::new(
"production_canvas_pending", true, false, "请等待 open_production_output 返回已保存的工作画布,再查询原生命令")),
"pi-native-catalog" => super::agent_native::catalog(w, app, input).map_err(BridgeFailure::from),
"pi-native-call" => super::agent_native::call(w, app, ctx.ok_or("原生操作需要当前客户端界面上下文")?, input),
"pi-native-poll" => super::agent_native::poll(w, app, input).map_err(BridgeFailure::from),

View File

@ -401,31 +401,39 @@ impl Workspace {
}
pub(super) fn continue_product_canvas(&mut self, app: &mut PhotocraftApp, doc: Box<Document>, meta: Value) {
if let Some(stage) = Stage::read(&meta) {
self.product_views.cached.remove(&stage);
self.product_views.prepared.remove(&stage);
self.product_views.preloading.remove(&stage);
let Some(stage) = Stage::read(&meta) else { return; };
let Some(run) = self.product_production.as_ref() else { return; };
if !run.current(self, app) || !run.accepts_canvas(&meta)
|| meta["accountId"] != self.account["id"] || meta["origin"] != self.origin { return; }
let opening_first = !run.output_selected;
if opening_first && !canvas_workspace::document_scope_matches(&doc, &meta["workflow"], &stage.output, &stage.variant) {
self.production_canvas_open_failed(app, "slot-skeleton", "已打开的模板画布与所选输出或花色不一致,请重新打开");
return;
}
self.product_views.cached.remove(&stage);
self.product_views.prepared.remove(&stage);
self.product_views.preloading.remove(&stage);
if self.join_product_view(app, &meta) { return; }
if self.product_views.worker.is_some() {
self.with_product_target(app, |w, app| w.receive_slot_canvas(app, doc, meta));
return;
}
let Some(run) = self.product_production.as_ref() else { return; };
if !run.current(self, app) || !run.accepts_canvas(&meta)
|| meta["accountId"] != self.account["id"] || meta["origin"] != self.origin { return; }
let Some(active) = app.session.active_mut().filter(|state| state.doc.id == doc.id) else { return; };
// A new project has no mapped editor canvas to preserve in the viewer.
if !run.output_selected && canvas_workspace::document_mapping(&active.doc).is_none() {
self.receive_slot_canvas(app, doc, meta);
return;
}
if Stage::read(&meta) == Stage::read(&self.template_workflow) {
let Some(active) = app.session.active().filter(|state| state.doc.id == doc.id) else { return; };
let visible = Stage::read(&self.template_workflow);
if visible.as_ref() == Some(&stage)
&& canvas_workspace::document_scope_matches(&active.doc, &meta["workflow"], &stage.output, &stage.variant) {
self.template_workflow = meta["workflow"].clone();
self.canvas_workspace.scope_switch_in_flight = false;
self.production_opened(app, &meta);
return;
}
// A preparation placeholder has no product view to keep alongside the worker.
if visible.as_ref() == Some(&stage) || opening_first && visible.as_ref().is_none_or(|shown|
!canvas_workspace::document_scope_matches(&active.doc, &self.template_workflow, &shown.output, &shown.variant)) {
self.receive_slot_canvas(app, doc, meta);
return;
}
let Some(active) = app.session.active_mut() else { return; };
let mut worker = DocState::new(*doc, active.path.clone());
worker.revision = active.revision + 1;
active.path = meta["previousViewPath"].as_str().map(str::to_owned);
@ -1021,7 +1029,7 @@ impl Workspace {
"outputId":stage.output,"variantId":stage.variant,"continueProduct":true
}))?;
}
let run = self.product_production.as_mut().unwrap();
let run = self.product_production.as_mut().ok_or("原制作项目已切换")?;
run.stages.remove(position);
run.stages.push_front(stage);
if already_saved {
@ -1235,9 +1243,15 @@ impl Workspace {
return;
}
if self.busy.as_deref() == Some("pi-agent") && self.pi_run.is_some() && run.awaiting_canvas_save()
&& !run.output_selected && app.session.active().is_some_and(|canvas|
self.persisted_revisions.get(&run.doc) == Some(&canvas.revision)) {
self.bind_production_canvas(app);
&& !run.output_selected
&& let Some(canvas) = app.session.active().filter(|canvas| self.persisted_revisions.get(&run.doc) == Some(&canvas.revision))
{
if run.stages.front().is_some_and(|stage|
canvas_workspace::document_scope_matches(&canvas.doc, &self.template_workflow, &stage.output, &stage.variant)) {
self.bind_production_canvas(app);
} else {
self.production_canvas_open_failed(app, "save", "已保存的画布与所选输出或花色不一致,请重新打开");
}
return;
}
if self.busy.is_some() || self.saving.is_some() || self.pending_slot_apply.is_some()