合入小壹制作上下文与文案修订校验

This commit is contained in:
WuYongJie 2026-11-27 23:35:28 +08:00
commit fa55f70941
20 changed files with 351 additions and 357 deletions

View File

@ -14,7 +14,6 @@ import { protectSession, redactText } from './credentials.mjs';
import { productionTools, callProductionTool, closeProductionTurn, runPiProductionGoal,
mayContinueProductionGoal } from './production-goal.mjs';
import { productionVideoTools } from './production-operations.mjs';
import { COPY_IMAGE_SCREEN_CRITERIA, DRAW_LIMIT_GUIDANCE } from './copy-image-alignment.mjs';
import { runToolCall } from '@earendil-works/pi-agent-core';
import { createAgentSession, DefaultResourceLoader, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, createAssistantMessageEventStream, parseStreamingJson } from '@earendil-works/pi-ai/compat';
@ -27,13 +26,14 @@ import { requestPurpose } from './request-purpose.mjs';
import { productContext } from './project-context.mjs';
import { workflowContext, workflowResult } from './workflow-context.mjs';
import { EnterpriseContext } from './enterprise-context.mjs';
import { productionKnowledge } from './production-knowledge.mjs';
import { openEnterpriseSkills } from './enterprise-skill-resources.mjs';
import { projectTools } from './project-tools.mjs';
import { responseUsage } from './usage.mjs';
import { contextSnapshot, modelCapacity, contextLengths } from './context-usage.mjs';
import { activityScope, activitySummary, canvasPresence, toolActivity } from './activity-event.mjs';
import { assertPiNodeVersion } from './runtime-policy.mjs';
import { NATIVE_CANVAS_QUICK_REFERENCE, nativeTools } from './native-tools.mjs';
import { nativeTools } from './native-tools.mjs';
import { NativeExtensionUI } from './native-ui.mjs';
import { canvasReadParameters, canvasReadQuery, previewTarget, previewParameters } from './canvas-contract.mjs';
import { PHOTOCRAFT_NAMESPACE, createPhotoCraftExtensions, photoCraftToolAllowlist, activatePhotoCraftTools } from './photocraft-extension.mjs';
@ -69,22 +69,12 @@ memory_set只记录对话记忆,不修改产品资料。用户希望改资料
references是用户提交时冻结的本轮引用;component为pixelMask或vectorMask时指所属图层对应的蒙版。liveSelected只表示实时界面选择,不能替代本轮引用。没有references时,不要猜测用户明确指向了哪个对象。
只确认已执行的修改。工具失败要说明。生图和画布操作结果未确认时,只核查原编号。`;
const PRODUCTION_SYSTEM = `你是小壹的制作助手。先读取本项目适用的企业制作指引,按指引和模板在画布中制作和复核。由你决定要做什么、顺序、并行和返工。
const PRODUCTION_SYSTEM = `你是小壹的制作助手。依据本项目发布的企业 Skill、商品实拍、资料和模板制作并复核。按需读取适用 Skill 和引用。由你决定工作范围内的顺序、并行和返工。
${PRODUCT_VOICE}
用 plan_production 读取本轮目标及待交付项。单独调用 open_production_output 在同一会话打开或切换到指定成品及花色,收到绑定回执后再查询 native_catalog 或操作画布。切换回执包含前一工程的保存结果、已取消的未派发图位和仍在处理的付费原请求编号。回到原成品时,可重新派发已取消的图位,并复核原请求留下的候选。打开失败时按回执处理,可重新打开或选择另一待制作成品。用户查看的页面和制作画布独立。
${DRAW_LIMIT_GUIDANCE}
用户附带引用时,按引用的 outputId、productVariantId、slotId、candidateId 或 nativeLayerId、component 定位目标,结合附带图片精修;实时选择不能替代本轮引用。
企业制作指引中的命令行编修可用等价的画布命令完成。用 read_production_knowledge 时,fileId 取自 knowledgeFiles 列表,模板编号不能当作文件编号。read_copy_fields 省略 pageId 和 fieldId 即可一次读取全页文案字段及修订号。
子代理生图和验图读取本屏实时文案,候选验图回执绑定当时的文案签名。文案还没写时派图,子代理缺少本款卖点,写入 goal 的模板原文也会变成制作要求。文案改动后要按新文案复核,画面与新卖点不符时需要返工。读清实拍、商品资料和制作规则后,建议每批选 1–3 屏,先用 write_copy_fields 把本批文案写到画布,再用 delegate_image_slots 派这批图位,生图期间写下一批。
围绕每屏卖点主角定镜头和验收候选。分派 goal 依据本款实拍、商品资料、品牌规则和已确认的卖点,写明画面要重点呈现的部件、动作或结构,避免引用画布上尚未更新的模板原文。模板对应图位的原图符合卖点部位和景别时可参考构图,用本款实拍还原商品。模板原图拍了不同部位或景别时,传 useTemplateReference: false 重定机位,或用 transform_slot_image / use_product_image 裁切本款实拍。回填回执列出压在图位上方的模板叠层。整屏成片填充完成后,可用 check_output_screens 并行复核实际成片,pages 从 1 编号,通过时自动登记。
${COPY_IMAGE_SCREEN_CRITERIA}
根据 needs_fix 回执中的 nativeLayerId、文案字段或图位定位修正。需要看实际像素时用 read_output_screen(其 page 从 0 编号)。可用 native_catalog 查命令,再用 native_call 移动、缩放、隐藏或改写叠层。映射文案可用 write_copy_fields,图片可用 transform_slot_image 调整或重新生图。结合实际画面和商品资料自行选择处理方式。
需要独立观察结果的工具(如 open_production_output、read_output_screen、await_image_slots、finish_production)单独调用。多项连续查目录、批量采纳、批量回填文案及图层隐藏、选择、变换、样式修正等确定性操作,优先合并在一次 codemode 脚本中依次 await,使用各步实际回执衔接后续操作。
${NATIVE_CANVAS_QUICK_REFERENCE}
其余命令或完整参数说明用 native_catalog({ ids: [...] }) 一次取齐,在本回合和后续回合复用已取得的 parameterDocs。
用 read_output_screen 复核多屏时,每次按需查看 2–4 屏。后续新读图时会自动释放较早的查看截图,保留文字元数据。
transform_slot_image 可在本地裁切、旋转、镜像、缩放或位移同图位或跨图位候选及本款实拍,并返回像素清晰度指标。仅有构图问题时可复用现有图片。近景和特写可裁切现有或用 prefer2k: true 请求的 2K 中景,担心模板参考影响商品结构时可用 useTemplateReference: false。
独立手动复核时可用 record_screen_check 登记实际结果。复核后用 finish_production 提交当前画布修订,以工具返回的文件和版本为交付依据。可随时用 open_production_output 切换其它成品或回到此前的草稿。收口时用 finish_production 的 scope=all 核验本轮交付。子代理正在运行时可用 await_image_slots 等待回执。已返回结果未知的生图请求用 reconcile_image_slots 按原编号核查,核查期间可继续其它可做的图位和画布编辑。普通缺项和验图退回继续制作,仅在需要外部介入时提交阻塞原因和所需动作。用简短中文说明实际进展。`;
用 plan_production 查看待交付项,open_production_output 切换工作画布。用户附带引用时,用其中的输出、花色、图位、候选或原生图层身份定位目标。
读实时文案并使画面与对应卖点一致。子代理读取本屏实时文案,验图回执绑定当时的文案签名。文案更新后可按新文案复核。安排图位任务时写清需呈现的内容,避免把模板原文当成当前卖点。
用 tool_search 查找按需工具。企业指引中的命令行编修可用等价的画布命令完成。通过 native_catalog 查原生命令与完整参数,复用已取得的 parameterDocs。连续的确定操作可用 codemode 依次 await,用真实回执衔接各步。
按实际像素和企业 Skill 复核成片。结果未知的付费请求用 reconcile_image_slots 按原编号核查。以文件与版本回执确认交付,用简短中文汇报实际进展。`;
const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value });
function imageLengthSummary(data, start = 0) {
@ -153,11 +143,14 @@ function toolsFor(host) {
];
const projectResources = [...commands, ...enterpriseTools(host, make), ...productionVideoTools(host, make)];
if (host.productionGoal) return [
...productionTools.map(([name, description, schema])=>
make(name,description,schema,(args,signal)=>callProductionTool(host,name,args,signal),
...productionTools.map(([name, description, schema])=>({
...make(name,description,schema,(args,signal)=>callProductionTool(host,name,args,signal),
['read_output_screen','read_slot_images'].includes(name)?result=>result:
name==='write_copy_fields'?({copyUpdates,...receipt})=>({...plain(receipt),details:{...receipt,copyUpdates}}):plain)),
...contextTools, ...projectResources,
name==='write_copy_fields'?({copyUpdates,...receipt})=>({...plain(receipt),details:{...receipt,copyUpdates}}):plain),
...(['read_archived_images','stage_archived_image','retire_production_image','record_screen_check']
.includes(name)?{exposure:'deferred'}:null),
})),
...contextTools.map(tool => ({...tool, exposure:'deferred'})), ...projectResources,
];
const tools = [
...contextTools,
@ -607,7 +600,8 @@ export class DetailPiAgent {
: SessionManager.create(store.dir, path.join(store.dir, 'sessions')));
if (typeof canvas?.uiRequest === 'function') host.nativeUI = new NativeExtensionUI(canvas, { abort: () => { void host.session?.abort(); } });
const files = await projectTools(host);
const customTools = [...toolsFor(host),...files.tools];
const customTools = [...toolsFor(host), ...files.tools.map(tool =>
productionGoal && tool.name !== 'read' ? {...tool, exposure:'deferred'} : tool)];
host.workingDirectory=files.cwd;
const {resourceLoader:loader} = await createPhotoCraftExtensions(host, [], {
includeGoal: !!productionGoal, mayContinueGoal: event => mayContinueProductionGoal(host, event),
@ -836,8 +830,8 @@ export class DetailPiAgent {
value.currentProduct=product;
if (workflow) value.currentWorkflow=workflow;
if (this.productionSkills && loadKnowledge) {
const {knowledge,documents}=this.productionSkills;
value.enterpriseKnowledge={execution:knowledge.execution,sources:[...documents.values()]};
const {knowledge}=this.productionSkills;
value.enterpriseKnowledge={execution:knowledge.execution,sources:productionKnowledge(knowledge).files};
value.snapshot.rules=value.snapshot.rules.filter(rule=>/原稿画布|源模板约束/.test(rule));
return value;
}

View File

@ -84,7 +84,7 @@ export async function reviewProductionCandidate({
const requirements=rule?.focus??input.prompt??input.requirements;
const prompt=JSON.stringify({candidateId,fieldId:slot.fieldId,slot:slot.label,rule,requirements,
templateContext:requirements===input.requirements?undefined:input.requirements,
screenCopy,taskGuidance:await reviewKnowledge.guidance(),knowledgeFiles:reviewKnowledge.files,
screenCopy,knowledgeFiles:reviewKnowledge.files,
productReferenceCount:originalImages.length,layoutReferenceCount:layoutImages.length,
originalReference,frame:input.frame,ratio:input.frame?.width>0&&input.frame?.height>0?input.frame.width+':'+input.frame.height:input.aspectRatio,
candidateFile:input.candidateFile,outputSpec:input.outputSpec,layoutIssue:input.layoutIssue,

View File

@ -12,6 +12,39 @@ export function contextLengths(context) {
}).length;
return {textChars, totalChars: textChars + imageChars};
}
const productionReads = new Set(['plan_production', 'read_copy_fields', 'review_image_slots']);
export function foldSupersededProductionReads(messages) {
const calls = new Map();
for (const message of messages) {
if (message.role !== 'assistant') continue;
for (const block of message.content) {
if (block.type === 'toolCall' && productionReads.has(block.name)) calls.set(block.id, block.arguments);
}
}
const latest = new Set();
let folded;
for (let index = messages.length - 1; index >= 0; index--) {
const message = messages[index];
if (message.role !== 'toolResult' || message.isError || !productionReads.has(message.toolName)) continue;
const {outputId, variantId} = message.details ?? {};
const args = calls.get(message.toolCallId);
if (!outputId || !variantId || !args) continue;
const {slotIds, pageId, fieldId, includeKnowledge} = args;
const scope = JSON.stringify([message.toolName,outputId,variantId,
[...new Set(slotIds?.map(id=>id.trim()).filter(Boolean))].sort(),
pageId?.trim()||null,fieldId?.trim()||null,Boolean(includeKnowledge)]);
if (!latest.has(scope)) {
latest.add(scope);
continue;
}
folded ??= messages.slice();
folded[index] = {...message, details:undefined, content:[{type:'text',
text:'同范围已有更新回执。旧回执编号:'+message.toolCallId+',可用 memory_search 读取。'}]};
}
return folded ?? messages;
}
export function modelCapacity(model) {
const limit = count(model.contextWindow);
return limit > 0 && typeof model.contextWindowSource === 'string' && model.contextWindowSource.length > 0

View File

@ -1,11 +1,7 @@
export const COPY_IMAGE_PLANNING_GUIDANCE='先看本款实拍和商品资料,结合模板各屏的版式职能与品牌调性策划卖点和文案,再以文案确定画面。只给实拍或资料能支撑的部件安排卖点屏。';
export const DRAW_LIMIT_GUIDANCE='每个图位最多发起 4 次远端生图。达到上限后,横向比较已有候选,选最合适的一张直接采纳,也可用实拍裁切或画布调整。汇报中简述取舍,后续可由人工通过「引用」定向精修。';
export const COPY_IMAGE_PROMPT_GUIDANCE='卖点主角就是画面主角。让文案讲的具体部件、动作或结构成为清晰的视觉焦点。模板原图与本屏卖点部位和景别一致时可参考构图,并用本款实拍还原商品。模板原图与当前卖点部位或景别不同时,可传 useTemplateReference: false 重定机位,或用 transform_slot_image / use_product_image 从本款实拍裁切对应部件。实拍或版式无法可靠呈现时,按资料调整对应文案。'+DRAW_LIMIT_GUIDANCE;
export const OVERLAY_SCREEN_CRITERIA='模板尺寸线、虚线轮廓、引线、标注文字和装饰角标沿用旧图与旧文案的位置。换图或改字后,结合整屏合成切片与 overlayLayers 才能看出叠层错位、压字或数值不符。overlapsSlots 对应图位的 fieldId,bounds 是画布像素边界,text 是图层当前文字,mapped 表示是否映射。对照商品资料核对尺寸数值、引线端点、产品结构线和虚线轮廓的贴合情况,也检查装饰对齐、文字溢出、裁切及浅色背景上的可读性。';
export const OVERLAY_FIX_GUIDANCE='按画面和商品资料自行选择修法。用 native_catalog 查命令,通过 native_call 按 nativeLayerId 移动、缩放、隐藏或改写叠层。映射文案可用 write_copy_fields,图片可用 transform_slot_image 调整或重新生图。用 read_output_screen 复看实际画面。';
const IMAGE_COPY_CRITERIA='对照 screenCopy、商品资料与实际画面逐条核对图文一致性,确认对应图位把卖点部位、动作或结构清晰呈现为焦点,并核对材质、颜色、款式和结构是否真实可见,场景或功能卖点是否与实拍及 SKU 花色相符,尺寸、规格、数量是否与画面和标注自洽。';
export const COPY_IMAGE_SCREEN_CRITERIA=IMAGE_COPY_CRITERIA+OVERLAY_SCREEN_CRITERIA;
export const COPY_IMAGE_SCREEN_GUIDANCE=COPY_IMAGE_SCREEN_CRITERIA+OVERLAY_FIX_GUIDANCE;
export const COPY_IMAGE_PROMPT_GUIDANCE='让画面清晰呈现关联文案的重点。模板原图与目标画面不符时可设置 useTemplateReference: false,用本款实拍保持商品一致。构图可用 transform_slot_image 调整,具体创作要求见适用企业 Skill。';
export const COPY_IMAGE_REVIEW_GUIDANCE='用 shownSubject 描述实际可见内容,再对照关联和同屏实时文案,填写 checks.copyAlignment,检查对应部位是否清晰可见,指出不符的文案和可见依据。按适用企业 Skill 判断视觉标准。';
export const OVERLAY_SCREEN_CRITERIA='核对叠层错位、压字或数值不符。overlayLayers 的 overlapsSlots 对应图位 fieldId,bounds 为像素边界,text 为当前文字,mapped 表示是否已映射。';
export const COPY_IMAGE_SCREEN_GUIDANCE='对照商品资料、实时文案和适用企业 Skill 核对整屏实际画面。检查材质、颜色、款式、结构、尺寸与标注是否一致,以及文字溢出、裁切和可读性。'+OVERLAY_SCREEN_CRITERIA;
const fieldId = row => row.field ?? row.fieldId;
const belongsTo = (ids, id) => Array.isArray(ids) && ids.includes(id);

View File

@ -86,12 +86,6 @@ export class EnterpriseContext {
skill=await this.specificDocument(directory,entry.target,'skill',options);
knowledge.skills.push(skill);
}
const prefix=path.posix.dirname(entry.target)+'/references/';
const references=new Set(links(skill).filter(({target})=>target.startsWith(prefix)).map(({target})=>target));
for (const target of references) {
if (knowledge.rules.some(rule=>rule.path===target)) continue;
knowledge.rules.push(await this.specificDocument(directory,target,'native-reference',options));
}
}
async declaredGuides(identity,options) {
@ -123,11 +117,13 @@ export class EnterpriseContext {
continue;
}
const target=kind==='skill'?skills:rules;
if (pinned) {
if (pinned?.text != null) {
target.push({...pinned,kind});
} else if (identity.task === 'production' && kind !== 'skill' && kind !== 'template-reference') {
target.push({fileId:pinned?.fileId??fileId,revision:pinned?.revision??revision,path:source,kind});
} else {
const {result}=await this.client.readDocument(fileId,revision,{signal},read);
target.push({fileId,revision,path:source,kind,pages:result.pages,text:result.text});
const {result}=await this.client.readDocument(pinned?.fileId??fileId,pinned?.revision??revision,{signal},read);
target.push({fileId:pinned?.fileId??fileId,revision:pinned?.revision??revision,path:source,kind,pages:result.pages,text:result.text});
}
}
if(!skills.length)throw Error('所选模板未声明制作 Skill 正文');
@ -141,17 +137,24 @@ export class EnterpriseContext {
const bytes = await fs.readFile(result.localPath, {signal});
return {...source,sha256:result.sha256,kind:'skill-runtime',bytes:bytes.toString('base64')};
}
if (source) {
const {result}=await this.client.readDocument(source.fileId,source.revision,{signal},read);
return {...source,kind:source.kind??'native-reference',text:result.text};
}
directory??=(await read(()=>this.client.call('list_libraries',{},{signal}))).result.navigation
?.find(item=>item.name==='Skills')?.path;
if (!directory || !target.startsWith(directory+'/')) throw Error('技能引用超出授权技能目录');
if (!source) return this.specificDocument(directory,target,'native-reference',{signal,read});
const {result}=await this.client.readDocument(source.fileId,source.revision,{signal},read);
return {...source,kind:'native-reference',text:result.text};
return this.specificDocument(directory,target,'native-reference',{signal,read});
}
async specificDocument(directory,target,kind,{signal,read,pins}) {
if (!target.startsWith(directory+'/')) throw Error('技能引用超出授权技能目录');
if (pins?.has(target)) return {...pins.get(target),kind};
const pinned=pins?.get(target);
if (pinned) {
if (typeof pinned.text === 'string') return {...pinned,kind};
const {result}=await this.client.readDocument(pinned.fileId,pinned.revision,{signal},read);
return {...pinned,kind,text:result.text};
}
let entry, offset=0, revision;
for (;;) {
const found=(await read(()=>this.client.call('search_files',{query:path.posix.basename(target),directory:path.posix.dirname(target),limit:40,offset,...(revision?{revision}:{})},{signal}))).result;

View File

@ -1,6 +1,6 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { loadSkills } from '@earendil-works/pi-coding-agent';
import { loadSkills, parseFrontmatter } from '@earendil-works/pi-coding-agent';
import { atomic, digest } from './store.mjs';
import { links } from './enterprise-context.mjs';
@ -21,7 +21,10 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
for (const source of prior.scriptSources ?? []) {
if (!pins.has(source.path)) pins.set(source.path, source);
}
for (const source of [...prior.skills, ...prior.rules]) pins.set(source.path, source);
for (const source of [...prior.skills, ...prior.rules]) {
const pinned = pins.get(source.path);
if (!pinned || pinned.text == null && source.text != null) pins.set(source.path, source);
}
}
return pins;
}
@ -68,7 +71,14 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
}
}
}
for (const item of [...knowledge.skills, ...knowledge.rules]) await materialize(item);
for (const item of knowledge.skills) await materialize(item);
for (const item of knowledge.rules) {
if (typeof item.text === 'string' || item.kind === 'skill-runtime') await materialize(item);
else {
if (!validPath(item.path)) throw Error('已发布的规则资源路径无效:' + item.path);
references.set(filePath(item.path), {target:item.path,from:'发布资源'});
}
}
const scriptSources = new Map();
for (const source of knowledge.scriptSources ?? []) {
@ -85,10 +95,11 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
async function resolveReference({target, from}, script, signal) {
try {
const pins = await readPins();
const source = script ?? knowledge.referenceSources?.find(item => item.path === target);
const source = script ?? knowledge.rules.find(item => item.path === target) ??
knowledge.referenceSources?.find(item => item.path === target);
const pinned = pins.get(target);
const hasContent = script ? pinned?.kind === 'skill-runtime' : typeof pinned?.text === 'string';
const item = hasContent ? {...pinned,kind:script ? 'skill-runtime' : 'native-reference'} :
const item = hasContent ? {...pinned,kind:source?.kind??pinned.kind} :
await loadReference(target, {source,directory:knowledge.skillDirectory,signal});
if (item.path !== target) throw Error('返回的资源路径与锁定路径不一致');
if (script && (item.fileId !== script.fileId || item.revision !== script.revision)) {
@ -96,10 +107,12 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
}
signal?.throwIfAborted();
const save = saving.then(async () => {
if (knowledge.rules.some(rule => rule.path === target)) return;
const rules = [...knowledge.rules, item];
const index = knowledge.rules.findIndex(rule => rule.path === target);
const rules = [...knowledge.rules];
if (index === -1) rules.push(item);
else rules[index] = item;
await atomic(snapshot, {...knowledge, rules});
knowledge.rules.push(item);
knowledge.rules = rules;
});
saving = save.catch(() => {});
await save;
@ -122,9 +135,9 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
}
async function shellFiles(signal) {
for (const file of scriptSources.keys()) {
for (const file of [...scriptSources.keys(), ...knowledge.rules.map(item => filePath(item.path))]) {
signal.throwIfAborted();
if (!await resolveFile(file, signal)) throw Error('无法读取已发布的脚本资源:' + scriptSources.get(file).path);
if (!await resolveFile(file, signal)) throw Error('无法读取已发布的脚本资料:' + path.basename(file));
}
return [...documents].map(([file, source]) => ({file, source}));
}
@ -139,5 +152,18 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
await store.appendEvent({type:'enterprise_skill_resources_bound', outputId:selection.outputId,
...((knowledge.resourceRevision) ? {resourceRevision:knowledge.resourceRevision} : null),
sources:[...documents.values()]});
return {knowledge, resource, documents, resolveFile, shellFiles};
const limits = knowledge.skills.map(({text}) => parseFrontmatter(text).frontmatter.maxGenerationAttempts)
.filter(limit => Number.isSafeInteger(limit) && limit > 0);
return {
maxGenerationAttempts: limits.length ? Math.min(...limits) : undefined,
get knowledge() {
return {...knowledge,rules:knowledge.rules.map(item => typeof item.text === 'string' || item.kind === 'skill-runtime' ? item : {
...item,loadText:async signal => {
await resolveFile(filePath(item.path),signal);
return fs.readFile(filePath(item.path),{encoding:'utf8',signal});
},
})};
},
resource, documents, resolveFile, shellFiles,
};
}

View File

@ -6,6 +6,8 @@ import {
DefaultResourceLoader,
SettingsManager,
} from '@earendil-works/pi-coding-agent';
import { foldSupersededProductionReads } from './context-usage.mjs';
import { productionObjective } from './production-goal.mjs';
import { createImageContextPruningExtension } from './image-context-pruning.mjs';
const sdkToolNames = Object.freeze(['codemode', 'tool_search']);
@ -63,6 +65,9 @@ export async function createPhotoCraftExtensions(host, existing = [], {
{name: 'photocraft-codemode', factory: createCodemodeExtension({models: false})},
{name: 'photocraft-tool-search', factory: createToolSearchExtension()},
{name: 'photocraft-image-context', factory: createImageContextPruningExtension()},
...(includeGoal ? [{name:'photocraft-production-context', factory: pi => {
pi.on('context', event => ({messages:foldSupersededProductionReads(event.messages)}));
}}] : []),
],
});
await loader.reload();
@ -74,15 +79,17 @@ export async function createPhotoCraftExtensions(host, existing = [], {
if (includeGoal) {
const goal = result.extensions.findLast(extension => extension.commands.has('goal'));
if (!goal) throw Error('当前客户端无法继续制作目标,请更新完整客户端');
goal.handlers.set('context', [...goal.handlers.get('context') ?? [], event => ({
messages: event.messages.map(message => {
const {kind,goal:state}=message.details??{};
if (message.role!=='custom'||message.customType!=='pi-goal-event'||
!['active','resumed','continuation'].includes(kind)||!state?.objective) return message;
return {...message,content:'继续当前制作目标:'+state.objective+
'\n沿用已完成的工作。需要事实或画布状态时按需读取,以实际文件回执确认交付。'};
}),
})]);
const isReminder = message => message.role === 'custom' && message.customType === 'pi-goal-event' &&
['active', 'resumed', 'continuation'].includes(message.details?.kind) && message.details.goal?.objective;
goal.handlers.set('context', [...goal.handlers.get('context') ?? [], event => {
const last = event.messages.findLast(isReminder);
if (!last) return;
const objective = host.productionGoal ? productionObjective(host.productionGoal.requestedOutputs) : last.details.goal.objective;
return {messages: event.messages.flatMap(message => {
if (message === last) return [{...message, content:'继续当前制作目标:' + objective}];
return isReminder(message) ? [] : [message];
})};
}]);
// Apply the production gate only when the plugin could queue another turn.
goal.handlers.set('agent_end', goal.handlers.get('agent_end').map(handler => async (event, ctx) => {
if (!ctx.hasPendingMessages() && (!mayContinueGoal || await mayContinueGoal(event))) return handler(event, ctx);

View File

@ -1,50 +0,0 @@
export const copyProofInstructions = [
'先拆分一句话中的各项商品主张,逐项核对当前款式的依据。照片可以证明看得见的颜色、纹理、形状、部件关系,以及画面实际显示的动作和接触。',
'材质成分、尺寸数值、功能效果、体感、使用难易、耐用性、认证和承诺需要本款资料明确记录。姿态、产品形状和能拍出的使用情景都不能证明这些结论。圆角能从照片核对,触感柔和、手感顺滑等描述需要同款资料。',
'相邻、分离、环绕或遮挡只能按原片写成可见位置关系。内部固定方式、部件承力路径、成型工艺和手工加工需要本款资料明确记录。照片中的独立轮廓可以写分离或两块,不能据此写分开成型。',
'同样的颜色或纹理只能证明外观。部件使用同一材料或处在同一平面,需要本款资料明确说明所指部件。按提交文案的实际意思核对,空间不足时改写为短而完整的句子。',
'一句话只要含有未经证实的结论,即使另半句的外观属实,也应退回或改写为原图可以核对的部件、位置和关系。创意设想仅用于布景。',
'卖点面向买家,使用自然完整的短语或短句。每段说清哪个部位有什么特点或平时怎么使用。用买家的口吻逐句读一遍,退回重复词、同义叠加和没有主体的部件罗列。机位要求、人物为取景做的避让及验图结论放在制作说明。',
];
// A finish or colour can be described from a photo, but its composition
// requires an explicit declaration from the product brief.
const materialTerms=/真皮|头层牛皮|牛皮|羊皮|皮革|超纤皮|不锈钢|铝合金|碳钢|铁艺|金属(?!色|感|光泽)|实木|橡胶木(?!色|纹)|橡木(?!色|纹)|胡桃木(?!色|纹)/gu;
const uncertain=/未确认|未登记|未提供|不明确|不确定|不是|并非|待确认|待核实|无法|不能|无依据|缺失|可能|疑似|看起来/u;
export function unsupportedMaterial(text,brief) {
const declarations=[brief?.name,brief?.note].filter(value=>typeof value==='string')
.flatMap(value=>value.split(/[。;;\n]+/u)).filter(line=>!uncertain.test(line));
const verified=new Set(declarations.flatMap(line=>line.match(materialTerms)??[]));
return [...new Set(text.match(materialTerms)??[])].filter(material=>!verified.has(material));
}
const assertedTerms = /不硌手|不磕碰|不顶背|不卡|不用绷着|不闷|不勒|透气|亲肤|(?:触感|手感)(?:柔和|柔软|细腻|顺滑|光滑|温润|舒适|偏硬)?|久坐不累|(?:可以|适合|可)久坐|不易侧倾|耐(?:磨|用|刮|久)|防(?:滑|水|潮)|抗菌|阻燃|防霉|环保|甲醛|承重|质保|[0-9]+(?:[..][0-9]+)?\s*(?:毫米|厘米|公分|公斤|千克|kg|mm|cm)|[eE][nN][fF]/gu;
const assemblyClaim = /(?<!不|未|非|没有)(?:承托|承载|支撑|支承)(?:了|着|住)?(?:独立|分体|一体|米色|软包|木质|圆弧|弧形|织纹){0,4}(?:靠背|坐垫|坐面|座垫|座面|扶手|桌面|框架)/u;
const clauses = text => text.split(/[,,、]+/u).map(part=>part.trim());
const materialOrPlaneClaim = /(?:同一(?:种|款|批)?|相同)(?:的)?[^、,。]{0,8}(?:面料|材质|材料)|同(?:面料|材质|材料)|(?:面料|材质|材料)(?:完全)?(?:相同|一致)|共面|同一平面/u;
const manufacturingClaim = /一体成型|分体成型|分开成型|整体成型|一体铸造|分体铸造|一体压铸|整体浇铸|手工打磨|手工缝制/u;
const incompletePlaneClaim = /(?:与|和|及).+同面$/u;
const relationClauses = text => text.split(/[,,]+/u).map(part=>part.trim());
export function unsupportedClaims(text, brief) {
const declarations=[brief?.name,brief?.note,brief?.dimensions]
.filter(item=>typeof item==='string')
.flatMap(item=>item.split(/[。;;\n]+/u))
.filter(line=>!uncertain.test(line)&&!/(模板|样例|示意|参考)/u.test(line));
const confirmed=new Set(declarations.flatMap(line=>line.match(assertedTerms)??[]));
const brand=brief?.brandName;
const templateBrand=brand&&brand.length>1&&text.includes(brand)&&
!declarations.some(line=>line.includes(brand)&&(line===brief.name||/(?:商品|产品|实物)?品牌\s*[::]/u.test(line)))?[brand]:[];
const statements=text.split(/[。;;\n]+/u).filter(line=>!/(?:未|待|请|以).{0,16}(?:核实|核对|确认|为准)/u.test(line));
const documentedAssembly=new Set(declarations.flatMap(clauses));
const unprovenAssembly=statements.flatMap(clauses).filter(clause=>{
const claim=assemblyClaim.exec(clause);
return claim&&(claim.index===0||!documentedAssembly.has(clause));
});
const documentedRelations=new Set(declarations.flatMap(relationClauses));
const unprovenRelations=statements.flatMap(relationClauses).filter(clause=>
incompletePlaneClaim.test(clause)||((materialOrPlaneClaim.test(clause)||manufacturingClaim.test(clause))&&!documentedRelations.has(clause)));
return [...new Set([...unsupportedMaterial(text,brief),...templateBrand,...unprovenAssembly,...unprovenRelations,...statements.flatMap(line=>line.match(assertedTerms)??[])
.filter(term=>!confirmed.has(term))])];
}

View File

@ -6,7 +6,6 @@ import { SessionManager } from '@earendil-works/pi-coding-agent';
import { openProductionOperations, productionOperationTools, reconcileProjectImageSlots } from './production-operations.mjs';
import { BridgeError } from './bridge-error.mjs';
import { checkOutputCapabilities } from './output-capabilities.mjs';
import { COPY_IMAGE_PLANNING_GUIDANCE, COPY_IMAGE_PROMPT_GUIDANCE } from './copy-image-alignment.mjs';
export function productionGoalPreflight(goal) {
const outputPreflight = checkOutputCapabilities(goal.requestedOutputs);
@ -18,7 +17,7 @@ export function productionGoalPreflight(goal) {
export function productionObjective(requestedOutputs) {
const outputs = [...new Set(requestedOutputs.map(row=>row.label || row.outputId))].join('、');
return `按适用制作指引和模板制作并交付本轮所选输出:${outputs}。当前由小壹原生画布自动合成并导出,无需询问制作软件或合成方式。${COPY_IMAGE_PLANNING_GUIDANCE}${COPY_IMAGE_PROMPT_GUIDANCE}验图和整屏复核时自主核对图文一致性,用 read_output_screen 逐条核对实时文案与对应图位的画面主角。发现不符时,依据商品资料用原生工具修图或改字,再看屏确认。`;
return `按适用制作指引和模板制作并交付本轮所选输出:${outputs}。`;
}
export function piGoalState(manager) {
@ -45,7 +44,7 @@ export async function runPiProductionGoal(host, text, continuation, images=[]) {
watchBoundOutput(host);
const current = piGoalState(host.manager);
const objective = productionObjective(host.productionGoal.requestedOutputs);
const continuing = current && current.status !== 'complete' && current.objective === objective;
const continuing = current && current.status !== 'complete' && current.objective.startsWith(objective);
if (!continuation || !continuing) {
const request = JSON.stringify({request:text,
requestedOutputs:host.productionGoal.requestedOutputs,product:host.productEvidence?.product});

View File

@ -1,34 +1,16 @@
import { Type } from '@sinclair/typebox';
const stageRules = {
strategy: ['selling-points', 'evidence', 'brand', 'product-visual', 'template-reference'],
copy: ['selling-points', 'content-planning', 'evidence', 'brand', 'output'],
image: ['image-production', 'image-prompt', 'composition', 'product-visual', 'template-reference', 'brand', 'output'],
review: ['review', 'composition', 'product-visual', 'template-reference', 'brand', 'output'],
};
export const knowledgeFileIdInstruction = 'fileId 必须取自 plan_production 的 knowledgeFiles 列表,不能传模板编号。';
export const knowledgeReadInstruction = '按需用 read 读取项目企业 Skill 及其引用,也可用 read_production_knowledge 读取固定版本。'+knowledgeFileIdInstruction;
export const knowledgeFileIdInstruction = 'fileId 必须取自 knowledgeFiles 列表,不能传模板编号。';
const pageSize = 6000;
export function productionKnowledge(knowledge, stage) {
export function productionKnowledge(knowledge) {
const documents = [...(knowledge?.skills ?? []), ...(knowledge?.rules ?? [])]
.filter(document => document.fileId && document.revision && (typeof document.text === 'string'||typeof document.loadText === 'function')
&& (!stage || document.kind === 'skill' || stageRules[stage].includes(document.kind)));
.filter(document => document.fileId && document.revision && (typeof document.text === 'string'||typeof document.loadText === 'function'));
const files = documents.map(({fileId,revision,path,kind}) => ({fileId,revision,path,kind}));
const brief = documents.find(document=>document.kind===(stage==='image'?'image-production':stage));
let taskGuidance;
const guidance = () => taskGuidance ??= brief && readPage(brief,0);
async function readPage(document,offset) {
const {fileId,revision}=document;
const body=document.text??await document.loadText();
const text=body.slice(offset,offset+pageSize);
const nextOffset=offset+text.length;
return {fileId,revision,text,nextOffset:nextOffset<body.length?nextOffset:null};
}
if (!files.length) return {files, tools:[], guidance};
return {files, guidance, tools:[{
if (!files.length) return {files, tools:[]};
return {files, tools:[{
name:'read_production_knowledge', label:'读取制作规则',
description:'读取当前阶段知识文件的固定版本,可用 nextOffset 继续读取。'+knowledgeFileIdInstruction,
description:'读取项目知识文件的固定版本,可用 nextOffset 继续读取。'+knowledgeFileIdInstruction,
parameters:Type.Object({
fileId:Type.String({minLength:1,maxLength:500}),
offset:Type.Optional(Type.Integer({minimum:0})),
@ -36,20 +18,13 @@ export function productionKnowledge(knowledge, stage) {
execute:async (_id,{fileId,offset=0},signal)=>{
signal?.throwIfAborted();
const document=documents.find(entry=>entry.fileId===fileId);
if(!document)throw Error('该文件不属于当前制作阶段使用的知识资料');
const details=await readPage(document,offset);
if(!document)throw Error('该文件不属于当前项目使用的知识资料');
const body=document.text??await document.loadText(signal);
signal?.throwIfAborted();
const text=body.slice(offset,offset+6000);
const nextOffset=offset+text.length;
const details={fileId,revision:document.revision,text,nextOffset:nextOffset<body.length?nextOffset:null};
return {content:[{type:'text',text:JSON.stringify(details)}],details};
},
}]};
}
export function productionRuleText(knowledge, kind, limit, headings) {
const text=knowledge?.rules?.find(document=>document.kind===kind)?.text;
if(typeof text!=='string')return undefined;
const sections=text.split(/\n(?=#{1,5}\s)/u);
const selected=headings&&sections.length>1
? sections.filter(section=>headings.test(section.split('\n',1)[0])).join('\n')
: text;
return selected.trim().slice(0,limit)||undefined;
}

View File

@ -1,7 +1,6 @@
import path from 'node:path';
import { isDeepStrictEqual } from 'node:util';
import { CanvasOperations } from './canvas-operations.mjs';
import { setTimeout as delay } from 'node:timers/promises';
import { Type } from '@sinclair/typebox';
import { formatDimensionNote, resizeImage } from '@earendil-works/pi-coding-agent';
import { productionLedger, recordProductionInputs } from './production-repository.mjs';
@ -10,7 +9,7 @@ import { loadSlots } from './production-slots.mjs';
import { productionKnowledge, knowledgeFileIdInstruction } from './production-knowledge.mjs';
import { productRequestScope } from './production-recovery.mjs';
import { canvasTransformArgs, reviewProductionCandidate } from './candidate-review.mjs';
import { COPY_IMAGE_PROMPT_GUIDANCE, COPY_IMAGE_SCREEN_GUIDANCE, DRAW_LIMIT_GUIDANCE, extractPageLiveCopy, resolveLiveSlotCopy } from './copy-image-alignment.mjs';
import { COPY_IMAGE_PROMPT_GUIDANCE, COPY_IMAGE_SCREEN_GUIDANCE, extractPageLiveCopy, resolveLiveSlotCopy } from './copy-image-alignment.mjs';
import { executeWorkflow, LOCAL_OPERATION_WAIT_MS, reconcileWorkflowReceipt } from './workflow-execute.mjs';
import { createVideoToolExecutors, videoTools } from './video-tools.mjs';
import { activityToolLabel, COPY_UPDATE_LIMIT, copyUpdateItem } from './activity-event.mjs';
@ -20,7 +19,7 @@ import { createTailWatcher } from './tail-watcher.mjs';
const obj=fields=>Type.Object(fields,{additionalProperties:false});
const text=Type.String({minLength:1});
const ids=Type.Array(text);
const slotRef=Type.String({minLength:1,description:'优先填写 plan_production 返回的当前画布 fieldId;字段编号重复时使用对应的完整 id。'});
const slotRef=text;
const layer=Type.Integer({minimum:1});
const page=Type.Integer({minimum:0});
const rev=Type.Integer({minimum:0});
@ -42,7 +41,6 @@ const recoveryNotices={
expired:'原请求结果已过期',
not_executed:'原操作已确认未执行',
};
const MAX_SLOT_GENERATIONS=4;
const expiryFields=receipt=>receipt?.resultExpiry?
{requestId:receipt.requestId,retryable:false,resultExpiry:receipt.resultExpiry}:{};
function rememberImageExpiry(item,candidateId,receipt){
@ -74,14 +72,14 @@ const imagePromptGuidance=COPY_IMAGE_PROMPT_GUIDANCE;
const dispatchArgs={requestId:text,expectedRevision:optional(rev),expectedHash:optional(text)};
export const productionOperationTools = [
['open_production_output','打开本轮指定输出和花色。切换前保存原工程,返回保存结果、新画布绑定及待交付项。用 plan_production 获取输出和花色。收到绑定回执后再操作画布。',obj({outputId:text,variantId:text})],
['plan_production','读取当前商品规格与备注、模板、图位、成品进度和本轮其它待处理输出。按 slotIds 读取指定图位的规则和要求。模板规则从项目 Skill 及其引用读取。pictures 中的 copyReady 表示关联字段没有待写文案。调用图位工具时优先使用 pictures 中的 fieldId。',obj({slotIds:optional(ids)})],
['read_production_knowledge','读取当前阶段固定版本的制作规则,按回执的 nextOffset 翻页。'+knowledgeFileIdInstruction,obj({fileId:text,offset:optional(page)})],
['read_copy_fields','省略 pageId 和 fieldId 可一次读取全页文案字段、当前文字及修订号。需要模板样稿与发布要求时,指定 pageId 或 fieldId 读取对应范围。',obj({
['open_production_output','打开本轮指定输出和花色。切换前保存原工程,返回新画布绑定、保存结果、已取消的未派发图位和仍在处理的付费原请求。用 plan_production 获取输出和花色。收到绑定回执后再操作画布。',obj({outputId:text,variantId:text})],
['plan_production','读取当前商品规格与备注、模板、图位、成品进度和本轮其它待处理输出。按 slotIds 获取指定图位及其发布要求;includeKnowledge=true 列出固定版本的规则索引。pictures 中的 copyReady 表示关联字段没有待写文案。图位工具优先使用 fieldId,重名时使用完整 id。',obj({slotIds:optional(ids),includeKnowledge:optional(Type.Boolean())})],
['read_production_knowledge','读取当前项目固定版本的制作规则,按回执的 nextOffset 翻页。'+knowledgeFileIdInstruction,obj({fileId:text,offset:optional(page)})],
['read_copy_fields','省略 pageId 和 fieldId 返回全页字段身份、当前文字、约束及修订号;指定页面或字段可读取图层样式、范围及关联字段。',obj({
pageId:optional(Type.String()),fieldId:optional(Type.String()),
})],
['write_copy_fields','使用最近一次读文案、写文案或复看整屏返回的文案修订号写入已读文字格。每个 layer 只传一次。可按屏或模块分批写入,原生命令已经写过时可用 recordOnly 登记现有文字。retryWrite 表示画布暂不可写,rejected 列出保留原文的格子。模板规定缺资料时留空的字段,可传空文字并用 reason 记录依据。',obj({
revision:rev,recordOnly:optional(Type.Boolean()),items:optional(Type.Array(obj({layer,text:Type.String(),sources:ids,pictures:ids,reason:optional(Type.String())}))),
['write_copy_fields','按 revision 原位写入指定文字格。可传 expectedText 让画布核对原文,修订已变化时用于匹配未改动的字段。每个 layer 只传一次。可按屏或模块分批写入,原生命令已经写过时可用 recordOnly 登记现有文字。retryWrite 表示画布暂不可写,rejected 列出保留原文的格子。模板规定缺资料时留空的字段,可传空文字并用 reason 记录依据。',obj({
revision:rev,recordOnly:optional(Type.Boolean()),items:optional(Type.Array(obj({layer,text:Type.String(),expectedText:optional(Type.String()),sources:ids,pictures:ids,reason:optional(Type.String())}))),
})],
['read_slot_images','查看当前图位的同款实拍和模板构图。候选只返回候选画面;需要同时查看或重新查看参考时传 includeReferences=true。',obj({
slotId:slotRef,candidateId:optional(Type.String()),adopted:optional(Type.Boolean()),includeReferences:optional(Type.Boolean()),
@ -89,8 +87,8 @@ export const productionOperationTools = [
['use_product_image','用本款原片或裁切区域创建候选。通过 adopt_production_image 回填时,放置回执会列出覆盖图位的模板叠层。',obj({slotId:slotRef,...productImageArgs})],
['transform_slot_image','在本机裁切、镜像、旋转、缩放或位移同图位或跨图位候选及本款实拍,返回新候选和像素清晰度指标。',obj({slotId:slotRef,...transformImageArgs})],
['prepare_image_request','保存完整生图请求,返回正式文本、参考顺序、模型参数与请求编号。'+imagePromptGuidance,obj({slotId:slotRef,...preparationArgs})],
['dispatch_image_request','审阅准备回执后填写 requestId 确认派发。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。'+DRAW_LIMIT_GUIDANCE,obj(dispatchArgs)],
['delegate_image_slots','异步分派一批图位,空闲的制作助手立即开始,其余图位顺序排队。每个 goal 写明对应屏的核心卖点与画面要证明的细节。逐图位返回接收情况及待写文案字段。生图派发后宿主继续跟踪原请求,可用 await_image_slots 查看回执。',obj({
['dispatch_image_request','审阅准备回执后填写 requestId 确认派发。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。',obj(dispatchArgs)],
['delegate_image_slots','异步分派一批图位,空闲的制作助手立即开始,其余图位顺序排队。每个 goal 写明对应屏的核心卖点与画面要证明的细节。逐图位返回接收情况及关联的待写文案字段。',obj({
jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})),
})],
['await_image_slots','等待任一在途制作、验图或生图请求返回,并读取已有回执。省略 slotIds 时也关注按屏复核,结论见 screenChecks。已经返回结果未知的原请求用 reconcile_image_slots 核查。',obj({slotIds:optional(ids)})],
@ -107,7 +105,7 @@ export const productionOperationTools = [
['adopt_production_image','采用你选择的候选,返回画布修订和覆盖该图位的模板叠层。尺寸线、虚线、引线、文字和装饰角标的错位或数值是否匹配本款,可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit)})],
['retire_production_image','清理你已判为失败的当前图位候选,保留原因、提示词和原请求记录。返工需要旧图时,先让子代理读取再清理。若该图已在画布上,回执会给出应替换的图层。',obj({slotId:slotRef,candidateId:text,reason:text})],
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号;expired 表示原结果已过期,可以为同图位另备新请求。',obj({slotIds:optional(ids)})],
['read_output_screen',`读取整屏合成画面的实际像素和 overlayLayers。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。后续新读图时自动释放较早的截图并保留文字元数据。${COPY_IMAGE_SCREEN_GUIDANCE}`,obj({
['read_output_screen',`读取整屏合成画面的实际像素和 overlayLayers。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。只保留最新一次查看图片。${COPY_IMAGE_SCREEN_GUIDANCE}需要修正时通过 native_catalog 查命令,再用 native_call 编辑叠层,或用 write_copy_fields、transform_slot_image 更新映射内容。`,obj({
page:optional(page),pages:optional(Type.Array(page)),
})],
['check_output_screens','按企业 Skill 并行复核整屏合成画面、商品实拍、实时文案与叠加图层。pages 从 1 编号,以当前画布实际屏数为准。默认等待结论,通过的屏自动登记。问题按图位、原生图层或文案字段定位。wait=false 可用不带 slotIds 的 await_image_slots 收取文字结论。',obj({
@ -306,7 +304,8 @@ export async function reconcileProjectImageSlots(host,{slotIds},signal) {
const results=[];
for(const {outputId,variantId} of goal.pendingOutputs??goal.requestedOutputs){
signal?.throwIfAborted();
const ledger=productionLedger(store,outputId,variantId);
const maxGenerationAttempts=configuredLimit??plan.template.production?.maxGenerationAttempts??host.productionSkills?.maxGenerationAttempts;
const ledger=productionLedger(store,outputId,variantId);
let journal=ledger.read();
if(!journal)continue;
const slots=Object.entries(journal.items).filter(([id])=>!requested.size||requested.has(id));
@ -327,11 +326,10 @@ const copyPage=field=>field.page??field.pageId;
const slotPage=slot=>slot.documentId??slot.page??slot.pageId;
const slotSignatures=slots=>Object.fromEntries(slots.map(slot=>[slot.id,slot.selectedCandidateId??null]));
export async function openProductionOperations(host,{maxActiveDelegates=6,maxGenerationAttempts=MAX_SLOT_GENERATIONS,
export async function openProductionOperations(host,{maxActiveDelegates=6,maxGenerationAttempts: configuredLimit,
maxTailWatchConcurrency=6,tailFastIntervalMs=8_000,tailSlowIntervalMs=20_000,tailFastWindowMs=180_000,
tailWatchClock}={}) {
if(!Number.isSafeInteger(maxActiveDelegates)||maxActiveDelegates<1)throw RangeError('图位子代理并发上限必须为正整数');
if(!Number.isSafeInteger(maxGenerationAttempts)||maxGenerationAttempts<1)throw RangeError('图位生图上限必须为正整数');
if(!Number.isSafeInteger(maxTailWatchConcurrency)||maxTailWatchConcurrency<1)throw RangeError('原请求核查并发上限必须为正整数');
const {canvas,store,productionGoal:{outputId,variantId}}=host;
const {plan:initialPlan,slots}=await loadSlots(canvas,outputId);
@ -353,10 +351,10 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
record.copyInputs=productionInputs(value,variantId);
record.creationRevision=value.revisions?.creation;
};
const source=host.productionSkills?.knowledge??host.knowledgeContext;
const knowledge=productionKnowledge(source);
const delegateKnowledge=productionKnowledge(source,'image');
const reviews=productionKnowledge(source,'review');
const productionIndex=()=>productionKnowledge(host.productionSkills?.knowledge??host.knowledgeContext);
const knowledge=productionIndex();
const reviews=knowledge;
const delegateKnowledge=knowledge;
const findSlot=reference=>{
const id=reference.trim();
const named=byField.get(id);
@ -379,14 +377,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
}
return {requested,matched,unmatched};
};
const copyReads=new Map();
const rememberCopy=({revision,fields=[]})=>{
if(!Number.isSafeInteger(revision))return;
const sampled=copyReads.get(revision)??new Map();
for(const field of fields)sampled.set(field.layer,field.currentText);
copyReads.delete(revision);
copyReads.set(revision,sampled);
};
const seenLayouts=new Set();
let seenProduct=false;
const jobs=new Map(), generation=new Map(), reviewWork=new Set(), candidates=new Map();
@ -462,9 +452,10 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
const nativeGenerations=slot=>(slot.candidates??[]).filter(row=>
!row.sourceType&&!row.reusedFrom&&row.status!=='prepared').map(row=>row.id);
const drawStatus=generationAttempts=>({
generationAttempts,maxGenerationAttempts,
remainingGenerationAttempts:Math.max(0,maxGenerationAttempts-generationAttempts),
drawLimitReached:generationAttempts>=maxGenerationAttempts,
generationAttempts,...(maxGenerationAttempts===undefined?null:{
maxGenerationAttempts,remainingGenerationAttempts:Math.max(0,maxGenerationAttempts-generationAttempts),
drawLimitReached:generationAttempts>=maxGenerationAttempts,
}),
});
const drawStatuses=selected=>{
const ids=new Map(selected.map(slot=>[slot.id,nativeGenerations(slot)]));
@ -474,7 +465,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
const slotDrawStatus=slot=>drawStatuses([slot]).get(slot.id);
const drawLimit=(slot,status)=>({slotId:slot.id,phase:'draw_limit_reached',limitReached:true,...status,
candidates:slot.candidates??[],
reason:`该图位已达到单张最多 ${maxGenerationAttempts} 次生图上限,请从已有候选中择优采纳(或使用实拍裁切/调整),后续可由人工通过引用精修。`,
reason:`该图位已用完已发布的 ${maxGenerationAttempts} 次生图额度。`,
});
const current=async({refresh=false}={})=>{
const value=await canvas.workflowRead({section:'overview',outputId});
@ -717,7 +708,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
const {claimed,pending,request:record,original,generationAttempts}=await commit(()=>{
signal?.throwIfAborted();
const claim=repository.claimImageRequest(approval,binding,(saved,prior)=>pendingGeneration(slot,saved)??prior,
{maxGenerationAttempts,nativeIds:nativeGenerations(live)});
{maxGenerationAttempts:maxGenerationAttempts??Infinity,nativeIds:nativeGenerations(live)});
if(claim.claimed){
claimedOperationId=claim.original.operationId;
submission=Promise.withResolvers();
@ -930,7 +921,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
},
screenReviewRevisions,
async unfinished(){return unfinished((await outstanding()).originals);},
async plan_production({slotIds}={}){
async plan_production({slotIds,includeKnowledge=false}={}){
await current({refresh:true});
recordProductionInputs(repository,plan,slots);
const {requested,matched,unmatched}=readSelection(slotIds);
@ -944,22 +935,24 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
return {id,fieldId,label,...statuses.get(id),copyReady:!pendingCopy.get(id)?.length,
...(requested.size?{productionRule,requirements,sourcePolicy}:null)};
});
const {production,...template}=plan.template;
const {production,skillSources,resourceSetId,...template}=plan.template;
return {outputId,variantId,template,product:{name,dimensions,note,variant:variant&&{id:variant.id,colorName:variant.colorName}},
pictures,knowledgeFiles:knowledge.files,requestedOutputs:host.productionGoal.requestedOutputs,
pictures,...(includeKnowledge?{knowledgeFiles:productionIndex().files}:null),
pendingOutputs:host.productionGoal.pendingOutputs??[],
progressSummary:await progressSummary(),
...(unmatched.length?{unmatched}:null)};
},
async read_production_knowledge(args,signal){
return knowledge.tools[0]? (await knowledge.tools[0].execute('',args,signal)).details:{files:[]};
const [read]=productionIndex().tools;
return read?(await read.execute('',args,signal)).details:{files:[]};
},
async read_copy_fields({pageId,fieldId}){
pageId=pageId?.trim()||undefined;
fieldId=fieldId?.trim()||undefined;
const snapshot=await canvas.detailCopyFields({includeFilled:true,pageId,fieldId});
rememberCopy(snapshot);
return snapshot;
if(pageId||fieldId)return {...snapshot,outputId,variantId};
const fields=snapshot.fields?.map(({nativeFrame,textSafeFrame,styleRoles,relatedFields,...field})=>field);
return {...snapshot,outputId,variantId,fields};
},
write_copy_fields({revision,recordOnly,items=[]},signal){
return serialize(async()=>{
@ -974,37 +967,9 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
const inputPlan=await current();
let result={appliedLayers:[]};
if(!recordOnly){
let sampled=copyReads.get(revision);
if(!items.every(({layer})=>sampled?.has(layer))){
const history=[...copyReads.values()];
sampled=new Map(sampled);
for(const layer of layers){
if(sampled.has(layer))continue;
const previous=history.findLast(fields=>fields.has(layer));
if(previous)sampled.set(layer,previous.get(layer));
}
const snapshot=await canvas.detailCopyFields({includeFilled:true});
const live=new Map(snapshot.fields.map(field=>[field.layer,field.currentText]));
const rejected=[...layers].flatMap(layer=>{
const reason=!live.has(layer)?'当前画布没有这个文字格':
!sampled.has(layer)?'尚未读取此文字格':live.get(layer)!==sampled.get(layer)?'原文已变化':null;
return reason?[{layer,reason}]:[];
});
if(rejected.length)return {appliedLayers:[],revision:snapshot.revision,copyUpdates:noUpdates,rejected,
reason:`请重读文字格 layer ${rejected.map(row=>row.layer).join('、')},当前修订号 ${snapshot.revision}。`};
revision=snapshot.revision;
}
const edits=items.map(({layer,text})=>({layer,text,expectedText:sampled.get(layer)}));
const deadline=Date.now()+LOCAL_OPERATION_WAIT_MS;
const edits=items.map(({layer,text,expectedText})=>({layer,text,...(expectedText===undefined?null:{expectedText})}));
result=await canvas.commitDetailCopy(edits,revision,signal);
while(result.retryWrite&&Date.now()<deadline){
await delay(150,undefined,{signal});
signal?.throwIfAborted();
if(Date.now()>=deadline)break;
result=await canvas.commitDetailCopy(edits,revision,signal);
}
if(result.retryWrite)return {...result,appliedLayers:[],copyUpdates:noUpdates,
reason:'写入时画布暂不可用。可先处理其他图位,稍后继续写入。'};
if(result.retryWrite || !result.appliedLayers?.length)return {...result,appliedLayers:[],copyUpdates:noUpdates};
}
return await registerCopy(result);
@ -1012,7 +977,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
const snapshot=await canvas.detailCopyFields({includeFilled:true});
const after=new Map(snapshot.fields.map(field=>[field.layer,field]));
const applied=items.filter(row=>(recordOnly||result.appliedLayers?.includes(row.layer))&&after.get(row.layer)?.currentText===row.text);
rememberCopy({revision:snapshot.revision,fields:applied.map(row=>after.get(row.layer))});
await update(journal=>{
syncCopyEvidence(journal,inputPlan);
journal.copyEvidence??={};
@ -1162,7 +1126,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
(rework?'\n先看随消息附上的退回图、验图回执和上次实发提示词。按发布规则处理,用 reworkChange 记录改动。':'')+
(delegateKnowledge.files.length?'\n用 read_production_knowledge 获取 knowledgeFiles 中本任务适用的企业 Skill 和制作规则。':'');
const screenCopy=await liveSlotCopy(slot);
const taskGuidance=await delegateKnowledge.guidance();
const taskGuidance=undefined;
delegateSignal.throwIfAborted();
await host.runDetailAgent(slot.id,instructions,
JSON.stringify({rework,goal,screenCopy,...status,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements,
@ -1350,7 +1314,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
return {...field,visible:context?.layers?.[0]?.effectiveVisible};
}));
const screenCopy=extractPageLiveCopy({pageIndex:page,pages:copyPages,fields:visibleCopy});
rememberCopy({revision:snapshot.revision,fields:visibleCopy.filter(field=>field.visible!==false)});
const previews=await Promise.all(images.map(async image=>{
if(image.type!=='image')return {image};
const resized=await resizeImage(Buffer.from(image.data,'base64'),image.mimeType,host.info?.model?.inputLimits?.images?.resize);
@ -1473,15 +1436,11 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
});
},
async defer_production_output({blocker}){
const active=running().map(job=>job.row.slotId);
const screens=runningScreens().map(job=>job.receipt.page);
if(active.length||screens.length)return {submitted:false,reason:'work_in_progress',slotIds:[...new Set(active)],
...(screens.length?{pages:screens}:null),nextTool:'await_image_slots'};
const {requests,originals}=await outstanding();
if(requests.length)return {submitted:false,reason:'originals_pending',requests,originals,
nextTool:'reconcile_image_slots'};
if(!blocker?.reason?.trim()||!blocker.requiredAction?.trim()){
return {submitted:false,reason:'work_can_continue',nextTool:'plan_production'};
const slotIds=[...new Set(running().map(job=>job.row.slotId))];
const pages=runningScreens().map(job=>job.receipt.page);
const {requests,originals}=await outstanding();
return {submitted:false,slotIds,pages,requests,originals};
}
await journalWrite;
const {reason}=blocker;

View File

@ -64,7 +64,7 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl
'有问题时填写 needs_fix 和至少一项问题。通过时三组问题均为空。',
].join('\n');
const prompt = JSON.stringify({page,revision,product,slots,screenCopy,overlayLayers,productReferenceCount:photos.length,
taskGuidance:await reviewKnowledge.guidance(),knowledgeFiles:reviewKnowledge.files});
knowledgeFiles:reviewKnowledge.files});
const captions = ['当前整屏成片', ...photos.map((_,index) => `本款实拍 ${index + 1}`)];
await runAgent(`screen-${page}`, instructions, prompt, [tool,...reviewKnowledge.tools], [...images,...photos], scope, captions,signal);
signal?.throwIfAborted();

View File

@ -197,12 +197,10 @@ test('switching outputs discards the prior canvas copy reads and uses the new li
await action('open_production_output',{outputId:'main_images',variantId});
const write={revision:detail.revision,items:[{layer:1,text:'确认圆角桌面'}]};
const blocked=await action('write_copy_fields',write);
assert.deepEqual(blocked.rejected,[{layer:1,reason:'尚未读取此文字格'}]);
assert.equal(edits,undefined);
const {details}=await action('read_output_screen',{page:1});
assert.deepEqual(details.screenCopy.map(row=>row.text),['圆角桌面']);
await action('write_copy_fields',{...write,revision:details.copyRevision??details.revision});
await action('write_copy_fields',{...write,revision:details.copyRevision??details.revision,
items:[{...write.items[0],expectedText:details.screenCopy[0].text}]});
assert.equal(edits[0].expectedText,'圆角桌面');
await action('check_image_slots',{wait:true,candidates:[{slotId:slot.id,candidateId:'candidate'}]});

View File

@ -4,6 +4,8 @@ import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import {EnterpriseContext} from '../src/enterprise-context.mjs';
import {openEnterpriseSkills} from '../src/enterprise-skill-resources.mjs';
import {productionKnowledge} from '../src/production-knowledge.mjs';
import {EnterpriseKnowledge} from '../src/enterprise-knowledge.mjs';
test('selected resource guides are read completely with their own versions',async t=>{
@ -35,10 +37,12 @@ test('selected resource guides are read completely with their own versions',asyn
assert.equal(result.rules[0].pages,2);
const production=await ctx.load({task:'production',brandName:'顾家',categoryName:'电脑桌',resourceSetId:'selected',outputId:'detail'});
assert.deepEqual(production.skills,result.skills);
assert.equal(production.rules[0].text,undefined);
assert.equal(documents.length,5);
assert.deepEqual(calls.slice(2).map(([name])=>name),['list_libraries','get_resource_set']);
});
test('explicit template skill sources are read by their published file identity and version', async t => {
test('published rule bodies load only when read and keep the locked version', async t => {
const root=await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-template-guides-'));
t.after(()=>fs.rm(root,{recursive:true}));
const calls=[];
@ -54,17 +58,33 @@ test('explicit template skill sources are read by their published file identity
},
async readDocument(id,revision) {
docs.push([id,revision]);
return {result:{text:id+' rules',revision}};
return {result:{text:id==='workflow'
? '---\nname: lighting\ndescription: Lighting instructions.\nmaxGenerationAttempts: 3\n---\n[Review](review.md)'
: 'rules body',revision}};
},
};
const ctx=new EnterpriseContext({root,appendEvent:async()=>{}},client);
const store={root,dir:root,appendEvent:async()=>{}};
const ctx=new EnterpriseContext(store,client);
const input={task:'production',brandName:'Lighting Lab',categoryName:'灯具',releaseId:'release-3'};
const result=await ctx.load({...input,skillSources});
const binding=await openEnterpriseSkills(store,input,pins=>ctx.load({...input,skillSources},{pins}),
(relative,lock)=>ctx.loadReference(relative,{...lock,read:execute=>execute()}));
assert.deepEqual(calls,['list_libraries']);
assert.deepEqual(docs,[['workflow','7']]);
assert.equal(binding.knowledge.resourceRevision,'release-3');
assert.equal(binding.maxGenerationAttempts,3);
assert.equal(binding.resource.skills[0].name,'lighting');
const {files,tools}=productionKnowledge(binding.knowledge);
assert.deepEqual(files.map(({fileId,revision})=>[fileId,revision]),[['workflow','7'],['rules','11']]);
const reviewPath=path.join(path.dirname(binding.resource.skills[0].filePath),'review.md');
const [{details}]=await Promise.all([
tools[0].execute('',{fileId:'rules'}),
binding.resolveFile(reviewPath),
]);
assert.equal(details.text,'rules body');
assert.equal(await fs.readFile(reviewPath,'utf8'),details.text);
assert.deepEqual(docs,[['workflow','7'],['rules','11']]);
assert.equal(result.resourceRevision,'release-3');
assert.equal(result.rules[0].text,'rules rules');
assert.equal(result.skills[0].path,'Skills/Lighting/SKILL.md');
const reopened=await openEnterpriseSkills(store,input,()=>assert.fail('use the existing release'));
assert.equal(reopened.knowledge.rules[0].text,'rules body');
await assert.rejects(ctx.load(input),/尚未发布制作 Skill/u);
});

View File

@ -479,16 +479,20 @@ test('the one-click goal resumes on changed fields at the same count without nam
if(n===5)return sse({tool_calls:[{index:0,id:'finish',type:'function',function:{name:'finish_production',arguments:'{"revision":1}'}}]},'tool_calls');
return sse({content:'本次复核有进展。'},'stop');
},undefined,{
callBudget:6,plan:()=>({pendingText:1,field:++plans===1?'标题':'规格'}),
callBudget:6,plan:()=>({outputId:'detail',variantId:'oak',pendingText:1,field:++plans===1?'标题':'规格'}),
progress:()=>({state:{fields:[plans===1?'标题':'规格']}}),
});
try {
const result=await x.host.prompt('完成整套制作');
assert.equal(result.production.complete,true);
assert.equal(plans,2);
assert.match(JSON.stringify(x.requests[4].messages),/同范围已有更新回执/);
const oldPlan=x.host.manager.getBranch().find(({message})=>message?.role==='toolResult'&&message?.toolCallId==='plan-1')?.message;
assert.equal(JSON.parse(oldPlan.content[0].text).field,'标题');
for(const request of [x.requests[2],x.requests[4]]){
const continuation=request.messages.findLast(message=>JSON.stringify(message).includes('继续当前制作目标'));
assert.ok(continuation);
const reminders=request.messages.filter(message=>JSON.stringify(message).includes('继续当前制作目标'));
assert.equal(reminders.length,1);
const [continuation]=reminders;
assert.doesNotMatch(JSON.stringify(request.messages), /prompt-to-artifact checklist|PR state/u);
assert.doesNotMatch(JSON.stringify(continuation),/调用 (?:plan_production|write_copy_fields)/);
}
@ -937,12 +941,13 @@ test('the Pi canvas contract forwards a deeper group summary with the requested
assert.deepEqual(canvasReadQuery(query),{mode:'summary',screenId:90,maxDepth:6,offset:0});
});
test('production exposes direct native tools and Pi file tools',async()=>{
test('production exposes native controls and reads with other file tools deferred',async()=>{
const x=await setup(payload=>{
const names=payload.tools.map(row=>row.function.name);
for(const name of ['native_catalog','native_call','native_reconcile','codemode','tool_search','read','write','edit','ls','find','grep','bash']){
for(const name of ['native_catalog','native_call','native_reconcile','codemode','tool_search','read']){
assert.ok(names.includes(name),name);
}
for(const name of ['write','edit','ls','find','grep','bash']) assert.ok(!names.includes(name),name);
return sse({tool_calls:[{index:0,id:'finish',type:'function',function:{name:'finish_production',arguments:'{"revision":1}'}}]},'tool_calls');
},undefined,{progress:()=>({state:{waitingOnOriginals:true}}),
canvas:{nativeCatalog(){},nativeCall(){},nativeReconcile(){}}});
@ -951,7 +956,8 @@ test('production exposes direct native tools and Pi file tools',async()=>{
const names=x.host.session.getActiveToolNames();
assert.ok(names.includes('codemode'));
assert.ok(names.includes('tool_search'));
assert.ok(names.includes('read')&&names.includes('write'));
assert.ok(names.includes('read'));
assert.ok(x.host.session.getToolDefinition('write'));
assert.equal((await x.host.prompt('核对制作工具')).production.complete,true);
assert.equal(x.requests.length,1);
} finally {await x.close();}
@ -991,8 +997,9 @@ test('Pi runs independent production reads from the same model turn concurrently
test('production publishes direct native commands and no duplicate conversation tools',async()=>{
const executed=[];
const x=await setup((_,request)=>{
const name=request===1?'native_call':'finish_production';
const args=request===1?{revision:1,method:'engine.execute',params:{command:'type.edit',params:{layer:2,text:'New'}}}:{revision:1};
const name=request===1?'native_call':request===2?'tool_search':'finish_production';
const args=request===1?{revision:1,method:'engine.execute',params:{command:'type.edit',params:{layer:2,text:'New'}}}:
request===2?{query:'bash',limit:1}:{revision:1};
return sse({tool_calls:[{index:0,id:'edit-'+request,type:'function',function:{name,arguments:JSON.stringify(args)}}]},'tool_calls');
},undefined,{
progress:()=>({state:{waitingOnOriginals:true}}),
@ -1023,6 +1030,12 @@ test('production publishes direct native commands and no duplicate conversation
assert.equal(x.host.session.getToolDefinition(name).executionMode,'sequential',name);
}
assert.equal((await x.host.prompt('完成制作')).production.complete,true);
const initialNames=x.requests[0].tools.map(tool=>tool.function.name);
assert.ok(initialNames.includes('read'));
assert.ok(x.requests[2].tools.some(tool=>tool.function.name==='bash'));
for (const name of ['bash','edit','write','find','grep','ls','memory_set','memory_search','context_read']) {
assert.ok(!initialNames.includes(name),name);
}
assert.deepEqual(executed,[{revision:1,method:'engine.execute',params:{command:'type.edit',params:{layer:2,text:'New'}}}]);
const row=x.host.manager.getBranch().find(({message})=>message?.toolCallId==='edit-1')?.message;
assert.equal(JSON.parse(row.content[0].text).executed,true);

View File

@ -307,7 +307,7 @@ test('explicit tools share one Pi transcript and submit each real canvas revisio
detailCopyFields:async()=>({fields:structuredClone(fields),revision}),
commitDetailCopy:async(items,expected)=>{
assert.equal(expected,revision);
assert.equal(items[0].expectedText,fields[0].currentText);
assert.equal(items[0].expectedText,undefined);
copyWrites++;
revision++;
fields[0].currentText=items[0].text;
@ -316,8 +316,8 @@ test('explicit tools share one Pi transcript and submit each real canvas revisio
};
const transport={info:info(id.scope),stream(_model,context){
const instructions=getCurrentSystemPrompt(context.messages);
assert.match(instructions,/由你决定要做什么、顺序、并行和返工/);
assert.match(instructions,/企业制作指引中的命令行编修可用等价的画布命令完成/);
assert.match(instructions,/由你决定[^。]*顺序、并行和返工/);
assert.match(instructions,/命令行编修可用等价的画布命令完成/);
const write=context.messages.find(message=>message.role==='toolResult'&&message.toolName==='write_copy_fields');
if(write)assert.deepEqual(JSON.parse(write.content[0].text),{appliedLayers:[1],revision:8});
const call=steps.shift();

View File

@ -297,8 +297,9 @@ for(const stop of ['abort','close','switch'])test(`${stop} stops queued lookups
assert.equal(ledger.read().items.active.state,'unknown');
});
const drawStatus=(attempts,max=4)=>({generationAttempts:attempts,maxGenerationAttempts:max,
remainingGenerationAttempts:Math.max(0,max-attempts),drawLimitReached:attempts>=max});
const drawStatus=(attempts,max)=>({generationAttempts:attempts,...(max===undefined?null:{
maxGenerationAttempts:max,remainingGenerationAttempts:Math.max(0,max-attempts),drawLimitReached:attempts>=max,
})});
test('canvas advice leaves review, transformation and generation under agent control',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-canvas-adjust-'));
@ -527,7 +528,7 @@ test('switch hands off original requests and cancels queued work without waiting
await closeProductionTurn(host);
});
test('deferral keeps active workers, unknown originals and ordinary rework in production',async t=>{
test('deferral reports ongoing work and records a supplied blocker without choosing the next action',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-defer-output-'));
t.after(()=>cleanup(dir));
const outputId='main_images', variantId='oak', slotId='main-photo';
@ -548,8 +549,11 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr
const call=(name,args)=>callProductionTool(host,name,args);
const blocker={kind:'missing_required_input',reason:'缺少官方承重参数',requiredAction:'请产品负责人提供承重规格'};
await call('delegate_image_slots',{jobs:[{slotId,goal:'补齐 M01'}]});
assert.deepEqual(await call('defer_production_output',{blocker}),
{submitted:false,reason:'work_in_progress',slotIds:[slotId],nextTool:'await_image_slots'});
const active=await call('defer_production_output',{});
assert.deepEqual(active.slotIds,[slotId]);
assert.equal(active.submitted,false);
assert.equal(active.nextTool,undefined);
assert.equal((await call('defer_production_output',{blocker})).stageStatus,'hard-blocked');
assert.equal(host.productionCompletion,undefined);
worker.resolve();
await call('await_image_slots',{});
@ -559,9 +563,9 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr
ledger.repository.replaceLedger({binding,items:{[slotId]:{state:'unknown',
pendingGenerations:{[original.candidateId]:original}}}});
host.productionOperations=null;
const deferred=await call('defer_production_output',{blocker});
assert.equal(deferred.reason,'originals_pending');
assert.equal(deferred.nextTool,'reconcile_image_slots');
const deferred=await call('defer_production_output',{});
assert.equal(deferred.submitted,false);
assert.equal(deferred.nextTool,undefined);
assert.deepEqual(deferred.originals,{models:[],images:[original.candidateId]});
assert.equal(host.productionCompletion,undefined);
const receipt=await call('finish_production',{revision:1});
@ -574,8 +578,7 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr
review:{candidateId:'rejected-image',decision:'revise',reason:'主体构图需要调整'}}}});
host.productionOperations=null;
host.productionCompletion=null;
assert.deepEqual(await call('defer_production_output',{reason:'M01 退回,需要返工'}),
{submitted:false,reason:'work_can_continue',nextTool:'plan_production'});
assert.equal((await call('defer_production_output',{reason:'M01 退回,需要返工'})).submitted,false);
assert.equal(host.productionCompletion,null);
});
@ -663,7 +666,8 @@ test('the unbound production plan lists the same readable knowledge files as the
host.productionGoal=boundGoal;
const actions=await openProductionOperations(host);
t.after(()=>actions.close());
assert.deepEqual((await actions.plan_production()).knowledgeFiles,plan.knowledgeFiles);
assert.equal((await actions.plan_production()).knowledgeFiles,undefined);
assert.deepEqual((await actions.plan_production({includeKnowledge:true})).knowledgeFiles,plan.knowledgeFiles);
});
test('candidate review leaves placement to the main agent, even with an old template policy',async t=>{
@ -1107,7 +1111,6 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca
await prepared.promise;
const blocked=await actions.defer_production_output({reason:'等待候选回执',nextOutput});
assert.equal(blocked.submitted,false);
assert.equal(blocked.reason,'work_in_progress');
assert.deepEqual(blocked.slotIds,[slotId]);
assert.equal((await actions.dispatch_image_request(approved)).phase,'already_running');
assert.equal((await actions.review_image_slots({slotIds:[slotId]})).pictures[0].generation.phase,'accepted');
@ -1330,7 +1333,7 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
copyAttempts.push({items,expected});
if(copyWaiting){copyWaiting=false;return {retryWrite:true,revision};}
assert.ok(expected<=revision);
if(items[0].expectedText!==fields[0].currentText)return {revision,appliedLayers:[],rejected:[{layer:7,reason:'原文已变化'}]};
if((expected!==revision||items[0].expectedText!==undefined)&&items[0].expectedText!==fields[0].currentText)return {revision,appliedLayers:[],rejected:[{layer:7,reason:'原文已变化'}]};
fields[0].currentText=items[0].text;
revision++;
return {appliedLayers:[7]};
@ -1416,19 +1419,18 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
const proposal={revision,items:[{layer:7,text:'光线落在桌面',sources:['P01'],pictures:['lamp']}]};
copyWaiting=true;
const waiting=await actions.write_copy_fields(proposal);
assert.equal(waiting.retryWrite,true);
assert.deepEqual(copyAttempts,[{items:[{layer:7,text:'光线落在桌面'}],expected:proposal.revision}]);
assert.deepEqual((await actions.write_copy_fields(proposal)).appliedLayers,[7]);
assert.deepEqual(copyAttempts,[
{items:[{layer:7,text:'光线落在桌面',expectedText:''}],expected:proposal.revision},
{items:[{layer:7,text:'光线落在桌面',expectedText:''}],expected:proposal.revision},
]);
assert.equal(fields[0].currentText,'光线落在桌面');
const beforeIndependentEdit=await actions.read_copy_fields({});
const checkedCopy={...proposal,revision,items:[{...proposal.items[0],expectedText:'光线落在桌面'}]};
revision++;
assert.deepEqual((await actions.write_copy_fields({...proposal,revision:beforeIndependentEdit.revision})).appliedLayers,[7]);
assert.deepEqual((await actions.write_copy_fields(checkedCopy)).appliedLayers,[7]);
const beforeUserEdit=await actions.read_copy_fields({});
fields[0].currentText='用户手改';
revision++;
const rejected=await actions.write_copy_fields({...proposal,revision:beforeUserEdit.revision});
const rejected=await actions.write_copy_fields({...checkedCopy,revision:beforeUserEdit.revision});
assert.deepEqual(rejected.appliedLayers,[]);
assert.deepEqual(rejected.rejected,[{layer:7,reason:'原文已变化'}]);
assert.equal(fields[0].currentText,'用户手改');
@ -1756,7 +1758,7 @@ test('copy update details contain only applied canvas text with a bounded previe
await actions.close();
});
test('copy writes reuse confirmed revisions and rebase only unchanged, previously read layers',async t=>{
test('copy writes forward revisions and optional expected text for the canvas to check',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-copy-revision-'));
t.after(()=>cleanup(dir));
let revision=1;
@ -1774,21 +1776,24 @@ test('copy writes reuse confirmed revisions and rebase only unchanged, previousl
detailRender:async()=>({revision}),
async commitDetailCopy(items,expected){
commits.push(expected);
assert.equal(expected,revision);
const appliedLayers=[],rejected=[];
for(const edit of items){
const field=fields.find(row=>row.layer===edit.layer);
assert.equal(edit.expectedText,field.currentText);
if(!field||(expected!==revision||edit.expectedText!==undefined)&&edit.expectedText!==field.currentText){
rejected.push({layer:edit.layer,reason:field?'原文已变化':'当前画布没有这个文字格'});
continue;
}
field.currentText=edit.text;
appliedLayers.push(edit.layer);
}
revision++;
return {appliedLayers:items.map(row=>row.layer)};
if(appliedLayers.length)revision++;
return {appliedLayers,rejected,revision};
},
};
const ops=await openProductionOperations({store:productionStore(dir),canvas,productionGoal:{outputId:'detail',variantId:'oak'}});
const item=(layer,text)=>({layer,text,sources:[],pictures:[]});
const write=(revision,items)=>ops.write_copy_fields({revision,items});
const start=await ops.read_copy_fields({fieldId:'title'});
const first=await write(start.revision,[item(7,'标题一')]);
const first=await write(revision,[item(7,'标题一')]);
await write(first.revision,[item(7,'标题二')]);
revision++;
@ -1800,14 +1805,13 @@ test('copy writes reuse confirmed revisions and rebase only unchanged, previousl
fields[0].currentText='用户手改';
revision++;
const stale=await write(revision,[item(7,'禁止覆盖'),item(9,'未读'),item(99,'不存在')]);
assert.deepEqual(stale.rejected,[{layer:7,reason:'原文已变化'},{layer:9,reason:'尚未读取此文字格'},
const stale=await write(revision-1,[{...item(7,'禁止覆盖'),expectedText:'图片采纳后的标题'},item(99,'不存在')]);
assert.deepEqual(stale.rejected,[{layer:7,reason:'原文已变化'},
{layer:99,reason:'当前画布没有这个文字格'}]);
assert.equal(stale.revision,revision);
assert.match(stale.reason,/layer 7、9、99.*修订号 8/u);
await assert.rejects(write(revision,[item(8,'一'),item(8,'二')]),/layer 8 重复/u);
await assert.rejects(write(revision,[item(-1,'无效')]),/无效的文字格 layer -1/u);
assert.equal(commits.length,4);
assert.deepEqual(commits,[1,2,4,6,7]);
assert.equal(fields[0].currentText,'用户手改');
await ops.close();
});
@ -1849,7 +1853,7 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand
},
};
let spare;
const host={canvas,store,productionGoal:{outputId:'detail',variantId:'oak'},
const host={canvas,store,productionGoal:{outputId:'detail',variantId:'oak'},productionSkills:{maxGenerationAttempts:4},
async runDetailAgent(_slot,_system,prompt,tools){
const {candidateId}=JSON.parse(prompt);
if(candidateId){
@ -1873,9 +1877,9 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand
for(const [key,value] of Object.entries(expected))assert.equal(row[key],value,key);
};
const plan=()=>ops.plan_production({slotIds:['hero']});
assertStatus((await plan()).pictures[0],drawStatus(1));
assertStatus((await plan()).pictures[0],drawStatus(1,4));
await ops.retire_production_image({slotId:'hero',candidateId:'existing',reason:'构图不合适'});
assertStatus((await plan()).pictures[0],drawStatus(1));
assertStatus((await plan()).pictures[0],drawStatus(1,4));
const input={slotId:'hero',prompt:'同款正面'};
const a=await ops.prepare_image_request(input);
const b=await ops.prepare_image_request({...input,prompt:'同款侧面'});
@ -1883,7 +1887,7 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand
while(ops.active)await ops.await_image_slots({slotIds:['hero']});
await ops.dispatch_image_request(approve(b));
while(ops.active)await ops.await_image_slots({slotIds:['hero']});
assertStatus((await plan()).pictures[0],drawStatus(3));
assertStatus((await plan()).pictures[0],drawStatus(3,4));
const fourth=await ops.prepare_image_request({...input,prompt:'同款俯拍'});
spare=await ops.prepare_image_request({...input,prompt:'同款低机位'});
@ -1892,21 +1896,21 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand
await fourthStarted.promise;
const stopped=await ops.dispatch_image_request(approve(spare));
fourthDone.resolve();
assertStatus(stopped,{limitReached:true,...drawStatus(4)});
assertStatus(stopped,{limitReached:true,...drawStatus(4,4)});
assert.ok(stopped.candidates.some(row=>row.id===a.requestId));
assert.match(stopped.reason,/最多 4 次.*择优采纳.*引用精修/u);
assert.match(stopped.reason,/已发布的 4 次生图额度/u);
await ops.await_image_slots({slotIds:['hero']});
assert.equal(dispatches.length,3);
assertStatus(await ops.prepare_image_request(input),{limitReached:true,...drawStatus(4)});
assertStatus((await ops.review_image_slots({slotIds:['hero']})).pictures[0],drawStatus(4));
assertStatus(await ops.prepare_image_request(input),{limitReached:true,...drawStatus(4,4)});
assertStatus((await ops.review_image_slots({slotIds:['hero']})).pictures[0],drawStatus(4,4));
const [review]=await ops.check_image_slots({wait:true,candidates:[{slotId:'hero',candidateId:a.requestId}]});
assert.equal(review.verdict,'revise');
assertStatus(review,drawStatus(4));
assertStatus(review,drawStatus(4,4));
const delegated=await ops.delegate_image_slots({jobs:[{slotId:'hero',goal:'比较候选'}]});
assertStatus(delegated.assigned[0],drawStatus(4));
assertStatus(delegated.assigned[0],drawStatus(4,4));
await ops.await_image_slots({slotIds:['hero']});
assert.equal(workerResults.length,2);
for(const result of workerResults)assertStatus(result,{limitReached:true,...drawStatus(4)});
for(const result of workerResults)assertStatus(result,{limitReached:true,...drawStatus(4,4)});
assert.equal((await ops.adopt_production_image({slotId:'hero',candidateId:a.requestId})).phase,'complete');
assert.equal(slot.selectedCandidateId,a.requestId);
host.productionOperations=Promise.resolve(ops);

View File

@ -237,11 +237,16 @@ test('真实会话按视频输出或显式运行时注册,平面工具清单
const goal = outputIds => ({ variantId, workspaceId: 'qa', requestedOutputs: outputIds.map(outputId => ({ outputId, variantId })) });
async function active(options) {
const host = await DetailPiAgent.open({ store, transport, canvas, ...options });
try { return host.session.getActiveToolNames(); }
try {
if (options.productionGoal) {
for (const [name] of productionOperationTools) assert.ok(host.session.getToolDefinition(name),name);
}
return host.session.getActiveToolNames();
}
finally { await host.dispose(); }
}
const plane = await active({ productionGoal: goal(['detail', 'main_images', 'sku_images']) });
assert.ok(productionOperationTools.every(([name]) => plane.includes(name)));
assert.ok(plane.includes('plan_production'));
assert.deepEqual(plane.filter(name => names.includes(name)), []);
assert.deepEqual(productionVideoTools({ productionGoal: goal(['seeding_images']) }, name => name), []);
for (const outputId of ['main_video', 'seeding_video']) {

View File

@ -3,7 +3,6 @@ import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { stripTypeScriptTypes } from 'node:module';
import { productionObjective, productionTools } from '../src/production-goal.mjs';
import { COPY_IMAGE_SCREEN_CRITERIA } from '../src/copy-image-alignment.mjs';
import { NATIVE_CANVAS_QUICK_REFERENCE, nativeTools } from '../src/native-tools.mjs';
const source = file => readFileSync(new URL(`../src/${file}`, import.meta.url), 'utf8');
@ -26,13 +25,11 @@ test('conversation status, errors and tool guidance use product terminology', ()
test('production guidance batches determined operations and scopes screenshot review', () => {
const prompt = source('agent.mjs').match(/const PRODUCTION_SYSTEM = `([\s\S]+?)`;/)?.[1];
assert.match(prompt, /open_production_output、read_output_screen、await_image_slots、finish_production)单独调用/);
assert.match(prompt, /批量采纳、批量回填文案[^。]*一次 codemode 脚本中依次 await/);
assert.match(prompt, /native_catalog\(\{ ids: \[\.\.\.\] \}\)[^。]*后续回合复用/);
assert.ok(prompt.includes('${NATIVE_CANVAS_QUICK_REFERENCE}'));
assert.match(prompt, /可用 check_output_screens 并行复核实际成片,pages 从 1 编号,通过时自动登记/);
assert.match(prompt, /codemode 依次 await[^。]*真实回执/);
assert.match(prompt, /native_catalog[^。]*复用[^。]*parameterDocs/);
assert.doesNotMatch(prompt, /NATIVE_CANVAS_QUICK_REFERENCE|2–4 屏/);
const description = productionTools.find(([name]) => name === 'read_output_screen')?.[1];
for (const copy of [prompt, description]) assert.match(copy, /2–4 屏[^]*释放[^。]*保留文字元数据/);
assert.match(description, /2–4 屏[^]*只保留最新一次查看图片/);
});
test('both conversation prompts and delegated production share the product voice rule', () => {
@ -46,39 +43,24 @@ test('both conversation prompts and delegated production share the product voice
assert.match(agent, /不得向用户暴露底层技术或开源底座名称/);
});
test('production review guidance covers copy, images and overlays followed by visual recheck', () => {
test('production prompts refer to the published skill and keep screen semantics with the tool', () => {
const prompt = source('agent.mjs').match(/const PRODUCTION_SYSTEM = `([\s\S]+?)`;/)?.[1];
const guidance = [
['PRODUCTION_SYSTEM', prompt?.replace('${COPY_IMAGE_SCREEN_CRITERIA}',COPY_IMAGE_SCREEN_CRITERIA)],
['read_output_screen', productionTools.find(([tool]) => tool === 'read_output_screen')?.[1]],
];
for (const [name, copy] of guidance) {
assert.ok(copy, name);
assert.match(copy, /图文一致性[^。]*材质、颜色、款式和结构[^。]*场景或功能卖点[^。]*SKU 花色[^。]*尺寸、规格、数量/, name);
assert.match(copy, /尺寸线、虚线轮廓、引线、标注文字和装饰角标/, name);
assert.match(copy, /整屏合成切片与 overlayLayers[^。]*错位、压字或数值不符/, name);
assert.match(copy, /overlapsSlots[^。]*fieldId[^。]*bounds[^。]*text[^。]*mapped/, name);
assert.match(copy, /native_call[^。]*移动、缩放、隐藏或改写叠层/, name);
assert.match(copy, /write_copy_fields[^。]*transform_slot_image[^。]*重新生图/, name);
assert.doesNotMatch(copy, technicalBrand, name);
}
const adopt = productionTools.find(([tool]) => tool === 'adopt_production_image')?.[1];
assert.match(adopt, /放置回执|返回画布修订和覆盖该图位的模板叠层/);
assert.match(adopt, /read_output_screen 查看整屏合成画面/);
const review = productionTools.find(([tool]) => tool === 'check_output_screens')?.[1];
assert.match(review, /按企业 Skill[^]*以当前画布实际屏数为准/);
assert.match(prompt, /read_copy_fields 省略 pageId 和 fieldId 即可一次读取全页文案字段/);
assert.match(prompt, /子代理生图和验图读取本屏实时文案[^。]*回执绑定当时的文案签名/);
assert.match(prompt, /建议每批选 1–3 屏[^。]*write_copy_fields[^。]*delegate_image_slots[^。]*生图期间写下一批/);
assert.match(prompt, /分派 goal[^。]*避免引用画布上尚未更新的模板原文/);
const knowledge = productionTools.find(([name]) => name === 'read_production_knowledge')?.[1];
assert.match(knowledge, /fileId 必须取自 knowledgeFiles/);
assert.match(prompt, /模板对应图位的原图[^。]*本款实拍/);
assert.match(prompt, /finish_production 提交当前画布修订[^]*scope=all 核验本轮交付/);
assert.match(productionTools.find(([name]) => name === 'open_production_output')?.[1], /切换前保存原工程/);
assert.match(prompt, /native_catalog[^。]*native_call/);
assert.match(productionTools.find(([name]) => name === 'check_image_slots')?.[1], /对照当前图位关联文案核对图文一致性/);
assert.match(source('candidate-review.mjs'), /read_production_knowledge[^。]*企业 Skill 和审稿规则/);
const tool = name => productionTools.find(([tool]) => tool === name)?.[1];
assert.match(prompt, /按需读取适用 Skill 和引用/);
assert.match(prompt, /验图回执绑定当时的文案签名/);
assert.match(prompt, /避免把模板原文当成当前卖点/);
assert.doesNotMatch(prompt, /overlayLayers|NATIVE_CANVAS_QUICK_REFERENCE|每批/);
assert.match(tool('read_output_screen'), /整屏合成画面[^]*叠层错位、压字或数值不符/);
assert.match(tool('read_output_screen'), /overlapsSlots.*fieldId.*bounds.*text.*mapped/);
assert.match(tool('read_output_screen'), /native_call.*write_copy_fields.*transform_slot_image/);
assert.match(tool('adopt_production_image'), /read_output_screen 查看整屏合成画面/);
assert.match(tool('check_output_screens'), /整屏合成画面[^]*叠层错位、压字或数值不符/);
assert.match(tool('read_copy_fields'), /全页字段[^。]*指定页面或字段/);
assert.match(tool('read_production_knowledge'), /fileId 必须取自[^。]*knowledgeFiles/);
assert.match(tool('open_production_output'), /切换前保存原工程/);
assert.match(tool('finish_production'), /scope=all.*核验本轮交付/);
assert.match(tool('check_image_slots'), /对照当前图位关联文案核对图文一致性/);
assert.doesNotMatch([prompt,tool('read_output_screen'),source('copy-image-alignment.mjs')].join('\n'), /桌腿|木种|SFY-CHAIR-001/);
});
test('native tooling and production share the documented canvas commands', () => {
@ -121,14 +103,10 @@ test('native tooling and production share the documented canvas commands', () =>
assert.doesNotMatch(call.description,technicalBrand);
});
test('the unattended objective uses the native canvas and frames the selling point', () => {
test('the unattended objective records the intended delivery', () => {
const objective = productionObjective([{ outputId: 'detail', label: '详情图' }]);
assert.match(objective, /详情图/);
assert.match(objective, /小壹原生画布自动合成并导出,无需询问制作软件或合成方式/);
assert.match(objective, /先看本款实拍和商品资料[^。]*策划卖点和文案,再以文案确定画面/);
assert.match(objective, /模板原图与本屏卖点部位和景别一致时可参考构图/);
assert.match(objective, /useTemplateReference: false[^。]*从本款实拍裁切对应部件/);
assert.match(objective, /验图和整屏复核时自主核对图文一致性[^]*用原生工具修图或改字,再看屏确认/);
assert.match(objective, /按适用制作指引和模板制作并交付[^。]*详情图/);
assert.doesNotMatch(objective, /useTemplateReference|read_output_screen/);
assert.doesNotMatch(objective, technicalBrand);
});

View File

@ -409,12 +409,14 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
return Err("文案未取得当前画布写入许可,原内容保留".into());
}
let active = app.session.active().ok_or("原项目未打开")?;
let requested_revision = input["revision"].as_u64();
if match_fields {
let live = super::agent_native::guard_production_field_write(w, app, input)?;
input["revision"].as_u64().filter(|revision| *revision <= live).ok_or("请先读取本轮文字格及其修订号")?;
super::agent_native::guard_production_field_write(w, app, input)?;
requested_revision.ok_or("缺少文案修订号")?;
}
let same_revision = requested_revision == Some(active.revision);
if super::canvas_workspace::detail_write_waiting(w, app)
|| !match_fields && (active.revision != w.expected_revision || input["revision"].as_u64() != Some(active.revision))
|| !match_fields && (active.revision != w.expected_revision || !same_revision)
{
if !match_fields { w.allow_apply = false; }
return Ok(json!({"retryWrite":true,"revision":active.revision}));
@ -434,11 +436,24 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
};
let current = field["currentText"].as_str().unwrap_or_default();
if let Some(reason) = w.production_layer_rejection(&active.doc, id) {
rejected.push(json!({"layer":layer,"code":reason.code(),"reason":reason.message()}));
rejected.push(json!({"layer":layer,"code":reason.code(),"reason":reason.message(),
"currentText":current,"revision":active.revision}));
continue;
}
if (match_fields || !current.trim().is_empty()) && item["expectedText"].as_str() != Some(current) {
rejected.push(json!({"layer":layer,"code":"layer_precondition_failed","reason":"文字格原文与读取值不一致,保留当前内容"}));
let expected = item["expectedText"].as_str();
let matches_original = if match_fields {
expected.map_or(same_revision, |text| text == current)
} else {
current.trim().is_empty() || expected == Some(current)
};
if !matches_original {
let reason = if match_fields && expected.is_none() {
"画布修订已变化,缺少用于比对的原文"
} else {
"文字格原文与读取值不一致,保留当前内容"
};
rejected.push(json!({"layer":layer,"code":"layer_precondition_failed","reason":reason,
"currentText":current,"revision":active.revision}));
continue;
}
let text = item["text"].as_str().ok_or("缺少填写文字")?;
@ -1442,7 +1457,7 @@ mod tests {
}
#[test]
fn production_copy_matches_the_sampled_fields_instead_of_the_document_revision() {
fn production_copy_uses_current_revision_or_explicit_original_text() {
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width":200,"height":300})).unwrap();
let [title, subtitle, locked] = ["原始标题", "原始副标题", "原始规格"].map(|text|
@ -1479,6 +1494,14 @@ mod tests {
}).unwrap();
let revision = app.session.active().unwrap().revision;
assert!(snapshot["revision"].as_u64().unwrap() < revision);
let stale = action_impl(&mut w, &mut app, None, "pi-detail-copy-apply", &json!({
"run":run,"documentId":doc,"revision":snapshot["revision"],"matchFields":true,
"items":[{"layer":subtitle,"text":"过时的改动"}]
}), true).unwrap();
assert_eq!(stale["appliedLayers"], json!([]));
assert_eq!(stale["revision"], revision);
assert_eq!(stale["rejected"][0], json!({"layer":subtitle,"code":"layer_precondition_failed",
"reason":"画布修订已变化,缺少用于比对的原文","currentText":"原始副标题","revision":revision}));
let apply = json!({"run":run,"documentId":doc,"revision":snapshot["revision"],"matchFields":true,"items":[
{"layer":title,"text":"小壹标题","expectedText":snapshot["fields"][0]["currentText"]},
{"layer":subtitle,"text":"小壹副标题","expectedText":snapshot["fields"][1]["currentText"]},
@ -1492,10 +1515,21 @@ mod tests {
.collect::<Vec<_>>(), vec![title, locked]);
assert_eq!(receipt["rejected"][0]["code"], "layer_manually_edited");
assert_eq!(receipt["rejected"][1]["code"], "layer_newly_locked");
let fresh = action_impl(&mut w, &mut app, None, "pi-detail-copy-apply", &json!({
"run":run,"documentId":doc,"revision":receipt["revision"],"matchFields":true,
"items":[{"layer":subtitle,"text":"小壹副标题二"},{"layer":title,"text":"覆盖用户标题"},
{"layer":locked,"text":"覆盖锁定规格"}]
}), true).unwrap();
assert_eq!(fresh["appliedLayers"], json!([subtitle]));
assert_eq!(fresh["revision"], revision + 2);
assert_eq!(fresh["rejected"][0]["code"], "layer_manually_edited");
assert_eq!(fresh["rejected"][0]["currentText"], "用户标题");
assert_eq!(fresh["rejected"][1]["code"], "layer_newly_locked");
assert_eq!(fresh["rejected"][1]["currentText"], "原始规格");
let read = action_impl(&mut w, &mut app, None, "pi-detail-copy-fields",
&json!({"run":run,"documentId":doc,"includeFilled":true}), true).unwrap();
assert_eq!(read["fields"][0]["currentText"], "用户标题");
assert_eq!(read["fields"][1]["currentText"], "小壹副标题");
assert_eq!(read["fields"][1]["currentText"], "小壹副标题二");
assert_eq!(read["fields"][2]["currentText"], "原始规格");
w.agent_native.cancel();
assert!(action_impl(&mut w, &mut app, None, "pi-detail-copy-apply", &apply, true).is_err());