From 210ebede701fa19fea209c5065ff16410a135d92 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Sat, 5 Dec 2026 09:59:12 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=B0=8F=E5=A3=B9=E4=BA=A4?= =?UTF-8?q?=E4=BB=98=E6=B1=87=E6=8A=A5=E4=B8=8E=E6=88=90=E5=93=81=E7=94=BB?= =?UTF-8?q?=E5=B8=83=E7=BB=91=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/detail-agent-pi/src/agent.mjs | 30 ++++++-- apps/detail-agent-pi/src/candidate-review.mjs | 38 ++++++---- .../src/output-capabilities.mjs | 2 + .../src/photocraft-extension.mjs | 2 +- apps/detail-agent-pi/src/production-goal.mjs | 75 +++++++++++-------- .../src/production-operations.mjs | 58 +++++++++----- apps/detail-agent-pi/src/production-tools.mjs | 6 +- .../src/skills/product-image-sources/SKILL.md | 24 +++--- apps/detail-agent-pi/src/stdio-canvas.mjs | 8 +- .../src/stream-presentation.mjs | 40 ++++++++++ .../test/production-goal.test.mjs | 53 ++++++++++++- .../test/production-operations.test.mjs | 10 ++- .../test/screen-review.test.mjs | 62 ++++++++++++++- apps/detail-agent-pi/test/whitelabel.test.mjs | 26 +++++++ 14 files changed, 334 insertions(+), 100 deletions(-) diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index 0f06e718..e514119c 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -2,7 +2,7 @@ import { canvasToolReceipts } from './stdio-canvas.mjs'; import { toolSchema, defineTool, normalizeToolArgs } from './tool-schema.mjs'; import { productRequestScope } from './production-recovery.mjs'; import { executeWorkflow } from './workflow-execute.mjs'; -import { PresentationBatch, StreamOutputMeter, StreamPresentation, presentText, stripProductionToolText } from './stream-presentation.mjs'; +import { PresentationBatch, StreamOutputMeter, StreamPresentation, presentText, presentProductReply, stripProductionToolText } from './stream-presentation.mjs'; import path from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import fs from 'node:fs/promises'; @@ -249,7 +249,9 @@ function observeStreamFailure(response, onFailure) { return new Response(body, {status:response.status,statusText:response.statusText,headers:response.headers}); } -const PRODUCT_VOICE = "对用户回复、状态汇报和错误说明始终使用「小壹」「画布」「工作台」「制作助手」等产品术语。不得向用户暴露底层技术或开源底座名称;工具及参考资料中的内部名称仅用于执行。"; +const PRODUCT_VOICE = `你是小壹,一位专业、温和、靠谱的电商视觉设计搭档。像设计师同事一样用自然、利落的中文短句沟通。先说用户最关心的结果,再补充有用的细节或下一步。进展说已经做到哪儿,报错说遇到什么、接下来怎么处理。 +对用户回复、状态汇报和错误说明始终使用「小壹」「画布」「工作台」「制作助手」等产品术语。不得向用户暴露底层技术或开源底座名称;工具及参考资料中的内部名称仅用于执行。 +严禁输出 Markdown 表格,分条对比用短句或项目符号。严禁复述内部字段名、状态枚举、技术布尔值、内部缓存路径、UUID 和候选哈希。把回执转述为「详情页」「主图」「SKU 图」「已全部完成」「已保存到交付文件夹」等自然中文,只说已核实的状态。`; const LIVE_CANVAS_WRITES = '写入与核验以实时 workflow_read / canvas_read 为准。waiting_save、revision_conflict 和 changedLayers 是可核对的事实。userCanvasChanges 直接提供人工改动,只处理事件指出的成品、花色和图位。保留人工修改,继续未受影响的图位。确需核对实际内容时,只读取相关图层或图位。只有写入许可明确被撤销时才停止对应写入。按真实回执说明原因,避免把保存或修订冲突说成权限被收回。'; const SYSTEM = `你是由壹点详情页的本地协作助手“小壹”。使用中文。讨论、解释或建议时直接回复;用户明确要求并确定范围后才修改画布。 @@ -1126,8 +1128,15 @@ export class DetailPiAgent { if(this.canvasEndAttempted)return; this.canvasEndAttempted=true; }else if(this.canvasEndAttempted||this.canvasNotificationsDetached)return; - if(this.productionGoal&&['delta','reply'].includes(method)&&typeof args[0]==='string'){ - args[0]=stripProductionToolText(args[0],method==='delta'); + if(['delta','reply','end'].includes(method)&&typeof args[0]==='string'){ + if(this.productionContext) args[0]=stripProductionToolText(args[0],method==='delta'); + args[0]=presentProductReply(args[0],method==='delta'); + } + if(method==='activity'){ + args[0]=presentProductReply(args[0]); + const event=args[1]; + if(event)args[1]={...event,summary:presentProductReply(event.summary), + ...(event.message?{message:presentProductReply(event.message)}:null)}; } try{return await this.canvas[method](...args);} catch(error){ @@ -1303,6 +1312,11 @@ export class DetailPiAgent { const {prompt,images}=referencedPrompt(text,referenceContent); this.requiredTool = requiredTool; const begun = await this.canvas.begin(text); + const liveOutput = this.canvas.productionOutput; + if (this.productionGoal && liveOutput) { + Object.assign(this.productionGoal,liveOutput); + this.bindGoalRequestScope(); + } this.nativeUI.start(begun?.editorText || ''); const references = frozenReferences(begun?.context); this.copyFieldsTargets = (references??[]).filter(ref=>ref.layerKind==='Type'&&ref.component==='layer') @@ -1319,8 +1333,8 @@ export class DetailPiAgent { if (!production || production.outputId) await this.readWorkflow({ section: 'overview' }); const request=begun?.context?.requestScope; const overview=this.workflowOverview; - const outputId=request?.outputId ?? overview?.outputId; - const variantId=request?.variantId ?? overview?.productVariantId; + const outputId=liveOutput?.outputId ?? overview?.outputId ?? request?.outputId; + const variantId=liveOutput?.variantId ?? overview?.productVariantId ?? request?.variantId; if (!production && outputId && variantId && (request?.productionTemplate || request?.canvasFirst || overview?.available && overview.canvasFirst)) { const choices=overview?.productEvidence?.brief?.outputVariantIds; @@ -1371,9 +1385,9 @@ export class DetailPiAgent { (this.previewCancelled&&!this.previewReceipt ? '已取消本次预览,没有应用这项修改。' : presentText(this.session.getLastAssistantText() || this.generatedCandidateReply() || '')); - const textResult=this.productionGoal?stripProductionToolText(resultText).trim(): + const textResult=presentProductReply(this.productionContext?stripProductionToolText(resultText).trim(): this.canvasNotificationsDetached&&last?.stopReason==='toolUse' - ? resultText+'\n\n原项目已切换,后续画布操作已停止。' : resultText; + ? resultText+'\n\n原项目已切换,后续画布操作已停止。' : resultText); if (!textResult.trim()) throw Error('模型没有返回正文,请更换模型后再试;本轮工具结果已保留'); await this.display.flush(); await this.updateContextUsage(null, 'ready'); diff --git a/apps/detail-agent-pi/src/candidate-review.mjs b/apps/detail-agent-pi/src/candidate-review.mjs index 162a320a..5eb81840 100644 --- a/apps/detail-agent-pi/src/candidate-review.mjs +++ b/apps/detail-agent-pi/src/candidate-review.mjs @@ -55,8 +55,8 @@ export async function reviewProductionCandidate({ } const screenCopy=mergeReviewCopy({copy,relatedCopy:input.relatedCopy,liveScreenCopy}); const reviewedCopy=copySignature(screenCopy); - const findings=screenFindings(screen.details); - const wholeScreen=screen.details.slots.length===1; + const findings=screen&&screenFindings(screen.details); + const wholeScreen=screen?.details.slots.length===1; const referenceCount=input.referenceCount; const originalIndex=input.originalReferenceIndex; const originalReference=Number.isInteger(originalIndex)&&originalIndex>=0&&originalIndex [key,Type.Optional(Type.Boolean({description}))])); const {imageIssues,overlayFixes,copyFixes,summary}=screenAssessment.properties; - const requirementsText='顶层填写候选 verdict(pass、revise 或 missing)和非空 reason。checks 可省略,按实际证据填写。整屏问题在顶层填写 imageIssues、overlayFixes 或 copyFixes。整屏通过时填 screenVerdict: pass,发现问题时可从问题列表推导 needs_fix。整屏模板风格填顶层 templateStyle;候选图的模板风格填在 checks 对象内的 templateStyle 字段。'; + const requirementsText='顶层填写候选 verdict(pass、revise 或 missing)和非空 reason。checks 可省略,按实际证据填写。'+(screen + ? '整屏问题在顶层填写 imageIssues、overlayFixes 或 copyFixes。整屏通过时填 screenVerdict: pass,发现问题时可从问题列表推导 needs_fix。整屏模板风格填顶层 templateStyle;候选图的模板风格填在 checks 对象内的 templateStyle 字段。' + : '本次只有候选原图可验,省略整屏结论与整屏问题。'); const example='最小提交示例 '+JSON.stringify({verdict:'revise',reason:'候选商品与实拍的部件形状不一致。'}); const assessment=params({ candidateId:Type.Optional(Type.String({description:'省略时使用本次受审候选。'})),verdict:StringEnum(['pass','revise','missing']), @@ -109,7 +111,7 @@ export async function reviewProductionCandidate({ 'screenCopy 是只读证据。提交文案修改建议时使用顶层 copyFixes。', example, shownFieldsGuide, - findings.facts(), + findings?.facts(), ...(guides.length?[`本次结构标注编号 ${JSON.stringify(guides.map(([id])=>id))}`]:[]), ].join('\n'); function normalize(value) { @@ -142,7 +144,8 @@ export async function reviewProductionCandidate({ const prepare=raw=>validateWorkerArguments('review_candidate',assessment,normalizeToolArgs(normalize(raw),assessment),facts); const review=tool('review_candidate',requirementsText+' '+example,assessment,raw=>{ const droppedReferences=[]; - const value=findings.normalize(prepare(raw),droppedReferences); + const prepared=prepare(raw); + const value=findings?findings.normalize(prepared,droppedReferences):prepared; if (Array.isArray(value.shownFields)) { value.shownFields=value.shownFields.flatMap((entry,index)=>{ if (!entry || typeof entry!=='object' || Array.isArray(entry)) return [entry]; @@ -160,7 +163,7 @@ export async function reviewProductionCandidate({ const {screenVerdict,screenSummary,templateStyle,imageIssues,overlayFixes,copyFixes}=value; const hasFindings=[imageIssues,overlayFixes,copyFixes].some(list=>list?.length); const verdict=screenVerdict??(hasFindings?'needs_fix':undefined); - const screenReview=verdict===undefined?undefined:{ + const screenReview=!screen||verdict===undefined?undefined:{ page:screen.details.page+1,name:screen.details.pageName,screenFingerprint:screen.details.screenFingerprint, wholeScreen,...(screen.details.templateFidelity?{templateEvidence:true}:null), verdict,summary:screenSummary??value.reason,templateStyle:templateStyle??null,imageIssues,overlayFixes,copyFixes, @@ -184,22 +187,25 @@ export async function reviewProductionCandidate({ templateContext:requirements===input.requirements?undefined:input.requirements, screenCopy,shownFieldOptions:fieldList,referenceMode, ...(referenceMode==='composition-only'?{candidatePrompt:input.candidatePrompt}:null), - productReferenceCount:originalImages.length,layoutReferenceCount:screen.templateImage?1:0, + productReferenceCount:originalImages.length,layoutReferenceCount:screen?.templateImage?1:0, originalReference,frame:input.frame,ratio:input.frame?.width>0&&input.frame?.height>0?input.frame.width+':'+input.frame.height:input.aspectRatio, candidateFile:input.candidateFile,generationEvidence,product:input.brief,outputSpec:input.outputSpec,layoutIssue:input.layoutIssue, - fit:screen.details.fit??fit,artDirection,textRegions:input.textRegions, - composite:{page:screen.details.page+1,name:screen.details.pageName,slots:numberScreenSlots(screen.details.slots), + fit:screen?.details.fit??fit,artDirection,textRegions:input.textRegions, + composite:screen&&{page:screen.details.page+1,name:screen.details.pageName,slots:numberScreenSlots(screen.details.slots), screenCopy:numberScreenCopy(screen.details.screenCopy), overlayLayers:screen.details.overlayLayers,templateFidelity:screen.details.templateFidelity, fieldRequirements:screen.details.fieldRequirements}}); const instructions=[ - '按项目锁定的企业 Skill 及小壹补充验图。第一张是候选原图,第二张是候选放入后的整屏画面。其余图片按图注识别。', - TEMPLATE_REVIEW_GUIDANCE('顶层 templateStyle'), + '按项目锁定的企业 Skill 及小壹补充验图。第一张是候选原图。其余图片按图注识别。', + ...(screen?[ + '第二张是候选放入后的整屏画面。', + TEMPLATE_REVIEW_GUIDANCE('顶层 templateStyle'), + 'verdict 描述候选图,screenVerdict 描述整屏,imageIssues、overlayFixes 和 copyFixes 分别记录整屏的图像、叠层和文字问题。', + '整屏问题使用 composite 中的 slotNumber、nativeLayerId 或 screenFieldNumber。找不到对应编号时用 location 描述。每项填写 issue 和 suggestion。', + 'subjectBounds 是按放置后像素与边缘背景色差估测的画布坐标 [x,y,w,h],并已裁到可见图框。', + ]:[]), requirementsText, - 'verdict 描述候选图,screenVerdict 描述整屏,imageIssues、overlayFixes 和 copyFixes 分别记录整屏的图像、叠层和文字问题。', example, - '整屏问题使用 composite 中的 slotNumber、nativeLayerId 或 screenFieldNumber。找不到对应编号时用 location 描述。每项填写 issue 和 suggestion。', - 'subjectBounds 是按放置后像素与边缘背景色差估测的画布坐标 [x,y,w,h],并已裁到可见图框。', '原件信息见 candidateFile,图框见 frame。requirements 是当前图位的要求,screenCopy 是实时文案。', '用 shownSubject 描述实际画面。shownFields 只填写 screenCopy 中存在且有画面依据的条目。每项原样复制 shownFieldOptions 中的一个 field。mustRedo 和 canvasFixes 分别记录建议重做和能用画布处理的问题。裁切坐标以未裁切原图为准。', ...(fieldList.length?[]:[shownFieldsGuide]), @@ -209,8 +215,8 @@ export async function reviewProductionCandidate({ ].join('\n'); const slotTemplate=input.layoutSource==='pinnedTemplateOriginal' ?input.images.slice(referenceCount,referenceCount+(input.layoutCount??0)):[]; - const images=[input.images.at(-1),screen.image,...slotTemplate,...(screen.templateImage?[screen.templateImage]:[]),...originalImages]; - const captions=['受审候选原图','候选放入后的整屏合成',...slotTemplate.map(()=>'固定模板图位原图'),...(screen.templateImage?['模板原屏']:[]),...originalImages.map((_image,index)=> + const images=[input.images.at(-1),...(screen?[screen.image]:[]),...slotTemplate,...(screen?.templateImage?[screen.templateImage]:[]),...originalImages]; + const captions=['受审候选原图',...(screen?['候选放入后的整屏合成']:[]),...slotTemplate.map(()=>'固定模板图位原图'),...(screen?.templateImage?['模板原屏']:[]),...originalImages.map((_image,index)=> '同款实拍 '+(originalReference??'P'+String(index+1).padStart(2,'0')))]; const scope=productRequestScope('review',candidateId); await runAgent(slot.id,instructions,prompt,[review],images,scope,captions,signal); diff --git a/apps/detail-agent-pi/src/output-capabilities.mjs b/apps/detail-agent-pi/src/output-capabilities.mjs index 6e9f8c9b..26d99425 100644 --- a/apps/detail-agent-pi/src/output-capabilities.mjs +++ b/apps/detail-agent-pi/src/output-capabilities.mjs @@ -18,6 +18,8 @@ const outputCapabilities = new Map([ }], ]); +export const productionOutputLabel = id => outputCapabilities.get(id)?.label ?? '成品'; + const issueSchema = Type.Object({ outputId: Type.String({ minLength: 1 }), variantId: Type.Optional(Type.String({ minLength: 1 })), diff --git a/apps/detail-agent-pi/src/photocraft-extension.mjs b/apps/detail-agent-pi/src/photocraft-extension.mjs index 751b5e5b..2c0cd6cd 100644 --- a/apps/detail-agent-pi/src/photocraft-extension.mjs +++ b/apps/detail-agent-pi/src/photocraft-extension.mjs @@ -17,7 +17,7 @@ export const PHOTOCRAFT_NAMESPACE = Object.freeze({ name: 'photocraft', aliases: ['PhotoCraft', 'native'], description: '查询并执行画布命令。', - instructions: 'Discover current native commands and their parameter documentation before calling them. All calls retain the current account, project, document, revision and host permission checks. A denied or proposed operation is not an executed operation.', + instructions: '调用前查询当前画布命令及参数说明。执行仍须符合当前账号、项目、文档和写入授权。被拒绝或仅提交为建议的操作未执行。工具回执用于核对事实,向用户用自然中文说明实际结果。', }); /** Metadata only: the host owns the real handlers, schemas and authorization. */ diff --git a/apps/detail-agent-pi/src/production-goal.mjs b/apps/detail-agent-pi/src/production-goal.mjs index 2e2d2586..0b17fd14 100644 --- a/apps/detail-agent-pi/src/production-goal.mjs +++ b/apps/detail-agent-pi/src/production-goal.mjs @@ -9,7 +9,7 @@ import { SessionManager } from '@earendil-works/pi-coding-agent'; import { imageResult, openProductionOperations, productionOperationTools, reconcileProjectImageSlots } from './production-operations.mjs'; import { randomUUID } from 'node:crypto'; import { BridgeError } from './bridge-error.mjs'; -import { checkOutputCapabilities } from './output-capabilities.mjs'; +import { checkOutputCapabilities, productionOutputLabel } from './output-capabilities.mjs'; export function productionGoalPreflight(goal) { const outputPreflight = checkOutputCapabilities(goal.requestedOutputs); @@ -20,7 +20,7 @@ export function productionGoalPreflight(goal) { } export function productionObjective(requestedOutputs) { - const outputs = [...new Set(requestedOutputs.map(row=>row.label || row.outputId))].join('、'); + const outputs = [...new Set(requestedOutputs.map(row=>row.label || productionOutputLabel(row.outputId)))].join('、'); return `按适用制作指引和模板制作并交付本轮所选输出:${outputs}。`; } @@ -133,7 +133,8 @@ export function describeProductionOutput(binding) { async function projectSlotMap(host, scope={}) { const context=host.productionContext ?? host.productionGoal; - const {requestedOutputs,outputId,variantId}=context; + const {requestedOutputs}=context; + const {outputId,variantId}=workingProductionOutput(host); if(!requestedOutputs?.length)return []; const requestedOutput=scope.outputId; const requestedVariant=scope.variantId; @@ -186,7 +187,8 @@ export async function callProductionTool(host, name, args, signal) { if (name==='open_production_output') { const started=performance.now(); const previous=await currentProductionOperations(host)?.catch(()=>undefined); - const switched=goal.outputId!==args.outputId||goal.variantId!==args.variantId; + const active=workingProductionOutput(host); + const switched=active.outputId!==args.outputId||active.variantId!==args.variantId; let binding; try { const previousImageRequests=switched?await previous?.suspendCanvas():undefined; @@ -208,10 +210,14 @@ export async function callProductionTool(host, name, args, signal) { const {candidateId,offset,...scope}=args; return candidateReceipt(await host.canvas.detailHistory({projectImages:true,...scope}),{},{candidateId,offset}); } - const {outputId=goal.outputId,variantId=goal.variantId,...input}=args; + const {outputId:requestedOutput,variantId:requestedVariant,...input}=args; + const active=workingProductionOutput(host); + const outputId=requestedOutput??active.outputId; + const choices=goal.requestedOutputs?.filter(row=>row.outputId===outputId)??[]; + const variantId=requestedVariant??(outputId!==active.outputId&&choices.length===1?choices[0].variantId:active.variantId); const target={outputId,variantId}; const documentKey=name==='read_output_screen'?host.canvas.canvasBinding?.documentKey:undefined; - const working=outputId===goal.outputId&&variantId===goal.variantId; + const working=outputId===active.outputId&&variantId===active.variantId; if (!working && !goal.requestedOutputs?.some(row=>row.outputId===outputId&&row.variantId===variantId)) throw Error('所选成品和花色不属于本轮制作'); if(!working&&name==='read_slot_images'){ @@ -222,9 +228,11 @@ export async function callProductionTool(host, name, args, signal) { ...(input.candidateId&&!input.includeReferences?{includeProductReferences:false}:null)}; return imageResult({...target,...await host.canvas.detailImages(input.slotId,input.candidateId,options)}); } - if(!working&&!['plan_production','review_image_slots','await_image_slots','read_screen_review','reconcile_image_slots','check_image_slots','use_product_image','transform_slot_image','read_copy_fields','read_archived_images','retire_production_image','stage_archived_image','read_output_screen','check_output_screens','defer_production_output'].includes(name)) - return {...target,accepted:false,reason:'canvas_inactive',workingOutput:goal.outputId?{ - outputId:goal.outputId,variantId:goal.variantId}:null}; + if(!working&&['read_output_screen','check_output_screens'].includes(name)) + return {...target,accepted:false,reason:'canvas_inactive',message:`请打开${productionOutputLabel(outputId)}画布后再复核。`, + ...(host.productionGoal?{nextAction:{tool:'open_production_output',args:target}}:null)}; + if(!working&&!['plan_production','review_image_slots','await_image_slots','read_screen_review','reconcile_image_slots','check_image_slots','use_product_image','transform_slot_image','prepare_image_request','dispatch_image_request','read_copy_fields','read_archived_images','retire_production_image','stage_archived_image','defer_production_output'].includes(name)) + return {...target,accepted:false,reason:'canvas_inactive',workingOutput:active.outputId?active:null}; if (name==='finish_production' && args.scope==='all' && args.revision===undefined) { const evidence=await (await currentProductionOperations(host))?.finishEvidence(); return submitProduction(host,{scope:'all',...(args.issues?{issues:args.issues}:null), @@ -285,9 +293,13 @@ async function bindProductionOutput(host, binding) { } const outputKey=({outputId,variantId})=>JSON.stringify([outputId,variantId]); +const workingProductionOutput=host=>{ + const {outputId,variantId}=host.canvas?.productionOutput??host.productionContext??host.productionGoal??{}; + return {outputId,variantId}; +}; export function currentProductionOperations(host) { - return host.productionWork?.get(outputKey(host.productionContext ?? host.productionGoal ?? {})); + return host.productionWork?.get(outputKey(workingProductionOutput(host))); } function productionOperationsFor(host,target,{readOnly=false}={}) { @@ -303,9 +315,9 @@ function productionOperationsFor(host,target,{readOnly=false}={}) { } function watchBoundOutput(host) { - const context=host.productionContext ?? host.productionGoal; - if(context.outputId&&!host.productionSignal?.aborted) - productionOperationsFor(host,context); + const target=workingProductionOutput(host); + if(target.outputId&&!host.productionSignal?.aborted) + productionOperationsFor(host,target); } async function productionWork(host) { @@ -331,10 +343,7 @@ async function submitProduction(host, input, signal) { const fullReceipt = result.stageStatus==='hard-blocked' ? {...result,availableOutputs:result.pendingOutputs} : result; const receipt=await compactDeliveryReceipt(host.store,fullReceipt); - const completed = receipt.allOutputsCompleted === true && receipt.deliveryStatus === 'completed' && - Array.isArray(receipt.missingSlots) && Array.isArray(receipt.unreviewedScreens) && - ![receipt.missingSlots,receipt.unreviewedScreens,receipt.pendingOutputs,receipt.pendingScreenReviews, - receipt.screensWithOpenIssues,receipt.reviewEvidenceMissing,receipt.failedOutputs].some(rows => rows?.length); + const completed = receipt.completed === true && receipt.allOutputsCompleted === true; if (Object.hasOwn(receipt,'completed') || Object.hasOwn(receipt,'allOutputsCompleted')) receipt.completed = completed; if (input.scope === 'all') receipt.complete = completed; if (!completed && receipt.finalized) { @@ -351,22 +360,24 @@ async function submitProduction(host, input, signal) { const current = productionGoalState(host.manager); if (current) host.manager.appendCustomEntry('production-goal',{goal:{...current,status:'complete'}}); await closeProductionTurn(host); - } else if (host.productionGoal && receipt.deliveryStatus) { - const OUTPUT_LABELS = { detail: '详情页', main_images: '主图', sku_images: 'SKU 图', main_video: '主图视频', seeding_video: '种草视频' }; - const outputLabel = id => OUTPUT_LABELS[id] ?? id; - const display = row => typeof row === 'string' ? outputLabel(row) : - [row.label ?? outputLabel(row.outputId),row.slotId ?? row.screenId ?? row.page].filter(value=>value!=null).join(' '); - const outstanding = [ - [receipt.pendingOutputs,'待交付成品'],[receipt.missingSlots,'缺失图位'], - [receipt.unreviewedScreens,'未复核画面'],[receipt.pendingScreenReviews,'待处理复核'], - ].filter(([rows])=>rows?.length).map(([rows,label])=>`${label}:${rows.map(display).join('、')}。`); - const delivered = [...new Set([...(receipt.published ?? []),...(receipt.availableOutputs ?? []), - ...(receipt.files?.length ? [receipt] : [])].filter(row=>row.complete || row.files?.length).map(display))]; + } else if (host.productionGoal && (completed || receipt.deliveryStatus)) { + const exported=[...(receipt.published??[]),...(receipt.availableOutputs??[]),receipt] + .filter(row=>row.outputId&&(row.generationId||row.complete||row.files?.length)); + const names=rows=>[...new Set(rows.map(row=>productionOutputLabel(typeof row==='string'?row:row.outputId)))].join('、'); + const delivered=names(exported); + const pending=names(receipt.pendingOutputs??[]); + const reviewScreens=receipt.pendingScreenReviews?.length||receipt.unreviewedScreens?.length||0; + const missingSlots=receipt.missingSlots?.length??0; host.productionDelivery={receipt,text:[ - receipt.deliveryStatus === 'failed' ? '本次导出失败。' : '本轮仅完成部分交付。', - ...(delivered.length ? [`已交付:${delivered.join('、')}。`] : []), - ...outstanding, - delivered.length || receipt.drafts?.length ? '已交付的文件和已保存的编辑稿均可保留,可以继续制作。' : '可以继续制作。', + completed ? '本轮成品已全部完成。' : receipt.deliveryStatus==='failed' ? '这次导出遇到了问题。' + : delivered ? '这次先导出了部分成品。' : '这次还没有可交付的成品。', + ...(delivered?[`已导出${delivered}。`]:[]), + ...(completed?[]:[ + ...(pending?[`${pending}还待交付。`]:[]), + ...(missingSlots?[`还有 ${missingSlots} 个图位待补。`]:[]), + ...(reviewScreens?[`还有 ${reviewScreens} 个画面待复核。`]:[]), + ...(receipt.drafts?.length?['编辑稿已保留,可以继续制作。']:['可以继续制作。']), + ]), ].join('')}; } return receipt; diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 215c59be..6d76ecbd 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -66,7 +66,8 @@ export async function openProductionOperations(host,{target=host.productionConte const {outputId,variantId}=target; const output={outputId,variantId}; const runDetailAgent=(...args)=>host.runDetailAgent(...args,output); - let canvasReady=context.outputId===outputId&&context.variantId===variantId + const working=canvas.productionOutput??context; + let canvasReady=working.outputId===outputId&&working.variantId===variantId ? null : Promise.withResolvers(); const canvasTasks=new Set(); const trackCanvas=async running=>{ @@ -135,6 +136,13 @@ export async function openProductionOperations(host,{target=host.productionConte if(!slot)throw Error(slotNotFound); return slot; }; + const findLiveSlot=(live,reference)=>{ + const id=reference.trim(); + const exact=live.find(slot=>slot.id===id); + if(exact)return exact; + const fields=live.filter(slot=>slot.fieldId===id); + if(fields.length===1)return fields[0]; + }; const selections=slotIds=>slotIds?.length?[...new Set(slotIds.map(matches))]:slots; const readSelection=slotIds=>{ const requested=new Set(slotIds?.map(id=>id.trim()).filter(Boolean)); @@ -441,7 +449,7 @@ export async function openProductionOperations(host,{target=host.productionConte const readImages=(slotId,args={})=>{ const candidateId=args.candidateId?.trim()||undefined; const background=Boolean(canvasReady); - const images=canvas.detailImages(matches(slotId).id,candidateId,{ + const images=canvas.detailImages(slotId,candidateId,{ ...(background?{targetOutput:output}:null), ...(args.adopted?{adopted:true}:null),...(candidateId?{inspectCandidate:true}:null), ...(args.includeProductReferences===false?{includeProductReferences:false}:null), @@ -747,8 +755,11 @@ export async function openProductionOperations(host,{target=host.productionConte ![1,2].includes(images?.length)||images[0].type!=='image'){ throw Error('未读取到该候选放入后的整屏画面'); } + const live=await liveSlots(); const slots=details.imageSlots.map(id=>{ - const {fieldId,label,nativeLayerId}=matches(id); + const slot=findLiveSlot(live,id); + if(!slot)throw Error(slotNotFound); + const {fieldId,label,nativeLayerId}=slot; return {id,fieldId,label,nativeLayerId,...details.slotGeometry?.find(row=>row.slotId===id)}; }); const screenCopy=extractPageLiveCopy({pageIndex:0,pages:[details.copyFields[0]?.page],fields:details.copyFields}); @@ -780,9 +791,15 @@ export async function openProductionOperations(host,{target=host.productionConte const source=nativeGenerations(live).includes(candidateId)?'generate':item?.candidateId===candidateId?item.source:undefined; try{ const copyInputs=productionInputs(await current(),variantId); - const screen=await candidateScreen(slot,candidateId,adopted,fit,signal); - const liveScreenCopy=await liveSlotCopy(slot,screen.details.copyFields); - row.pageIndex=screen.details.page; + let screen; + try { + screen=await candidateScreen(slot,candidateId,adopted,fit,signal); + } catch (error) { + if (adopted || error.message!=='候选图位不是智能图层') throw error; + // The bridge requires a smart source for a placement preview. Original pixels are independent. + } + const liveScreenCopy=await liveSlotCopy(slot,screen?.details.copyFields); + row.pageIndex=screen?.details.page; notice('子代理正在验图'); const readCanvas={detailImages:(id,candidate,options)=>canvas.detailImages(id,candidate,{ ...options,...(canvasReady?{targetOutput:output}:null), @@ -813,7 +830,8 @@ export async function openProductionOperations(host,{target=host.productionConte item?.attempts?.find(row=>row.candidateId===candidateId)?.reworkOf; await store.appendEvent({type:'whole_detail_review',outputId,variantId,slotId:slot.id,fieldId:slot.fieldId, ...review,...(reworkOf?{reworkOf}:null)}); - return {slotId:slot.id,...review,...(reworkOf?{reworkOf}:null)}; + return {slotId:slot.id,...review,...(!screen?{screenNotice:'已检查候选原图。放入画布后的效果待复核。'}:null), + ...(reworkOf?{reworkOf}:null)}; }catch(error){ return {slotId:slot.id,candidateId,error:error.message}; } @@ -924,7 +942,7 @@ export async function openProductionOperations(host,{target=host.productionConte ...(requested.size?{productionRule,requirements,sourcePolicy}:null)}; }); const {production,skillSources,resourceSetId,...template}=plan.template; - const {outputId:workingOutputId,variantId:workingVariantId}=context; + const {outputId:workingOutputId,variantId:workingVariantId}=canvas.productionOutput??context; const snapshot=await copySnapshot({screenReviewFingerprints:screenReviewFingerprints(plan)}); return {outputId,variantId,workingOutput:workingOutputId?{outputId:workingOutputId,variantId:workingVariantId}:null, fieldConflicts:await fieldConflicts(snapshot,plan),fieldRequirements:fieldRequirements(plan), @@ -1027,12 +1045,16 @@ export async function openProductionOperations(host,{target=host.productionConte transform_slot_image({slotId,...options},signal){ return transformImage(matches(slotId),options,signal); }, - prepare_image_request({slotId,...args},signal){ - return prepareImageRequest(matches(slotId),args,signal); + async prepare_image_request({slotId,fieldId,...args},signal){ + const reference=slotId??fieldId; + const slot=reference&&findLiveSlot(await liveSlots(),reference); + if(!slot)throw Error(slotNotFound); + return prepareImageRequest(slot,args,signal); }, async dispatch_image_request(approval,signal){ const request=await preparedRequest(approval.requestId); - const slot=matches(request.slotId); + const slot=findLiveSlot(await liveSlots(),request.slotId); + if(!slot)throw Error(slotNotFound); return queueDispatch(slot,approval,request,signal?AbortSignal.any([signal,stageSignal]):stageSignal); }, async delegate_image_slots({jobs:requested},signal){ @@ -1267,16 +1289,12 @@ export async function openProductionOperations(host,{target=host.productionConte async check_image_slots({candidates:requested,wait=false},signal){ const activeSignal=signal?AbortSignal.any([signal,stageSignal]):stageSignal; activeSignal.throwIfAborted(); - const live=new Map((await liveSlots()).map(slot=>[slot.id,slot])); - const statuses=drawStatuses([...live.values()]); + const live=await liveSlots(); + const statuses=drawStatuses(live); const batch=requested.map(({slotId,candidateId,adopted,fit})=>{ if(canvasReady&&adopted)return {receipt:{slotId,candidateId,accepted:false,reason:'canvas_inactive'}}; - let slot; - try { - slot=matches(slotId); - } catch (error) { - return {receipt:{slotId,candidateId,error:error.message}}; - } + const slot=findLiveSlot(live,slotId); + if(!slot)return {receipt:{slotId,candidateId,error:slotNotFound}}; const pending=pendingReviews().find(job=>job.row.slotId===slot.id&&job.row.candidateId===candidateId&&job.adopted===Boolean(adopted)&&job.fit===fit); if(pending)return pending; const row={number:nextWorkerNumber(),slotId:slot.id,label:slot.label,candidateId,step:'排队中',active:true}; @@ -1287,7 +1305,7 @@ export async function openProductionOperations(host,{target=host.productionConte return check(slot,candidateId,adopted,fit,activeSignal,row); }) .catch(error=>({slotId:slot.id,candidateId,error:error.message})).then(receipt=>{ - job.receipt={...receipt,...slotDrawStatus(live.get(slot.id)??slot)}; + job.receipt={...receipt,...slotDrawStatus(slot)}; return job.receipt; }).finally(()=>{ job.run=null; diff --git a/apps/detail-agent-pi/src/production-tools.mjs b/apps/detail-agent-pi/src/production-tools.mjs index 40deda56..7ec57ddd 100644 --- a/apps/detail-agent-pi/src/production-tools.mjs +++ b/apps/detail-agent-pi/src/production-tools.mjs @@ -29,7 +29,9 @@ export const productionOperationTools = [ })], ['use_product_image','用本款原片或裁切区域创建候选。通过 adopt_production_image 回填时,放置回执会列出覆盖图位的模板叠层。',obj({...outputScope,slotId:slotRef,...productImageArgs})], ['transform_slot_image',transformDescription,obj({...outputScope,slotId:slotRef,...transformImageArgs})], - ['prepare_image_request',imageRequestDescription,obj({...outputScope,slotId:slotRef,...preparationArgs})], + ['prepare_image_request',imageRequestDescription+' 图位可用 slotId 或 fieldId。指定成品和花色时按该成品的图位准备。',obj({ + ...outputScope,slotId:optional(slotRef),fieldId:optional(slotRef),...preparationArgs, + })], ['dispatch_image_request','确认准备回执后,传首个 requestId 派发同批请求。宿主读取该编号绑定的版本及哈希。用 await_image_slots 或 review_image_slots 查看结果。',obj({...outputScope,...dispatchArgs})], ['delegate_image_slots','异步分派主图位 slotId,reuseTargets 可附同花色的额外图位及 outputId。委托可查候选并裁切至组内图位,在可写画布显式采用。返回分派状态和待写字段。',obj({ ...outputScope,jobs:Type.Array(obj({slotId:slotRef,goal:text,reuseTargets:optional(Type.Array(reuseTarget)),reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})), @@ -56,7 +58,7 @@ export const productionOperationTools = [ zoom:optional(Type.Number({minimum:1,maximum:4})), includeTemplateImage:optional(Type.Boolean()),templateLayerId:optional(Type.Integer({minimum:1})),templateChangeOffset:optional(Type.Integer({minimum:0})), })], - ['check_output_screens','按企业 Skill 并行复核整屏合成画面、实拍、实时文案和叠加层。pages 从 1 开始(第 1 屏传 1,区别于 read_output_screen 的从 0 开始),以实际屏数为准。默认等待结论,保存通过及待修正意见,按图位、图层或字段定位。wait=false 时可用省略 slotIds 的 await_image_slots 取摘要。',obj({ + ['check_output_screens','按企业 Skill 并行复核整屏合成画面、实拍、实时文案和叠加层。指定成品未打开时,按回执在目标画布复核。pages 从 1 开始(第 1 屏传 1,区别于 read_output_screen 的从 0 开始),以实际屏数为准。默认等待结论,保存通过及待修正意见,按图位、图层或字段定位。wait=false 时可用省略 slotIds 的 await_image_slots 取摘要。',obj({ ...outputScope, pages:Type.Array(Type.Integer({minimum:1}),{minItems:1}), wait:optional(Type.Boolean({default:true})), 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 22515e10..16918d9f 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 @@ -40,19 +40,17 @@ maxGenerationAttempts: 4 - 锁定知识资料的 `read` 路径来自 `plan_production(includeKnowledge=true)` 或文件里的引用。主小壹的 `read` 也可读取交付回执中的 `reportPath`。 - 暂停或重开后,在途图片用 `reconcile_image_slots` 按原请求号核查;原请求已确认失败且没有结果时,可为该图位另备新请求。 -| 命令 | 参数与结果 | -| --- | --- | -| `layer.list` | 列出文档图层及其可见状态。 | -| `shape.info` | 用 `layer` 读取形状的锚点、控制柄、开闭状态、填充和描边,包括虚线。 | -| `path.info` | 用 `layer` 查询图层路径,返回子路径及锚点、控制柄。 | -| `path.moveAnchors` | 用 `layer` 指定图层路径,用 `anchors` 列出 `[subpath,knot]`,`move: [dx,dy]` 平移锚点及其控制柄。positions: [[x,y],…] 则逐一设置对应锚点的绝对画布坐标并平移控制柄,与 move 和 curvature 互斥。 | -| `path.moveHandle` | 用 `layer`、`subpath` 和 `knot` 定位,`handle` 选 `in` 或 `out`,`to` 指定目标坐标。 | -| `shape.edit` | 用 `layer` 指定形状,可传 `path`、`move`、`fill` 或 `stroke` 更新几何和样式。 | -| `type.info` | 用 `layer` 读取文字及其排版边界。 | -| `edit.transform` | 用 `layer` 指定整层变换,`dx`、`dy` 平移,`scaleX`、`scaleY` 缩放,`rotate` 旋转。 | -| `layer.subjectGeometry` | 用 `layer` 查询已置入素材的主体包围盒、简化轮廓、四向极值像素中心及按高度分带的左右边缘。透明素材按像素覆盖度取轮廓,实景图按显著主体估算。 | -| `paint.burn`、`paint.dodge` | 在智能对象上方新建像素图层做局部修饰,或用上方调整图层及蒙版处理局部明暗。 | -| `paint.remove` | 用 `layer` 指定图层,`target: pixels` 指定像素,闭合的 `points` 指定区域,`size` 是笔刷尺寸。`newLayer: true` 可将智能对象的补片保存为剪贴图层。替换候选或改变放置方式时,回填回执的 `hiddenRetouchLayers` 列出已隐藏的旧补片。 | +- `layer.list` 列出文档图层及其可见状态。 +- `shape.info` 用 `layer` 读取形状的锚点、控制柄、开闭状态、填充和描边,包括虚线。 +- `path.info` 用 `layer` 查询图层路径,返回子路径及锚点、控制柄。 +- `path.moveAnchors` 用 `layer` 指定图层路径,用 `anchors` 列出 `[subpath,knot]`,`move: [dx,dy]` 平移锚点及其控制柄。positions: [[x,y],…] 则逐一设置对应锚点的绝对画布坐标并平移控制柄,与 move 和 curvature 互斥。 +- `path.moveHandle` 用 `layer`、`subpath` 和 `knot` 定位,`handle` 选 `in` 或 `out`,`to` 指定目标坐标。 +- `shape.edit` 用 `layer` 指定形状,可传 `path`、`move`、`fill` 或 `stroke` 更新几何和样式。 +- `type.info` 用 `layer` 读取文字及其排版边界。 +- `edit.transform` 用 `layer` 指定整层变换,`dx`、`dy` 平移,`scaleX`、`scaleY` 缩放,`rotate` 旋转。 +- `layer.subjectGeometry` 用 `layer` 查询已置入素材的主体包围盒、简化轮廓、四向极值像素中心及按高度分带的左右边缘。透明素材按像素覆盖度取轮廓,实景图按显著主体估算。 +- `paint.burn`、`paint.dodge` 在智能对象上方新建像素图层做局部修饰,或用上方调整图层及蒙版处理局部明暗。 +- `paint.remove` 用 `layer` 指定图层,`target: pixels` 指定像素,闭合的 `points` 指定区域,`size` 是笔刷尺寸。`newLayer: true` 可将智能对象的补片保存为剪贴图层。替换候选或改变放置方式时,回填回执的 `hiddenRetouchLayers` 列出已隐藏的旧补片。 `native_call` 示例 diff --git a/apps/detail-agent-pi/src/stdio-canvas.mjs b/apps/detail-agent-pi/src/stdio-canvas.mjs index 2662032e..e742627b 100644 --- a/apps/detail-agent-pi/src/stdio-canvas.mjs +++ b/apps/detail-agent-pi/src/stdio-canvas.mjs @@ -66,12 +66,16 @@ export class StdioCanvas { async begin(text) { this.run = randomUUID(); this.canvasBinding = null; + this.productionOutput = null; const status = await this.action('pi-begin', {text,...this.identity}); - this.#bind(status?.productionCanvas); + this.#bind(status?.productionCanvas,status?.context?.requestScope); return status; } - #bind(binding) { + #bind(binding,requestScope) { this.canvasBinding=binding?.documentKey ? {documentKey:binding.documentKey,writeEpoch:binding.writeEpoch} : null; + const outputId=binding?.documentKey?.outputId??binding?.outputId??requestScope?.outputId; + const variantId=binding?.documentKey?.variantId??binding?.variantId??requestScope?.variantId; + this.productionOutput=outputId&&variantId?{outputId,variantId}:null; } read() { return this.#observe('pi-state'); } async openProductionOutput({outputId,variantId,previousImageRequests},signal,knowledge) { diff --git a/apps/detail-agent-pi/src/stream-presentation.mjs b/apps/detail-agent-pi/src/stream-presentation.mjs index bd6f8614..872d14ed 100644 --- a/apps/detail-agent-pi/src/stream-presentation.mjs +++ b/apps/detail-agent-pi/src/stream-presentation.mjs @@ -44,6 +44,46 @@ export function presentText(text) { const view = new StreamPresentation(); view.push(text || ''); view.endText(); return view.text; } +const receiptLabels = new Map(Object.entries({ + detail: '详情页', main_images: '主图', sku_images: 'SKU 图', + completed: '已完成', exported: '已导出', pendingOutputs: '待交付成品', + deliveryStatus: '交付进度', partial_delivered: '部分成品已交付', + allOutputsCompleted: '整套成品完成情况', writeBlocked: '画布编辑状态', + true: '是', false: '否', +})); + +/** Convert chat-only formatting and known receipt fragments at the presentation boundary. */ +export function presentProductReply(text, streaming = false) { + const lines=text.split(/\r?\n/u); + const tableRule=/^\s*\|?(?:\s*:?-{2,}:?\s*\|)+\s*:?-{2,}:?\s*\|?\s*$/u; + let table=false; + const prose=lines.map((line,index)=>{ + const startsWithPipe=/^\s*\|/u.test(line); + if(tableRule.test(line)){ + table=true; + return ''; + } + if(!line.includes('|'))table=false; + const row=startsWithPipe||table||line.includes(' |')||tableRule.test(lines[index+1]??''); + if(!row)return line; + if(streaming&&startsWithPipe&&index===lines.length-1&&!/\|\s*$/u.test(line.trim().slice(1)))return ''; + const columns=line.trim().replace(/^\||\|$/gu,'').split('|').map(cell=>cell.trim()).filter(Boolean); + return columns.length?'- '+columns.join(','):''; + }).join('\n'); + return prose + .replace(/\x60?\ballOutputsCompleted\s*[:=]\s*(true|false)\b\x60?/gu,(_match,value)=>value==='true'?'成品已全部完成':'成品还没全部完成') + .replace(/\x60?\bwriteBlocked\s*[:=]\s*(true|false)\b\x60?/gu,(_match,value)=>value==='true'?'画布暂不能编辑':'画布可以编辑') + .replace(/\x60?\bcompleted\s*[:=]\s*(true|false)\b\x60?/gu,(_match,value)=>value==='true'?'已完成':'尚未完成') + .replace(/\x60?\bpendingOutputs\s*(?:[:=]\s*\[\s*\]|为空)\x60?/gu,'没有待交付成品') + .replace(/(?:[A-Za-z]:)?(?:[/\\][^ \t\r\n"',。;、<>|\x60]+[/\\])?\bproduct-exports(?:[/\\][^ \t\r\n"',。;、<>|\x60]*)?/giu,'本机成品目录') + .replace(/\b(?:Pi(?: Agent)?|PhotoCraft)\b/gu,'小壹') + .replace(/\x60?\b(?:candidateId|generationId|operationId|requestId)\s*[:=]?\s*[\x60'"]?[a-f0-9-]{6,}\b[\x60'"]?/giu,'制作记录') + .replace(/(?:候选(?:图)?(?:编号|号|哈希)?|哈希)\s*[::]?\s*\x60?\b(?=[a-f0-9]*[a-f])[a-f0-9]{7,}(?:[.…]+[a-f0-9]+)?\b\x60?/giu,'候选图') + .replace(/\x60?\b(?:[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}|(?=[a-f0-9]*[a-f])[a-f0-9]{32,}|[a-f0-9]{8,}[.…]+[a-f0-9]{4,})\b\x60?/giu,'制作记录') + .replace(/\x60?\b(?:allOutputsCompleted|writeBlocked|deliveryStatus|pendingOutputs|main_images|sku_images|detail|partial_delivered|completed|exported|true|false)\b\x60?/gu, + match=>receiptLabels.get(match.replaceAll('\x60',''))); +} + const productionToolText = /[\s\S]*?(?:<\/tool_calls?\s*>|$)/giu; export function stripProductionToolText(text, streaming = false) { let visible = text.replace(productionToolText, ''); diff --git a/apps/detail-agent-pi/test/production-goal.test.mjs b/apps/detail-agent-pi/test/production-goal.test.mjs index dc6a4e03..8aad33a4 100644 --- a/apps/detail-agent-pi/test/production-goal.test.mjs +++ b/apps/detail-agent-pi/test/production-goal.test.mjs @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; -import { productionObjective, runProductionGoal, callProductionTool } from '../src/production-goal.mjs'; +import { productionObjective, runProductionGoal, callProductionTool, closeProductionTurn } from '../src/production-goal.mjs'; import { completeCanvas } from './fake-canvas.mjs'; import { productionStore } from './production-store-fixture.mjs'; import { productContext } from '../src/project-context.mjs'; @@ -11,7 +11,9 @@ import { productContext } from '../src/project-context.mjs'; test('a partial delivery keeps its files and concrete missing items without completing the goal',async()=>{ const receipt={finalized:true,complete:true,completed:true,allOutputsCompleted:false, deliveryStatus:'partial_delivered',pendingOutputs:[],missingSlots:['I06'],unreviewedScreens:[{outputId:'detail',page:4}], - availableOutputs:[{outputId:'sku_images',label:'SKU 图',complete:true,files:[{path:'sku.jpg'}]}]}; + published:[{outputId:'main_images',generationId:'previous-verified-export'}], + availableOutputs:[{outputId:'sku_images',label:'SKU 图',complete:true,files:[]}, + {outputId:'detail',files:[{path:'detail.jpg'}]}]}; const host={productionGoal:{requestedOutputs:[{outputId:'sku_images'},{outputId:'detail'}]}, store:{},canvas:{finishProduction:async()=>receipt}}; const result=await callProductionTool(host,'finish_production',{scope:'all'}); @@ -20,10 +22,55 @@ test('a partial delivery keeps its files and concrete missing items without comp assert.equal(result.finalized,false); assert.deepEqual(result.availableOutputs,receipt.availableOutputs); assert.equal(host.productionCompletion,undefined); - assert.match(host.productionDelivery.text,/SKU 图.*I06.*detail 4.*可以继续制作/); + assert.match(host.productionDelivery.text,/已导出主图、SKU 图、详情页。.*1 个图位待补。.*1 个画面待复核。.*可以继续制作/); + assert.doesNotMatch(host.productionDelivery.text,/I06|detail\.jpg|previous-verified-export/); assert.doesNotMatch(host.productionDelivery.text,/整套成品已核验完成/); }); +test('all completed outputs are reported as complete before the host finalizes the package',async()=>{ + const published=['detail','main_images','sku_images'].map(outputId=>({outputId,generationId:outputId+'-generation'})); + const receipt={finalized:false,completed:true,allOutputsCompleted:true,deliveryStatus:'completed',published}; + const host={productionGoal:{},store:{},canvas:{finishProduction:async()=>receipt}}; + const result=await callProductionTool(host,'finish_production',{scope:'all'}); + assert.equal(result.complete,true); + assert.equal(host.productionCompletion,undefined); + assert.equal(host.productionDelivery.text,'本轮成品已全部完成。已导出详情页、主图、SKU 图。'); +}); + +test('post-delivery image preparation uses the live output and resolves updated slots by either identifier',async t=>{ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-live-slots-')); + const detail={outputId:'detail',variantId:'white'}; + const main={outputId:'main_images',variantId:'wood'}; + let slots=[{id:'initial-main',fieldId:'M01'}]; + let revision=1; + const prepared=[]; + const canvas=completeCanvas({ + productionOutput:main, + workflowRead:async({outputId})=>{ + assert.equal(outputId,main.outputId); + return {outputId,productVariantId:main.variantId,available:true,canvasFirst:true,version:revision, + template:{contentHash:'main-template'},revisions:{slots:revision},totalSlots:slots.length,slots}; + }, + detailHistory:()=>assert.fail('当前主图应读取实时画布'), + imageRequest:async(action,request,_execution,scope)=>{ + if(action==='pending')return []; + assert.equal(action,'prepare'); + assert.deepEqual(scope,{...main,templateHash:'main-template'}); + prepared.push(request.slotId); + return {requestId:'prepared'}; + }, + }); + const host={store:productionStore(dir),canvas, + productionContext:{...detail,requestedOutputs:[detail,main]}}; + t.after(async()=>{await closeProductionTurn(host);await fs.rm(dir,{recursive:true,force:true});}); + const prepare=args=>callProductionTool(host,'prepare_image_request',{...args,prompt:'展示正面'}); + await prepare({outputId:main.outputId,fieldId:'M01'}); + slots=[{id:'updated-main',fieldId:'M01'}]; + revision++; + await prepare({slotId:'updated-main'}); + assert.deepEqual(prepared,['initial-main','updated-main']); +}); + test('a standalone plan reads the current template without creating a ledger or scheduling reconciliation',async t=>{ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-read-only-plan-')); t.after(()=>fs.rm(dir,{recursive:true,force:true})); diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index 00f1bd46..dee9e453 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -958,7 +958,13 @@ test('project image discovery can stage a completed image on another output with if(options.outputId)assert.deepEqual(options,{projectImages:true,...source}); return [candidate]; }; - host.canvas.imageRequest=async action=>{assert.equal(action,'pending','本地复用不应派发生图');return [];}; + host.canvas.imageRequest=async (action,request,_execution,scope)=>{ + if(action==='pending')return []; + assert.equal(action,'prepare','本地复用和准备请求均不应派发生图'); + assert.deepEqual(scope,{...source,templateHash:'main'}); + assert.equal(request.slotId,candidate.slotId); + return {requestId:'prepared-main'}; + }; host.canvas.detailArchive=async(slotId,args)=>{ staged.push({slotId,...args}); return {id:'reused',status:'complete',reusedFrom:{candidateId:args.candidateId}}; @@ -969,7 +975,7 @@ test('project image discovery can stage a completed image on another output with const plan=await call('plan_production',source); assert.equal(plan.pictures[0].completedCandidates,1); assert.deepEqual(plan.workingOutput,target); - assert.equal((await call('prepare_image_request',{...source,slotId:candidate.slotId,prompt:'试拍'})).reason,'canvas_inactive'); + assert.equal((await call('prepare_image_request',{...source,slotId:candidate.slotId,prompt:'试拍'})).requestId,'prepared-main'); const reused=await call('stage_archived_image',{...target,slotId:'target',candidateId:candidate.candidateId}); assert.equal(reused.reusedFrom.candidateId,candidate.candidateId); assert.deepEqual(staged,[{slotId:'target',projectId:undefined,candidateId:candidate.candidateId,forReview:true}]); diff --git a/apps/detail-agent-pi/test/screen-review.test.mjs b/apps/detail-agent-pi/test/screen-review.test.mjs index 91a627b0..a73e460e 100644 --- a/apps/detail-agent-pi/test/screen-review.test.mjs +++ b/apps/detail-agent-pi/test/screen-review.test.mjs @@ -9,7 +9,7 @@ import { createAssistantMessageEventStream } from '@earendil-works/pi-ai/compat' import { activityToolLabel, toolActivity } from '../src/activity-event.mjs'; import { completeCanvas, openAgent } from './fake-canvas.mjs'; import { openProductionOperations, productionOperationTools } from '../src/production-operations.mjs'; -import { callProductionTool } from '../src/production-goal.mjs'; +import { callProductionTool, closeProductionTurn } from '../src/production-goal.mjs'; import { screenReviewScope } from '../src/screen-review.mjs'; import { ProjectStore } from '../src/store.mjs'; import { WORKER_TURN_LIMIT } from '../src/worker-receipts.mjs'; @@ -307,6 +307,66 @@ test('非当前成品的候选等待验图时直接读取其已保存画布', {t await actions.close(); }); +test('合法图位无法合成预览时仍核对候选原图与实拍,整屏保持待验',async t=>{ + const {host,actions,state,slots,journal}=await fixture(t); + const candidateId=randomUUID(); + slots[0]={...slots[0],id:'live-slot',fieldId:'D01'}; + state.revision++; + host.canvas.detailCandidateScreen=async({slotId},_signal,target)=>{ + assert.equal(slotId,'live-slot'); + assert.equal(target,undefined); + throw Error('候选图位不是智能图层'); + }; + host.canvas.detailImages=async(slotId,id)=>{ + assert.equal(slotId,'live-slot'); + return {candidateId:id,referenceCount:1,images:[pixels,pixels]}; + }; + host.runDetailAgent=async(_slot,_system,input,[tool],images)=>{ + assert.equal(JSON.parse(input).composite,undefined); + assert.equal(images.length,2); + tool.execute('',{candidateId,verdict:'pass',reason:'候选与实拍结构一致',screenVerdict:'pass'}); + }; + const [review]=await actions.check_image_slots({candidates:[{slotId:'D01',candidateId}],wait:true}); + assert.equal(review.verdict,'pass'); + assert.match(review.screenNotice,/效果待复核/); + assert.equal(review.observation.screenReview,undefined); + assert.equal(journal().screenReviews?.length??0,0); + await actions.close(); +}); + +test('跨成品整屏复核指向目标画布,打开后复核该成品的画面',async t=>{ + const {host,state}=await fixture(t); + t.after(()=>closeProductionTurn(host)); + const detail={outputId,variantId}; + const sku={outputId:'sku_images',variantId:'white'}; + host.productionGoal.requestedOutputs=[detail,sku]; + host.bindGoalRequestScope=()=>{}; + host.canvas.productionOutput=detail; + const check=()=>callProductionTool(host,'check_output_screens',{outputId:sku.outputId,pages:[1]}); + const route=await check(); + assert.deepEqual(route.nextAction,{tool:'open_production_output',args:sku}); + assert.match(route.message,/SKU 图画布/); + assert.deepEqual(state.reads,[]); + + const workflowRead=host.canvas.workflowRead; + host.canvas.openProductionOutput=async args=>{ + assert.deepEqual(args,sku); + host.canvas.productionOutput=sku; + return sku; + }; + // The genuine bridge completes the previous save before returning the new binding. + host.canvas.workflowRead=async args=>args.outputId===detail.outputId?workflowRead(args): + {...await workflowRead(args),outputId:sku.outputId,productVariantId:sku.variantId}; + host.runDetailAgent=async(_id,_system,_input,[tool],_images,scope)=>{ + assert.equal(scope,screenReviewScope(sku.variantId,sku.outputId,1)); + tool.execute('',pass); + }; + await callProductionTool(host,route.nextAction.tool,route.nextAction.args); + const [reply]=await check(); + assert.equal(reply.verdict,'pass'); + assert.deepEqual(state.reads,[0]); +}); + test('screen reviews keep images in the worker and persist findings and passes',async t=>{ const {host,state,journal}=await fixture(t); state.slotImageFacts=[{slotId:'slot', source:{kind:'generation',requestId:'request'},nearest:[],nearWhiteFlatRatio:0.2,templateNearWhiteFlatRatio:0.1}]; diff --git a/apps/detail-agent-pi/test/whitelabel.test.mjs b/apps/detail-agent-pi/test/whitelabel.test.mjs index 9f2c037d..0561e7d2 100644 --- a/apps/detail-agent-pi/test/whitelabel.test.mjs +++ b/apps/detail-agent-pi/test/whitelabel.test.mjs @@ -5,6 +5,8 @@ import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { productionObjective, productionTools } from '../src/production-goal.mjs'; import { NATIVE_CANVAS_QUICK_REFERENCE, nativeTools } from '../src/native-tools.mjs'; +import { sessionSystemPrompt } from '../src/agent.mjs'; +import { presentProductReply } from '../src/stream-presentation.mjs'; const source = file => readFileSync(new URL(`../src/${file}`, import.meta.url), 'utf8'); const technicalBrand = /(?{ + for(const production of [false,true]){ + const prompt=sessionSystemPrompt(production); + assert.match(prompt,/专业、温和、靠谱的电商视觉设计搭档/); + assert.match(prompt,/先说用户最关心的结果/); + assert.match(prompt,/严禁输出 Markdown 表格.*项目符号/); + assert.match(prompt,/严禁复述内部字段名、状态枚举、技术布尔值、内部缓存路径、UUID 和候选哈希/); + } +}); + +test('chat renders table rows as bullets and translates receipt fragments before display',()=>{ + const raw='| 成品 | 交付状态 |\n|---|---|\n| main_images | exported |\n| sku_images | completed |\n'+ + 'allOutputsCompleted=true,pendingOutputs 为空,writeBlocked=false。'+ + 'product-exports\\dd6f9c0b-a03b-4d42-8aac-f5ce110a681c\\files,候选号 5b05b95。'; + const visible=presentProductReply(raw); + assert.match(visible,/- 主图,已导出\n- SKU 图,已完成/); + assert.match(visible,/成品已全部完成,没有待交付成品,画布可以编辑/); + assert.doesNotMatch(visible,/\||main_images|sku_images|exported|completed|allOutputsCompleted|pendingOutputs|writeBlocked|product-exports|dd6f9c0b|5b05b95/); + assert.equal(presentProductReply('正在核对。\n| 主图 | 已导',true),'正在核对。\n'); + assert.equal(presentProductReply('成品 | 进度\n--- | ---\n详情页 | 已导出'),'- 成品,进度\n\n- 详情页,已导出'); + assert.equal(presentProductReply('成品 | 进度',true),'- 成品,进度'); + assert.equal(presentProductReply('候选号 5b05b953…c6aa。'),'候选图。'); +}); + test('production prompts refer to the published skill and keep screen semantics with the tool', () => { const prompt = source('agent.mjs').match(/const PRODUCTION_SYSTEM = `([\s\S]+?)`;/)?.[1]; const tool = name => productionTools.find(([tool]) => tool === name)?.[1];