From bd5e425c7732ddc3e3151f244293a84642ca84e7 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Thu, 26 Nov 2026 16:14:04 +0800 Subject: [PATCH] fix(xiaoyi): streamline native tools and frozen image dispatch --- apps/detail-agent-pi/src/activity-event.mjs | 3 +- apps/detail-agent-pi/src/agent.mjs | 92 +++++++----- apps/detail-agent-pi/src/desktop-daemon.mjs | 9 +- apps/detail-agent-pi/src/desktop-host.mjs | 8 +- .../src/enterprise-knowledge.mjs | 2 +- apps/detail-agent-pi/src/native-tools.mjs | 5 +- .../src/photocraft-extension.mjs | 3 +- .../src/production-operations.mjs | 95 ++++++------ .../src/skills/product-image-sources/SKILL.md | 2 +- .../src/stream-presentation.mjs | 25 +++ .../test/conversation.test.mjs | 40 ++++- .../test/desktop-daemon.test.mjs | 24 ++- .../detail-agent-pi/test/native-wire.test.mjs | 48 +++++- .../test/production-operations.test.mjs | 49 +++--- .../photocraft/src/jiansun_agent_daemon.rs | 8 +- .../src/jiansun_canvas_workspace.rs | 142 +++++++++++------- .../apps/photocraft/src/jiansun_images.rs | 33 ++-- .../apps/photocraft/src/jiansun_pi_runtime.rs | 18 ++- .../ui-egui/src/jiansun/agent_native.rs | 51 ++++--- .../crates/ui-egui/src/jiansun/pi_bridge.rs | 15 +- docs/development/xiaoyi/implementation.md | 4 +- 21 files changed, 436 insertions(+), 240 deletions(-) diff --git a/apps/detail-agent-pi/src/activity-event.mjs b/apps/detail-agent-pi/src/activity-event.mjs index 064528f3..ca5e3cc0 100644 --- a/apps/detail-agent-pi/src/activity-event.mjs +++ b/apps/detail-agent-pi/src/activity-event.mjs @@ -12,8 +12,7 @@ const labels = Object.freeze({ plan_production: '读取制作进度', start_production_strategy: '准备制作策划', read_production_knowledge: '读取制作规则', read_copy_fields: '查看待处理图文', delegate_image_slots: '分派图片图位', review_image_slots: '查看图位结果', retire_production_image: '清理已退回的候选图', read_slot_images: '查看图位图片', use_product_image: '取用商品实拍', - prepare_image_request: '准备生图请求', read_image_request: '核对生图请求', - freeze_image_request: '冻结生图请求', dispatch_image_request: '生成候选图片', + prepare_image_request: '准备生图请求', dispatch_image_request: '生成候选图片', await_image_slots: '等待子代理回执', adopt_production_image: '回填候选图片', reconcile_image_slots: '核查图片原请求', read_archived_images: '查找同款历史候选', stage_archived_image: '加入待验历史候选', read_output_screen: '查看实际画布', record_screen_check: '记录本屏复核', check_page_copy: '发起文案复核', diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index 1ef2e0bd..a215c05d 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -2,7 +2,7 @@ import {setTimeout as delay} from 'node:timers/promises'; import { confirmProductionResponse, confirmedProductionFailure, piRetryPolicy, productRequestScope, productionUsesAutomaticTools, ProductionOutputLimit, ProductionRequestFailed, ProductionRequestPending } from './production-recovery.mjs'; import { enterpriseTools } from './enterprise-knowledge.mjs'; import { executeWorkflow } from './workflow-execute.mjs'; -import { StreamOutputMeter, StreamPresentation, presentText, stripProductionToolText } from './stream-presentation.mjs'; +import { PresentationBatch, StreamOutputMeter, StreamPresentation, presentText, stripProductionToolText } from './stream-presentation.mjs'; import path from 'node:path'; import fs from 'node:fs/promises'; import lockfile from 'proper-lockfile'; @@ -69,8 +69,17 @@ const frozenReferences = context => Array.isArray(context?.requestScope?.referen // Only the native owner's explicit inactive-document response detaches display. // Connection, account/authentication and all other failures must still surface. const inactiveDocument = error => error?.category === 'scope_changed'; +const sequentialTools = new Set([ + 'memory_set', 'canvas_edit', 'canvas_preview', 'copywriting_options', 'copywriting_fields', + 'workflow_navigate', 'workflow_execute', 'workflow_propose', + 'open_production_output', 'write_copy_fields', 'use_product_image', 'prepare_image_request', + 'dispatch_image_request', 'delegate_image_slots', 'stage_archived_image', 'check_image_slots', + 'adopt_production_image', 'retire_production_image', 'reconcile_image_slots', 'record_screen_check', + 'defer_production_output', 'finish_production', +]); function toolsFor(host) { - const make = (name, description, parameters, execute, format = plain) => ({ name, label: name, description, parameters:JSON.parse(JSON.stringify(parameters)), executionMode: 'sequential', execute: async (_id, args, signal, _update, ctx) => { + const make = (name, description, parameters, execute, format = plain) => ({ name, label: name, description, parameters:JSON.parse(JSON.stringify(parameters)), + ...(sequentialTools.has(name) ? {executionMode:'sequential'} : {}), execute: async (_id, args, signal, _update, ctx) => { const epoch = host.turnEpoch; if (host.compromised) throw Error('本地会话锁失效,已停止工具执行'); if (name === 'memory_set' && !host.productionGoal && host.canvas?.workflowRead) await host.readWorkflow({section:'overview'}); @@ -569,10 +578,10 @@ export class DetailPiAgent { const supervisor = ['supervisor','production-strategy','production-strategy-audit'].includes(slotId); let thinking = false; let outputMeter = new StreamOutputMeter(); - if (supervisor && host.canvas?.run) agent.subscribe(async event => { + if (supervisor && host.canvas?.run) agent.subscribe(event => { if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') { const activity = toolActivity(event, host.activityScope); - if (activity) await host.notifyCanvas('activity', activitySummary(event), activity).catch(()=>{}); + if (activity) void host.notifyCanvas('activity', activitySummary(event), activity).catch(()=>{}); } const type = event.type === 'message_update' ? event.assistantMessageEvent?.type : null; const next = type === 'thinking_start' || type === 'thinking_delta' ? true @@ -581,7 +590,7 @@ export class DetailPiAgent { if (event.type === 'message_end') outputMeter = new StreamOutputMeter(); if (thinking !== next || meter) { thinking = next; - await host.notifyCanvas('delta', '', thinking, undefined, meter).catch(()=>{}); + host.display.push({thinking, output:meter}); } }); agent.beforeToolCall=async ({toolCall})=>{ @@ -710,8 +719,18 @@ export class DetailPiAgent { retry:session.settingsManager.getRetrySettings(),defaultRetry:defaults.getRetrySettings(), thinking:session.thinkingLevel,tools:session.getActiveToolNames()}); } - // AgentSession UI listeners are fire-and-forget. Core listeners are awaited: - // the native UI, durable activity journal and handover gates must settle first. + host.display = new PresentationBatch(async ({text, thinking, output, delta}) => { + await Promise.allSettled([ + canvas && (text !== undefined || thinking !== undefined || output) + ? host.notifyCanvas('delta', text ?? '', thinking, undefined, output) : undefined, + delta ? Promise.resolve().then(() => onEvent({type:'text_delta',delta})) : undefined, + ]); + }, (pending, next) => ({ + text:next.text ?? pending.text, + thinking:next.thinking ?? pending.thinking, + output:next.output ?? pending.output, + delta:(pending.delta ?? '') + (next.delta ?? ''), + })); let outputMeter = new StreamOutputMeter(); session.agent.subscribe(async event => { if (event.type === 'message_start' && event.message.role === 'assistant') outputMeter = new StreamOutputMeter(); @@ -736,34 +755,35 @@ export class DetailPiAgent { } const changed = thinking !== host.thinking; host.thinking = thinking; - if (canvas) { - const meter = outputMeter.update(event, thinking); - if (text || changed) { - await host.notifyCanvas('delta', host.presentation.text.slice(-65000), changed || meter ? thinking : undefined, undefined, meter); - } else if (meter) { - await host.notifyCanvas('delta', '', thinking ?? false, undefined, meter).catch(()=>{}); - } - } - if (text) await onEvent({ type: 'text_delta', delta: text }); + const meter = canvas && outputMeter.update(event, thinking); + if (text || changed || meter) host.display.push({ + text:text ? host.presentation.text.slice(-65000) : undefined, + thinking:changed || meter ? thinking ?? false : undefined, + output:meter || undefined, + delta:text, + }); } if (event.type === 'message_end' && event.message.role === 'assistant' && !host.compacting && canvas) { const meter = outputMeter.update(event, false); if (host.thinking === true || meter) { host.thinking = false; - await host.notifyCanvas('delta', '', false, undefined, meter).catch(()=>{}); + host.display.push({thinking:false,output:meter}); } if (event.message.stopReason==='toolUse' && typeof canvas.reply==='function') { const prose=host.presentation?.text.trim(); - if(prose) await host.notifyCanvas('reply',prose.slice(-16000)); + if(prose) { + await host.display.flush(); + await host.notifyCanvas('reply',prose.slice(-16000)); + } host.presentation=new StreamPresentation(); } } if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') { const activity = toolActivity(event, host.activityScope || activityScope(store.identity)); - if (canvas) await host.notifyCanvas('activity', activitySummary(event), activity); + if (canvas) void host.notifyCanvas('activity', activitySummary(event), activity).catch(()=>{}); await store.appendEvent({ type: event.type, toolName: event.toolName, toolCallId: event.toolCallId, isError: event.isError ?? false }); - await onEvent({ type: event.type, toolName: event.toolName, isError: event.isError ?? false, ...(activity ? { activity } : {}) }); + void Promise.resolve().then(() => onEvent({ type: event.type, toolName: event.toolName, isError: event.isError ?? false, ...(activity ? { activity } : {}) })).catch(()=>{}); } }); // Restore the meter from Pi's durable session, not a cached local estimate. @@ -784,6 +804,9 @@ export class DetailPiAgent { } async readWorkflow(args) { + return (await this.readWorkflowContext(args)).workflow; + } + async readWorkflowContext(args) { const epoch = this.turnEpoch; if (this.canvasNotificationsDetached) throw Error('当前项目已切换,未读取其他项目工作流'); if (this.workflowBindingChanged) throw Error('品牌或品类已变化,请重新开始一轮对话以加载对应规则;未继续执行当前回合'); @@ -801,29 +824,31 @@ export class DetailPiAgent { this.currentWorkflow = latest.workflow; this.productEvidence = latest.product; if (this.productionGoal && args.section === 'overview') this.productionTemplate = snapshot.template; - return latest.workflow; + return latest; } - async readEnterpriseRules() { - const template = this.currentWorkflow?.template; - if (!this.currentWorkflow?.available || !template?.enterprise) return null; - const product = this.productEvidence.product; + async readEnterpriseRules(workflow, productEvidence) { + const template = workflow?.template; + if (!workflow?.available || !template?.enterprise) return null; + const product = productEvidence.product; this.enterpriseContext ??= new EnterpriseContext(this.store); return this.enterpriseContext.load({task:this.task || 'chat', brandName:product.brandName,categoryName:product.categoryName, templateId:template.id,releaseId:template.version,turn:this.turnEpoch}); } async modelContext(options = {}, {loadKnowledge = false} = {}) { - if ((!this.productionGoal || this.productionGoal.outputId) && this.canvas?.workflowRead) await this.readWorkflow({section:'overview'}); - const value=await this.store.modelContext({workflow:this.currentWorkflow,canvas:this.currentCanvas,...options}); - value.currentProduct=this.productEvidence; - if (this.currentWorkflow) value.currentWorkflow=this.currentWorkflow; + const {workflow,product}=(!this.productionGoal || this.productionGoal.outputId) && this.canvas?.workflowRead + ? await this.readWorkflowContext({section:'overview'}) + : {workflow:this.currentWorkflow,product:this.productEvidence}; + const value=await this.store.modelContext({workflow,canvas:this.currentCanvas,...options}); + value.currentProduct=product; + if (workflow) value.currentWorkflow=workflow; if (this.productionSkills && loadKnowledge) { const {knowledge,documents}=this.productionSkills; value.enterpriseKnowledge={execution:knowledge.execution,sources:[...documents.values()]}; value.snapshot.rules=value.snapshot.rules.filter(rule=>/原稿画布|源模板约束/.test(rule)); return value; } - const knowledge = this.knowledgeContext ?? (loadKnowledge ? await this.readEnterpriseRules() : null); + const knowledge = this.knowledgeContext ?? (loadKnowledge ? await this.readEnterpriseRules(workflow,product) : null); if (knowledge) { value.enterpriseKnowledge=knowledge; value.snapshot.rules=value.snapshot.rules.filter(rule=>/原稿画布|源模板约束/.test(rule)); @@ -836,7 +861,7 @@ export class DetailPiAgent { if(method==='end'){ if(this.canvasEndAttempted)return; this.canvasEndAttempted=true; - }else if(this.canvasNotificationsDetached)return; + }else if(this.canvasEndAttempted||this.canvasNotificationsDetached)return; if(this.productionGoal&&['delta','reply','end'].includes(method)&&typeof args[0]==='string'){ args[0]=stripProductionToolText(args[0],method==='delta'); } @@ -962,9 +987,7 @@ export class DetailPiAgent { ? stripProductionToolText(resultText).trim()||this.goalStageResult?.text||'' : resultText; if (!textResult.trim()) throw Error('模型没有返回正文,请更换模型后再试;本轮工具结果已保留'); - if (this.canvas?.delta && this.presentation) { - await this.notifyCanvas('delta', this.presentation.text.slice(-65000), this.thinking === true ? false : undefined); - } + await this.display.flush(); await this.updateContextUsage(null, 'ready'); await this.nativeUI?.stop(); if (this.canvas) await this.notifyCanvas('end',textResult); @@ -974,6 +997,7 @@ export class DetailPiAgent { if (result?.complete) result.piGoalId = piGoalState(this.manager)?.id; return { ...(result?{production:result}:null), text: textResult, rounds: this.rounds, messages: this.session.messages.length, sessionFile: this.manager.getSessionFile() }; } catch (error) { + await this.display.flush(); await this.nativeUI?.stop().catch(() => {}); const generated = this.generatedCandidateReply(); if (this.canvas) await this.notifyCanvas('end', generated && !this.canvasOperations.stopReason diff --git a/apps/detail-agent-pi/src/desktop-daemon.mjs b/apps/detail-agent-pi/src/desktop-daemon.mjs index e7b9f8b8..e0279634 100644 --- a/apps/detail-agent-pi/src/desktop-daemon.mjs +++ b/apps/detail-agent-pi/src/desktop-daemon.mjs @@ -73,7 +73,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out if (task.runId !== runId) continue; waiting.delete(id); clearTimeout(task.timer); - task.reject(error); + task.reject(new BridgeError(error.message,'cancelled',{dispatched:true})); } }; active={runId,config,abort}; @@ -81,7 +81,12 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out const timer = deadline === null ? null : setTimeout(expire, Math.max(0, deadline - Date.now())); const call=(action,input)=>new Promise((resolve,reject)=>{ if(closed||active?.runId!==runId){reject(new BridgeError('客户端连接已关闭,原操作需核查','transport_interrupted',{retryable:true}));return;} - if(controller?.signal.aborted){reject(controller.signal.reason);return;} + if(controller?.signal.aborted){reject(new BridgeError(controller.signal.reason.message,'cancelled'));return;} + if (action === 'pi-delta' || action === 'pi-activity') { + send({type:'presentation',runId,action,input}); + resolve(); + return; + } const id=++serial; waiting.set(id,{resolve,reject,runId});send({type:'canvas',runId,id,action,input}); }); diff --git a/apps/detail-agent-pi/src/desktop-host.mjs b/apps/detail-agent-pi/src/desktop-host.mjs index 4c0289f7..5a2db4b3 100644 --- a/apps/detail-agent-pi/src/desktop-host.mjs +++ b/apps/detail-agent-pi/src/desktop-host.mjs @@ -39,12 +39,16 @@ async function cli() { const value = JSON.parse(line); if (!initial) { initial = value; void runSession(value, call).then(result => send({type:'complete',value:result})).finally(() => { lines.close(); process.stdin.destroy(); }); return; } const pending = waiting.get(value.id); - if (pending) { waiting.delete(value.id); value.error ? pending.reject(Error(value.error)) : pending.resolve(value.value); } + if (pending) { + waiting.delete(value.id); + if (value.error) pending.reject(typeof value.error === 'string' ? Error(value.error) : BridgeError.from(value.error)); + else pending.resolve(value.value); + } } catch { send({ type: 'fatal', error: '本地连接消息无效;不会重发模型请求' }); } }); lines.on('close', () => { closed = true; - for (const pending of waiting.values()) { pending.reject(Error('客户端已关闭,原请求需只读核查')); } + for (const pending of waiting.values()) { pending.reject(new BridgeError('客户端已关闭,原请求需只读核查','transport_interrupted',{retryable:true,dispatched:true})); } waiting.clear(); }); } diff --git a/apps/detail-agent-pi/src/enterprise-knowledge.mjs b/apps/detail-agent-pi/src/enterprise-knowledge.mjs index 52aa5021..d792e6bb 100644 --- a/apps/detail-agent-pi/src/enterprise-knowledge.mjs +++ b/apps/detail-agent-pi/src/enterprise-knowledge.mjs @@ -318,7 +318,7 @@ export function enterpriseTools(host, make, client = new EnterpriseKnowledge({st } }; const tools=names.map(name=>({...make('ekb_'+name, descriptions[name], schemas[name], args=>execute(name,args),enterpriseToolResult),namespace,exposure:'deferred',...(name==='read_image'?{promptGuidelines:['读取图片时,通过tool_search启用后直接调用ekb_read_image,让实际image内容进入视觉上下文;不要放进只返回文字的CodeMode嵌套调用。']}:{})})); - tools.push({...make('ekb_download_file','下载选定附件到当前项目;保留同一revision或release引用,核对完整字节后返回本地路径,不导入画布',schemas.get_file,args=>execute('download_file',args),enterpriseToolResult),namespace,exposure:'deferred'}); + tools.push({...make('ekb_download_file','下载选定附件到当前项目;保留同一revision或release引用,核对完整字节后返回本地路径,不导入画布',schemas.get_file,args=>execute('download_file',args),enterpriseToolResult),namespace,exposure:'deferred',executionMode:'sequential'}); return tools; } export function enterpriseToolResult(value) { diff --git a/apps/detail-agent-pi/src/native-tools.mjs b/apps/detail-agent-pi/src/native-tools.mjs index 4e76aaf8..af6b4c63 100644 --- a/apps/detail-agent-pi/src/native-tools.mjs +++ b/apps/detail-agent-pi/src/native-tools.mjs @@ -111,9 +111,10 @@ export function nativeTools(host, make) { revision: settled.revision, receipt: settled.receipt ?? (settled.kind === 'native-operation' ? settled : undefined) }); return settled; } catch (error) { - if (!readOnly && dispatched && !terminal) scope.retain({ kind:'native', job:pendingJob, run, documentId, identity, epoch }); + const outcomeUnknown = dispatched && !terminal && (pendingJob !== undefined || error?.dispatched !== false); + if (!readOnly && outcomeUnknown) scope.retain({ kind:'native', job:pendingJob, run, documentId, identity, epoch }); if (!host.productionGoal && !readOnly && host.turnEpoch === epoch && - (dispatched && !terminal || stoppedCanvas(error) || pendingJob !== undefined || signal?.aborted)) scope.writesBlocked = true; + (outcomeUnknown || stoppedCanvas(error) || pendingJob !== undefined || signal?.aborted)) scope.writesBlocked = true; throw error; } finally { if (scope.active === owner) scope.active=null; } }), ...nativeToolMetadata('native_call')}, diff --git a/apps/detail-agent-pi/src/photocraft-extension.mjs b/apps/detail-agent-pi/src/photocraft-extension.mjs index 6465e569..f018db73 100644 --- a/apps/detail-agent-pi/src/photocraft-extension.mjs +++ b/apps/detail-agent-pi/src/photocraft-extension.mjs @@ -21,7 +21,8 @@ export const PHOTOCRAFT_NAMESPACE = Object.freeze({ /** Metadata only: the host owns the real handlers, schemas and authorization. */ export function nativeToolMetadata(name) { if (!PHOTOCRAFT_NATIVE_TOOL_NAMES.includes(name)) throw new TypeError(`Unknown PhotoCraft native tool: ${name}`); - return {namespace: PHOTOCRAFT_NAMESPACE, exposure: 'direct', executionMode: 'sequential'}; + return {namespace: PHOTOCRAFT_NAMESPACE, exposure: 'direct', + ...(name === 'native_catalog' ? {} : {executionMode: 'sequential'})}; } /** diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 3fa6b1e4..98f74a48 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -3,6 +3,7 @@ import path from 'node:path'; import { Type } from '@sinclair/typebox'; import { formatDimensionNote, resizeImage } from '@earendil-works/pi-coding-agent'; import { atomic } from './store.mjs'; +import { PresentationBatch } from './stream-presentation.mjs'; import { loadSlots } from './production-slots.mjs'; import { productionKnowledge, knowledgeReadInstruction } from './production-knowledge.mjs'; import { productRequestScope } from './production-recovery.mjs'; @@ -31,9 +32,7 @@ const preparationArgs={ prefer2k:optional(Type.Boolean()), retryOf:optional(Type.String({description:'仅限已确认可重试的失败候选。'})), }; -const requestIdArgs={requestId:text}; -const freezeArgs={...requestIdArgs,expectedRevision:rev,expectedHash:text}; -const dispatchArgs={frozenRequestId:text}; +const dispatchArgs={requestId:text,expectedRevision:rev,expectedHash:text}; export const productionOperationTools = [ ['open_production_output','打开本轮待制作的工作画布,返回已保存画布的绑定回执。用 plan_production 获取输出和花色。',obj({outputId:text,variantId:text})], @@ -49,10 +48,8 @@ export const productionOperationTools = [ slotId:slotRef,candidateId:optional(Type.String()),adopted:optional(Type.Boolean()),includeReferences:optional(Type.Boolean()), })], ['use_product_image','用本款原片或裁切区域创建候选,返回后可继续处理其他图位。',obj({slotId:slotRef,...productImageArgs})], - ['prepare_image_request','按完整提示词、图位与参考设置准备并保存生图请求。回执含完整文本、实际参考顺序及模型参数。',obj({slotId:slotRef,...preparationArgs})], - ['read_image_request','从项目记录回读完整请求与实际参考,取得冻结所需版本和内容 hash。',obj(requestIdArgs)], - ['freeze_image_request','核对完整请求后,传入刚回读的版本和内容 hash 冻结。',obj(freezeArgs)], - ['dispatch_image_request','按冻结 ID 提交原请求并立即返回受理,使用 await_image_slots 或 review_image_slots 查看结果。',obj(dispatchArgs)], + ['prepare_image_request','保存完整生图请求。回执含可审阅的正式文本、实际参考顺序和模型参数,以及 requestId、revision 和 requestSpecHash。',obj({slotId:slotRef,...preparationArgs})], + ['dispatch_image_request','审阅准备回执后,以 requestId、expectedRevision 和 expectedHash 确认派发。使用 await_image_slots 或 review_image_slots 查看实际结果。',obj(dispatchArgs)], ['delegate_image_slots','把图位和可执行要求交给 Pi 子代理并行制作。每个图位单独返回已接收或无法定位的结果。',obj({ jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})), })], @@ -205,7 +202,9 @@ export async function openProductionOperations(host) { const {fields=[]}=await canvas.detailCopyFields({includeFilled:true}); return fields; }; - const progress=async heading=>{ + let displayEpoch=0; + const progress=async ({heading,epoch})=>{ + if(epoch!==displayEpoch||host.canvasEndAttempted)return; const pictureCells=slots.map(({id,label})=>{ const item=journal.items[id]; const matched=filled.has(id); @@ -215,13 +214,15 @@ export async function openProductionOperations(host) { label,state:!templateSample&&evidenceMatches(plan)&&journal.copyEvidence?.[layer]?.text===currentText?'verified': !templateSample&¤tText?'filled':'empty', })); + if(epoch!==displayEpoch||host.canvasEndAttempted)return; return canvas.delta('',undefined,{heading,outputId,variantId,workers:[...jobs.values()].map(job=>job.row), reviews:pendingReviews().map(job=>job.row),candidateReviews:Object.fromEntries(candidates),pictureCells,copyCells, total:slots.length,rendered:filled.size,copy:copyCells.filter(row=>row.state==='verified').length, copyPending:copyCells.filter(row=>row.state!=='verified').length, unresolved:Object.values(journal.items).filter(item=>item.pendingOperation||item.pendingAdoption).length}); }; - const notice=heading=>progress(heading).catch(()=>{}); + const display=new PresentationBatch(progress); + const notice=heading=>display.push({heading,epoch:displayEpoch}); const readImages=(slotId,args={})=>{ const candidateId=args.candidateId?.trim()||undefined; return canvas.detailImages(matches(slotId).id,candidateId,{ @@ -294,27 +295,32 @@ export async function openProductionOperations(host) { return {slotId:slot.id,phase:'unknown',operationId:original?.operationId,candidateId, pendingOriginal:candidateId??original?.operationId}; }; - const readImageRequest=async(requestId,slot)=>{ - const data=await canvas.imageRequest('read',{requestId}); - if (data.requestId!==requestId || data.outputId!==outputId || data.variantId!==variantId || - slot && data.slotId!==slot.id) throw Error('生图请求不属于本轮工作画布或委托图位'); - return data; - }; const prepareImageRequest=async(slot,{prompt,retryOf,useTemplateReference,prefer2k,geometryReferenceIndex,reworkCandidateId,reworkChange},signal)=>{ signal?.throwIfAborted(); await current(); - return canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf,useTemplateReference, + const receipt=await canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf,useTemplateReference, prefer2k,geometryReferenceIndex,reworkOf:reworkCandidateId,reworkChange}); + await update(()=>{ + (journal.preparedRequests??={})[receipt.requestId]={ + slotId:receipt.slotId,prompt:receipt.spec.prompt,reworkOf:receipt.reworkOf,reworkChange:receipt.reworkChange, + }; + }); + return receipt; }; - const dispatchImageRequest=async(slot,request,signal)=>{ + const preparedRequest=(requestId,slot)=>{ + const request=journal.preparedRequests?.[requestId]; + if (!request || slot && request.slotId!==slot.id) throw Error('生图请求不属于本轮工作画布或委托图位'); + return request; + }; + const dispatchImageRequest=async(slot,approval,request,signal)=>{ signal?.throwIfAborted(); const prior=pendingGeneration(slot); if(prior)return prior; - const candidateId=request.requestId; + const candidateId=approval.requestId; const original={candidateId,operationId:candidateId,kind:'frozen-image'}; await save(slot,{pendingOperation:original,state:'dispatching'}); let receipt; - try { receipt=await canvas.imageRequest('dispatch',{frozenRequestId:candidateId}); } + try { receipt=await canvas.imageRequest('dispatch',{...approval,slotId:slot.id}); } catch(error) { if (error.dispatched===false) { await save(slot,{pendingOperation:null,state:'failed',reason:error.message}); @@ -327,10 +333,10 @@ export async function openProductionOperations(host) { await update(()=>{ const item=journal.items[slot.id]??={}; Object.assign(item,{pendingOperation:settled?null:original,candidateId,state:phase==='complete'?'candidate':phase, - prompt:request.spec.prompt,source:'generate'}); + prompt:request.prompt,source:'generate'}); const attempts=item.attempts??=[]; if(!attempts.some(row=>row.candidateId===candidateId))attempts.push({candidateId,source:'generate', - prompt:request.spec.prompt,reworkOf:request.reworkOf,change:request.reworkChange}); + prompt:request.prompt,reworkOf:request.reworkOf,change:request.reworkChange}); }); return {candidateId,operationId:candidateId,phase:settled?phase:'unknown',reason:receipt.message, requestedSource:'generate',...(request.reworkOf?{reworkOf:request.reworkOf}:null), @@ -398,7 +404,7 @@ export async function openProductionOperations(host) { const source=item?.candidateId===candidateId?item.source:undefined; const copy=Object.values(evidenceMatches(plan)?journal.copyEvidence??{}:{}).filter(row=>row.pictures.includes(slot.fieldId)||row.pictures.includes(slot.id)); try{ - await notice('正在核验候选图片'); + notice('正在核验候选图片'); const {referenceCount,...review}=await reviewProductionCandidate({canvas,host,runAgent:host.runDetailAgent, slot,candidateId,signal,copy,rule:slot.productionRule,source,adopted,reviewKnowledge:reviews}); const {verdict,checks,reason,observation}=review; @@ -422,7 +428,7 @@ export async function openProductionOperations(host) { } return { get active(){return jobs.size;}, - close:drain, + async close(){await drain();displayEpoch++;}, async plan_production({slotIds}={}){ await current({refresh:true}); const {requested,matched,unmatched}=readSelection(slotIds); @@ -504,7 +510,7 @@ export async function openProductionOperations(host) { for(const {layer,mapping} of result.styleMappings)journal.copyStyleMappings[layer]=mapping; } }); - await notice('文字已更新'); + notice('文字已更新'); return {...result,appliedLayers:applied.map(row=>row.layer),revision:(await canvas.read()).revision}; } }); @@ -535,18 +541,10 @@ export async function openProductionOperations(host) { prepare_image_request({slotId,...args},signal){ return prepareImageRequest(matches(slotId),args,signal); }, - read_image_request({requestId}){ - return readImageRequest(requestId); - }, - async freeze_image_request(args){ - await readImageRequest(args.requestId); - return canvas.imageRequest('freeze',args); - }, - async dispatch_image_request({frozenRequestId},signal){ - const request=await readImageRequest(frozenRequestId); - if(!request.frozen)throw Error('请先回读并冻结生图请求'); + async dispatch_image_request(approval,signal){ + const request=preparedRequest(approval.requestId); const slot=matches(request.slotId); - return launchImage(slot,()=>dispatchImageRequest(slot,request,signal)); + return launchImage(slot,()=>dispatchImageRequest(slot,approval,request,signal)); }, async delegate_image_slots({jobs:requested},signal){ const assigned=[],unmatched=[]; @@ -557,7 +555,7 @@ export async function openProductionOperations(host) { const row={number:Math.max(0,...[...jobs.values()].map(job=>job.row.number??0))+1,slotId:slot.id,label:slot.label,step:'正在准备',active:true}; let rework; const workerTool=(name,description,properties,execute,terminate=false)=>({ - name,label:description,description,parameters:obj(properties), + name,label:description,description,parameters:obj(properties),executionMode:'sequential', execute:async(_id,args,workerSignal)=>{ const signals=[workerSignal,signal].filter(Boolean); const activeSignal=signals.length?AbortSignal.any(signals):undefined; @@ -571,16 +569,11 @@ export async function openProductionOperations(host) { (args,activeSignal)=>useProductImage(slot,args,activeSignal),true), workerTool('prepare_image_request','准备并持久保存完整生图请求',preparationArgs, (args,activeSignal)=>prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal)), - workerTool('read_image_request','回读请求文本、参考顺序和模型参数',requestIdArgs, - ({requestId})=>readImageRequest(requestId,slot)), - workerTool('freeze_image_request','按回读的版本和内容 hash 冻结请求',freezeArgs, - async args=>{await readImageRequest(args.requestId,slot);return canvas.imageRequest('freeze',args);}), - workerTool('dispatch_image_request','仅按冻结 ID 提交请求',dispatchArgs, - async ({frozenRequestId},activeSignal)=>{ - const request=await readImageRequest(frozenRequestId,slot); - if(!request.frozen)throw Error('请先回读并冻结生图请求'); + workerTool('dispatch_image_request','用已审阅回执的 requestId、expectedRevision 和 expectedHash 确认派发',dispatchArgs, + (approval,activeSignal)=>{ + const request=preparedRequest(approval.requestId,slot); row.step='正在生图'; - return dispatchImageRequest(slot,request,activeSignal); + return dispatchImageRequest(slot,approval,request,activeSignal); },true), ]; const readTool={name:'read_slot_images',label:'查看本图位实拍与构图',description:'读取本图位的原片与模板构图。', @@ -609,7 +602,7 @@ export async function openProductionOperations(host) { }; } } - const instructions='完成主代理委托的图位。按 Skill 选择直接用实拍,或准备生图请求、回读核对、冻结,再按冻结 ID 派发。'+ + const instructions='完成主代理委托的图位。按 Skill 选择直接用实拍,或准备生图请求、审阅准备回执并确认派发。'+ (rework?'\n先看随消息附上的退回图、验图回执和上次实发提示词。按发布规则处理,用 reworkChange 记录改动。':'')+ knowledgeReadInstruction; await host.runDetailAgent(slot.id,instructions, @@ -620,15 +613,15 @@ export async function openProductionOperations(host) { }).catch(async error=>{ generation.set(slot.id,{slotId:slot.id,phase:'failed',reason:error.message}); await save(slot,{reason:error.message}); - }).finally(async()=>{ + }).finally(()=>{ jobs.delete(slot.id); - await notice('子代理已有回执'); + notice('子代理已有回执'); }); generation.delete(slot.id); jobs.set(slot.id,{row,run}); assigned.push({id:slot.id,state:'assigned'}); } - if(assigned.length)await notice('子代理正在制作'); + if(assigned.length)notice('子代理正在制作'); return {assigned,...(unmatched.length?{unmatched}:{})}; }, async await_image_slots({slotIds}){ @@ -714,7 +707,7 @@ export async function openProductionOperations(host) { const slot=matches(slotId); const result=await serialize(()=>operate(slot,'adopt_candidate',{candidateId,fit},signal)); if(result.phase==='complete'&&candidates.has(candidateId))candidates.get(candidateId).status='adopted'; - await notice('画布回填回执'); + notice('画布回填回执'); return result; }, async retire_production_image({slotId,candidateId,reason},signal){ @@ -734,7 +727,7 @@ export async function openProductionOperations(host) { candidates.delete(candidateId); host.generatedCandidates?.delete(candidateId); await store.appendEvent({type:'production_image_retired',slotId:slot.id,candidateId,reason,requestId:result.requestId}); - await notice('已清理退回的候选图'); + notice('已清理退回的候选图'); } return result; }, diff --git a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md index 40631012..2ad6d25a 100644 --- a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md +++ b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md @@ -8,6 +8,6 @@ description: Use product image sources and Image Request tools in PhotoCraft. 从本项目企业 Skill 及其引用取得图位制作、素材选择、审稿和返工规则。用 `read_production_knowledge` 回读已锁定的文件,工具回执会注明版次。 - `read_slot_images` 读取实拍、模板参考和候选。`use_product_image` 可直接用原片或指定裁切区域。 -- `prepare_image_request` 保存完整生图请求。`read_image_request` 回读正式文本、参考顺序与模型参数。用回读的版本和内容 hash 调 `freeze_image_request`。`dispatch_image_request` 接收冻结 ID。 +- 审阅 `prepare_image_request` 回执中的正式文本、参考顺序与模型参数。用该回执的 `requestId`、`revision` 和 `requestSpecHash` 确认 `dispatch_image_request` 的 `requestId`、`expectedRevision` 和 `expectedHash`。 - `review_image_slots` 读取候选及已有结论,`check_image_slots` 委托独立审稿。返工可带原候选号和具体改动。用 `reconcile_image_slots` 查看原请求的结果。 - 用 `native_catalog`、`native_call` 在模板允许的范围内调整画布。用 `read_output_screen` 回看实际图框与文字。 diff --git a/apps/detail-agent-pi/src/stream-presentation.mjs b/apps/detail-agent-pi/src/stream-presentation.mjs index 5b9fd0b5..bd6f8614 100644 --- a/apps/detail-agent-pi/src/stream-presentation.mjs +++ b/apps/detail-agent-pi/src/stream-presentation.mjs @@ -94,3 +94,28 @@ export class StreamOutputMeter { return { tokens, tokensPerSecond, estimated: confirmedOutput === null }; } } + +/** Deliver the newest presentation state with at most one delivery in flight. */ +export class PresentationBatch { + constructor(deliver, merge = (_pending, next) => next) { + this.deliver = deliver; + this.merge = merge; + } + + push(value) { + this.pending = this.pending === undefined ? value : this.merge(this.pending, value); + this.running ??= new Promise(resolve => setImmediate(resolve)).then(async () => { + try { + while (this.pending !== undefined) { + const next = this.pending; + this.pending = undefined; + await this.deliver(next).catch(() => {}); + } + } finally { + this.running = undefined; + } + }); + } + + flush() { return this.running; } +} diff --git a/apps/detail-agent-pi/test/conversation.test.mjs b/apps/detail-agent-pi/test/conversation.test.mjs index 0b63da3a..62662d2e 100644 --- a/apps/detail-agent-pi/test/conversation.test.mjs +++ b/apps/detail-agent-pi/test/conversation.test.mjs @@ -225,18 +225,43 @@ test('inactive activity delivery preserves the original assistant/tool transcrip }finally{await x.close();} }); -test('UI detachment never swallows transport or account errors and never retries a sent end',async()=>{ - for(const [method,message] of [['delta','画布连接中断,原操作需核查'],['activity','本地Agent会话或账户已改变'],['end','画布连接中断,结束动作结果未知']]){ +test('presentation errors leave the original result intact while an end failure is reported once',async()=>{ + for(const method of ['delta','activity','end']){ let attempts=0; - const x=await fixture(()=>method==='activity'?tool('memory_search',{query:'讨论'}):sse({content:'原回复。'})); + const message='本机通知未确认'; + const x=await fixture((_payload,n)=>method==='activity'&&n===1?tool('memory_search',{query:'讨论'}):sse({content:'原回复。'})); x.native[method]=async()=>{attempts++;throw Error(message);}; try{ - await assert.rejects(x.host.prompt('当前项目普通讨论'),new RegExp(message)); - assert.equal(attempts,1);assert.equal(x.requests.length,1);assert.notEqual(x.host.canvasNotificationsDetached,true); + if(method==='end')await assert.rejects(x.host.prompt('当前项目普通讨论'),new RegExp(message)); + else assert.equal((await x.host.prompt('当前项目普通讨论')).text,'原回复。'); + assert.equal(attempts,method==='activity'?2:1); + assert.equal(x.requests.length,method==='activity'?2:1); + assert.notEqual(x.host.canvasNotificationsDetached,true); }finally{await x.close();} } }); +test('a blocked presentation delivery does not stop a tool or the next original model round',async()=>{ + let release,started; + const held=new Promise(resolve=>{release=resolve;}); + const nextRound=new Promise(resolve=>{started=resolve;}); + const x=await fixture((_payload,n)=>{ + if(n===1)return sse({content:'现在查一下。',tool_calls:[{index:0,id:'search',type:'function', + function:{name:'memory_search',arguments:'{"query":"讨论"}'}}]},'tool_calls'); + started(); + return sse({content:'核对完成。'}); + }); + x.native.delta=()=>held; + const result=x.host.prompt('当前项目普通讨论'); + try{ + await Promise.race([nextRound,new Promise((_,reject)=>{const timer=setTimeout(()=>reject(Error('展示回执阻止了后续模型交互')),2000);timer.unref();})]); + assert.equal(x.requests.length,2); + }finally{ + release(); + try{assert.equal((await result).text,'核对完成。');}finally{await x.close();} + } +}); + test('handover rejects the proposed write and skips subsequent editing inference, then a new question works',async()=>{ const x=await fixture((_payload,n,native)=>{ if(n===1)return tool('canvas_read',{}); @@ -396,14 +421,13 @@ test('a desktop turn continues past 12 useful model calls',async()=>{ }finally{await x.close();} }); -test('first reply text reaches the canvas even when a reasoning update just arrived',async()=>{ +test('a burst of text and reasoning delivers the complete coalesced reply to the canvas',async()=>{ const chunk=delta=>'data: '+JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta,finish_reason:null}]})+'\n\n'; const x=await fixture(()=>chunk({reasoning_content:'检查资料'})+chunk({content:'第一段'})+sse({content:'。第二段。'})); const presented=[]; x.native.delta=async text=>{presented.push(text);}; try{ assert.equal((await x.host.prompt('用两句短话介绍一下你自己')).text,'第一段。第二段。'); - assert.ok(presented.includes('第一段')); - assert.ok(presented.includes('第一段。第二段。')); + assert.deepEqual(presented.filter(Boolean),['第一段。第二段。']); }finally{await x.close();} }); diff --git a/apps/detail-agent-pi/test/desktop-daemon.test.mjs b/apps/detail-agent-pi/test/desktop-daemon.test.mjs index 814975dd..372c2129 100644 --- a/apps/detail-agent-pi/test/desktop-daemon.test.mjs +++ b/apps/detail-agent-pi/test/desktop-daemon.test.mjs @@ -107,9 +107,9 @@ test('a pause on the bound production stops further tools and leaves the origina const config = { productProduction: true, documentId: 27, project: 'desk', scope: 'account-a' }; const { frames, send } = daemonFixture(t, { runSession: async (_, call, _broker, _recovery, signal) => { - await assert.rejects(call('pi-detail-images', { original: 'original-1' }), /制作已停止/); + await assert.rejects(call('pi-detail-images', { original: 'original-1' }), {category:'cancelled',dispatched:true}); cancelled = signal.aborted; - await assert.rejects(call('pi-detail-images', { original: 'original-1' }), /制作已停止/); + await assert.rejects(call('pi-detail-images', { original: 'original-1' }), {category:'cancelled',dispatched:false}); return { pending: ['original-1'], unknown: true, reposted: false }; }, }); @@ -126,3 +126,23 @@ test('a pause on the bound production stops further tools and leaves the origina type: 'complete', runId, value: { pending: ['original-1'], unknown: true, reposted: false }, }); }); + +test('presentation notifications do not wait for replies and the terminal command still does', async t => { + const {frames,send}=daemonFixture(t,{ + runSession:async(_config,call)=>{ + await call('pi-delta',{text:'正在写'}); + await call('pi-activity',{text:'读取画布'}); + await call('pi-end',{text:'写完'}); + return {text:'写完'}; + }, + }); + send({type:'run',runId,config:{}}); + await tick(); + assert.deepEqual(frames.slice(1).map(({type,action})=>[type,action]),[ + ['presentation','pi-delta'],['presentation','pi-activity'],['canvas','pi-end'], + ]); + const {id}=frames.at(-1); + send({type:'canvas_result',runId,id,value:null}); + await tick(); + assert.equal(frames.at(-1).type,'complete'); +}); diff --git a/apps/detail-agent-pi/test/native-wire.test.mjs b/apps/detail-agent-pi/test/native-wire.test.mjs index 5d147df0..a607cd17 100644 --- a/apps/detail-agent-pi/test/native-wire.test.mjs +++ b/apps/detail-agent-pi/test/native-wire.test.mjs @@ -1,3 +1,4 @@ +import { BridgeError } from '../src/bridge-error.mjs'; import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; @@ -662,6 +663,37 @@ test('production exposes direct native tools and Pi file tools',async()=>{ } finally {await x.close();} }); +test('Pi runs independent production reads from the same model turn concurrently',async()=>{ + let release; + const gate=new Promise(resolve=>{release=resolve;}); + const started=[]; + const read=async name=>{ + started.push(name); + if(started.length===2)release(); + await gate; + return {items:[]}; + }; + const x=await setup((_,round)=>{ + const calls=round===1?['plan_production','native_catalog']:['finish_production']; + return sse({tool_calls:calls.map((name,index)=>({index,id:name,type:'function', + function:{name,arguments:round===1?'{}':'{"revision":1}'}}))},'tool_calls'); + },undefined,{plan:()=>read('plan_production'),canvas:{ + nativeCatalog:()=>read('native_catalog'),nativeCall(){}, + }}); + const result=x.host.prompt('读取制作计划和原生命令目录'); + try{ + await Promise.race([gate,new Promise((_,reject)=>{ + const timer=setTimeout(()=>reject(Error('同批只读工具没有并发开始')),2000); + timer.unref(); + })]); + assert.equal(started.length,2); + assert.equal((await result).production.complete,true); + }finally{ + release(); + try{await result;}finally{await x.close();} + } +}); + test('production publishes direct native commands and no duplicate conversation tools',async()=>{ const executed=[]; const x=await setup((_,request)=>{ @@ -687,6 +719,15 @@ test('production publishes direct native commands and no duplicate conversation for(const name of ['plan_production','native_catalog','native_call','native_reconcile','read','bash','tool_search','codemode']){ assert.ok(x.host.session.getToolDefinition(name),name); } + for(const name of ['read_image_request','freeze_image_request']){ + assert.equal(x.host.session.getToolDefinition(name),undefined,name); + } + for(const name of ['plan_production','native_catalog','read_production_knowledge','read_copy_fields','read_slot_images','review_image_slots','read_output_screen']){ + assert.notEqual(x.host.session.getToolDefinition(name).executionMode,'sequential',name); + } + for(const name of ['native_call','prepare_image_request','dispatch_image_request','finish_production']){ + assert.equal(x.host.session.getToolDefinition(name).executionMode,'sequential',name); + } assert.equal((await x.host.prompt('完成制作')).production.complete,true); assert.deepEqual(executed,[{revision:1,method:'engine.execute',params:{command:'type.edit',params:{layer:2,text:'New'}}}]); const row=x.host.manager.getBranch().find(({message})=>message?.toolCallId==='edit-1')?.message; @@ -713,9 +754,10 @@ test('a temporary write wait and a rejected native edit can be corrected in the requestWrite: async revision => ++leases === 1 ? {allowed: false, revision, retryWrite: true, detailWriteWaiting: true} : {allowed: true, revision}, - nativeCall: async () => ++edits === 1 - ? {completed: true, executed: false, error: '画布已修改,请先读取当前修订'} - : {completed: true, executed: true, revision: 2}, + nativeCall: async () => { + if (++edits === 1) throw new BridgeError('画布已修改,请先读取当前修订','revision_conflict',{dispatched:false}); + return {completed:true,executed:true,revision:2}; + }, }, }); try { diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index 16009221..8cbe63d6 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -20,32 +20,25 @@ function imageBridge(host,dispatch,id=()=>randomUUID()) { prepared.set(requestId,{receipt,args}); return structuredClone(receipt); } - const request=prepared.get(args.requestId??args.frozenRequestId); - assert.ok(request); - if(action==='read')return structuredClone(request.receipt); - if(action==='freeze'){ - assert.equal(args.expectedHash,request.receipt.requestSpecHash); - assert.equal(args.expectedRevision,request.receipt.revision); - request.receipt.frozen=true; - return structuredClone(request.receipt); - } assert.equal(action,'dispatch'); - assert.deepEqual(Object.keys(args),['frozenRequestId']); - assert.equal(request.receipt.frozen,true); - return dispatch(request.args,args.frozenRequestId); + assert.deepEqual(Object.keys(args),['requestId','expectedRevision','expectedHash','slotId']); + const request=prepared.get(args.requestId); + assert.ok(request); + assert.equal(args.slotId,request.receipt.slotId); + if(args.expectedHash!==request.receipt.requestSpecHash||args.expectedRevision!==request.receipt.revision){ + throw new BridgeError('生图请求版本已变化,请重新准备'); + } + return dispatch(request.args,args.requestId); }; } -async function freezeForDispatch(actions,options) { - const draft=await actions.prepare_image_request(options); - const saved=await actions.read_image_request({requestId:draft.requestId}); - await actions.freeze_image_request({requestId:saved.requestId,expectedRevision:saved.revision,expectedHash:saved.requestSpecHash}); - return {frozenRequestId:saved.requestId}; +function approve({requestId,revision,requestSpecHash}) { + return {requestId,expectedRevision:revision,expectedHash:requestSpecHash}; } async function generateAndWait(actions, {source,...request}) { let receipt; try { receipt=source==='product' ? await actions.use_product_image({slotId:request.slotId}) : - await actions.dispatch_image_request(await freezeForDispatch(actions,request)); + await actions.dispatch_image_request(approve(await actions.prepare_image_request(request))); } catch(error) { return {phase:'failed',reason:error.message}; } if(receipt.phase!=='accepted')return receipt; const {generation}=await actions.await_image_slots({slotIds:[request.slotId]}); @@ -142,9 +135,7 @@ test('a rework delegate sees the rejected image, exact previous prompt and revie const call=(name,args)=>tools.find(tool=>tool.name===name).execute('fixture-call',args).then(row=>row.details); const draft=await call('prepare_image_request',{prompt:'以同款原片直杆为准,改为单张自然光近景', reworkChange:'去掉模板构图并以原片确认支撑形状',useTemplateReference:false}); - const saved=await call('read_image_request',{requestId:draft.requestId}); - await call('freeze_image_request',{requestId:saved.requestId,expectedRevision:saved.revision,expectedHash:saved.requestSpecHash}); - await call('dispatch_image_request',{frozenRequestId:saved.requestId}); + await call('dispatch_image_request',approve(draft)); }}; imageBridge(host,async args=>{requests.push(args);return {status:'complete'};},()=> 'replacement'); const ops=await openProductionOperations(host); @@ -312,7 +303,7 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca const nextOutput={outputId:'sku_images',variantId:'white'}; const host={canvas,store,productionGoal:{outputId,variantId,pendingOutputs:[nextOutput]}}; imageBridge(host,async(_args,id)=>{submissions.push(id);prepared.resolve();await submit.promise;return {status:'complete'};}); - const actions=await openProductionOperations(host); + let actions=await openProductionOperations(host); assert.deepEqual((await actions.plan_production()).pendingOutputs,[nextOutput]); await actions.write_copy_fields({revision:3,recordOnly:true,items:[{layer:5,text:'木纹展示',sources:[],pictures:[]}]}); const request={slotId,source:'generate',prompt:'给商品正面留出文字区域'}; @@ -320,14 +311,16 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca creation++; const draft=await actions.prepare_image_request(request); assert.equal(draft.spec.prompt,request.prompt); - await assert.rejects(actions.dispatch_image_request({frozenRequestId:draft.requestId}),/先回读并冻结/u); - const saved=await actions.read_image_request({requestId:draft.requestId}); - await actions.freeze_image_request({requestId:saved.requestId,expectedRevision:saved.revision,expectedHash:saved.requestSpecHash}); assert.equal(submissions.length,0); - const frozen={frozenRequestId:saved.requestId}; - assert.equal((await actions.dispatch_image_request(frozen)).phase,'accepted'); + const approved=approve(draft); + actions=await openProductionOperations(host); + assert.equal((await actions.dispatch_image_request({...approved,expectedHash:'stale-digest'})).phase,'accepted'); + const {generation:[staleApproval]}=await actions.await_image_slots({slotIds:[slotId]}); + assert.equal(staleApproval.phase,'failed'); + assert.equal(submissions.length,0); + assert.equal((await actions.dispatch_image_request(approved)).phase,'accepted'); await prepared.promise; - assert.equal((await actions.dispatch_image_request(frozen)).phase,'already_running'); + assert.equal((await actions.dispatch_image_request(approved)).phase,'already_running'); assert.equal((await actions.review_image_slots({slotIds:[slotId]})).pictures[0].generation.phase,'accepted'); assert.deepEqual((await actions.write_copy_fields({revision:3,recordOnly:true, items:[{layer:5,text:'木纹展示',sources:[],pictures:[]}]})).appliedLayers,[5]); 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 6fa17804..7baa9018 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs @@ -80,7 +80,7 @@ impl Daemon { number => Some(u32::try_from(number.as_u64().ok_or("模型桥身份无效")?).map_err(|_| "模型桥身份无效")?), }; } - Some("canvas" | "complete") if state.ready => { + Some("canvas" | "presentation" | "complete") if state.ready => { let (run, sender) = state.active.as_ref().ok_or("本机Agent收到无主回合消息")?; if value["runId"].as_str() != Some(run.as_str()) { return Err("本机Agent回合身份不一致".into()); } sender.send(Ok(value)).map_err(|_| "原回合已关闭")?; @@ -316,7 +316,7 @@ mod tests { fn synthetic_daemon_reuses_one_child_and_rejects_foreign_frames() { let script = r#"const rl=require('node:readline').createInterface({input:process.stdin}); console.log(JSON.stringify({type:'ready'})); -rl.on('line',line=>{const x=JSON.parse(line);if(x.type==='run')console.log(JSON.stringify({type:'complete',runId:x.runId,value:{ok:true}}));if(x.type==='knowledge'){console.log(JSON.stringify({type:'knowledge_progress',id:x.id,value:{phase:'download',completed:1,fileCount:2}}));if(!x.input.slow)console.log(JSON.stringify({type:'knowledge_result',id:x.id,value:{ok:true}}));}});"#; +rl.on('line',line=>{const x=JSON.parse(line);if(x.type==='run'){console.log(JSON.stringify({type:'presentation',runId:x.runId,action:'pi-delta'}));console.log(JSON.stringify({type:'complete',runId:x.runId,value:{ok:true}}));}if(x.type==='knowledge'){console.log(JSON.stringify({type:'knowledge_progress',id:x.id,value:{phase:'download',completed:1,fileCount:2}}));if(!x.input.slow)console.log(JSON.stringify({type:'knowledge_result',id:x.id,value:{ok:true}}));}});"#; let mut command = Command::new("node"); command.args(["-e", script]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()); #[cfg(windows)] @@ -350,7 +350,9 @@ rl.on('line',line=>{const x=JSON.parse(line);if(x.type==='run')console.log(JSON. assert!(daemon.begin("overlap", &json!({})).is_err()); assert!(daemon.handle(json!({"type":"complete","runId":"foreign","value":{}})).is_err()); let frame = receiver.recv_timeout(Duration::from_secs(5)).unwrap().unwrap(); - assert_eq!(frame["runId"], run); + assert_eq!((frame["type"].as_str(), frame["runId"].as_str()), (Some("presentation"), Some(run))); + let frame = receiver.recv_timeout(Duration::from_secs(5)).unwrap().unwrap(); + assert_eq!((frame["type"].as_str(), frame["runId"].as_str()), (Some("complete"), Some(run))); assert_eq!(daemon.pid, pid); daemon.end(run); } 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 03d67ade..1b57b71c 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -1,6 +1,7 @@ //! Canvas-first project state. Template selection fixes structure; it does not //! manufacture an AI plan. Original A/B files and image journals stay intact. use super::{json, Path, Value, R, Uuid, PathBuf, hash, original_project_present, read_json, template_slots, Digest, sync, write_json, fs, Sha256, creation, mpsc, Event, template_workflow, now, Document, Backend, production_profile, slot_canvas, Arc}; +use photocraft_ui_egui::jiansun::BridgeFailure; const FILE: &str = "canvas-workspace.json"; const CANDIDATE: &str = "canvas-candidate.json"; @@ -3212,7 +3213,7 @@ impl Backend { json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"workflow":workflow,"creation":enrich_creation(dir,creation::load(dir)?)?,"pending":workflow["pending"],"canvasFirst":true}), ) } - pub(super) fn production_image_request(&mut self, doc: u64, binding: &Value, events: &mpsc::Sender, ctx: &egui::Context) -> R { + pub(super) fn production_image_request(&mut self, doc: u64, binding: &Value, events: &mpsc::Sender, ctx: &egui::Context) -> Result { self.ensure_owner(doc)?; let dir = self.project_dir(doc)?; original_project_present(&dir)?; @@ -3226,63 +3227,58 @@ impl Backend { input["detailBatch"] = json!(true); input["detailWorkspace"] = binding["scope"].clone(); input["prepareRequest"] = json!(true); - return self.canvas_workspace_action("slot-append", &input, events, ctx); + return self.canvas_workspace_action("slot-append", &input, events, ctx).map_err(BridgeFailure::from); } - let id = uuid(if phase == "dispatch" { &request["frozenRequestId"] } else { &request["requestId"] }, "生图请求")?; - let task = super::images::read_image_request(&dir, &id)?; - let belongs = |task: &Value| { - task["doc"] == doc && task["accountScope"] == self.scope() + if phase != "dispatch" { return Err("生图请求动作无效".into()); } + let id = uuid(&request["requestId"], "生图请求")?; + let (task, _dispatch) = { + let _guard = sync::context_guard(); + let mut task = super::images::read_image_request(&dir, &id)?; + let belongs = task["doc"] == doc && task["accountScope"] == self.scope() && task["localProjectId"].as_str() == self.locations.get(&doc).map(String::as_str) && task["origin"] == self.origin && task["outputScope"] == binding["scope"]["outputId"] + && task["slotBinding"]["slotId"] == request["slotId"] && ["workspaceId","templateHash","structureHash","variantId"].iter().all(|field| - task["slotBinding"][*field] == binding["scope"][if *field=="workspaceId" {"id"}else{*field}]) + task["slotBinding"][*field] == binding["scope"][if *field=="workspaceId" {"id"}else{*field}]); + if !belongs { return Err("生图请求不属于当前账户、项目、工作画布或图位".into()); } + super::images::freeze_image_request_locked(&dir, &mut task, request)?; + let Some(dispatch) = lock_candidate_dispatch(&dir, &id)? else { + return Ok(json!({"phase":"running","candidateId":id})); + }; + (task, dispatch) }; - if !belongs(&task) { return Err("生图请求不属于当前账户、项目或工作画布".into()); } - match phase { - "read" => Ok(super::images::image_request_receipt(&task)), - "freeze" => super::images::freeze_image_request(&dir, &id, request), - "dispatch" => { - if !task["frozenAt"].is_number() { return Err("请先回读并冻结生图请求".into()); } - let Some(_dispatch) = lock_candidate_dispatch(&dir, &id)? else { - return Ok(json!({"phase":"running","candidateId":id})); - }; - let task = super::images::read_image_request(&dir, &id)?; - if task["phase"] != "prepared" { - // Original outcome, including unknown, cannot enter the POST path again. - let record = reconcile_candidate(&dir, &task)?; - return Ok(candidate_receipt(&record)); - } - super::images::validate_frozen_spec(&dir, &task)?; - let slot = &task["slotBinding"]; - let state = load_detail_workspace(&dir)?; - let record = &task["candidateRecord"]; - if !candidate_uses_current_inputs(&dir, &state, record, slot["variantId"].as_str().ok_or("花色缺失")?)? { - return Err("商品资料或制作依据已变化,请重新准备请求".into()); - } - if candidate_path(&dir, &id)?.exists() { - let existing = read_candidate(&dir, &id)?; - if existing["phase"] != "prepared" || existing["retirement"].is_object() { - return Ok(candidate_receipt(&existing)); - } - } else { - reserve(&dir, state, record)?; - } - publish_prepared(events, self.canvas_workspace_result(doc, &dir)?)?; - ctx.request_repaint(); - validate_image_context(&dir, Some(slot))?; - let call = self.image_job(None, &json!({"doc":doc,"frozenRequestId":id}), false, events, ctx); - let (receipt, failure) = self.settle_image_candidate(&dir, doc, &id, slot, call, events, ctx)?; - let mut receipt = receipt; - if receipt["status"] == "failed" && let Some(message) = failure { - receipt["message"] = json!(message); - } - let snapshot = operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(receipt.clone()), None); - let _ = events.send(Event::Json("slot-append".into(), Ok(snapshot))); - ctx.request_repaint(); - Ok(receipt) - } - _ => Err("生图请求动作无效".into()), + let original_error = |error| BridgeFailure::new("image_request_failed", false, true, error); + if task["phase"] != "prepared" { + return reconcile_candidate(&dir, &task).map(|record| candidate_receipt(&record)).map_err(original_error); } + let slot = &task["slotBinding"]; + let state = load_detail_workspace(&dir)?; + let record = &task["candidateRecord"]; + if !candidate_uses_current_inputs(&dir, &state, record, slot["variantId"].as_str().ok_or("花色缺失")?)? { + return Err("商品资料或制作依据已变化,请重新准备请求".into()); + } + if candidate_path(&dir, &id)?.exists() { + let existing = read_candidate(&dir, &id)?; + if existing["phase"] != "prepared" || existing["retirement"].is_object() { + return Ok(candidate_receipt(&existing)); + } + } else { + reserve(&dir, state, record)?; + } + publish_prepared(events, self.canvas_workspace_result(doc, &dir)?)?; + ctx.request_repaint(); + validate_image_context(&dir, Some(slot))?; + let call = self.image_job(None, &json!({"doc":doc,"frozenRequestId":id}), false, events, ctx); + let dispatch_error = |error, backend: &Self| BridgeFailure::new("image_request_failed", false, backend.image_dispatch_may_have_started(doc, &id), error); + let (mut receipt, failure) = self.settle_image_candidate(&dir, doc, &id, slot, call, events, ctx) + .map_err(|error| dispatch_error(error, self))?; + if receipt["status"] == "failed" && let Some(message) = failure { + receipt["message"] = json!(message); + } + let snapshot = operation_receipt(self.canvas_workspace_result(doc, &dir).map_err(|error| dispatch_error(error, self))?, Some(receipt.clone()), None); + let _ = events.send(Event::Json("slot-append".into(), Ok(snapshot))); + ctx.request_repaint(); + Ok(receipt) } fn settle_image_candidate(&mut self, dir: &Path, doc: u64, id: &str, binding: &Value, mut call: R, @@ -4509,6 +4505,48 @@ mod tests { fixture } + #[test] + fn image_confirmation_checks_the_original_slot_and_revision_before_freezing() { + let fixture = fixture(); + let mut backend = Backend::new(fixture.dir.join("profile")).unwrap(); + let doc = 1; + backend.bind_new(doc); + let dir = backend.project_dir(doc).unwrap(); + write_json(&dir.join("context.json"), &json!({"doc":doc})).unwrap(); + let creation = creation::load(&dir).unwrap(); + write_json(&dir.join("creation.json"), &creation).unwrap(); + let state = load(&fixture.dir).unwrap(); + persist(&dir, state.clone(), 0).unwrap(); + let id = Uuid::new_v4().to_string(); + let slot = "saved-slot"; + let scope = json!({"id":state["id"],"templateHash":state["template"]["contentHash"], + "structureHash":state["structureHash"],"outputId":"detail","variantId":state["activeVariantId"]}); + let mut task = json!({"id":id,"doc":doc,"localProjectId":backend.locations.get(&doc),"accountScope":backend.scope(), + "origin":backend.origin,"outputScope":"detail","phase":"prepared","requestSpecRevision":1,"references":[], + "prompt":"正式提示词","candidateRecord":{"inputHash":"stale-product"}, + "slotBinding":{"slotId":slot,"workspaceId":scope["id"],"templateHash":scope["templateHash"], + "structureHash":scope["structureHash"],"variantId":scope["variantId"]}}); + let spec = super::super::images::image_request_receipt(&task)["spec"].to_string(); + task["requestSpecHash"] = json!(hash(&spec)); + let file = dir.join("image-jobs").join(&id).join("task.json"); + write_json(&file, &task).unwrap(); + let (events, _) = mpsc::channel(); + let ctx = egui::Context::default(); + let mut approval = json!({"action":"dispatch","scope":scope,"request":{ + "requestId":id,"slotId":"other-slot","expectedRevision":1,"expectedHash":task["requestSpecHash"]}}); + for (field, value) in [("slotId",json!("other-slot")), ("expectedRevision",json!(2)), ("expectedHash",json!("other-hash"))] { + let prior = std::mem::replace(&mut approval["request"][field], value); + let failure = backend.production_image_request(doc, &approval, &events, &ctx).unwrap_err(); + assert!(!failure.dispatched); + assert!(read_json(&file).unwrap()["frozenAt"].is_null()); + approval["request"][field] = if field == "slotId" { json!(slot) } else { prior }; + } + let failure = backend.production_image_request(doc, &approval, &events, &ctx).unwrap_err(); + assert!(!failure.dispatched); + assert!(read_json(&file).unwrap()["frozenAt"].is_number()); + assert_eq!(read_json(&file).unwrap()["phase"], "prepared"); + } + #[test] fn product_start_reports_runnable_outputs_without_opening_a_canvas() { let fixture = fixture(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs index 717d9941..5664b493 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs @@ -128,19 +128,20 @@ pub(super) fn validate_frozen_spec(dir: &Path, task: &Value) -> R<()> { Ok(()) } -pub(super) fn freeze_image_request(dir: &Path, id: &str, input: &Value) -> R { - let _guard = sync::context_guard(); - let mut task = read_image_request(dir, id)?; +// The caller holds the context guard from the scoped journal read. +pub(super) fn freeze_image_request_locked(dir: &Path, task: &mut Value, input: &Value) -> R<()> { if task["requestSpecRevision"] != input["expectedRevision"] || task["requestSpecHash"] != input["expectedHash"] { - return Err("生图请求版本已变化,请重新读取".into()); + return Err("生图请求版本已变化,请重新准备".into()); } - validate_frozen_spec(dir, &task)?; - if task["frozenAt"].is_null() { - verified_reference_bytes(&task)?; - task["frozenAt"] = json!(now()); - job_save_locked(dir, &task, false)?; + if task["phase"] == "prepared" { + validate_frozen_spec(dir, task)?; + if task["frozenAt"].is_null() { + verified_reference_bytes(task)?; + task["frozenAt"] = json!(now()); + job_save_locked(dir, task, false)?; + } } - Ok(image_request_receipt(&task)) + Ok(()) } pub(super) fn reference_preview_id(id: &str) -> bool { @@ -1164,10 +1165,16 @@ mod tests { let read = image_request_receipt(&read_image_request(&fixture.dir, &id).unwrap()); assert_eq!(read["spec"]["prompt"], prompt); assert_eq!(read["spec"]["references"][0]["sha256"], task["references"][0]["sha256"]); - assert!(freeze_image_request(&fixture.dir, &id, &json!({"expectedRevision":2,"expectedHash":read["requestSpecHash"]})).is_err()); - let frozen = freeze_image_request(&fixture.dir,&id,&json!({"expectedRevision":1,"expectedHash":read["requestSpecHash"]})).unwrap(); - assert_eq!(frozen["frozen"], true); + let mut draft = read_image_request(&fixture.dir, &id).unwrap(); + { + let _guard = sync::context_guard(); + assert!(freeze_image_request_locked(&fixture.dir, &mut draft, &json!({"expectedRevision":2,"expectedHash":read["requestSpecHash"]})).is_err()); + assert!(freeze_image_request_locked(&fixture.dir, &mut draft, &json!({"expectedRevision":1,"expectedHash":"wrong"})).is_err()); + assert!(read_image_request(&fixture.dir, &id).unwrap()["frozenAt"].is_null()); + freeze_image_request_locked(&fixture.dir, &mut draft, &json!({"expectedRevision":1,"expectedHash":read["requestSpecHash"]})).unwrap(); + } let saved = read_image_request(&fixture.dir, &id).unwrap(); + assert_eq!(image_request_receipt(&saved)["frozen"], true); let payload = image_payload(&saved, &verified_reference_bytes(&saved).unwrap()).unwrap(); assert_eq!(payload["prompt"], prompt); assert_eq!(payload["quality"], "medium"); 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 87b05387..09e770a1 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -516,7 +516,7 @@ impl Drop for DaemonTurnGuard { } fn allowed_canvas_action(action: &str) -> bool { matches!(action, "pi-begin" | "pi-state" | "pi-production-open" | "pi-ui-request" | "pi-ui-poll" | "pi-ui-cancel" | "pi-canvas-read" | "pi-template-image" | "pi-detail-images" | "pi-detail-archive" | "pi-detail-copy-fields" | "pi-detail-copy-apply" | "pi-product-screen" | "pi-image-request" | "pi-preview" | "pi-copy-options" | "pi-copy-fields" | "pi-native-catalog" | "pi-native-call" | "pi-native-poll" - | "pi-delta" | "pi-reply" | "pi-activity" | "pi-context-usage" | "pi-write-request" | "pi-edit" | "pi-end" | "pi-workflow-read" + | "pi-reply" | "pi-context-usage" | "pi-write-request" | "pi-edit" | "pi-end" | "pi-workflow-read" | "pi-workflow-navigate" | "pi-workflow-propose" | "pi-workflow-execute" | "pi-workflow-poll" | "pi-native-reconcile" | "pi-edit-reconcile" | "pi-workflow-reconcile") } @@ -667,7 +667,13 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender } }; if value["runId"] != daemon_run { return Err("本机Agent回合身份不一致".into()); } - if value["type"] == "canvas" { + if value["type"] == "presentation" { + let action = value["action"].as_str().filter(|action| matches!(*action, "pi-delta" | "pi-activity")) + .ok_or("Agent展示动作未授权")?; + let (reply, _) = mpsc::channel(); + let _ = events.send(Event::PiAction(action.into(), value["input"].clone(), reply)); + ctx.request_repaint(); + } else if value["type"] == "canvas" { let request_id = value["id"].as_u64().filter(|id| *id > 0).ok_or("Agent请求身份无效")?; if !request_ids.insert(request_id) { return Err("Agent请求身份重复".into()); } let action = value["action"].as_str().filter(|action| allowed_canvas_action(action)).ok_or("Agent本机动作未授权")?; @@ -704,11 +710,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender let result = worker.production_image_request(doc, &v, &task_events, &task_ctx); let reply = match result { Ok(value) => json!({"value":value}), - Err(error) => { - let dispatched = v["request"]["frozenRequestId"].as_str() - .is_some_and(|id| worker.image_dispatch_may_have_started(doc, id)); - json!({"error":BridgeFailure::new("image_request_failed", false, dispatched, error).wire()}) - } + Err(error) => json!({"error":error.wire()}), }; let _ = transport.reply(&run, &id, &reply); })); @@ -842,6 +844,8 @@ mod tests { for action in ["pi-native-reconcile", "pi-edit-reconcile", "pi-workflow-reconcile"] { assert!(allowed_canvas_action(action), "{action} must reach the scope-checking native adapter"); } + assert!(allowed_canvas_action("pi-end")); + assert!(!allowed_canvas_action("pi-delta") && !allowed_canvas_action("pi-activity")); for action in ["pi-reconcile", "pi-native-reconcile-write", "pi-edit-reconcile-apply", "pi-workflow-reconcile-retry", "preview-accept"] { assert!(!allowed_canvas_action(action), "{action} must not bypass the explicit action allowlist"); } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs index b47fc7f3..f7bdb36c 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs @@ -1,7 +1,7 @@ //! Pi's scoped bridge to the existing native command/control dispatcher. //! Command discovery uses native metadata and parameter documentation, not a //! second implementation of editor features or invented JSON schemas. -use super::{json, Value, VecDeque, Workspace, PhotocraftApp}; +use super::{json, Value, VecDeque, Workspace, PhotocraftApp, BridgeFailure}; use crate::control::{ControlRequest, Outcome}; use photocraft_doc::LayerId; use photocraft_engine::{CommandScope, jobs::JobId}; @@ -511,7 +511,7 @@ fn register_job(w: &mut Workspace, app: &PhotocraftApp, job: JobId, document: u6 /// The method is fixed to the current native control capabilities; no arbitrary /// IPC, paths, shell programs, model calls or new authentication are forwarded. -pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Context, input: &Value) -> Result { +pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Context, input: &Value) -> Result { arguments(input, &["run", "documentId", "revision", "method", "params"])?; let method = input["method"].as_str().filter(|method| METHODS.contains(method)).ok_or("此原生控制方法未开放")?; let params = input["params"].as_object().ok_or("原生控制params须为对象")?; @@ -539,7 +539,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte Ok(current) => current, Err(error) if w.pi_request_scope["productProduction"] == true => return Ok(json!({"executed":false,"completed":true,"pending":false,"error":error})), - Err(error) => return Err(error), + Err(error) => return Err(error.into()), }; if input["revision"].as_u64() != Some(before) && !read { let error = "原生操作修订已过期,未执行"; @@ -554,7 +554,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte if !read { w.agent_native.make_room()?; } let (mut scope, token) = w.agent_native.scope(input["run"].as_str().unwrap_or(""), document, index)?; if method == "engine.execute" { - if let Some(error) = authority(w, app, &scope, &command, &native_params["params"]) { return Err(error); } + if let Some(error) = authority(w, app, &scope, &command, &native_params["params"]) { return Err(error.into()); } if photocraft_engine::commands::find(&command).is_none() && !crate::menus::is_enabled(app, &command) { return Err("当前原生界面命令不可用".into()); } @@ -595,37 +595,39 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte let outcome = crate::control::handle(app, ctx, &request); app.automation_input = old_automation; app.session.command_scope = old_scope; - let revision = app.session.active().filter(|state| state.doc.id.0 == document).map(|state| state.revision).ok_or("原生操作改变了项目身份,结果待核查")?; + let unknown = |message: String| BridgeFailure::new("result_unknown", false, !read, message); + let revision = app.session.active().filter(|state| state.doc.id.0 == document).map(|state| state.revision).ok_or_else(|| unknown("原生操作改变了项目身份,结果待核查".into()))?; let result = match outcome { Outcome::Done(value) => { if value["ok"] != true { let error = value["error"].as_str().unwrap_or("原生控制未返回成功结果"); + if value["ok"] == false && method == "ui.set" { return Err(error.into()); } if value["ok"] == false && method == "engine.execute" && !read && revision == before { return Ok(json!({"dispatched":true,"executed":false,"pending":false,"completed":true, "method":method,"command":command,"revision":revision,"error":error})); } - return Err(error.to_owned()); + return Err(unknown(error.to_owned())); } let result = value["result"].clone(); if result["pending"] == true { - let job = result["job"].as_u64().map(JobId).ok_or("原生任务未返回可核查编号")?; - register_job(w, app, job, document, before, &command, token)?; - let result = w.agent_native.project_result(result)?; + let job = result["job"].as_u64().map(JobId).ok_or_else(|| unknown("原生任务未返回可核查编号".into()))?; + register_job(w, app, job, document, before, &command, token).map_err(unknown)?; + let result = w.agent_native.project_result(result).map_err(unknown)?; let mut value = receipt(w, document, (before, revision), method, &command, &result, true); value["job"] = json!(job.0); value["templatePolicy"] = json!(template_policy); - let receipt = w.agent_native.record(value)?; + let receipt = w.agent_native.record(value).map_err(unknown)?; return Ok(json!({"dispatched":true,"executed":false,"pending":true,"completed":false,"job":job.0,"method":method,"command":command,"beforeRevision":before,"revision":revision,"result":result,"receipt":receipt})); } result } Outcome::AfterJob(job) => { - register_job(w, app, job, document, before, &command, token)?; + register_job(w, app, job, document, before, &command, token).map_err(unknown)?; let result = json!({"job":job.0,"pending":true}); let mut value = receipt(w, document, (before, revision), method, &command, &result, true); value["job"] = json!(job.0); value["templatePolicy"] = json!(template_policy); - let receipt = w.agent_native.record(value)?; + let receipt = w.agent_native.record(value).map_err(unknown)?; return Ok(json!({"dispatched":true,"executed":false,"pending":true,"completed":false,"job":job.0,"method":method,"command":command,"beforeRevision":before,"revision":revision,"receipt":receipt})); } Outcome::AfterInput => { @@ -635,7 +637,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte return Ok(json!({"dispatched":true,"executed":false,"pending":true,"completed":false,"inputQueued":true,"method":method,"beforeRevision":before,"revision":revision, "error":"原生输入等待尚未核查,不会重复派发"})); } - Outcome::Screenshot { .. } => return Err("此原生调用意外产生截图等待,结果待核查".into()), + Outcome::Screenshot { .. } => return Err(unknown("此原生调用意外产生截图等待,结果待核查".into())), }; if !read { w.expected_revision = revision; @@ -644,8 +646,9 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte w.sync_dirty = true; } } - let result = scoped_read_result(w, app, method, result, w.agent_native.scope.as_ref().ok_or("原生能力已失效")?)?; - let result = w.agent_native.project_result(result)?; + let scope = w.agent_native.scope.as_ref().ok_or_else(|| unknown("原生能力已失效".into()))?; + let result = scoped_read_result(w, app, method, result, scope).map_err(unknown)?; + let result = w.agent_native.project_result(result).map_err(unknown)?; let state = current(w, app); let changed = state != before_state || app.ui != before_ui || app.session.tools.brush != before_brush || app.session.tools.foreground != before_foreground || app.session.tools.background != before_background @@ -654,7 +657,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte let mut value = receipt(w, document, (before, revision), method, &command, &result, false); value["changed"] = json!(changed); value["templatePolicy"] = json!(template_policy); - Some(w.agent_native.record(value)?) + Some(w.agent_native.record(value).map_err(unknown)?) }; Ok(json!({"executed":true,"pending":false,"completed":true,"method":method,"command":command,"beforeRevision":before,"revision":revision, "changed":changed,"result":result,"state":state,"receipt":operation_receipt})) @@ -934,7 +937,7 @@ mod tests { input["revision"] = json!(w.expected_revision); input["method"] = json!(method); input["params"] = params; - call(w, app, &egui::Context::default(), &input) + call(w, app, &egui::Context::default(), &input).map_err(String::from) } #[test] @@ -1133,6 +1136,20 @@ mod tests { } } + #[test] + fn a_rejected_native_write_reports_not_dispatched() { + let (mut w, mut app, _) = fixture(); + let mut input = base(&w); + input["revision"] = json!(w.expected_revision); + input["method"] = json!("ui.set"); + input["params"] = json!({"unexpected":true}); + let ctx = egui::Context::default(); + let error = call(&mut w, &mut app, &ctx, &input).unwrap_err(); + assert!(!error.dispatched); + input["params"] = json!({"tileGrid":true}); + assert_eq!(call(&mut w, &mut app, &ctx, &input).unwrap()["executed"], true); + } + #[test] fn an_engine_write_rejection_is_terminal_when_the_document_did_not_change() { let (mut w, mut app, _) = fixture(); 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 fcddf089..42f24815 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 @@ -56,7 +56,6 @@ fn tool_activity(w: &Workspace, event: &Value) -> Result { "plan_production" => "读取制作进度", "read_production_knowledge" => "读取制作规则", "read_copy_fields" => "读取画布文字格", "read_slot_images" => "查看图位图片", "use_product_image" => "取用商品实拍", "prepare_image_request" => "准备生图请求", - "read_image_request" => "核对生图请求", "freeze_image_request" => "冻结生图请求", "dispatch_image_request" => "生成候选图片", "delegate_image_slots" => "分派图片图位", "await_image_slots" => "等待子代理回执", "review_image_slots" => "查看图位结果", "adopt_production_image" => "回填候选图片", "retire_production_image" => "清理已退回的候选图", @@ -488,27 +487,25 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co "templateHash":w.template_workflow["templateHash"],"canvasLayerId":canvas_layer})) } "pi-image-request" => { - let action = input["action"].as_str().filter(|action| matches!(*action,"prepare"|"read"|"freeze"|"dispatch")) + let action = input["action"].as_str().filter(|action| matches!(*action,"prepare"|"dispatch")) .ok_or("生图请求动作无效")?; if w.pi_request_scope["productProduction"] != true || !w.canvas_scope_valid(app) || w.pi_request_scope["outputId"] != w.template_workflow["outputId"] || w.pi_request_scope["variantId"] != w.template_workflow["variantId"] { return Err(BridgeFailure::new("scope_changed", false, false, "生图请求未绑定本轮工作画布")); } - if action != "read" && (w.pi_write_blocked || w.agent_effects_paused) { + if w.pi_write_blocked || w.agent_effects_paused { return Err(BridgeFailure::new("write_revoked", false, false, "本轮制作已暂停,原请求保留")); } let request = &input["request"]; let allowed: &[&str] = match action { "prepare" => &["slotId","instructions","geometryReferenceIndex","prefer2k","retryOf","reworkOf","reworkChange","useTemplateReference"], - "freeze" => &["requestId","expectedRevision","expectedHash"], - "dispatch" => &["frozenRequestId"], - _ => &["requestId"], + _ => &["requestId","expectedRevision","expectedHash","slotId"], }; if request.as_object().is_none_or(|fields| fields.keys().any(|key| !allowed.contains(&key.as_str()))) { return Err("生图请求包含不适用于当前动作的字段".into()); } - if action == "prepare" && !w.template_workflow["slots"].as_array().into_iter().flatten().any(|slot| + if !w.template_workflow["slots"].as_array().into_iter().flatten().any(|slot| slot["id"] == request["slotId"] && slot["outputId"] == w.pi_request_scope["outputId"] && slot["variantId"] == w.pi_request_scope["variantId"] && slot["nativeLayerId"].is_u64()) { return Err("图位不属于本轮制作画布".into()); @@ -573,7 +570,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co "documentId":mapping["outputId"],"variantId":mapping["variantId"]})) } "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).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), "pi-preview" => super::agent_preview::create(w, app, input).map_err(BridgeFailure::from), "pi-delta" => { @@ -630,7 +627,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co if input.get("event").is_some_and(|event| !event.is_null()) { // Presentation metadata must never interrupt a real tool call. // Discard invalid/foreign events instead of storing untrusted - // text or surfacing an error to the SDK's awaited subscriber. + // text or interrupting the SDK subscriber. if let Ok(event) = tool_activity(w, &input["event"]) { record_tool_activity(w, event); } diff --git a/docs/development/xiaoyi/implementation.md b/docs/development/xiaoyi/implementation.md index 06c188f0..60c36ab4 100644 --- a/docs/development/xiaoyi/implementation.md +++ b/docs/development/xiaoyi/implementation.md @@ -805,9 +805,9 @@ PhotoCraft 工具桥统一传出分类、是否可重试、是否已派发和可 ## 架构 1.2 纠偏 · 正式生图请求 -Pi 用 `prepare_image_request` 准备完整请求。PhotoCraft 在候选任务目录保存文本、实际模型及参数、顺序与用途、归一化前后的图片身份。可通过 `read_image_request` 单独回读,使用回执中的 revision/hash 冻结。参考超过线路契约或内容有变化时,回执提示 Pi 调整输入或重新准备。 +Pi 用 `prepare_image_request` 准备完整请求。PhotoCraft 在候选任务目录保存文本、实际模型及参数、顺序与用途、归一化前后的图片身份。准备回执直接提供完整审阅内容、请求编号、修订与内容 hash。参考超过线路契约或内容有变化时,回执提示 Pi 调整输入或重新准备。 -`dispatch_image_request` 只收冻结 ID。按已保存的文本、参考和参数做协议序列化,派发前核对账户、项目、模板、商品修订与实际参考。已开始派发的图位继续查原编号。同款实拍裁切保留本机工具入口。时间轴按结构化错误分类更新,图位准备不触发网络派发。预加载按模板声明的输出清单工作。 +`dispatch_image_request` 使用模型审阅确认的请求编号、修订与 hash。PhotoCraft 回读请求并核对账户、项目、模板和图位,冻结后仅凭冻结 ID 派发。派发前核对商品修订与实际参考,协议载荷使用已保存的文本、参考和参数。已开始派发的图位继续查原编号。同款实拍裁切保留本机工具入口。时间轴按结构化错误分类更新,图位准备不触发网络派发。预加载按模板声明的输出清单工作。 本轮 Pi 19 项针对性回归与原生 4 项请求回归通过,覆盖提前派发失败、回读版本、精确参考字节、单次 POST 与原号 GET。原生画布交接 8 项通过。证据 `batch-09/frozen-image-request-20261126/task4-node-final.log`、`task4-native-final.log`、`task4-output-preload.log`。