Merge commit 'c9c1d326876c65c0666db02a5d34eb41aa9e0590' into feat/xiaoyi-hajimi-v2-20261127
This commit is contained in:
commit
4bcf94d7d5
@ -619,7 +619,6 @@ export class DetailPiAgent {
|
||||
});
|
||||
agent.beforeToolCall=async ({toolCall})=>{
|
||||
if(productionSignal?.aborted)return {block:true,terminate:true,reason:'原制作回合已停止'};
|
||||
if(host.productionRequests)return;
|
||||
const key=JSON.stringify([toolCall.name,toolCall.arguments]);
|
||||
const count=(used.get(key)??0)+1;
|
||||
used.set(key,count);
|
||||
@ -683,7 +682,6 @@ export class DetailPiAgent {
|
||||
...(usage?{inputTokens:usage.inputTokens,outputTokens:usage.outputTokens,cachedTokens:usage.cachedTokens}:null)});
|
||||
if(receipt.phase==='rejected'&&message.stopReason==='length')throw new ProductionOutputLimit();
|
||||
const failure=confirmedProductionFailure(receipt,round.id);
|
||||
if(['complete','failed'].includes(receipt.phase))host.productionRequests?.delete(requestScope);
|
||||
if(failure)throw failure;
|
||||
if(!valid||receipt.phase!=='complete')throw Error(message.errorMessage ?? 'network error: inference stream did not complete');
|
||||
if(!raw)throw Error('原始模型响应尚未读完,工具未执行');
|
||||
@ -1068,48 +1066,6 @@ export class DetailPiAgent {
|
||||
if (this.heartbeat) clearInterval(this.heartbeat);
|
||||
}
|
||||
}
|
||||
async wholeDetail(text, {outputId='detail', production=false}={}) {
|
||||
return this.exclusive(async () => {
|
||||
if (!this.canvas?.detailImages || this.info.model.supportsImageInput===false) {
|
||||
throw Error('整套详情页需要可识图的对话模型及完整的小壹客户端');
|
||||
}
|
||||
const pending=(await this.broker?.info())?.pending??[];
|
||||
const begun=await this.canvas.begin(text);
|
||||
this.activityScope=activityScope(this.store.identity,this.canvas,begun);
|
||||
try {
|
||||
const result=await this.executeWholeDetail(outputId,production,pending);
|
||||
await this.canvas.end(result.text);
|
||||
return result;
|
||||
} catch(error) {
|
||||
await this.canvas.end(error.message).catch(()=>{});
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async executeWholeDetail(outputId, production, pending) {
|
||||
const heartbeat=setInterval(()=>{this.canvas.read().catch(()=>{});},2000);
|
||||
heartbeat.unref();
|
||||
this.wholeDetailActive=true;
|
||||
this.productionRequests=production?new Map(pending.map(request=>[request.detailSlot,request])):null;
|
||||
try {
|
||||
const [{runWholeDetail},{prepareProductStrategy}] = await Promise.all([
|
||||
import('./legacy/whole-detail.mjs'), import('./legacy/product-strategy.mjs'),
|
||||
]);
|
||||
return await runWholeDetail(this,this.runDetailAgent,plan=>{
|
||||
if(!production&&!plan.template.enterprise)return null;
|
||||
const brief=plan.productEvidence?.brief;
|
||||
return this.loadWholeDetailKnowledge({task:production?'production':'image',outputId,brandName:brief?.brandName,categoryName:brief?.categoryName,
|
||||
templateId:plan.template.id,releaseId:plan.template.version,resourceSetId:plan.template.resourceSetId,skillSources:plan.template.skillSources});
|
||||
},{outputId,production,
|
||||
prepareStrategy:production ? (plan,slots,knowledge,runMainAgent)=>prepareProductStrategy(this,runMainAgent,plan,slots,knowledge) : undefined});
|
||||
} finally {
|
||||
this.wholeDetailActive=false;
|
||||
this.productionRequests=null;
|
||||
clearInterval(heartbeat);
|
||||
}
|
||||
}
|
||||
|
||||
async loadWholeDetailKnowledge(selection, signal, pins) {
|
||||
this.enterpriseContext??=new EnterpriseContext(this.store);
|
||||
return this.enterpriseContext.load({task:'production',...selection,turn:this.canvas.run}, {
|
||||
|
||||
@ -135,7 +135,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
|
||||
}
|
||||
let host, broker, store, output, atomic, heartbeat;
|
||||
let releaseRecovery;
|
||||
const productionGoal=config.mode==='prompt'&&config.wholeDetail===true&&config.productProduction===true
|
||||
const productionGoal=config.mode==='prompt'&&config.productProduction===true
|
||||
? {outputId:config.outputId,variantId:config.variantId,requestedOutputs:config.requestedOutputs,
|
||||
pendingOutputs:config.pendingOutputs,workspaceId:config.workspaceId,template:config.productionTemplate,
|
||||
...(config.autoAdoptionPolicy?{autoAdoptionPolicy:config.autoAdoptionPolicy}:null),
|
||||
@ -153,7 +153,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
|
||||
const blocked = productionGoalPreflight(productionGoal);
|
||||
if (blocked) return blocked;
|
||||
}
|
||||
const modelRole=config.mode==='recover'?config.modelRole||'chat':config.wholeDetail?'detail':'chat';
|
||||
const modelRole=config.mode==='recover'?config.modelRole||'chat':productionGoal?'detail':'chat';
|
||||
const bindingConfig={binary:config.binary,profile:config.profile,project:config.project,scope:config.scope,modelRole,
|
||||
dispatchLease:config.dispatchLease,onAuthorizationLost};
|
||||
broker=sharedBroker??new Native98kBroker(bindingConfig);
|
||||
@ -230,10 +230,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
|
||||
// Acknowledge/discard recovered mutation proposals. Never replay them.
|
||||
await atomic(path.join(store.dir, 'recovered-tools.json'), pending.map(t => t.phase === 'review' ? { ...t, phase: 'discarded', reviewedAt: Date.now() } : t));
|
||||
result = { text: '已放弃原响应中的未执行建议;已完成的修改保留。', reposted: false };
|
||||
} else if (config.wholeDetail === true && !productionGoal) result = await host.wholeDetail(config.text,{
|
||||
outputId:config.outputId, production:config.productProduction===true,
|
||||
});
|
||||
else result = await host.prompt(config.text, { referenceContent: config.referenceContent, goalContinuation: !!productionGoal&&!config.goalUserEntry });
|
||||
} else result = await host.prompt(config.text, { referenceContent: config.referenceContent, goalContinuation: !!productionGoal&&!config.goalUserEntry });
|
||||
signal?.throwIfAborted();
|
||||
if (broker.authority?.error) throw broker.authority.error;
|
||||
const pending = (await broker.status()).pending;
|
||||
|
||||
@ -1,182 +0,0 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { ProductionOutputLimit } from '../production-recovery.mjs';
|
||||
import { knowledgeReadInstruction } from '../production-knowledge.mjs';
|
||||
|
||||
const text = Type.String({minLength:1,maxLength:360});
|
||||
const object = properties => Type.Object(properties,{additionalProperties:false});
|
||||
const identity = values => values.length ? Type.Union(values.map(value=>Type.Literal(value))) : text;
|
||||
|
||||
export function pageCopyInputs(fields, slots, pageOrder) {
|
||||
const pages = new Map(pageOrder.map(page=>[page,{page,fields:[],pictures:[]}]));
|
||||
for (const {page,field,role,label,maxChars,maxLines,rows,pictures,currentText} of fields) {
|
||||
if (!page || !field) throw Error('模板文字格缺少屏序或字段身份');
|
||||
if (!pages.has(page)) throw Error('模板文字格不属于已登记屏');
|
||||
const screen = pages.get(page);
|
||||
screen.fields.push({field,role:role??label,maxChars,maxLines,rows,pictures,currentText});
|
||||
}
|
||||
if(!pages.size)throw Error('模板未返回整页屏序');
|
||||
for (const screen of pages.values()) {
|
||||
const linkedPictures = new Set(screen.fields.flatMap(field=>field.pictures));
|
||||
screen.pictures = slots.filter(slot=>slot.documentId===screen.page||linkedPictures.has(slot.fieldId))
|
||||
.map(({fieldId,label,role,requirements})=>({picture:fieldId,role:role??label,requirements:requirements?.slice(0,320)}));
|
||||
}
|
||||
return [...pages.values()];
|
||||
}
|
||||
|
||||
export async function planPageCopy(runAgent, scope, evidence, pages, direction) {
|
||||
try {
|
||||
return await planPageCopyBatch(runAgent, scope, evidence, pages, direction);
|
||||
} catch (error) {
|
||||
if (!(error instanceof ProductionOutputLimit) || pages.length < 2) throw error;
|
||||
const split = Math.ceil(pages.length / 2);
|
||||
const first = await planPageCopy(runAgent, scope, evidence, pages.slice(0, split), direction);
|
||||
const {lead,voice} = first;
|
||||
const prior=[...(direction?.prior??[]),...first.screens.map(({page,message})=>({page,message}))];
|
||||
const rest = await planPageCopy(runAgent, scope, evidence, pages.slice(split), {lead,voice,prior});
|
||||
return {lead,voice,screens:[...first.screens,...rest.screens]};
|
||||
}
|
||||
}
|
||||
|
||||
async function planPageCopyBatch(runAgent, scope, evidence, pages, direction) {
|
||||
const pageIds = pages.map(({page})=>page);
|
||||
const sourceIds = new Set(evidence.strategy.sourceIds);
|
||||
const allowed = new Map(pages.map(({page,pictures})=>[page,new Set(pictures.map(({picture})=>picture))]));
|
||||
const needsProof = new Set(pages.filter(screen=>screen.fields.some(field=>field.pictures.length)).map(({page})=>page));
|
||||
const brief = Type.String({minLength:1,maxLength:64});
|
||||
const screensSchema=object(Object.fromEntries(pages.map(({page,pictures})=>[page,object({
|
||||
purpose:brief,message:brief,sources:Type.Array(identity([...sourceIds]),{maxItems:sourceIds.size,uniqueItems:true}),
|
||||
proofs:Type.Array(object({picture:identity(pictures.map(row=>row.picture)),show:brief}),
|
||||
{minItems:needsProof.has(page)?1:0,maxItems:pictures.length}),
|
||||
})])));
|
||||
let outline;
|
||||
const plan = {
|
||||
name:'plan_page_copy',label:'规划整页卖点',
|
||||
description:'按模板顺序记录整页主张,以及各屏承担的内容和能拍清它的图位。',
|
||||
parameters:object({...(direction?{}:{lead:brief,voice:brief}),screens:screensSchema}),
|
||||
execute:(_id,{lead,voice,screens},signal)=>{
|
||||
signal?.throwIfAborted();
|
||||
if(Object.keys(screens).length!==pageIds.length||pageIds.some(page=>!Object.hasOwn(screens,page)))
|
||||
throw Error('使用 screens 中已有的屏号作为键,为每一屏记录策划。');
|
||||
const entries=pageIds.map(page=>({page,...screens[page]}));
|
||||
if(entries.some(({page,sources,proofs})=>sources.some(source=>!sourceIds.has(source))||
|
||||
needsProof.has(page)&&(!proofs.length||!sources.length)||
|
||||
new Set(proofs.map(row=>row.picture)).size!==proofs.length||
|
||||
proofs.some(({picture})=>!allowed.get(page)?.has(picture)))) {
|
||||
throw Error('每屏使用本款的资料原编号与该屏列出的图位编号。有图位关联的文字屏需填写至少一项可见证据。');
|
||||
}
|
||||
outline={lead:direction?.lead??lead,voice:direction?.voice??voice,screens:entries};
|
||||
return {content:[{type:'text',text:'已记录整页策划和图位证据。'}],terminate:true};
|
||||
},
|
||||
};
|
||||
await runAgent('supervisor',[
|
||||
'通读原片、产品资料、品牌用语、模板顺序和已填文案,为当前输出制定整体策划和逐屏写作方向。',
|
||||
'用一句话定下本款最值得讲的、能被证据支持的主卖点。品牌和模板决定语气、节奏、篇幅及各屏用途。商品事实来自当前资料和原片。',
|
||||
'按模板原序给每屏一个不同的阅读任务。总览交代差异,使用场景写能拍到的动作,结构或纹理近景写可定位的细节,规格屏交代有据参数。承接与转场屏可以只安排引导文字。具体职责服从模板。',
|
||||
'同一部件能在多屏出现,每次要增加新的可见证据、观察角度或使用场景。避免跨屏换词重复一个意思。',
|
||||
'每屏用短语写目的、主张和可见部位。只登记支撑主张所需的图位及证据编号。直接提交工具。',
|
||||
direction&&'沿用 direction 中的主卖点与语气,避开 prior 已分配的主张,只提交当前批次。',
|
||||
evidence.knowledge?.files.length&&knowledgeReadInstruction,
|
||||
'screens 必须以模板提供的屏号为键,键里不加空格或标题。为需要照片证明的主张填写图位编号和最终图框要看清的位置。已有文字保留,规格或承接屏可无独立配图。完成后调用 plan_page_copy。',
|
||||
].filter(Boolean).join('\n'),JSON.stringify({product:evidence.product,facts:evidence.facts,strategy:evidence.strategy,
|
||||
brandCopy:evidence.brandCopy,guidance:evidence.guidance,direction,
|
||||
...(evidence.knowledge?.files.length?{knowledgeFiles:evidence.knowledge.files}:null),
|
||||
pages:pages.map(({page,fields,pictures})=>({page,pictures,fields:fields.map(({role,pictures,currentText})=>({role,pictures,currentText}))}))}),
|
||||
[plan,...(evidence.knowledge?.tools??[])],evidence.photos,scope);
|
||||
if(!outline)throw Error('整页卖点规划尚未取得回执');
|
||||
return outline;
|
||||
}
|
||||
|
||||
export async function auditPageCopy(runAgent, scope, outline, pages, drafts, fields, outstanding, eligibleLayers) {
|
||||
const byField = new Map(fields.map(field=>[field.field,field.layer]));
|
||||
const previous = new Map(outstanding?.map(row=>[row.page,row]));
|
||||
const followup = previous.size>0;
|
||||
const review = pages.map(({page,pictures,fields:rows})=>({
|
||||
page,pictures,fields:rows.map(({field,role,maxChars,maxLines,rows:fixedRows,currentText,pictures:pictureOptions})=>{
|
||||
const draft = drafts.get(byField.get(field));
|
||||
return {field,role,maxChars,maxLines,rows:fixedRows,text:draft?.text??currentText,
|
||||
editable:Boolean(draft)&&(eligibleLayers?eligibleLayers.has(byField.get(field)):
|
||||
!followup||previous.get(page)?.fields.includes(field)===true),
|
||||
pictureOptions,
|
||||
...(draft?{sources:draft.sources,pictures:draft.pictures}:null)};
|
||||
}),
|
||||
}));
|
||||
const context = new Map(review.flatMap(({page,fields})=>fields.map(row=>[row.field,{...row,page}])));
|
||||
const editableFields = new Map(review.map(({page,fields})=>[page,new Set(fields.filter(row=>row.editable).map(row=>row.field))]));
|
||||
const writablePages = [...editableFields].filter(([,ids])=>ids.size).map(([page])=>page);
|
||||
if(!writablePages.length)return [];
|
||||
const findings = outstanding?.flatMap(row=>{
|
||||
const remaining=row.fields.filter(field=>editableFields.get(row.page)?.has(field));
|
||||
return remaining.length?[{...row,fields:remaining}]:[];
|
||||
});
|
||||
let result;
|
||||
const tool = {
|
||||
name:'review_page_copy',label:'复核整页文案',
|
||||
description:'通读整页,记录通过结论或仍需重写的屏与具体问题。',
|
||||
parameters:object({
|
||||
revisions:Type.Array(object({page:identity(writablePages),
|
||||
fields:Type.Array(identity([...editableFields.values()].flatMap(fields=>[...fields])),{minItems:1,uniqueItems:true}),
|
||||
reason:text,
|
||||
issues:Type.Optional(Type.Array(object({
|
||||
field:identity([...editableFields.values()].flatMap(fields=>[...fields])),
|
||||
kind:Type.Union(['duplicate','evidence','fit','wording','coherence'].map(value=>Type.Literal(value))),
|
||||
reason:Type.String({minLength:1,maxLength:140}),
|
||||
conflicts:Type.Array(identity([...context.keys()]),{maxItems:4,uniqueItems:true}),
|
||||
alternative:Type.Optional(object({picture:text,observation:Type.String({minLength:1,maxLength:100})})),
|
||||
}))),}),{maxItems:writablePages.length}),
|
||||
}),
|
||||
execute:(_id,{revisions},signal)=>{
|
||||
signal?.throwIfAborted();
|
||||
if(new Set(revisions.map(row=>row.page)).size!==revisions.length||
|
||||
revisions.some(({page,fields})=>!writablePages.includes(page)||
|
||||
fields?.some(field=>!editableFields.get(page)?.has(field)))) {
|
||||
throw Error('每个可改写屏只返回一条意见,列出这一屏实际需要修改的字段。');
|
||||
}
|
||||
result=revisions.map(row=>{
|
||||
const original=previous.get(row.page);
|
||||
const issues=row.issues??[];
|
||||
if(new Set(issues.map(item=>item.field)).size!==issues.length
|
||||
||issues.some(item=>!row.fields.includes(item.field)
|
||||
||item.conflicts.some(other=>other===item.field||!context.has(other))
|
||||
||(item.kind==='duplicate'&&!item.conflicts.length)
|
||||
||(item.alternative&&!context.get(item.field)?.pictureOptions?.includes(item.alternative.picture)))){
|
||||
throw Error('返修意见必须引用当前页面已有的文字格。重复项需标明冲突文字格,改写建议必须使用该格允许的图位。');
|
||||
}
|
||||
const byId=new Map(issues.map(item=>[item.field,item]));
|
||||
return {...row,...(original?{originalReason:original.originalReason??original.reason}:null),
|
||||
issues:row.fields.map(field=>{
|
||||
const item=byId.get(field);
|
||||
const current=context.get(field);
|
||||
const prior=original?.issues?.find(issue=>issue.field===field);
|
||||
const conflicts=(item?.conflicts??[]).map(id=>{
|
||||
const {page,field,text,pictures}=context.get(id);
|
||||
return {page,field,text,pictures};
|
||||
});
|
||||
const sameConflict=!item?.conflicts?.length||!prior?.conflicts?.length
|
||||
||(item.conflicts.length===prior.conflicts.length&&prior.conflicts.every(other=>item.conflicts.includes(other.field)));
|
||||
const changeAngle=original?.fields.includes(field)===true&&(!prior?.kind||!item?.kind||prior.kind===item.kind)&&sameConflict;
|
||||
return {field,kind:item?.kind,reason:item?.reason??row.reason,rejectedText:current.text,
|
||||
pictures:current.pictures?.length?current.pictures:current.pictureOptions,conflicts,
|
||||
...(item?.alternative?{alternative:item.alternative}:null),changeAngle};
|
||||
}),
|
||||
};
|
||||
});
|
||||
return {content:[{type:'text',text:revisions.length?'已记录需改写的屏。':'整页文案已通过通读。'}],terminate:true};
|
||||
},
|
||||
};
|
||||
await runAgent('supervisor',[
|
||||
'逐屏通读整页文案,然后核查首屏到末屏的阅读顺序。对照原策划里的每屏任务、语气和配图证据。',
|
||||
...(followup?[
|
||||
'这是上一轮具体问题的复验。整页用作上下文,仅核对 findings 中问题是否已解决。已经改为不同观察角度、补全真实依据或消除原矛盾,即应关闭该问题。只退回原问题仍存在或改写直接带来实质性错误的字段。',
|
||||
]:[
|
||||
'检查相邻或间隔屏是否重复了同一个商品主张,是否遗漏本款核心区分点,是否从场景自然推进到细节、搭配或规格。同一部件可以从使用动作、结构关系和材质特写分别展开。章节引导、总览预告、专名和规格复现可保留。',
|
||||
'需要处理重复时指出哪处先保留、哪处改写,并按原策划给改写处一个不同的可见信息。仅复用同一个部件名或花色不算重复。',
|
||||
]),
|
||||
'站在买家角度,把每屏标题、导语和卖点连起来读。标题说本屏重点,正文用自然的短句说清能看到的细节或使用方式。检查图文是否对应,是否有未经证实的延伸。',
|
||||
'把拍摄口令、验图记录和零散观察句当成实质措辞问题。例如「侧面取景,圆角清楚可见」是制作描述;写「靠背两端做成圆角」才是买家能读懂的商品描述。复读句子,退回重复词、同义叠加、词组硬拼和缺少主体的半句话。标签、固定规格行和品牌专名按各自用途判断。已有文字用于相邻语境,具体返修只给 editable 字段。',
|
||||
'遵守字段的字数、行数和固定行名。缺少资料的规格保留待核实,短标签承担一个具体观察即可。仅有措辞偏好或需要超出字段篇幅的补充无需退回。',
|
||||
'有具体问题时返回屏号、fields 中实际要重写的字段编号、重复内容或缺口及改写方向。每条只选这一屏需要重写的字段。多屏都要改时分别列出。没有需要改的屏时返回空 revisions。',
|
||||
'对每个退回字段在 issues 中分别提交短原因和问题类型。重复主张用 duplicate,conflicts 填承载同一主张的其他字段号,保留那些字段原文。证据不足、模板限制、措辞和衔接问题分别用 evidence、fit、wording、coherence;无冲突对象时 conflicts 为空。能指出替代观察角度时,alternative 写清图上要看见的部位、动作或关系,picture 只能从该格的 pictureOptions 选。避免把上一稿的同一主张换个说法再提交。',
|
||||
].join('\n'),JSON.stringify({outline,pages:review,...(followup?{findings}:null)}),[tool],undefined,scope);
|
||||
if(!result)throw Error('整页文案复核尚未取得回执');
|
||||
return result;
|
||||
}
|
||||
@ -1,187 +0,0 @@
|
||||
import path from 'node:path';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { atomic } from '../store.mjs';
|
||||
import { copyProofInstructions, unsupportedClaims } from '../product-copy-evidence.mjs';
|
||||
import { productRequestScope, ProductionRequestFailed, ProductionRequestPending } from '../production-recovery.mjs';
|
||||
import { knowledgeReadInstruction, productionKnowledge, productionRuleText } from '../production-knowledge.mjs';
|
||||
|
||||
const phrase = Type.String({ minLength:1, maxLength:240 });
|
||||
const sceneNote = Type.String({ minLength:1, maxLength:120 });
|
||||
export const sceneGroundLabels = Object.freeze({
|
||||
woven_rug:'有清晰织纹的地毯', wood_planks:'可见木纹和板缝的木地板',
|
||||
light_stone:'可见天然纹理的浅色石面', smooth_concrete:'连续的素色灰泥或水泥地面',
|
||||
ceramic_tile:'可见规则接缝的瓷砖面',
|
||||
});
|
||||
export const sceneGarmentLabels = Object.freeze({
|
||||
long_trousers:'有两条独立裤管的长裤', shorts:'短裤', skirt:'半身裙', dress:'连衣裙',
|
||||
});
|
||||
const sceneGround = Type.Union(Object.keys(sceneGroundLabels).map(value=>Type.Literal(value)));
|
||||
const sceneGarment = Type.Union(Object.keys(sceneGarmentLabels).map(value=>Type.Literal(value)));
|
||||
const evidenceIds = sourceIds => Type.Array(Type.Union([...sourceIds].map(id=>Type.Literal(id))),
|
||||
{minItems:1,maxItems:4,description:'每项只填一个来源编号,如 P01。观察描述单独填写。'});
|
||||
const pointSchema = sourceIds => ({
|
||||
copy:phrase,
|
||||
evidence:evidenceIds(sourceIds),
|
||||
});
|
||||
const strategySchema = (sourceIds, inspectSharedGround, inspectSharedGarment) => Type.Object({
|
||||
concept:phrase,
|
||||
audience:phrase,
|
||||
visualDirection:phrase,
|
||||
sceneContinuity:Type.Object({
|
||||
setting:sceneNote,
|
||||
lighting:sceneNote,
|
||||
cast:sceneNote,
|
||||
...(inspectSharedGround?{ground:sceneGround}:null),
|
||||
...(inspectSharedGarment?{garment:sceneGarment}:null),
|
||||
},{additionalProperties:false}),
|
||||
copyDirection:phrase,
|
||||
sellingPoints:Type.Array(Type.Object(pointSchema(sourceIds),{additionalProperties:false}),{minItems:1,maxItems:8}),
|
||||
missing:Type.Array(phrase,{maxItems:12}),
|
||||
},{additionalProperties:false});
|
||||
const reviewSchema = sourceIds => Type.Object({
|
||||
concept:phrase,
|
||||
sellingPoints:Type.Array(Type.Object({
|
||||
...pointSchema(sourceIds),observation:phrase,
|
||||
},{additionalProperties:false}),{minItems:1,maxItems:8}),
|
||||
},{additionalProperties:false});
|
||||
|
||||
export async function prepareProductStrategy(host, runAgent, plan, slots, knowledge) {
|
||||
const {canvas,store}=host;
|
||||
const binding=plan.productEvidence;
|
||||
if(!binding?.project||!binding.brief?.name||!Number.isSafeInteger(binding.revision)) {
|
||||
throw Error('请先保存当前项目的产品资料');
|
||||
}
|
||||
const file='product-production-strategy.json';
|
||||
const original=await store.get(file,null);
|
||||
const inspectSharedGround=slots.some(slot=>slot.productionRule?.sharedGround===true);
|
||||
const inspectSharedGarment=slots.some(slot=>slot.productionRule?.sharedGarment===true);
|
||||
const currentBinding=original?.project===binding.project&&original.revision===binding.revision&&
|
||||
original.evidenceVariantId===plan.productVariantId;
|
||||
if(currentBinding&&original.reviewed===true&&original.strategy?.sourceIds) return original.strategy;
|
||||
|
||||
const input=slots[0] ? await canvas.detailImages(slots[0].id) : null;
|
||||
const images=input?.images?.slice(0,input.referenceCount)??[];
|
||||
const layout=input?.layoutCount?input.images.slice(input.referenceCount):[];
|
||||
const layoutSlots=layout.length?[slots[0].fieldId]:[];
|
||||
const castingSlot=slots.find(slot=>slot!==slots[0]&&slot.layoutReference&&slot.productionRule?.people>0);
|
||||
if(castingSlot){
|
||||
const reference=await canvas.detailImages(castingSlot.id);
|
||||
if(reference?.layoutCount){
|
||||
layout.push(...reference.images.slice(reference.referenceCount));
|
||||
layoutSlots.push(castingSlot.fieldId);
|
||||
}
|
||||
}
|
||||
if(slots.length&&!images.length)throw Error('当前花色缺少已核验的同款产品图');
|
||||
const sources=[
|
||||
{id:'资料',value:binding.brief},
|
||||
...((binding.facts?.items??[]).map((fact,index)=>({id:'F'+(index+1),value:fact}))),
|
||||
...images.map((_,index)=>({id:'P'+String(index+1).padStart(2,'0'),value:'同款原图,按查看顺序编号'})),
|
||||
];
|
||||
const sourceIds=new Set(sources.map(source=>source.id));
|
||||
const sourceList=[...sourceIds];
|
||||
const record={project:binding.project,revision:binding.revision,evidenceVariantId:plan.productVariantId,
|
||||
evidenceSources:sourceList,adoption:'automatic',sources:[...knowledge.skills,...knowledge.rules]
|
||||
.map(({fileId,revision,kind})=>({fileId,revision,kind}))};
|
||||
const toResult=value=>({content:[{type:'text',text:JSON.stringify(value)}],details:value,terminate:true});
|
||||
const validate=value=>{
|
||||
if(value.sellingPoints.some(point=>point.evidence.some(id=>!sourceIds.has(id)))) {
|
||||
throw Error('evidence 每项只填一个编号,不附说明。当前可用编号:'+sourceList.join('、'));
|
||||
}
|
||||
const reject=claims=>{
|
||||
throw Error('商品资料未确认「'+[...claims].join('、')+'」,请改为可见的颜色、纹理或结构。');
|
||||
};
|
||||
const unsupportedConcept=unsupportedClaims(value.concept,binding.brief);
|
||||
if(unsupportedConcept.length)reject(unsupportedConcept);
|
||||
const excluded=new Set();
|
||||
const sellingPoints=value.sellingPoints.filter(point=>{
|
||||
const unsupported=unsupportedClaims(point.copy,binding.brief);
|
||||
unsupported.forEach(claim=>excluded.add(claim));
|
||||
return !unsupported.length;
|
||||
});
|
||||
if(!sellingPoints.length)reject(excluded);
|
||||
return {...value,sellingPoints};
|
||||
};
|
||||
const persist=async (value,signal)=>{
|
||||
signal?.throwIfAborted();
|
||||
const current=await canvas.workflowRead({section:'materials'});
|
||||
if(!current.available||current.productEvidence?.project!==binding.project||current.revisions?.creation!==binding.revision||
|
||||
current.productVariantId!==plan.productVariantId) {
|
||||
throw Error('商品资料已变化,未保存旧策划');
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
await atomic(path.join(store.dir,file),{...record,...value});
|
||||
};
|
||||
|
||||
// Keep the proposal while its independent review is still pending. A later
|
||||
// output can recover that original review without dispatching the proposal again.
|
||||
let proposal=currentBinding?(original.proposal??original.strategy):undefined;
|
||||
let selected;
|
||||
try {
|
||||
if(!proposal){
|
||||
const rules=productionKnowledge(knowledge,'strategy');
|
||||
const guidance=[
|
||||
['selling-points',productionRuleText(knowledge,'selling-points',1400,/总则|需求|选卖点|证据/u)],
|
||||
['brand',productionRuleText(knowledge,'brand',3600)],
|
||||
].flatMap(([kind,text])=>text?[{kind,text}]:[]);
|
||||
const scope=host.productionRequests?.has('production-strategy')?'production-strategy':productRequestScope('strategy',plan.productVariantId);
|
||||
await runAgent('production-strategy',[
|
||||
'依据知识库方法策划商品内容。先看按 P01、P02 编号的同款原图,再按 layoutSlots 看可选模板构图参考。模板图片用于确定构图、摄影风格和出镜类型。',
|
||||
'明确购买任务和人群假设,比较可行方向,选一条由同款资料支持的核心概念。优先提炼当前产品区别于其他同品类商品的可证实特征;概念要能讲出区别。',
|
||||
'每条卖点的 evidence 只填 sources 里的编号数组,如 ["P01","P02"]。卖点描述写入 copy。资料只支持外观时,写可见的部件、纹理、位置和关系。',
|
||||
...copyProofInstructions,
|
||||
'需要本款资料而当前缺失的信息填在 missing。',
|
||||
'visualDirection 写整组场景图共用的产品调性,包括场景与材质、光线方向和软硬、色温及画面氛围。从模板图片、模板调性和当前视觉规范提炼。各图位保留自己的镜头与取景,同款实物与 SKU 原图保持真实配色。',
|
||||
'sceneContinuity 锁定一套可反复拍摄的方案。setting 写同一空间的墙地材质、主家具与少量道具;lighting 写实际光源、方向和色温;cast 写同一出镜人物的年龄段、发型和服装的颜色及款式。模板明确要求换场景或角色时保留该图位的要求。无人图位保持无人。',
|
||||
...(inspectSharedGround?['共用布景的全景图需要能核对主体正下方的地面。根据模板设定选定 sceneContinuity.ground,材质代码见 groundOptions,并在 setting 中写清相同材质,避免另写相互矛盾的地面。镜头可以变化。']:[]),
|
||||
...(inspectSharedGarment?['为同组人物的可见下装选定 sceneContinuity.garment,款式代码见 garmentOptions。cast 写清与这个款式一致的颜色、质地和轮廓。']:[]),
|
||||
'copyDirection 根据当前商品证据、品牌规范与模板调性确定表达方式,写清主打卖点、买家措辞和句式节奏。模板字段与品牌规范只提供表达约束,不能作为商品事实来源。不要照抄模板示例、品牌口号或其他产品文案。',
|
||||
'已有模板承接其图位和文字限制。主图独立策划、SKU 按款式选图。共享概念写款式共通卖点;原图能核对的专有花色词留到对应款式的文案。',
|
||||
rules.files.length&&knowledgeReadInstruction,
|
||||
'完成后调用 save_product_strategy 提交当前策划。',
|
||||
].filter(Boolean).join('\n'),JSON.stringify({sources,selected:binding.sellingPoints?.selected,
|
||||
template:plan.template.name,route:plan.template.productionRoute,templateVisualDirection:plan.template.production?.visualDirection,
|
||||
layout:layout.length,layoutSlots,
|
||||
...(inspectSharedGround?{groundOptions:sceneGroundLabels}:null),
|
||||
...(inspectSharedGarment?{garmentOptions:sceneGarmentLabels}:null),
|
||||
guidance,...(rules.files.length?{knowledgeFiles:rules.files}:null)}),[
|
||||
{name:'save_product_strategy',label:'保存策划稿',description:'保存需要独立核验的商品策划稿。',parameters:strategySchema(sourceIds,inspectSharedGround,inspectSharedGarment),
|
||||
execute:async(_id,value,signal)=>{
|
||||
if(proposal)return toResult(proposal);
|
||||
const checked=validate(value);
|
||||
await persist({proposal:checked},signal);
|
||||
proposal=checked;
|
||||
return toResult(proposal);
|
||||
}},
|
||||
...rules.tools,
|
||||
],[...images,...layout],scope);
|
||||
}
|
||||
if(!proposal)throw Error('整套制作尚未取得商品策划稿');
|
||||
await runAgent('production-strategy-audit',[
|
||||
'独立复核商品策划中的核心概念和每条卖点。按 P01、P02 顺序读取同款原片。逐句用实际列出的证据核对。优先保留能区分本款的可见卖点,删去适用于几乎所有同品类商品的泛化口号。',
|
||||
...copyProofInstructions,
|
||||
'对连续、闭合同一部件、部件穿过空隙等表述,定位每个可见端点和接合处。开口的弧线可以写环抱造型;只有能确认首尾闭合时才称闭环。明确指出原片实际支持的范围。',
|
||||
'同款原片可以支持弯曲轮廓、可见边缘和表面。通过净空、适配尺寸或对摆放空间的保证需要同款资料的已确认尺寸。布景设想只用于后续取景。',
|
||||
'用 review_product_strategy 返回核实后的概念和卖点。证据不足的部分删减或改写为可见事实。为每条卖点列出真实来源编号,observation 写出该编号里能看到的具体部件、位置或已明确的资料值。概念概括核实后的卖点。',
|
||||
].join('\n'),JSON.stringify({sources,concept:proposal.concept,sellingPoints:proposal.sellingPoints}),[
|
||||
{name:'review_product_strategy',label:'复核策划卖点',description:'保存已核实的商品概念和逐条证据。',parameters:reviewSchema(sourceIds),
|
||||
execute:async(_id,value,signal)=>{
|
||||
if(selected)return toResult(selected);
|
||||
const checked=validate(value);
|
||||
if(checked.sellingPoints.some(point=>!point.observation.trim()))throw Error('每条核实的卖点需记录同款来源中的可见依据');
|
||||
const strategy={...proposal,...checked,sourceIds:sourceList};
|
||||
await persist({proposal,strategy,reviewed:true},signal);
|
||||
selected=strategy;
|
||||
return toResult(selected);
|
||||
}},
|
||||
],images,productRequestScope('strategy-audit',plan.productVariantId));
|
||||
} catch(error){
|
||||
if(selected)return selected;
|
||||
const waiting=error instanceof ProductionRequestPending;
|
||||
if(!waiting&&!(error instanceof ProductionRequestFailed))throw error;
|
||||
await store.appendEvent({type:'production_strategy_deferred',id:error.id,reason:error.message,variantId:plan.productVariantId});
|
||||
await canvas.delta((waiting?'商品策划原回执待核查':'商品策划服务已确认失败')+',按本款资料与模板继续制作').catch(()=>{});
|
||||
return {sourceIds:sourceList,sellingPoints:[],planning:'current-product-evidence'};
|
||||
}
|
||||
if(!selected)throw Error('整套制作尚未取得有依据的商品策划');
|
||||
return selected;
|
||||
}
|
||||
@ -1,168 +0,0 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { unsupportedClaims } from '../product-copy-evidence.mjs';
|
||||
|
||||
export function productionImageRule(slot) {
|
||||
const rule=slot?.productionRule;
|
||||
return ['product','generate'].includes(rule?.source) && typeof rule.focus==='string' && rule.focus.trim()
|
||||
? rule : null;
|
||||
}
|
||||
|
||||
export function copyPictures(template, field, slots) {
|
||||
const available=new Set(slots.map(slot=>slot.fieldId));
|
||||
const configured=template?.production?.copyRules?.[field.field]?.pictures;
|
||||
if(Array.isArray(configured))return configured.filter(id=>available.has(id));
|
||||
const own=slots.filter(slot=>slot.documentId===field.page).map(slot=>slot.fieldId);
|
||||
const direct=Array.isArray(field.relatedFields)?field.relatedFields.filter(id=>available.has(id)):[];
|
||||
const reverse=slots.filter(slot=>Array.isArray(slot.relatedFields)&&slot.relatedFields.includes(field.field)).map(slot=>slot.fieldId);
|
||||
const declared=[...new Set([...direct,...reverse])];
|
||||
return declared.length ? declared : own.length ? own : [...available];
|
||||
}
|
||||
|
||||
const text = Type.String({minLength:1,maxLength:500});
|
||||
export const copyEvidenceShape = sourceIds => ({
|
||||
sources:Type.Array(Type.Union(sourceIds.map(id=>Type.Literal(id))),{
|
||||
minItems:1,maxItems:8,uniqueItems:true,description:'只填项目来源编号。引用说明写在文案或验收理由中。',
|
||||
}),
|
||||
pictures:Type.Array(text,{minItems:1,maxItems:8,uniqueItems:true}),
|
||||
});
|
||||
|
||||
export function rejectedCopy(item, field, strategy, brief, slots=[]) {
|
||||
if (!field) return '文字格不存在或已经填写';
|
||||
if (!item.sources?.length || item.sources.some(id=>!strategy.sourceIds.includes(id))) {
|
||||
return '来源仅填写本款编号 '+strategy.sourceIds.join('、');
|
||||
}
|
||||
if (!item.pictures?.length || item.pictures.some(id=>!field.pictures.includes(id))) return '配图须来自该字段允许的图位';
|
||||
if (!item.sources.some(id=>/^P\d{2}$/u.test(id))) return '商品可见特点至少关联一张同款实拍';
|
||||
const lines=item.text.split('\n');
|
||||
const chars=Array.from(item.text).length;
|
||||
const maxChars=field.maxChars??120;
|
||||
const maxLines=field.maxLines??8;
|
||||
if(chars>maxChars||lines.length>maxLines){
|
||||
return `当前 ${chars} 字(含换行)、${lines.length} 行,模板最多 ${maxChars} 字、${maxLines} 行。保留必要项,缩短各项的值。`;
|
||||
}
|
||||
if(Array.isArray(field.rows)&&(lines.length!==field.rows.length||field.rows.some((label,index)=>{
|
||||
const parts=lines[index].match(/^([^::]+)[::]\s*(\S.*)$/u);
|
||||
return parts?.[1]!==label;
|
||||
}))){
|
||||
return `按模板顺序逐行填写 ${field.rows.join('、')}。每行写「行名:值」,资料缺项写「待核实」。`;
|
||||
}
|
||||
const unsupported=unsupportedClaims(item.text,brief);
|
||||
if (unsupported.length) return '缺少同款资料支持「'+unsupported.join('、')+'」';
|
||||
return item.pictures.length===1?copyCompositionConflict(slots,item.pictures,item.text):null;
|
||||
}
|
||||
|
||||
function excludedClause(exclusions,prompt) {
|
||||
if(!Array.isArray(exclusions))return null;
|
||||
const clauses=prompt.replace(/(?:不要|禁止|避免|不出现|不得|不可|不能|切勿)[^,,。;;\n]*/gu,'').split(/[,,。;;\n]/u);
|
||||
for(const entry of exclusions) {
|
||||
const terms=entry?.terms;
|
||||
if(!Array.isArray(terms)||!terms.length||!terms.every(term=>typeof term==='string'&&term))continue;
|
||||
if(clauses.some(clause=>terms.every(term=>clause.includes(term)))){
|
||||
return typeof entry.message==='string'&&entry.message?entry.message:'文案与图位构图要求不一致';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function generationConflict(rule,prompt) {
|
||||
return excludedClause(rule?.exclusions,prompt);
|
||||
}
|
||||
|
||||
const depictedHumanAction=/(?:落座|倚坐|侧坐|坐下|起身|双手持|前臂搭|手腕搭)(?!高度|空间|位置|区域|区)/u;
|
||||
|
||||
function copyConflict(rule,text) {
|
||||
const action=rule?.people===0?depictedHumanAction.exec(text):null;
|
||||
if(action)return '该图位为无人取景,无法展示「'+action[0]+'」动作。请写此图可见的外观,或将动作分配给可拍到人物的图位。';
|
||||
return excludedClause(rule?.copyExclusions,text)??generationConflict(rule,text);
|
||||
}
|
||||
|
||||
export function copyCompositionConflict(slots,pictures,text) {
|
||||
for(const slot of slots) {
|
||||
if(!pictures.includes(slot.fieldId))continue;
|
||||
const conflict=copyConflict(productionImageRule(slot),text);
|
||||
if(conflict)return conflict;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function visualCopy(copy, template) {
|
||||
const title=/^(?:[一二三四五六七八九十\d]+(?:[大处点项])?)?(?:外观|设计|产品|造型)?(?:亮点|细节|特色|总览|一览|优势|介绍)$/u;
|
||||
return copy.flatMap(row=>{
|
||||
if (title.test(row.text.trim())) return [];
|
||||
const lines=template?.production?.copyRules?.[row.field]?.visualLines;
|
||||
if(!Array.isArray(lines))return [row];
|
||||
const appearance=row.text.split('\n').filter(line=>{
|
||||
const value=line.trim();
|
||||
return lines.some(label=>value.startsWith(label)&&/^(?:[::]|\s)\s*\S/u.test(value.slice(label.length)));
|
||||
}).join('\n');
|
||||
return appearance ? [{...row,text:appearance}] : [];
|
||||
});
|
||||
}
|
||||
|
||||
export function visualClauses(row,template) {
|
||||
const content=visualCopy([row],template)[0]?.text??'';
|
||||
return content.split(/[,,。;;、\n]+/u).map(clause=>clause.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
export function assignCopyEvidence(pictures,clauses,links) {
|
||||
if(!links?.length)return null;
|
||||
const covered=new Set();
|
||||
const assigned=Object.create(null);
|
||||
for(const {picture,claims:indices} of links){
|
||||
if(!pictures.includes(picture)||Object.hasOwn(assigned,picture)||!indices?.length)return null;
|
||||
for(const index of indices){
|
||||
if(!clauses[index]||covered.has(index))return null;
|
||||
covered.add(index);
|
||||
}
|
||||
assigned[picture]=indices.map(index=>clauses[index]);
|
||||
}
|
||||
return covered.size===clauses.length?assigned:null;
|
||||
}
|
||||
|
||||
export function evidenceAtPicture(row,picture) {
|
||||
const clauses=row.evidenceByPicture?.[picture];
|
||||
return Array.isArray(clauses)?clauses.join(';'):row.text;
|
||||
}
|
||||
|
||||
export function pictureCopyClaims(row,picture) {
|
||||
const clauses=row.evidenceByPicture?.[picture]??visualClauses(row);
|
||||
return {...row,text:evidenceAtPicture(row,picture),...(clauses.length>1?{claims:clauses}:null)};
|
||||
}
|
||||
|
||||
export function visibleCounts(rule,copy) {
|
||||
const counts=rule?.visibleCounts;
|
||||
if(counts==null)return [];
|
||||
if(!Array.isArray(counts)||counts.some(item=>
|
||||
!item||typeof item.id!=='string'||!item.id||typeof item.target!=='string'||!item.target||
|
||||
!Number.isInteger(item.count)||item.count<0||item.count>30||
|
||||
(item.minimum!==undefined&&(typeof item.minimum!=='boolean'||item.minimum&&item.count===0))||
|
||||
(item.confirmFrameSide!==undefined&&(typeof item.confirmFrameSide!=='boolean'||item.confirmFrameSide&&item.count!==1))||
|
||||
(item.whenCopyIncludes!=null&&(!Array.isArray(item.whenCopyIncludes)||
|
||||
item.whenCopyIncludes.some(term=>typeof term!=='string'||!term))))){
|
||||
throw Error('模板图位的可见证据项无效');
|
||||
}
|
||||
if(counts.filter(item=>item.confirmFrameSide).length>1)throw Error('模板图位只能为一处轮廓核对画面侧别');
|
||||
return counts.filter(({whenCopyIncludes})=>
|
||||
!whenCopyIncludes?.length||copy.some(row=>whenCopyIncludes.some(term=>row.text.includes(term))));
|
||||
}
|
||||
|
||||
export function locatedCopyEvidence(values,copy) {
|
||||
const allowed=new Map(copy.map(row=>[row.field,row]));
|
||||
return values.flatMap(value=>{
|
||||
const field=value?.field;
|
||||
const row=allowed.get(field);
|
||||
const claim=value?.claim;
|
||||
const location=typeof value?.location==='string'?value.location.trim():'';
|
||||
if(!row||!location)return [];
|
||||
if(!row.claims)return [{field,location}];
|
||||
if(!Number.isInteger(claim)||!row.claims[claim])return [];
|
||||
return [{field,claim,location}];
|
||||
});
|
||||
}
|
||||
|
||||
export function missingCopyEvidence(copy,evidence) {
|
||||
return visualCopy(copy).flatMap(({field,text,claims})=>{
|
||||
const entries=evidence.filter(found=>found.field===field);
|
||||
return claims ? claims.filter((_,index)=>!entries.some(found=>found.claim===index)) : entries.length?[]:[text];
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -74,7 +74,7 @@ test('production startup rejects the full requested scope before broker or canva
|
||||
const brokerBind = test.mock.fn();
|
||||
const canvasCall = test.mock.fn();
|
||||
const result = await runSession({
|
||||
mode:'prompt', wholeDetail:true, productProduction:true,
|
||||
mode:'prompt', productProduction:true,
|
||||
outputId:'detail', variantId:'oak',
|
||||
requestedOutputs:[nativeOutputs[0], {...video, templateRoles:['original', 'mapping']}],
|
||||
pendingOutputs:[nativeOutputs[0]],
|
||||
|
||||
18
apps/detail-agent-pi/test/production-goal.test.mjs
Normal file
18
apps/detail-agent-pi/test/production-goal.test.mjs
Normal file
@ -0,0 +1,18 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { runPiProductionGoal } from '../src/production-goal.mjs';
|
||||
|
||||
test('the production deadline aborts a goal still waiting for a local tool',async()=>{
|
||||
const idle=Promise.withResolvers();
|
||||
let called=0,aborted=0;
|
||||
const host={manager:{getBranch:()=>[]},productionGoal:{deadline:(Date.now()+50)/1000,requestedOutputs:[{outputId:'detail'}]},
|
||||
session:{
|
||||
sendCustomMessage:async()=>{},
|
||||
prompt:async()=>{called++},
|
||||
waitForIdle:()=>idle.promise,
|
||||
abort:async()=>{aborted++;idle.resolve()},
|
||||
}};
|
||||
await assert.rejects(runPiProductionGoal(host,'制作',false),/达到时限/u);
|
||||
assert.equal(called,1);
|
||||
assert.equal(aborted,1);
|
||||
});
|
||||
@ -6,7 +6,7 @@ import os from 'node:os';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { ProjectStore } from '../src/store.mjs';
|
||||
import { DetailPiAgent } from '../src/agent.mjs';
|
||||
import { ProductionRequestPending } from '../src/production-recovery.mjs';
|
||||
import { ProductionRequestPending, recoverProductionResponse } from '../src/production-recovery.mjs';
|
||||
import { cleanup } from './cleanup.mjs';
|
||||
|
||||
const setup = async () => {
|
||||
@ -442,3 +442,11 @@ test('a result from another shop cannot be restored or queried into this convers
|
||||
assert.equal(reads, 0);
|
||||
await host.dispose(); await cleanup(root);
|
||||
});
|
||||
|
||||
test('production recovery verifies the original request identity before confirming failure',async()=>{
|
||||
const requestId='confirmed-failed-review';
|
||||
const settled={phase:'failed',requestId,originalLookup:{verified:true,status:'failed',requestId}};
|
||||
assert.equal((await recoverProductionResponse({read:async()=>settled},'local',null,[])).confirmedFailure,true);
|
||||
assert.equal((await recoverProductionResponse({read:async()=>({...settled,originalLookup:{...settled.originalLookup,
|
||||
requestId:'another-request'}})},'local',null,[])).confirmedFailure,undefined);
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -3473,7 +3473,7 @@ impl Backend {
|
||||
if method == "slot-skeleton" && input["brief"].is_object() {
|
||||
self.creation_guard(doc, &dir)?;
|
||||
let previous = if exists(&dir) { Some(load(&dir)?) } else { None };
|
||||
if (input["generateWhole"] == true || input["generateProduct"] == true) && previous.as_ref().is_some_and(|old| old["activeMapping"].is_string()) {
|
||||
if input["generateProduct"] == true && previous.as_ref().is_some_and(|old| old["activeMapping"].is_string()) {
|
||||
return Err("请在新项目中一键生成整套详情页,当前画布与编辑已保留".into());
|
||||
}
|
||||
if previous.is_some() && !pending_summary(&dir)?.is_empty() {
|
||||
@ -3635,7 +3635,6 @@ impl Backend {
|
||||
if browsing {
|
||||
report(json!({"phase":if has_edit {"view-open"} else {"metadata"}}));
|
||||
}
|
||||
let generate_whole = input["generateWhole"] == true;
|
||||
let mut saved_view_can_be_reused = false;
|
||||
let mut native = if has_edit {
|
||||
let mut saved = photocraft_format::load_path(&edited).map_err(|_| "原生编辑稿无法读取,未用空骨架覆盖")?;
|
||||
@ -3723,7 +3722,6 @@ impl Backend {
|
||||
result["variantId"] = json!(variant_id);
|
||||
result["canvasFirst"] = json!(true);
|
||||
result["workspaceId"] = result["workflow"]["workspaceId"].clone();
|
||||
result["startWholeDetail"] = json!(generate_whole);
|
||||
result["continueProduct"] = input["continueProduct"].clone();
|
||||
if let Some(previous) = previous_view { result["previousViewPath"] = json!(previous); }
|
||||
if browsing {
|
||||
|
||||
@ -665,7 +665,6 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
|
||||
"projectEvidence":project_evidence(&super::creation::load(&dir)?,&b.scope(),&project,doc,&input["context"]["requestScope"]["variantId"]),
|
||||
"mode":mode,"text":input["text"],"productionOriginals":production_originals,
|
||||
"writeEpoch":scope["writeEpoch"],"documentKey":scope["documentKey"],"revision":input["context"]["revision"],
|
||||
"wholeDetail":input["context"]["requestScope"]["wholeDetail"] == true,
|
||||
"outputId":if scope["productProduction"] == true { scope["outputId"].as_str() }
|
||||
else { Some(scope["outputId"].as_str().unwrap_or("detail")) },
|
||||
"variantId":input["context"]["requestScope"]["variantId"],
|
||||
@ -820,7 +819,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
|
||||
}
|
||||
if matches!(action, "pi-detail-images" | "pi-detail-archive") {
|
||||
let archive = action == "pi-detail-archive";
|
||||
let queued = if archive && config["wholeDetail"] != true {
|
||||
let queued = if archive && config["productProduction"] != true {
|
||||
Err("当前回合没有整套详情页的授权".into())
|
||||
} else {
|
||||
let pool = detail_image_reads.get_or_insert_with(super::reads::ReadPool::detail_review);
|
||||
|
||||
@ -1244,7 +1244,7 @@ impl Workspace {
|
||||
fn slot_action_inner(&mut self, app: &PhotocraftApp, method: &str, mut input: Value, delegated: bool) -> Result<Value, String> {
|
||||
if method == "slot-skeleton" && input["outputId"].is_string() && input["documentId"].is_null()
|
||||
&& !input["brief"].is_object() && input["continueProduct"] != true && input["resumeProduct"] != true
|
||||
&& input["generateWhole"] != true && input["generateProduct"] != true
|
||||
&& input["generateProduct"] != true
|
||||
&& (self.template_workflow["productionStages"].is_array()
|
||||
|| self.product_production.is_some() || self.product_view_detached())
|
||||
{
|
||||
@ -1855,7 +1855,7 @@ impl Workspace {
|
||||
return;
|
||||
}
|
||||
if self.pi_write_blocked { return; }
|
||||
if self.pi_request_scope["wholeDetail"] == true {
|
||||
if self.pi_request_scope["productProduction"] == true {
|
||||
// Batch writes check the actual target against the canvas at the start of the run.
|
||||
if let Some((doc, revision)) = self.production_revision(app)
|
||||
&& Some(doc) == self.owner_doc && revision >= self.expected_revision
|
||||
@ -2360,60 +2360,62 @@ impl Workspace {
|
||||
"product":self.creation["brief"],"facts":self.creation["facts"],"sellingPoints":self.creation["sellingPoints"],"plan":self.creation["plan"]})
|
||||
}
|
||||
pub fn submit(&mut self, app: &PhotocraftApp, text: String) {
|
||||
if self.template_workflow["productionStages"].is_array()
|
||||
&& matches!(text.trim().trim_end_matches('。'),
|
||||
if matches!(text.trim().trim_end_matches('。'),
|
||||
"继续制作整套" | "继续整套制作" | "一键制作整套详情页" | "继续制作整套详情页")
|
||||
{
|
||||
self.submit_whole_detail(app);
|
||||
self.resume_product_production(app);
|
||||
} else {
|
||||
self.submit_turn(app, text, false);
|
||||
}
|
||||
}
|
||||
|
||||
fn can_resume_product(&self) -> bool {
|
||||
fn has_production_stages(&self) -> bool {
|
||||
self.template_workflow["productionStages"].as_array().is_some_and(|stages| !stages.is_empty())
|
||||
}
|
||||
|
||||
fn can_resume_product(&self) -> bool {
|
||||
self.has_production_stages()
|
||||
&& self.product_production.is_none() && self.turn_idle()
|
||||
&& (!self.unknown || self.scoped_production_pending())
|
||||
&& self.model_ready && self.image_ready && !self.creation_dirty
|
||||
}
|
||||
|
||||
fn submit_whole_detail(&mut self, app: &PhotocraftApp) {
|
||||
fn resume_product_production(&mut self, app: &PhotocraftApp) {
|
||||
if !self.has_production_stages() {
|
||||
self.error = "当前工程没有待继续的分期制作任务,可从产品资料启动制作".into();
|
||||
return;
|
||||
}
|
||||
if !(self.model_ready && self.image_ready) {
|
||||
self.error = "请先在小壹设置中选择可用的对话模型和生图模型,配置后可继续制作整套详情页".into();
|
||||
return;
|
||||
}
|
||||
if self.template_workflow["productionStages"].is_array() {
|
||||
if self.can_resume_product() {
|
||||
if let Some(problem) = self.production_model_problem() {
|
||||
self.error = problem;
|
||||
return;
|
||||
}
|
||||
if !self.resume_saved_production(app)
|
||||
&& let Err(error) = self.slot_action(app, "slot-skeleton", json!({"resumeProduct":true}))
|
||||
{
|
||||
self.error = error;
|
||||
}
|
||||
} else if self.unknown && !self.scoped_production_pending() {
|
||||
self.error = "请先核查原任务结果".into();
|
||||
} else if self.creation_dirty {
|
||||
self.error = "请先保存产品资料".into();
|
||||
if self.can_resume_product() {
|
||||
if let Some(problem) = self.production_model_problem() {
|
||||
self.error = problem;
|
||||
return;
|
||||
}
|
||||
} else if self.can_start_turn() {
|
||||
self.agent_effects_paused = false;
|
||||
self.submit_turn(app, "一键制作整套详情页".into(), true);
|
||||
if !self.resume_saved_production(app)
|
||||
&& let Err(error) = self.slot_action(app, "slot-skeleton", json!({"resumeProduct":true}))
|
||||
{
|
||||
self.error = error;
|
||||
}
|
||||
} else if self.unknown && !self.scoped_production_pending() {
|
||||
self.error = "请先核查原任务结果".into();
|
||||
} else if self.creation_dirty {
|
||||
self.error = "请先保存产品资料".into();
|
||||
}
|
||||
}
|
||||
fn submit_turn(&mut self, app: &PhotocraftApp, text: String, whole_detail: bool) {
|
||||
if !whole_detail && !self.composer_draft_ready(app) { self.error = "正在加载项目草稿".into(); return; }
|
||||
let ready = if whole_detail && self.product_production.is_some() {
|
||||
self.can_start_production_turn()
|
||||
fn submit_turn(&mut self, app: &PhotocraftApp, text: String, production: bool) {
|
||||
if !production && !self.composer_draft_ready(app) { self.error = "正在加载项目草稿".into(); return; }
|
||||
let ready = if production {
|
||||
self.product_production.is_some() && self.can_start_production_turn()
|
||||
} else { self.can_start_turn() };
|
||||
if text.trim().is_empty() || !ready { return; }
|
||||
if whole_detail && let Some(problem) = self.production_model_problem() {
|
||||
if production && let Some(problem) = self.production_model_problem() {
|
||||
self.error = problem;
|
||||
return;
|
||||
}
|
||||
if !whole_detail && !self.composer_text_send_allowed_for(app) {
|
||||
if !production && !self.composer_text_send_allowed_for(app) {
|
||||
self.error = "当前对话模型暂不支持图片,请先移除附件或使用生图".into();
|
||||
return;
|
||||
}
|
||||
@ -2421,8 +2423,8 @@ impl Workspace {
|
||||
self.error = "请在对话栏设置可用的对话模型".into();
|
||||
return;
|
||||
}
|
||||
if !whole_detail { self.composer_reference_sync(app); }
|
||||
let references = match if whole_detail { Ok(Vec::new()) } else { self.composer_reference_snapshot(app) } {
|
||||
if !production { self.composer_reference_sync(app); }
|
||||
let references = match if production { Ok(Vec::new()) } else { self.composer_reference_snapshot(app) } {
|
||||
Ok(references) => references,
|
||||
Err(error) => { self.error = error; return; }
|
||||
};
|
||||
@ -2445,9 +2447,8 @@ impl Workspace {
|
||||
"selectedLayerIds":references.iter().filter_map(|item|item["nativeLayerId"].as_u64()).collect::<std::collections::BTreeSet<_>>() }),
|
||||
};
|
||||
let mut scope = self.request_scope(active.doc.id.0, subject, &references);
|
||||
if whole_detail { scope["wholeDetail"] = json!(true); }
|
||||
let mut text = text;
|
||||
if whole_detail && let Some(run) = self.product_production.as_mut() {
|
||||
if production && let Some(run) = self.product_production.as_mut() {
|
||||
run.cancel_deferred_image_recovery();
|
||||
self.write_epoch += 1;
|
||||
scope["writeEpoch"] = json!(self.write_epoch);
|
||||
@ -2487,7 +2488,7 @@ impl Workspace {
|
||||
);
|
||||
if self.busy.as_deref() != Some("agent") {
|
||||
self.pi_request_scope = Value::Null;
|
||||
} else if !whole_detail {
|
||||
} else if !production {
|
||||
self.composer_reference_clear(app);
|
||||
}
|
||||
}
|
||||
@ -2550,7 +2551,7 @@ impl Workspace {
|
||||
self.unknown = v["pending"].as_bool().unwrap_or(self.unknown);
|
||||
}
|
||||
let settled_batch_candidate = name == "slot-append" && self.pi_run.is_some()
|
||||
&& self.pi_request_scope["wholeDetail"] == true && v["candidateResult"]["id"].is_string();
|
||||
&& self.pi_request_scope["productProduction"] == true && v["candidateResult"]["id"].is_string();
|
||||
if let Some(error) = v["error"].as_str().filter(|_| !settled_batch_candidate) {
|
||||
if !self.show_library_action_error(error) { self.error = error.into(); }
|
||||
} else if name != "slot-adopt-prep" && (name != "slot-skeleton" || self.canvas_scope_valid(app)) {
|
||||
@ -2922,11 +2923,11 @@ impl Workspace {
|
||||
if let Ok(value) = &result {
|
||||
if value["accountId"] == self.account["id"] && value["origin"] == self.origin
|
||||
&& value["doc"].as_u64() == app.session.active().map(|s|s.doc.id.0) {
|
||||
if self.pi_request_scope["wholeDetail"] != true {
|
||||
if self.pi_request_scope["productProduction"] != true {
|
||||
self.unknown = value["pending"].as_bool().unwrap_or(self.unknown);
|
||||
}
|
||||
}
|
||||
} else if self.pi_request_scope["wholeDetail"] != true { self.unknown = true; }
|
||||
} else if self.pi_request_scope["productProduction"] != true { self.unknown = true; }
|
||||
}
|
||||
self.workflow_feedback(app, &method, &result);
|
||||
if matches!(method.as_str(), "creation-catalog" | "creation-thumbnail") {
|
||||
@ -3265,9 +3266,6 @@ impl Workspace {
|
||||
self.sync_dirty = true;
|
||||
if self.product_production.is_some() {
|
||||
self.production_opened(app, &meta);
|
||||
} else if meta["startWholeDetail"] == true && self.busy.as_deref() == Some("slot-skeleton") {
|
||||
self.busy = None;
|
||||
self.submit_whole_detail(app);
|
||||
}
|
||||
if meta["canvasFirst"] != true {
|
||||
let mut ack = meta.clone();
|
||||
@ -3522,7 +3520,7 @@ impl Workspace {
|
||||
{
|
||||
let recording_owner = self.recording_edit_owner.take();
|
||||
let before = app.session.active().map(|s| s.revision);
|
||||
let before_doc = if recording_owner.is_some() && self.pi_request_scope["wholeDetail"] == true {
|
||||
let before_doc = if recording_owner.is_some() && self.pi_request_scope["productProduction"] == true {
|
||||
self.record_product_view_edits(app);
|
||||
app.session.active().map(|state| state.doc.clone())
|
||||
} else { None };
|
||||
@ -4713,7 +4711,7 @@ mod agent_daemon_control_tests {
|
||||
{"outputId":"main_images","variantId":"wood"},{"outputId":"sku_images","variantId":"wood"}]});
|
||||
let state = app.session.active().unwrap();
|
||||
let (doc, revision) = (state.doc.id.0, state.revision);
|
||||
if typed { w.submit(&app, "继续制作整套".into()); } else { w.submit_whole_detail(&app); }
|
||||
if typed { w.submit(&app, "继续制作整套".into()); } else { w.resume_product_production(&app); }
|
||||
assert!(matches!(requests.try_recv().unwrap(), Request::Save(..)));
|
||||
assert!(requests.try_recv().is_err(), "the canvas is checkpointed before the continuation");
|
||||
w.saving = None;
|
||||
@ -5772,7 +5770,7 @@ mod tests {
|
||||
w.model_ready = true;
|
||||
w.image_ready = true;
|
||||
w.unknown = true;
|
||||
w.submit_whole_detail(&app);
|
||||
w.resume_product_production(&app);
|
||||
let Request::Action(method, checkpoint) = requests.try_recv().unwrap() else { panic!("expected durable checkpoint"); };
|
||||
assert_eq!(method, "product-run-checkpoint");
|
||||
assert_eq!(checkpoint["checkpoint"]["active"], true);
|
||||
|
||||
@ -522,7 +522,7 @@ fn register_job(w: &mut Workspace, app: &PhotocraftApp, job: JobId, document: u6
|
||||
let actual = app.session.job(job).or_else(|| app.session.jobs_with_recent().into_iter().find(|info| info.id == job)).ok_or("原生任务编号无对应记录,结果待核查")?;
|
||||
if actual.document.map(|doc| doc.0) != Some(document) || actual.command != command { return Err("原生任务归属不符,结果待核查".into()); }
|
||||
if w.agent_native.jobs.iter().any(|record| record.id == job) { return Err("原生任务编号已登记,不会重复派发".into()); }
|
||||
let before_doc = if w.pi_request_scope["wholeDetail"] == true {
|
||||
let before_doc = if w.pi_request_scope["productProduction"] == true {
|
||||
app.session.active().filter(|state| state.revision == before).map(|state| state.doc.clone())
|
||||
} else { None };
|
||||
w.agent_native.jobs.push_back(OwnedJob { id:job,run:w.pi_run.clone().ok_or("原生会话已结束")?,account:w.account["id"].clone(),
|
||||
@ -594,7 +594,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte
|
||||
Err(error) => return Ok(json!({"executed":false,"completed":true,"pending":false,"revision":before,"error":error})),
|
||||
}
|
||||
} else { None };
|
||||
let before_doc = if !read && w.pi_request_scope["wholeDetail"] == true {
|
||||
let before_doc = if !read && w.pi_request_scope["productProduction"] == true {
|
||||
w.record_product_view_edits(app);
|
||||
app.session.active().map(|state| state.doc.clone())
|
||||
} else { None };
|
||||
@ -1121,7 +1121,7 @@ mod tests {
|
||||
let (mut w, mut app, _) = fixture();
|
||||
let layer = app.session.execute("type.create", json!({"text":"旧款","size":18})).unwrap()["layer"].as_u64().unwrap();
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
w.expected_revision = app.session.active().unwrap().revision;
|
||||
let applied = invoke(&mut w, &mut app, "engine.execute",
|
||||
json!({"command":"type.edit","params":{"layer":layer,"text":"New"}})).unwrap();
|
||||
@ -1618,7 +1618,7 @@ mod tests {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn whole_detail_background_transform_updates_only_its_owned_layer_baseline() {
|
||||
fn production_background_transform_updates_only_its_owned_layer_baseline() {
|
||||
let (mut w, mut app, _) = fixture();
|
||||
app.session.execute("select.rect", json!({"x":4,"y":4,"width":16,"height":16})).unwrap();
|
||||
app.session.execute("edit.fill", json!({"color":"#c86528"})).unwrap();
|
||||
@ -1626,7 +1626,7 @@ mod tests {
|
||||
let state = app.session.active().unwrap();
|
||||
let layer = state.active_layer.unwrap();
|
||||
let other = state.doc.layers[0].id;
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
w.pi_canvas_basis = Some(state.doc.clone());
|
||||
app.session.execute("layer.setProps", json!({"layer":other.0,"name":"人为修改背景"})).unwrap();
|
||||
w.track_pi_canvas(&app);
|
||||
|
||||
@ -1204,17 +1204,14 @@ impl Workspace {
|
||||
.map(|prompts| ("followupPrompts", prompts))
|
||||
.or_else(|| (app.session.active().is_some() && conversation_settled(self, production))
|
||||
.then(|| ("quickPrompts", self.suggestion_prompts(has_text, selected))));
|
||||
let staged_production = self.template_workflow["productionStages"].is_array();
|
||||
let detail_output = self.template_workflow["outputId"] == "detail";
|
||||
let whole_detail = (app.session.active().is_some() && conversation_settled(self, production)
|
||||
&& (self.template_workflow["canvasFirst"] == true || staged_production || detail_output))
|
||||
.then(|| if staged_production { self.can_resume_product() } else { detail_output && self.can_start_turn() });
|
||||
let resume_production = (app.session.active().is_some() && conversation_settled(self, production)
|
||||
&& self.has_production_stages()).then(|| self.can_resume_product());
|
||||
let composer_width = (ui.available_width() - 20.0).max(1.0);
|
||||
use super::agent_stream::{SUGGESTION_GAP, SuggestionSize};
|
||||
let (suggestion_size, wrap_suggestions) = suggestions.map_or((SuggestionSize::Standard, false), |(_, prompts)| {
|
||||
let width = |size: SuggestionSize| {
|
||||
prompts.iter().map(|(label, _)| size.width(ui, label)).sum::<f32>() + SUGGESTION_GAP
|
||||
+ whole_detail.map_or(0.0, |_| size.width(ui, CONTINUE_PRODUCTION) + SUGGESTION_GAP)
|
||||
+ resume_production.map_or(0.0, |_| size.width(ui, CONTINUE_PRODUCTION) + SUGGESTION_GAP)
|
||||
};
|
||||
if width(SuggestionSize::Standard) <= composer_width {
|
||||
(SuggestionSize::Standard, false)
|
||||
@ -1240,10 +1237,10 @@ impl Workspace {
|
||||
if let Some((key, prompts)) = suggestions {
|
||||
if compact_suggestions {
|
||||
Frame::NONE.inner_margin(egui::Margin::symmetric(2, 0)).show(ui, |ui| {
|
||||
self.suggestion_row(app, ui, key, prompts, whole_detail, suggestion_size, wrap_suggestions);
|
||||
self.suggestion_row(app, ui, key, prompts, resume_production, suggestion_size, wrap_suggestions);
|
||||
});
|
||||
} else {
|
||||
self.suggestion_row(app, ui, key, prompts, whole_detail, suggestion_size, wrap_suggestions);
|
||||
self.suggestion_row(app, ui, key, prompts, resume_production, suggestion_size, wrap_suggestions);
|
||||
}
|
||||
}
|
||||
if compact_suggestions {
|
||||
@ -1627,12 +1624,12 @@ impl Workspace {
|
||||
let delivery_error = receipt.and_then(|row| row["productionDelivery"]["error"].as_str());
|
||||
let completed = summary.and_then(|summary| summary["exported"].as_u64().zip(summary["total"].as_u64()));
|
||||
let completion = completed.map(|(done, total)| format!("已交付 {done}/{total} 份"));
|
||||
let whole_detail = self.pi_request_scope["wholeDetail"] == true || self.pi_request_scope["productProduction"] == true;
|
||||
let producing = self.pi_request_scope["productProduction"] == true;
|
||||
let outcome = if production {
|
||||
None
|
||||
} else if whole_detail && self.agent_effects_paused {
|
||||
} else if producing && self.agent_effects_paused {
|
||||
Some(RunOutcome::Stopped { request_kept: self.pending() || self.unknown })
|
||||
} else if whole_detail && self.result_needs_check() {
|
||||
} else if producing && self.result_needs_check() {
|
||||
Some(RunOutcome::NeedsCheck)
|
||||
} else if self.pending() {
|
||||
None
|
||||
@ -1641,8 +1638,10 @@ impl Workspace {
|
||||
} else if let Some((done, total)) = completed {
|
||||
Some(if done == total {
|
||||
RunOutcome::Completed { summary: completion.as_deref().unwrap_or_default() }
|
||||
} else {
|
||||
} else if self.has_production_stages() {
|
||||
RunOutcome::Waiting { reason: "还有输出待完成,可继续制作整套" }
|
||||
} else {
|
||||
RunOutcome::Waiting { reason: "还有输出待完成" }
|
||||
})
|
||||
} else {
|
||||
None
|
||||
@ -2261,20 +2260,20 @@ impl Workspace {
|
||||
suggestions
|
||||
}
|
||||
|
||||
fn suggestion_row(&mut self, app: &PhotocraftApp, ui: &mut Ui, key: &str, suggestions: [(&'static str, &'static str); 2], whole_detail: Option<bool>, size: super::agent_stream::SuggestionSize, wrap: bool) {
|
||||
fn suggestion_row(&mut self, app: &PhotocraftApp, ui: &mut Ui, key: &str, suggestions: [(&'static str, &'static str); 2], resume_production: Option<bool>, size: super::agent_stream::SuggestionSize, wrap: bool) {
|
||||
use super::agent_stream::{SUGGESTION_CHIP_HEIGHT, SUGGESTION_GAP, suggestion_chip};
|
||||
let mut rects = Vec::new();
|
||||
let draft_ready = self.composer_draft_ready(app);
|
||||
let layout = egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(wrap);
|
||||
ui.allocate_ui_with_layout(vec2(ui.available_width(), SUGGESTION_CHIP_HEIGHT), layout, |ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(SUGGESTION_GAP, SUGGESTION_GAP);
|
||||
if let Some(enabled) = whole_detail {
|
||||
if let Some(enabled) = resume_production {
|
||||
let hint = "按图位完成剩余图片,保留已采纳结果和现有图层";
|
||||
let response = suggestion_chip(ui, "sparkles", CONTINUE_PRODUCTION, enabled, self.reduce_motion, size)
|
||||
.on_hover_text(hint).on_disabled_hover_text(hint);
|
||||
rects.push(json!({"label":CONTINUE_PRODUCTION,"rect":rect_value(response.rect)}));
|
||||
if response.clicked() {
|
||||
self.submit_whole_detail(app);
|
||||
self.resume_product_production(app);
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
@ -2379,7 +2378,7 @@ impl Workspace {
|
||||
|
||||
fn batch_progress_visible(&self) -> bool {
|
||||
!self.agent_effects_paused && (self.product_start_queued || self.product_production.is_some()
|
||||
|| self.pi_request_scope["wholeDetail"] == true && self.pending())
|
||||
|| self.pi_request_scope["productProduction"] == true && self.pending())
|
||||
}
|
||||
|
||||
fn production_workers(&self) -> Vec<ProductionWorker<'_>> {
|
||||
@ -2484,7 +2483,7 @@ impl Workspace {
|
||||
let working = run.and_then(|run| run.working_output());
|
||||
let current = working.as_ref().and_then(|row| row["outputId"].as_str())
|
||||
.or_else(|| show_work.then(|| progress["outputId"].as_str()).flatten())
|
||||
.or_else(|| (preparing.is_some() || self.pi_request_scope["wholeDetail"] == true && fraction.is_some()).then_some("detail"));
|
||||
.or_else(|| (preparing.is_some() || self.pi_request_scope["productProduction"] == true && fraction.is_some()).then_some("detail"));
|
||||
let requested = run.map(|run| run.requested_outputs());
|
||||
let pending = run.map(|run| run.pending_outputs());
|
||||
let contains = |value: &Option<Value>, output: &str| value.as_ref().and_then(Value::as_array)
|
||||
@ -4084,7 +4083,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_detail_quick_action_precedes_followups_and_submits_directly() {
|
||||
fn production_quick_action_requires_stages_and_checkpoints_before_resuming() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
for width in [250.0, 360.0, 420.0] {
|
||||
let (app, requests) = production_quick_actions_fixture();
|
||||
@ -4097,6 +4096,13 @@ mod tests {
|
||||
PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium);
|
||||
harness.run_steps(5);
|
||||
let workspace = harness.state().jiansun.as_ref().unwrap();
|
||||
assert_eq!(workspace.panel_geometry["followupPrompts"][0]["label"], "查看未完成项");
|
||||
assert!(harness.query_by_label("还有输出待完成").is_some());
|
||||
assert!(harness.query_by_label(CONTINUE_PRODUCTION).is_none());
|
||||
harness.state_mut().jiansun.as_mut().unwrap().template_workflow["productionStages"] =
|
||||
json!([{"outputId":"detail","variantId":"wood"}]);
|
||||
harness.run_steps(2);
|
||||
let workspace = harness.state().jiansun.as_ref().unwrap();
|
||||
let prompts = workspace.panel_geometry["followupPrompts"].as_array().unwrap();
|
||||
let labels = [CONTINUE_PRODUCTION, "查看未完成项", "核对已有结果"];
|
||||
let composer_top = workspace.panel_geometry["composer"][1].as_f64().unwrap() as f32;
|
||||
@ -4121,11 +4127,11 @@ mod tests {
|
||||
|
||||
harness.get_by_label(CONTINUE_PRODUCTION).click();
|
||||
harness.run_steps(2);
|
||||
let request = requests.try_iter().find_map(|request| match request {
|
||||
Request::Action(method, body) if method == "agent" => Some(body),
|
||||
_ => None,
|
||||
}).expect("the production shortcut directly dispatches an offline request");
|
||||
assert_eq!(request["context"]["requestScope"]["wholeDetail"], true);
|
||||
let workspace = harness.state().jiansun.as_ref().unwrap();
|
||||
assert_eq!(workspace.pending_slot_apply.as_ref().unwrap()["resumeProduct"], true);
|
||||
let queued: Vec<_> = requests.try_iter().collect();
|
||||
assert!(queued.iter().any(|request| matches!(request, Request::Save(..))));
|
||||
assert!(!queued.iter().any(|request| matches!(request, Request::Action(method, _) if method == "agent")));
|
||||
assert_eq!(harness.state().jiansun.as_ref().unwrap().composer, draft);
|
||||
}
|
||||
}
|
||||
@ -4136,7 +4142,7 @@ mod tests {
|
||||
w.composer.clear();
|
||||
w.pi_run = Some("offline-production".into());
|
||||
w.busy = Some("pi-agent".into());
|
||||
w.pi_request_scope = json!({"wholeDetail":true,"productProduction":true});
|
||||
w.pi_request_scope = json!({"productProduction":true});
|
||||
w.template_workflow = json!({"canvasFirst":true,"outputId":"detail","slots":[
|
||||
{"id":"hero","outputId":"detail","label":"首屏产品场景","frame":{"width":1440,"height":1800}},
|
||||
{"id":"scene","outputId":"detail","label":"空间搭配","frame":{"width":1600,"height":1200}}
|
||||
@ -4209,6 +4215,7 @@ mod tests {
|
||||
let w = app.jiansun.as_mut().unwrap();
|
||||
w.composer.clear();
|
||||
if !live {
|
||||
w.template_workflow["productionStages"] = json!([{"outputId":"sku_images","variantId":"wood"}]);
|
||||
w.messages = vec![
|
||||
json!({"role":"user","text":"继续制作整套"}),
|
||||
json!({"role":"assistant","kind":"image","taskId":"offline-hero","width":4,"height":5}),
|
||||
@ -4446,7 +4453,7 @@ mod tests {
|
||||
w.reduce_motion = true;
|
||||
w.composer.clear();
|
||||
w.busy = Some("pi-agent".into());
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
w.messages.clear();
|
||||
for index in 0..16 {
|
||||
w.messages.push(json!({"role":"user","text":format!("此前的输入 {index}")}));
|
||||
@ -4483,7 +4490,7 @@ mod tests {
|
||||
w.reduce_motion = true;
|
||||
w.composer.clear();
|
||||
w.busy = Some("pi-agent".into());
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
w.messages.clear();
|
||||
w.stream_reply = "正在验图\n已回填 2/21 个图位\n准备核对扶手的木纹。".into();
|
||||
fn tinted(shape: &egui::Shape, fill: Color32, out: &mut Vec<Rect>) {
|
||||
@ -4546,7 +4553,7 @@ mod tests {
|
||||
w.composer.clear();
|
||||
w.busy = Some("pi-agent".into());
|
||||
w.pi_run = Some("visual-qa".into());
|
||||
w.pi_request_scope = json!({"wholeDetail":true,"productProduction":true});
|
||||
w.pi_request_scope = json!({"productProduction":true});
|
||||
w.messages = vec![
|
||||
json!({"role":"user","text":"制作详情、主图和 SKU"}),
|
||||
json!({"role":"assistant","kind":"reply","text":"先做首屏的产品场景图。"}),
|
||||
@ -7197,7 +7204,7 @@ mod tests {
|
||||
w.reduce_motion = true;
|
||||
w.pi_run = Some("visual-qa".into());
|
||||
w.busy = Some("pi-agent".into());
|
||||
w.pi_request_scope = json!({"wholeDetail":true,"productProduction":true});
|
||||
w.pi_request_scope = json!({"productProduction":true});
|
||||
let cells = |count, filled, verified| (0..count).map(|i| json!({
|
||||
"label":format!("第 {} 项", i + 1),
|
||||
"state":if i < verified { "verified" } else if i < filled { "filled" } else { "empty" },
|
||||
@ -7671,7 +7678,7 @@ mod tests {
|
||||
w.product_start_queued = false;
|
||||
w.busy = Some("pi-agent".into());
|
||||
w.pi_run = Some("goal-fixture".into());
|
||||
w.pi_request_scope = json!({"wholeDetail":true,"productProduction":true});
|
||||
w.pi_request_scope = json!({"productProduction":true});
|
||||
w.workflow.set_production_progress(&json!({"heading":"正在制作详情页","total":21,"rendered":2,
|
||||
"workers":[{"number":1,"label":"首屏完整产品场景图","step":"正在生图","active":true}]}));
|
||||
w.messages.push(json!({"role":"assistant","kind":"reply","text":"我先核对商品原图和模板,再安排制作。"}));
|
||||
@ -8398,7 +8405,7 @@ mod tests {
|
||||
PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium);
|
||||
let w = app.jiansun.as_mut().unwrap();
|
||||
w.busy = Some("pi-agent".into());
|
||||
w.pi_request_scope = json!({"wholeDetail":true});
|
||||
w.pi_request_scope = json!({"productProduction":true});
|
||||
w.messages.push(json!({"role":"user","text":"一键制作整套详情页"}));
|
||||
w.composer.clear();
|
||||
w.focus_composer = false;
|
||||
|
||||
@ -963,7 +963,7 @@ fn valid_detail_adoption(w: &Workspace, doc: &Document, meta: &Value) -> bool {
|
||||
if let Some(fields) = shared.as_object_mut() { fields.remove("variants"); }
|
||||
expected.get("row") == Some(current_variant) && expected.get("shared") == Some(&shared)
|
||||
});
|
||||
w.pi_request_scope["wholeDetail"] == true && w.pi_run.is_some()
|
||||
w.pi_request_scope["productProduction"] == true && w.pi_run.is_some()
|
||||
&& !w.pi_write_blocked && !w.agent_effects_paused
|
||||
&& (!w.pi_request_scope["documentKey"].is_object()
|
||||
|| w.pi_request_scope["documentKey"] == super::product_document_key(doc))
|
||||
@ -5000,7 +5000,7 @@ mod tests {
|
||||
w.expected_revision = revision;
|
||||
w.pi_run = Some("detail-run".into());
|
||||
w.pi_binding = json!({"accountId":w.account["id"],"origin":w.origin});
|
||||
w.pi_request_scope = json!({"wholeDetail":true});
|
||||
w.pi_request_scope = json!({"productProduction":true});
|
||||
w.pi_canvas_basis = Some(active.doc.clone());
|
||||
let meta = json!({"accountId":"owner","origin":"https://local.test","doc":doc,"baseRevision":revision,
|
||||
"nativeLayerId":layer,"templateHash":"fixed","slotId":"image-slot","variantId":"wood",
|
||||
@ -5049,7 +5049,7 @@ mod tests {
|
||||
};
|
||||
attach(&mut w, doc);
|
||||
w.pi_run = Some(run.into());
|
||||
w.pi_request_scope = json!({"wholeDetail":true});
|
||||
w.pi_request_scope = json!({"productProduction":true});
|
||||
w.pi_canvas_basis = Some(baseline.clone());
|
||||
w.expected_revision = before;
|
||||
let meta = json!({"accountId":"owner","origin":"https://local.test","doc":doc,"baseRevision":before,
|
||||
@ -5132,7 +5132,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_detail_adoption_uses_the_mask_of_a_large_embedded_template_object() {
|
||||
fn production_adoption_uses_the_mask_of_a_large_embedded_template_object() {
|
||||
use photocraft_doc::{LayerId, LayerContent, Path, SmartSource, Subpath, VectorMask};
|
||||
let (mut workspace, mut app, _requests, layer, candidate) = native_fixture();
|
||||
let active = app.session.active_mut().unwrap();
|
||||
@ -5149,7 +5149,7 @@ mod tests {
|
||||
let original = active.doc.clone();
|
||||
let revision = active.revision;
|
||||
workspace.pi_run = Some("detail-run".into());
|
||||
workspace.pi_request_scope = json!({"wholeDetail":true});
|
||||
workspace.pi_request_scope = json!({"productProduction":true});
|
||||
workspace.owner_doc = Some(original.id.0);
|
||||
workspace.pi_canvas_basis = Some(original.clone());
|
||||
workspace.expected_revision = revision;
|
||||
@ -5168,7 +5168,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_detail_adoption_keeps_unrelated_manual_edits_and_skips_an_edited_target() {
|
||||
fn production_adoption_keeps_unrelated_manual_edits_and_skips_an_edited_target() {
|
||||
let _guard = ADOPTION_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
|
||||
for edit_target in [false, true] {
|
||||
let (mut w, mut app, _requests, id, bytes) = native_fixture();
|
||||
@ -5178,7 +5178,7 @@ mod tests {
|
||||
let edited = if edit_target { layer } else { other };
|
||||
let started = state.revision;
|
||||
w.pi_run = Some("detail-run".into());
|
||||
w.pi_request_scope = json!({"wholeDetail":true});
|
||||
w.pi_request_scope = json!({"productProduction":true});
|
||||
w.owner_doc = Some(state.doc.id.0);
|
||||
w.pi_canvas_basis = Some(state.doc.clone());
|
||||
w.expected_revision = started;
|
||||
@ -5208,7 +5208,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_detail_replaces_its_own_candidate_and_preserves_manual_layer_edits() {
|
||||
fn production_replaces_its_own_candidate_and_preserves_manual_layer_edits() {
|
||||
use super::super::workflow_bridge;
|
||||
let (mut w, mut app, _requests, layer, bytes) = native_fixture();
|
||||
let state = app.session.active().unwrap();
|
||||
@ -5225,7 +5225,7 @@ mod tests {
|
||||
w.busy = Some("pi-agent".into());
|
||||
w.pi_run = Some("whole-detail-test".into());
|
||||
w.pi_binding = json!({"accountId":"owner","origin":"https://local.test"});
|
||||
w.pi_request_scope = json!({"wholeDetail":true,"outputId":"detail","variantId":"wood",
|
||||
w.pi_request_scope = json!({"productProduction":true,"outputId":"detail","variantId":"wood",
|
||||
"account":{"id":"owner","origin":"https://local.test"},"project":{"documentId":doc,"localId":local}});
|
||||
w.allow_apply = true;
|
||||
w.product_target_hidden = true;
|
||||
@ -5292,7 +5292,7 @@ mod tests {
|
||||
w.creation_brief = json!({"name":"展桌","variants":[oak,{"id":"white","colorName":"米白色"}]});
|
||||
w.pi_canvas_basis = Some(state.doc.clone());
|
||||
w.pi_run = Some("detail-run".into());
|
||||
w.pi_request_scope = json!({"wholeDetail":true,"documentKey":crate::jiansun::product_document_key(&state.doc)});
|
||||
w.pi_request_scope = json!({"productProduction":true,"documentKey":crate::jiansun::product_document_key(&state.doc)});
|
||||
let meta = json!({"variantId":"wood","outputId":"detail","nativeLayerId":layer,
|
||||
"variantBrief":{"row":oak,"shared":{"name":"展桌"}}});
|
||||
assert!(valid_detail_adoption(&w, &state.doc, &meta));
|
||||
|
||||
@ -1413,10 +1413,10 @@ impl Workspace {
|
||||
}
|
||||
let actions_ready = self.busy.is_none() && !self.unknown;
|
||||
self.brief_enter_button(app, ui, &template, blocked.is_none(), actions_ready && missing.is_empty());
|
||||
if self.template_workflow["productionStages"].as_array().is_some_and(|stages| !stages.is_empty()) {
|
||||
if self.has_production_stages() {
|
||||
let resume = stitch_ui::action_button(ui, "继续整套制作", stitch_ui::ButtonRole::Primary, self.can_resume_product());
|
||||
self.control_geometry("resume-product", resume.rect);
|
||||
if resume.clicked() { self.submit_whole_detail(app); }
|
||||
if resume.clicked() { self.resume_product_production(app); }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@ -23,11 +23,11 @@ fn identity(w: &Workspace, input: &Value) -> Result<(), BridgeFailure> {
|
||||
fn status(w: &Workspace, app: &PhotocraftApp) -> Value {
|
||||
let same = app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc && s.revision == w.expected_revision);
|
||||
let active = w.pi_run.is_some() && app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc);
|
||||
let context = if active && w.pi_request_scope["wholeDetail"] != true { w.context(app) } else { Value::Null };
|
||||
let context = if active && w.pi_request_scope["productProduction"] != true { w.context(app) } else { Value::Null };
|
||||
let revision = if active { app.session.active().map(|s| s.revision) } else { None };
|
||||
json!({"run":w.pi_run,"conversationActive":active,"editorText":if active{json!(w.composer)}else{Value::Null},"allowed":w.allow_apply && same && !w.pi_write_blocked,"writeBlocked":w.pi_write_blocked || !same,
|
||||
"productionCanvas":w.production_canvas_receipt(app),"openingProductionCanvas":w.production_canvas_opening(app),
|
||||
"manualEdit":w.pi_manual_edit,"detailWriteWaiting":active && w.pi_request_scope["wholeDetail"] == true && super::canvas_workspace::detail_write_waiting(w, app),"queued":if active {w.queue.len()} else {0},"revision":revision,"context":context,"error":if active {json!(w.error)} else {Value::Null}})
|
||||
"manualEdit":w.pi_manual_edit,"detailWriteWaiting":active && w.pi_request_scope["productProduction"] == true && super::canvas_workspace::detail_write_waiting(w, app),"queued":if active {w.queue.len()} else {0},"revision":revision,"context":context,"error":if active {json!(w.error)} else {Value::Null}})
|
||||
}
|
||||
|
||||
fn stream_output(value: &Value) -> Option<Value> {
|
||||
@ -122,7 +122,7 @@ pub(super) fn private_action_in_ui(w: &mut Workspace, app: &mut PhotocraftApp, c
|
||||
action_impl(w, app, Some(ctx), method, input, true)
|
||||
}
|
||||
fn detail_copy_fields(
|
||||
doc: &photocraft_doc::Document, include_filled: bool, page_id: Option<&str>, field_id: Option<&str>,
|
||||
doc: &photocraft_doc::Document, page_id: Option<&str>, field_id: Option<&str>,
|
||||
) -> Vec<Value> {
|
||||
let Some(mapping) = super::canvas_workspace::document_mapping(doc) else { return Vec::new() };
|
||||
let detail = page_id.is_some() || field_id.is_some();
|
||||
@ -134,7 +134,6 @@ fn detail_copy_fields(
|
||||
let id = field["nativeLayerId"].as_u64()?;
|
||||
let layer = doc.layer(photocraft_doc::LayerId(id))?;
|
||||
let photocraft_doc::LayerContent::Text(text) = &layer.content else { return None };
|
||||
if !include_filled && !text.text.trim().is_empty() { return None; }
|
||||
let mut row = json!({"layer":id,"page":page["documentId"],"field":field["fieldId"],
|
||||
"label":field["label"],"role":field["role"],"maxChars":field["maxChars"],"maxLines":field["maxLines"],
|
||||
"relatedFields":field["relatedFields"],"nativeFrame":field["nativeFrame"],
|
||||
@ -143,11 +142,9 @@ fn detail_copy_fields(
|
||||
row["originalText"] = field["originalText"].clone();
|
||||
row["requirements"] = field["requirements"].clone();
|
||||
}
|
||||
if include_filled {
|
||||
row["currentText"] = json!(text.text);
|
||||
if !text.text.trim().is_empty() && field["originalText"].as_str() == Some(text.text.as_str()) {
|
||||
row["templateSample"] = json!(true);
|
||||
}
|
||||
row["currentText"] = json!(text.text);
|
||||
if !text.text.trim().is_empty() && field["originalText"].as_str() == Some(text.text.as_str()) {
|
||||
row["templateSample"] = json!(true);
|
||||
}
|
||||
Some(row)
|
||||
})
|
||||
@ -235,7 +232,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
if !own_submit {
|
||||
w.pi_write_blocked = false;
|
||||
}
|
||||
let batch = request_scope["wholeDetail"] == true;
|
||||
let batch = request_scope["productProduction"] == true;
|
||||
if !own_submit || w.pi_canvas_basis.as_ref().is_none_or(|basis| basis.id != st.doc.id) {
|
||||
w.pi_canvas_basis = Some(st.doc.clone());
|
||||
w.pi_manual_edit = false;
|
||||
@ -285,7 +282,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
return Err(BridgeFailure::new("scope_changed", false, false, "原工作画布的输出、花色或模板映射已变化"));
|
||||
}
|
||||
w.pi_touched = Instant::now();
|
||||
if w.pi_request_scope["wholeDetail"] == true { super::agent_native::settle_jobs(w, app); }
|
||||
if w.pi_request_scope["productProduction"] == true { super::agent_native::settle_jobs(w, app); }
|
||||
w.track_pi_canvas(app);
|
||||
if method != "pi-state" && !app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc) {
|
||||
if method == "pi-end" {
|
||||
@ -329,14 +326,13 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
"signatureOnly":input["signatureOnly"] == true,"preflight":input["preflight"] == true}))
|
||||
}
|
||||
"pi-detail-copy-fields" => {
|
||||
if w.pi_request_scope["wholeDetail"] != true || w.pi_write_blocked { return Err("当前回合无整套详情页文案授权".into()); }
|
||||
if w.pi_request_scope["productProduction"] != true || w.pi_write_blocked { return Err("当前回合无整套详情页文案授权".into()); }
|
||||
let active = app.session.active().ok_or("原项目未打开")?;
|
||||
let doc = &active.doc;
|
||||
let production = w.pi_request_scope["productProduction"] == true;
|
||||
let include_filled = input["includeFilled"] == true && production;
|
||||
let include_filled = input["includeFilled"] == true;
|
||||
let scope = |key: &str| input[key].as_str().map(str::trim)
|
||||
.filter(|value| include_filled && !value.is_empty());
|
||||
let fields = detail_copy_fields(doc, production, scope("pageId"), scope("fieldId"));
|
||||
let fields = detail_copy_fields(doc, scope("pageId"), scope("fieldId"));
|
||||
if include_filled {
|
||||
let mapping = super::canvas_workspace::document_mapping(doc).ok_or("缺少模板文案映射")?;
|
||||
let pages: Vec<_> = mapping["outputs"].as_array().into_iter().flatten()
|
||||
@ -346,10 +342,9 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
Ok(json!(fields.into_iter().filter(|field| pending_detail_copy(w, doc, field)).collect::<Vec<_>>()))
|
||||
}
|
||||
"pi-detail-copy-apply" => {
|
||||
let production = w.pi_request_scope["productProduction"] == true;
|
||||
let match_fields = input["matchFields"] == true;
|
||||
if w.pi_request_scope["wholeDetail"] != true || w.pi_write_blocked || !w.queue.is_empty()
|
||||
|| match_fields && !production || !match_fields && !w.allow_apply
|
||||
if w.pi_request_scope["productProduction"] != true || w.pi_write_blocked || !w.queue.is_empty()
|
||||
|| !match_fields && !w.allow_apply
|
||||
{
|
||||
return Err("文案未取得当前画布写入许可,原内容保留".into());
|
||||
}
|
||||
@ -364,7 +359,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
if !match_fields { w.allow_apply = false; }
|
||||
return Ok(json!({"retryWrite":true,"revision":active.revision}));
|
||||
}
|
||||
let fields = detail_copy_fields(&active.doc, production, None, None);
|
||||
let fields = detail_copy_fields(&active.doc, None, None);
|
||||
let items = input["items"].as_array().ok_or("文字格应为列表")?;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut edits = Vec::new();
|
||||
@ -394,21 +389,12 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
} else if item["expectedText"].as_str() != Some(current) || !writable() {
|
||||
continue;
|
||||
}
|
||||
let text = item["text"].as_str().filter(|text| production || !text.trim().is_empty()).ok_or("缺少填写文字")?;
|
||||
if !production {
|
||||
let max = field["maxChars"].as_u64().unwrap_or(120).min(500) as usize;
|
||||
let lines = field["maxLines"].as_u64().unwrap_or(8).min(32) as usize;
|
||||
if text.chars().count() > max || text.lines().count() > lines {
|
||||
return Err(format!("{} 超出模板文字格容量", field["layer"]).into());
|
||||
}
|
||||
}
|
||||
let text = item["text"].as_str().ok_or("缺少填写文字")?;
|
||||
if text.chars().any(|ch| ch.is_control() && ch != '\n' && ch != '\t' && ch != '\r') {
|
||||
rejected.push(json!({"layer":layer,"reason":"文案含无法写入的控制字符"}));
|
||||
continue;
|
||||
}
|
||||
if production
|
||||
&& let Some(photocraft_doc::LayerContent::Text(native)) = active.doc.layer(id).map(|layer| &layer.content)
|
||||
{
|
||||
if let Some(photocraft_doc::LayerContent::Text(native)) = active.doc.layer(id).map(|layer| &layer.content) {
|
||||
let strict = field["styleRoles"].as_array().is_some_and(|roles| !roles.is_empty());
|
||||
match photocraft_engine::type_cmds::template_text_mapping(native, text, strict) {
|
||||
Ok(true) => style_mappings.push(json!({"layer":layer,"mapping":"default"})),
|
||||
@ -425,32 +411,26 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
let remaining = fields.iter().filter(|field| pending_detail_copy(w, &active.doc, field)
|
||||
&& !edits.iter().any(|(layer, _)| field["layer"] == layer.0)).count();
|
||||
if count == 0 { return Ok(json!({"applied":0,"appliedLayers":[],"pending":remaining,"rejected":rejected,"revision":active.revision})); }
|
||||
let edited_ids: Vec<_> = if w.pi_request_scope["wholeDetail"] == true {
|
||||
edits.iter().filter_map(|(id, _)| w.detail_layer_unchanged(&active.doc, *id).then_some(*id)).collect()
|
||||
} else { Vec::new() };
|
||||
let edited_ids: Vec<_> = edits.iter()
|
||||
.filter_map(|(id, _)| w.detail_layer_unchanged(&active.doc, *id).then_some(*id)).collect();
|
||||
if !edited_ids.is_empty() { w.record_product_view_edits(app); }
|
||||
if production {
|
||||
photocraft_engine::type_cmds::replace_template_layer_texts(&mut app.session, "回填商品文案", &edits)
|
||||
} else {
|
||||
photocraft_engine::type_cmds::replace_layer_texts(&mut app.session, "回填商品文案", &edits)
|
||||
}.map_err(|error| error.to_string())?;
|
||||
photocraft_engine::type_cmds::replace_template_layer_texts(&mut app.session, "回填商品文案", &edits)
|
||||
.map_err(|error| error.to_string())?;
|
||||
if !w.product_target_hidden { app.sync_views(); }
|
||||
let active = app.session.active().ok_or("当前画布未打开")?;
|
||||
w.sync_pi_canvas_basis_layers(&active.doc, &edited_ids);
|
||||
let mut layout_warnings = Vec::new();
|
||||
if production {
|
||||
for (layer, _) in &edits {
|
||||
let Some(field) = fields.iter().find(|field| field["layer"] == layer.0) else { continue };
|
||||
let Some(photocraft_doc::LayerContent::Text(text)) = active.doc.layer(*layer).map(|layer| &layer.content) else { continue };
|
||||
let max_lines = field["maxLines"].as_u64().unwrap_or(usize::MAX as u64) as usize;
|
||||
// A sample's ink bounds locate the text layer. Only a published frame specifies size.
|
||||
let frame = (field["textSafeFrame"] == true).then(|| production_text_frame(field)).flatten();
|
||||
if !text.text.trim().is_empty()
|
||||
&& !photocraft_engine::type_cmds::text_fits(text, active.doc.resolution_dpi, max_lines, frame)
|
||||
{
|
||||
layout_warnings.push(json!({"layer":layer.0,"field":field["field"],"page":field["page"],
|
||||
"reason":"文案已上画布,可能截断或超出模板文字框,请查看实际页面决定是否调整"}));
|
||||
}
|
||||
for (layer, _) in &edits {
|
||||
let Some(field) = fields.iter().find(|field| field["layer"] == layer.0) else { continue };
|
||||
let Some(photocraft_doc::LayerContent::Text(text)) = active.doc.layer(*layer).map(|layer| &layer.content) else { continue };
|
||||
let max_lines = field["maxLines"].as_u64().unwrap_or(usize::MAX as u64) as usize;
|
||||
// A sample's ink bounds locate the text layer. Only a published frame specifies size.
|
||||
let frame = (field["textSafeFrame"] == true).then(|| production_text_frame(field)).flatten();
|
||||
if !text.text.trim().is_empty()
|
||||
&& !photocraft_engine::type_cmds::text_fits(text, active.doc.resolution_dpi, max_lines, frame)
|
||||
{
|
||||
layout_warnings.push(json!({"layer":layer.0,"field":field["field"],"page":field["page"],
|
||||
"reason":"文案已上画布,可能截断或超出模板文字框,请查看实际页面决定是否调整"}));
|
||||
}
|
||||
}
|
||||
w.expected_revision = active.revision;
|
||||
@ -539,7 +519,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
}
|
||||
"pi-detail-images" => {
|
||||
let inspect = private && input["inspectCandidate"] == true;
|
||||
if !inspect && (w.pi_request_scope["wholeDetail"] != true || w.pi_write_blocked || w.agent_effects_paused) {
|
||||
if !inspect && (w.pi_request_scope["productProduction"] != true || w.pi_write_blocked || w.agent_effects_paused) {
|
||||
return Err("已暂停整套详情页制作".into());
|
||||
}
|
||||
let slot = w.template_workflow["slots"].as_array().into_iter().flatten()
|
||||
@ -607,9 +587,8 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let production_progress = private && w.pi_request_scope["wholeDetail"] == true && input["production"].is_object();
|
||||
if !(production_progress && w.pi_request_scope["productProduction"] == true)
|
||||
&& (!text.is_empty() || thinking.is_none()) { w.stream_reply = text.into(); }
|
||||
let production_progress = private && w.pi_request_scope["productProduction"] == true && input["production"].is_object();
|
||||
if !production_progress && (!text.is_empty() || thinking.is_none()) { w.stream_reply = text.into(); }
|
||||
if production_progress
|
||||
&& let Some(notice) = w.workflow.set_production_progress(&input["production"])
|
||||
{
|
||||
@ -664,7 +643,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"pi-write-request" => {
|
||||
let batch = w.pi_request_scope["wholeDetail"] == true;
|
||||
let batch = w.pi_request_scope["productProduction"] == true;
|
||||
if batch && !w.pi_write_blocked
|
||||
&& (super::canvas_workspace::detail_write_waiting(w, app) || input["revision"].as_u64() != Some(w.expected_revision))
|
||||
{
|
||||
@ -898,7 +877,6 @@ mod tests {
|
||||
#[test]
|
||||
fn production_screen_receipt_freezes_the_document_and_carries_its_run_cancellation() {
|
||||
let (mut w, mut app, input) = activity_fixture();
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
let (reply, receive) = mpsc::channel();
|
||||
let revision = app.session.active().unwrap().revision;
|
||||
@ -1338,7 +1316,6 @@ mod tests {
|
||||
w.busy = None;
|
||||
let run = "5fa89197-949f-466c-b939-cc6296edc45c";
|
||||
action(&mut w, &mut app, "pi-begin", &json!({"run":run,"text":"核对本机模板文案"})).unwrap();
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
let revision = w.expected_revision;
|
||||
action(&mut w, &mut app, "pi-write-request", &json!({"run":run,"revision":revision})).unwrap();
|
||||
@ -1384,7 +1361,6 @@ mod tests {
|
||||
w.open_projects.insert(doc, "copy-fixture".into());
|
||||
let run = "12345678-1234-1234-1234-123456789012";
|
||||
action(&mut w, &mut app, "pi-begin", &json!({"run":run,"text":"制作详情页"})).unwrap();
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
let snapshot = action_impl(&mut w, &mut app, None, "pi-detail-copy-fields",
|
||||
&json!({"run":run,"documentId":doc,"includeFilled":true}), true).unwrap();
|
||||
@ -1461,7 +1437,6 @@ mod tests {
|
||||
w.busy = None;
|
||||
let run = "12345678-1234-1234-1234-123456789012";
|
||||
action(&mut w, &mut app, "pi-begin", &json!({"run":run,"text":"制作详情页"})).unwrap();
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
let original = w.expected_revision;
|
||||
action(&mut w, &mut app, "pi-write-request", &json!({"run":run,"revision":original})).unwrap();
|
||||
|
||||
@ -659,7 +659,7 @@ fn read(w: &Workspace, version: u64, section: &str, output: &str, offset: usize,
|
||||
let candidates=slot["candidates"].as_array().into_iter().flatten().rev().map(|candidate| json!({"id":clip(&candidate["id"],100),"variant":clip(&candidate["variant"],100),"status":clip(&candidate["status"],24),"sourceType":candidate["sourceType"],
|
||||
"materialTaskId":candidate["materialTaskId"],"sourceRequestId":candidate["sourceRequestId"],
|
||||
"reused":candidate["reusedFrom"].is_object()})).collect::<Vec<_>>();
|
||||
let manually_edited = w.pi_request_scope["wholeDetail"] == true && w.pi_canvas_basis.is_some()
|
||||
let manually_edited = w.pi_request_scope["productProduction"] == true && w.pi_canvas_basis.is_some()
|
||||
&& slot["nativeLayerId"].as_u64().is_some_and(|id| active_doc
|
||||
.is_some_and(|doc| !w.detail_layer_unchanged(doc, photocraft_doc::LayerId(id))));
|
||||
json!({"id":clip(&slot["id"],160),"fieldId":clip(&slot["fieldId"],100),"documentId":clip(&slot["documentId"],100),"outputId":output,
|
||||
@ -712,12 +712,12 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u
|
||||
if op["run"] != run { return Err("操作身份不属于当前回合".into()); }
|
||||
return Ok(json!({"operationId":id,"phase":op["phase"],"candidateId":op["candidateId"]}));
|
||||
}
|
||||
let batch = w.pi_request_scope["wholeDetail"] == true && input["outputId"] == w.pi_request_scope["outputId"];
|
||||
let batch = w.pi_request_scope["productProduction"] == true && input["outputId"] == w.pi_request_scope["outputId"];
|
||||
let intent = input["intent"].as_str().filter(|s| matches!(*s, "generate_candidate" | "adopt_candidate")).ok_or("此操作不能直接执行")?;
|
||||
if w.pi_request_scope["productProduction"] == true && intent == "generate_candidate" && input["useProductReference"] != true {
|
||||
return Err("正式生图须先准备并审阅完整请求,再按冻结编号派发".into());
|
||||
}
|
||||
let completed_placement = batch && intent == "adopt_candidate" && w.pi_request_scope["productProduction"] == true
|
||||
let completed_placement = batch && intent == "adopt_candidate"
|
||||
&& w.template_workflow["slots"].as_array().into_iter().flatten().any(|slot| slot["id"] == input["slotId"]
|
||||
&& slot["variantId"] == input["productVariantId"] && slot["outputId"] == input["outputId"]
|
||||
&& slot["candidates"].as_array().into_iter().flatten().any(|candidate|
|
||||
@ -772,8 +772,7 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u
|
||||
}
|
||||
if intent == "adopt_candidate" && !w.allow_apply { return Err("本轮原生操作尚未取得当前修订许可".into()); }
|
||||
let instruction = input.get("instruction").map_or(Ok(""), |v| v.as_str().ok_or("调整要求须为文本"))?;
|
||||
let production = batch && w.pi_request_scope["productProduction"] == true;
|
||||
if !production && instruction.chars().count() > 500
|
||||
if !batch && instruction.chars().count() > 500
|
||||
|| instruction.chars().any(|ch| ch.is_control() && !matches!(ch, '\n' | '\r' | '\t'))
|
||||
|| intent != "generate_candidate" && !instruction.trim().is_empty()
|
||||
{
|
||||
@ -784,7 +783,7 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u
|
||||
if w.saving.is_some() || !w.product_target_hidden && app.saving() {
|
||||
return Ok(json!({"operationId":id,"phase":"waiting_save","dispatched":false,"revision":w.expected_revision}));
|
||||
}
|
||||
if !production && input["retryOf"].is_null() && w.workflow.operations.iter().any(|op| op["run"] == run && op["intent"] == intent
|
||||
if !batch && input["retryOf"].is_null() && w.workflow.operations.iter().any(|op| op["run"] == run && op["intent"] == intent
|
||||
&& op["slotId"] == operation_input["slotId"] && op["productVariantId"] == operation_input["variantId"]
|
||||
&& op["candidateIdInput"] == input["candidateId"] && op["instruction"] == instruction
|
||||
&& op["referenceIndex"] == input["referenceIndex"] && op["referenceCrop"] == input["referenceCrop"]) {
|
||||
@ -819,13 +818,13 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u
|
||||
operation_input["useTemplateReference"] = json!(false);
|
||||
}
|
||||
if !input["retryOf"].is_null() {
|
||||
if w.pi_request_scope["wholeDetail"] != true {
|
||||
if w.pi_request_scope["productProduction"] != true {
|
||||
return Err("当前回合未授权整套详情页制作".into());
|
||||
}
|
||||
operation_input["retryOf"] = input["retryOf"].clone();
|
||||
}
|
||||
if let Some(index) = input.get("geometryReferenceIndex") {
|
||||
if !batch || w.pi_request_scope["productProduction"] != true || input["useProductReference"] == true
|
||||
if !batch || input["useProductReference"] == true
|
||||
|| !index.as_u64().is_some()
|
||||
{
|
||||
return Err("形体参考须为当前制作图位的同款实拍".into());
|
||||
@ -833,16 +832,16 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u
|
||||
operation_input["geometryReferenceIndex"] = index.clone();
|
||||
}
|
||||
if input["useProductReference"] == true {
|
||||
if w.pi_request_scope["wholeDetail"] != true { return Err("当前回合未授权整套详情页制作".into()); }
|
||||
if w.pi_request_scope["productProduction"] != true { return Err("当前回合未授权整套详情页制作".into()); }
|
||||
operation_input["useProductReference"] = json!(true);
|
||||
if let Some(crop) = input.get("referenceCrop") {
|
||||
if !batch || (output_id != "detail" && w.pi_request_scope["productProduction"] != true) {
|
||||
if !batch {
|
||||
return Err("局部取景仅用于整套制作的实物证据图".into());
|
||||
}
|
||||
operation_input["referenceCrop"] = crop.clone();
|
||||
}
|
||||
if let Some(index) = input.get("referenceIndex") {
|
||||
if w.pi_request_scope["productProduction"] != true || !index.as_u64().is_some() {
|
||||
if !index.as_u64().is_some() {
|
||||
return Err("同款原图序号不属于本轮制作".into());
|
||||
}
|
||||
operation_input["referenceIndex"] = index.clone();
|
||||
@ -850,7 +849,7 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u
|
||||
}
|
||||
}
|
||||
let worker = if let Some(worker) = input.get("workerNumber") {
|
||||
if !batch || w.pi_request_scope["productProduction"] != true || intent != "generate_candidate" || input["useProductReference"] == true {
|
||||
if !batch || intent != "generate_candidate" || input["useProductReference"] == true {
|
||||
return Err("此操作没有子代理生图任务".into());
|
||||
}
|
||||
Some(worker.as_u64().filter(|number| *number > 0).ok_or("子代理编号无效")?)
|
||||
@ -1009,7 +1008,7 @@ fn template_input(w: &Workspace, intent: &str, proposal: &Value) -> Result<Value
|
||||
let slot =
|
||||
w.template_workflow["slots"].as_array().into_iter().flatten().find(|s| s["id"] == id && s["outputId"] == output).ok_or("图位不属于当前项目输出")?;
|
||||
if intent == "generate_candidate" {
|
||||
let detail_batch = w.pi_request_scope["wholeDetail"] == true && proposal["outputId"] == w.pi_request_scope["outputId"];
|
||||
let detail_batch = w.pi_request_scope["productProduction"] == true && proposal["outputId"] == w.pi_request_scope["outputId"];
|
||||
if !detail_batch && (w.unknown || !template_slots::capability(&w.template_workflow, "imageDispatchAllowed")) {
|
||||
return Err("原请求待核查或当前无法生成,不会重发".into());
|
||||
}
|
||||
@ -1407,7 +1406,7 @@ mod tests {
|
||||
w.reduce_motion = true;
|
||||
w.library = false;
|
||||
w.material = false;
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
w.workflow.set_production_progress(&json!({"heading":"正在核对详情图",
|
||||
"total":21,"rendered":2,"workers":[
|
||||
{"number":1,"slotId":"wide","label":"S08-餐桌搭配","step":"正在生图","active":true},
|
||||
@ -1802,7 +1801,6 @@ mod tests {
|
||||
#[test]
|
||||
fn production_workflow_cannot_delegate_an_unfrozen_image_generation() {
|
||||
let (mut w, mut app, requests, ctx) = direct_fixture();
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
let read = private_call(&mut w, &mut app, &ctx, "pi-workflow-read", json!({})).unwrap();
|
||||
let result = private_call(&mut w, &mut app, &ctx, "pi-workflow-execute", direct_input(read["version"].clone())).unwrap();
|
||||
@ -1962,7 +1960,6 @@ mod tests {
|
||||
("unknown", "adopt_candidate", "held", "complete", true, false),
|
||||
] {
|
||||
let (mut w, mut app, requests, ctx) = direct_fixture();
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
w.allow_apply = true;
|
||||
w.product_target_hidden = true;
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user