From 45fe35fb16c114bba0edc5ce8d93f532eb9d49f3 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Sun, 29 Nov 2026 01:27:56 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A5=E5=85=A8=E5=B0=8F=E5=A3=B9=E5=B7=A5?= =?UTF-8?q?=E5=85=B7=E5=A4=B1=E8=B4=A5=E5=9B=9E=E6=89=A7=E5=B9=B6=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E5=88=B6=E4=BD=9C=E7=94=BB=E5=B8=83=E4=BA=A4=E6=8E=A5?= =?UTF-8?q?=E4=B8=8E=E6=89=B9=E9=87=8F=E9=AA=8C=E5=9B=BE=E8=AF=BB=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/detail-agent-pi/src/activity-event.mjs | 24 ++++- apps/detail-agent-pi/src/agent.mjs | 25 +++-- apps/detail-agent-pi/src/candidate-review.mjs | 4 +- apps/detail-agent-pi/src/desktop-host.mjs | 17 +++- apps/detail-agent-pi/src/native-tools.mjs | 9 +- .../src/production-operations.mjs | 14 ++- apps/detail-agent-pi/src/project-tools.mjs | 24 ++++- apps/detail-agent-pi/src/screen-review.mjs | 7 +- apps/detail-agent-pi/src/store.mjs | 28 +++++- .../test/activity-event.test.mjs | 12 +++ .../test/context-usage.test.mjs | 21 ++++- .../test/desktop-daemon.test.mjs | 17 ++++ .../detail-agent-pi/test/native-wire.test.mjs | 11 +++ .../test/production-operations.test.mjs | 8 ++ .../apps/photocraft/src/jiansun_backend.rs | 9 +- .../src/jiansun_canvas_workspace.rs | 19 +++- .../photocraft/src/jiansun_image_transform.rs | 4 +- .../apps/photocraft/src/jiansun_images.rs | 5 +- .../apps/photocraft/src/jiansun_pi_runtime.rs | 3 +- .../ui-egui/src/jiansun/agent_native.rs | 2 +- .../crates/ui-egui/src/jiansun/pi_bridge.rs | 12 ++- .../ui-egui/src/jiansun/product_production.rs | 4 +- .../ui-egui/src/jiansun/stitch_state.rs | 2 + .../ui-egui/src/jiansun/workflow_bridge.rs | 2 +- scripts/audit-xiaoyi-tool-events.mjs | 91 +++++++++++++++++++ 25 files changed, 327 insertions(+), 47 deletions(-) create mode 100644 scripts/audit-xiaoyi-tool-events.mjs diff --git a/apps/detail-agent-pi/src/activity-event.mjs b/apps/detail-agent-pi/src/activity-event.mjs index 66715dbc..7f8d2475 100644 --- a/apps/detail-agent-pi/src/activity-event.mjs +++ b/apps/detail-agent-pi/src/activity-event.mjs @@ -1,3 +1,5 @@ +import { redactText } from './credentials.mjs'; + // UI activity projects allowlisted fields from SDK events. const labels = Object.freeze({ ask_user: '等待用户回复', @@ -12,6 +14,7 @@ const labels = Object.freeze({ plan_production: '读取制作进度', start_production_strategy: '准备制作策划', read_copy_fields: '查看待处理图文', delegate_image_slots: '分派图片图位', review_image_slots: '查看图位结果', retire_production_image: '清理已退回的候选图', read_slot_images: '查看图位图片', use_product_image: '取用商品实拍', transform_slot_image: '调整候选图片', + review_candidate: '提交候选图复核', review_output_screen: '提交整屏复核', prepare_image_request: '准备生图请求', dispatch_image_request: '生成候选图片', await_image_slots: '等待子代理回执', adopt_production_image: '回填候选图片', reconcile_image_slots: '核查图片原请求', list_project_images: '查找本项目候选', read_archived_images: '查找同款历史候选', stage_archived_image: '加入待验历史候选', @@ -104,16 +107,30 @@ export function activityScope(identity, canvas, begun) { return Object.freeze(Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined))); } +export function toolFailure(event) { + if (!event.isError) return; + const failure = event.result?.details?.failure; + const message = failure?.message || event.result?.content?.findLast(item => item.type === 'text')?.text; + return { + failureCategory: failure?.category || 'tool_failed', + message: redactText(message?.trim() || '工具执行失败,执行器未提供原因').slice(0, 1000), + }; +} + function details(event) { const toolName = Object.hasOwn(labels, event.toolName) ? event.toolName : 'other'; const stopped = event.isError && ['write_revoked','revision_conflict','cancelled'] .includes(event.result?.details?.failure?.category); - const pending = typeof event.result?.details?.pendingOriginal === 'string'; + const result = event.result?.details; + const activeImage = ['dispatch_image_request','use_product_image'].includes(toolName) && + ['accepted','already_running'].includes(result?.phase); + const pending = activeImage || typeof result?.pendingOriginal === 'string'; const status = event.type === 'tool_execution_start' ? 'started' : stopped ? 'stopped' : event.isError ? 'failed' : pending ? 'pending' : 'completed'; const label = activityToolLabel(toolName); - const summary = `${{ started: '开始', stopped: '已停止', failed: '失败', pending: '待核查', completed: '完成' }[status]}:${label}`; - return { toolName, status, summary }; + const failure = toolFailure(event); + const summary = `${{ started: '开始', stopped: '已停止', failed: '失败', pending: activeImage ? '进行中' : '待核查', completed: '完成' }[status]}:${label}${failure ? ` · ${failure.message}` : ''}`; + return { toolName, status, summary, ...(status === 'pending' && activeImage ? {pendingKind:'active'} : null) }; } export function activitySummary(event) { return details(event).summary; } @@ -166,5 +183,6 @@ export function toolActivity(event, scope, timestampMs = Date.now()) { ? activityCopyUpdates(event.result?.details?.copyUpdates) : undefined; return { version: 1, type: 'tool', toolCallId, ...activity, phase:activity.status, category:executionCategory(activity.toolName),timestampMs, ...(durationMs === undefined ? {} : { durationMs }), + ...toolFailure(event), ...(copyUpdates ? { copyUpdates } : {}), scope }; } diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index be4f0506..940d7c57 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -25,7 +25,7 @@ import { EnterpriseContext } from './enterprise-context.mjs'; import { openEnterpriseSkills } from './enterprise-skill-resources.mjs'; import { projectTools } from './project-tools.mjs'; import { contextSnapshot, modelCapacity, contextLengths } from './context-usage.mjs'; -import { activityScope, activitySummary, canvasPresence, toolActivity } from './activity-event.mjs'; +import { activityScope, activitySummary, canvasPresence, toolActivity, toolFailure } from './activity-event.mjs'; import { assertPiNodeVersion } from './runtime-policy.mjs'; import { nativeTools } from './native-tools.mjs'; import { NativeExtensionUI } from './native-ui.mjs'; @@ -140,14 +140,14 @@ function toolsFor(host) { const contextTools = [ make('context_read', '按需读取当前项目规则。未指定topic返回当前任务必需规则;brand为品牌细节、template为模板模块、sources为来源。普通问答涉及企业知识库或模板规则时,先用此工具取依据。', Type.Object({ topic: Type.Optional(Type.Union([Type.Literal('brand'), Type.Literal('template'), Type.Literal('sources')])) }, { additionalProperties: false }), args => host.modelContext(args, {loadKnowledge:true})), make('memory_set', '持久记录用户明确确认的事实/决定;evidence必须是用户消息中的原话。', Type.Object({ key: string(64), value: string(1000), evidence: Type.String({ minLength: 4, maxLength: 1000 }) }), args => host.store.remember(args)), - make('memory_search', '用 query 查本项目对话。只有拿到真实 toolCallId 时才填写它,可用 offset 分段读取该回执。回执无匹配时仍按 query 查询。', Type.Object({ + make('memory_search', '用 query 查本项目对话。用真实 toolCallId 读取工具回执或子代理失败原因,可用 offset 分段读取。回执无匹配时仍按 query 查询。', Type.Object({ query:Type.Optional(Type.String({maxLength:200})), toolCallId:Type.Optional(Type.String()), offset:Type.Optional(Type.Integer({minimum:0})), }, {additionalProperties:false}), async ({query,toolCallId,offset=0}) => { const id=toolCallId?.trim(); if (!id) return host.store.search(query,host.manager); - const receipt=host.store.readToolReceipt(host.manager,id,offset); + const receipt=await host.store.readToolReceipt(host.manager,id,offset); return receipt ?? {toolCallId:id,found:false,matches:await host.store.search(query,host.manager)}; }), ]; @@ -391,12 +391,16 @@ export class DetailPiAgent { const mainRetry = {enabled:true,maxRetries:6,baseDelayMs:3000}; const workers = new Map(); // Worker sessions are in memory, so the event log is the only place a failed tool's reason survives. - const recordToolEvent = (event,activity,scope) => store.appendEvent({ - type:event.type,toolName:event.toolName,toolCallId:event.toolCallId,isError:event.isError??false,...scope, - ...(activity?{status:activity.status,phase:activity.phase,category:activity.category,durationMs:activity.durationMs}:null), - // Script failures put the error after the output, so the last text block carries the reason. - ...(event.isError?{error:event.result?.content?.findLast(item=>item.type==='text')?.text?.slice(0,300)}:null), - }); + const recordToolEvent = (event,activity,scope) => { + const failure = toolFailure(event); + return store.appendEvent({ + type:event.type,toolName:event.toolName,toolCallId:event.toolCallId,isError:event.isError??false,...scope, + ...(activity?{status:activity.status,phase:activity.phase,category:activity.category,durationMs:activity.durationMs}:null), + ...(activity?.status==='pending'?{requestId:event.result.details.pendingOriginal ?? event.result.details.operationId, + operationPhase:event.result.details.phase,pendingKind:activity.pendingKind}:null), + ...(failure ? {...failure,error:failure.message.slice(0,300)} : null), + }); + }; runtime.registerProvider('jiansun-native-98k', { api, apiKey: 'native-broker-only', baseUrl: api === 'anthropic-messages' ? 'https://api.vip98k.com' : 'https://api.vip98k.com/v1', models: [{ @@ -594,6 +598,9 @@ export class DetailPiAgent { void recordToolEvent(event,activity,{slotId,requestScope, outputId:workerActivityScope.outputId,variantId:workerActivityScope.variantId}) .catch(error=>console.warn('子代理工具事件未保存',error.code??error.name)); + if (activity && (event.isError || activity.status === 'pending')) { + void host.notifyCanvas('activity', activity.summary, {...activity,scope:host.activityScope}).catch(()=>{}); + } } }); try { diff --git a/apps/detail-agent-pi/src/candidate-review.mjs b/apps/detail-agent-pi/src/candidate-review.mjs index 8a81e9b9..74cae244 100644 --- a/apps/detail-agent-pi/src/candidate-review.mjs +++ b/apps/detail-agent-pi/src/candidate-review.mjs @@ -103,7 +103,7 @@ export async function reviewProductionCandidate({ const errors=[]; if(value.candidateId!==candidateId)errors.push(`candidateId ${JSON.stringify(value.candidateId)} 与本次受审候选不一致`); value.shownFields?.forEach(({field},index)=>{ - if(!fields.has(field))errors.push(`shownFields[${index}].field ${JSON.stringify(field)} 不在本次文案清单中`); + if(!fields.has(field))errors.push(`shownFields[${index}].field ${JSON.stringify(field)} 不在本次文案清单中。请原样复制清单中的单个 field;没有对应字段时删除这一项。`); }); if(errors.length)throw new InvalidToolReply([...errors,facts()].join('\n')); findings.validate(value.screenReview); @@ -144,7 +144,7 @@ export async function reviewProductionCandidate({ '在 screenReview 中提交问题及位置。使用 composite 提供的图位、叠层编号和文案字段。找不到编号时省略编号并填写 location。有问题时填 needs_fix,通过时三组问题均为空。', 'subjectBounds 是按放置后像素与边缘背景色差估测的画布坐标 [x,y,w,h],并已裁到可见图框。', '原件信息见 candidateFile,图框见 frame。requirements 是当前图位的要求,screenCopy 是实时文案。', - '用 shownSubject 描述实际画面,用 shownFields 标明与文案对应的画面依据,其中 field 填 screenCopy 的字段号,label 用于识别文案。mustRedo 和 canvasFixes 分别记录建议重做和能用画布处理的问题。裁切坐标以未裁切原图为准。', + '用 shownSubject 描述实际画面。shownFields 只填写 screenCopy 中存在且有画面依据的条目;每项 field 原样复制一个字段号。文案标题、其他屏字段和多个字段的拼接值均无法定位。mustRedo 和 canvasFixes 分别记录建议重做和能用画布处理的问题。裁切坐标以未裁切原图为准。', ...(guides.length?['模板要求的结构标注落点用图框内 [0,0] 到 [1000,1000] 的坐标。']:[]), '按 checks 逐项记录结论,比较同款实拍和模板参考。对不适用或缺乏证据的检查填 null,并在 reason 说明。检查 generationEvidence 中的实发模型、参数和像素。根据本款 product 资料和已发布的企业 Skill 判定禁止标识,查看主体和配饰上的铭牌、文字及 logo。未读到模板原图时记录依据缺失。暗中遮住标题,描述仍能看出的用途。任何实际问题要记录位置和依据。', '调用 review_candidate 提交结论。', diff --git a/apps/detail-agent-pi/src/desktop-host.mjs b/apps/detail-agent-pi/src/desktop-host.mjs index 7408caaa..3933dd73 100644 --- a/apps/detail-agent-pi/src/desktop-host.mjs +++ b/apps/detail-agent-pi/src/desktop-host.mjs @@ -16,11 +16,14 @@ export function observeCanvasCalls(store, call) { return async (action, input, execution) => { if (action === 'pi-delta' || action === 'pi-activity') return call(action,input); const identity={...store.executionScope,operationId:input.operationId ?? execution?.operationId ?? randomUUID(), - attempt:execution?.attempt ?? 1,requestId:execution?.requestId,revision:input.revision ?? store.executionScope.revision}; + attempt:execution?.attempt ?? 1,requestId:execution?.requestId ?? input.request?.requestId, + revision:input.revision ?? store.executionScope.revision}; const category=executionCategory(action); const startedAt = performance.now(); const record = (status, extra) => store.appendEvent({ - type:'canvas_receipt', action, ...identity, phase:'receipt', status, + type:'canvas_receipt', action, ...(action === 'pi-image-request' ? {imageAction:input.action} : null), + ...(action === 'pi-native-call' ? {nativeMethod:input.method,command:input.params?.command} : null), + ...identity, phase:'receipt', status, durationMs:Math.round(performance.now() - startedAt), ...extra, }).catch(error=>console.warn('小壹画布事件写入失败',error.code ?? error.name)); store.executionHealth.agentHeartbeat=Date.now(); @@ -43,12 +46,15 @@ export function observeCanvasCalls(store, call) { } const status=value?.executed===false && value?.error ? 'failed' : [value?.status,value?.phase].find(v=>typeof v==='string') ?? 'completed'; - if (!canvasTelemetry.has(action) || status === 'failed') await record(status,{category,revision:value?.revision ?? identity.revision, + const failure = status === 'failed' ? BridgeError.from(value.failure ?? value.error ?? value) : undefined; + if (!canvasTelemetry.has(action) || failure) await record(status,{category,revision:value?.revision ?? identity.revision, + ...(failure ? {failureCategory:failure.category,message:failure.message} : null), ...(value?.requestId ? {requestId:value.requestId} : null)}); return value; } catch(error) { - const status=error.category==='cancelled'?'cancelled':error.category==='transport_interrupted'?'unknown':'failed'; - await record(status,{category:accepted?category:'ui_ack',failureCategory:error.category}); + const failure=BridgeError.from(error); + const status=failure.category==='cancelled'?'cancelled':failure.category==='transport_interrupted'?'unknown':'failed'; + await record(status,{category:accepted?category:'ui_ack',failureCategory:failure.category,message:failure.message}); throw error; } }; @@ -169,6 +175,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o binding = resolveRules({ brandId: shop.brandId, shopId: shop.id, categoryId: combo.categoryId }, config.ruleCatalog); } store = await storage.ProjectStore.open(config.root, { scope: config.scope, project: config.project }, binding, { continuous:true }); + store.projectExportRoot = config.projectExportRoot; signal?.throwIfAborted(); broker.bind(bindingConfig); const info = await broker.info(productionGoal&&!config.goalUserEntry?{reuseDetailSelection:true}:undefined); diff --git a/apps/detail-agent-pi/src/native-tools.mjs b/apps/detail-agent-pi/src/native-tools.mjs index f0f1497f..8ae1c482 100644 --- a/apps/detail-agent-pi/src/native-tools.mjs +++ b/apps/detail-agent-pi/src/native-tools.mjs @@ -145,7 +145,7 @@ export function nativeTools(host, make) { continue; } if (waiting) throw Error('当前画布暂不可写。就绪后可用同一修订提交,本次未执行原生命令。'); - throw new BridgeError('写入修订已变化,请重新读取画布','revision_conflict'); + throw new BridgeError(`写入修订已变化,请重新读取画布。当前修订 ${permission.revision};用 canvas_read 重新核对目标图层,再决定是否提交本次更改。对于映射文案,可以用 write_copy_fields 并填写 expectedText 核对原文。`,'revision_conflict'); } args = {...args,revision}; } @@ -179,7 +179,12 @@ export function nativeTools(host, make) { throw new BridgeError('用户已修改画布,原任务后续应用许可已撤销;请重新读取后在新回合明确操作,不会重发','write_revoked',{dispatched:true}); } terminal = true; - if (settled.executed !== true) throw Error(settled.error || '原生命令未执行,未报告成功'); + if (settled.executed !== true) { + if (args.params?.command === 'edit.transform' && settled.error?.includes('nothing to transform')) { + throw new BridgeError('目标图层在当前操作范围内没有可变换内容。用 canvas_read 核对图层类型和边界,再对含有内容的图层执行 edit.transform。','local_precondition_failed',{dispatched:true}); + } + throw Error(settled.error || '原生命令未执行,未报告成功'); + } if (pendingJob !== undefined && (settled.state !== 'done' || settled.applied !== true || settled.applicationVerified !== true)) throw Error(settled.error || '原生任务未完成经验证的文档应用,保留原job核查;禁止重复执行'); if (!readOnly && settled.revision !== args.revision) (await currentProductionOperations(host))?.markProgressDirty?.(); await host.store.appendEvent({ type: 'native_operation_completed', run: host.canvas.run, diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 9129d4eb..62d36efa 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -105,7 +105,7 @@ export const productionOperationTools = [ ...outputScope,jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})), })], ['await_image_slots','等待任一在途制作、验图或生图请求返回,并读取已有回执。单次最多等待 3 分钟,超时返回 pendingWork(在途阶段及耗时)和已有回执,原工作继续运行。省略 slotIds 时也关注按屏复核,结论见 screenChecks。已返回结果未知的原请求用 reconcile_image_slots 核查。可指定成品和花色,非当前可写成品直接返回已有回执和在途状态,waiting_canvas 表示等切回可写画布。',obj({...outputScope,slotIds:optional(ids)})], - ['review_image_slots','只读查看指定成品和花色的候选、验图、原请求、覆盖统计与整屏复核进度。screensReadyForReview 是图位已齐、当前画面待复核的多图位屏。dispatchReady 列出关联文案已写好且尚未派发或采纳的图位;waiting_canvas 的图位在等待切回可写画布。指定 slotIds 获取候选、退回原因、原请求和验图详细结论。',obj({...outputScope,slotIds:optional(Type.Array(Type.String()))})], + ['review_image_slots','只读查看指定成品和花色的候选、验图、原请求、覆盖统计与整屏复核进度。screensReadyForReview 是图位已齐、当前画面待复核的多图位屏。dispatchReady 列出关联文案已写好且尚未派发或采纳的图位;waiting_canvas 的图位在等待切回可写画布。指定 slotIds 查看详情;批量详情超出预算时返回摘要及图位和候选 ID,再用单个 slotId 查看。',obj({...outputScope,slotIds:optional(Type.Array(Type.String()))})], ['list_project_images','列出本项目已完成且可读的候选,包括有采纳记录的图。可按来源成品和花色筛选,生图次数取自宿主已派发的记录。用候选号在当前目标图位做本地变换或复用。',obj(outputScope)], ['read_archived_images','只读查找其他本机项目同款的历史候选。可选 slotIds 查看有对应图位的结果。不同模板或花色的已完成候选也可放入当前图位复核。',obj({ slotIds:optional(Type.Array(Type.String())), @@ -1329,7 +1329,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, (args,activeSignal)=>transformImage(slot,args,activeSignal)), workerTool('prepare_image_request','准备并持久保存完整生图请求。',preparationArgs, (args,activeSignal)=>prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal)), - workerTool('dispatch_image_request','审阅准备回执后填写 requestId 确认派发',dispatchArgs, + workerTool('dispatch_image_request','审阅准备回执后原样复制 requestId 确认派发。版本和哈希由宿主从原请求读取,可省略 expectedRevision 和 expectedHash。',dispatchArgs, async(approval,activeSignal)=>{ const request=await preparedRequest(approval.requestId,slot).catch(error=>{ throw Error(`requestId ${JSON.stringify(approval.requestId)},slotId ${JSON.stringify(slot.id)}。请核对当前图位的生图准备回执。原因:${error.message}`,{cause:error}); @@ -1474,7 +1474,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, const selected=live.filter(slot=>!requested.size||matched.has(slot.id)); const statuses=drawStatuses(selected); const summary=await progressSummary(); - return {outputId,variantId,active:jobs.size,coverage,progressSummary:summary, + const result={outputId,variantId,active:jobs.size,coverage,progressSummary:summary, screensReadyForReview:summary?.screensReadyForReview??[], dispatchReady:dispatchReady(selected,await pendingCopyBySlot(selected)), pictures:selected.map(slot=>{ @@ -1507,6 +1507,14 @@ export async function openProductionOperations(host,{target=host.productionGoal, decision??generationReceipt?.phase??latest?.status??record?.state??'empty'; return {id,fieldId,label,state,selectedCandidateId,latestCandidateId,attemptCount,...status,rejectionCount:rejections.length}; }),...(unmatched.length?{unmatched}:{})}; + if (selected.length > 1 && requested.size && JSON.stringify(result).length > 200_000) { + result.detailsOmitted = true; + result.pictures = result.pictures.map(({id,fieldId,label,selectedCandidateId,candidates,working,state}) => ({ + id,fieldId,label,selectedCandidateId,working,state, + candidates:candidates?.map(({id,status})=>({id,status})), + })); + } + return result; }, async read_archived_images({slotIds}){ const {requested,matched,unmatched}=readSelection(slotIds); diff --git a/apps/detail-agent-pi/src/project-tools.mjs b/apps/detail-agent-pi/src/project-tools.mjs index 36137c08..35ed691d 100644 --- a/apps/detail-agent-pi/src/project-tools.mjs +++ b/apps/detail-agent-pi/src/project-tools.mjs @@ -16,9 +16,12 @@ export async function projectTools(host) { await fs.mkdir(cwd,{recursive:true}); const root = await fs.realpath(cwd); if (path.relative(cwd,root)) throw Error('项目工作目录必须位于本项目内'); - const inside = (parent,file) => { + const within = (parent,file) => { const relative=path.relative(parent,file); - if (relative==='..' || relative.startsWith('..'+path.sep) || path.isAbsolute(relative)) { + return relative!=='..' && !relative.startsWith('..'+path.sep) && !path.isAbsolute(relative); + }; + const inside = (parent,file) => { + if (!within(parent,file)) { throw Error('路径在本项目工作目录之外'); } }; @@ -36,21 +39,34 @@ export async function projectTools(host) { try {await fs.access(file);return true;} catch(error) {if(error.code==='ENOENT')return false;throw error;} }; + const exports = host.store.projectExportRoot; + const exportMimeType = file => exports && within(exports,file) ? + ({'.jpg':'image/jpeg','.jpeg':'image/jpeg','.png':'image/png'})[path.extname(file).toLowerCase()] : undefined; + const checkedRead = async file => { + if (exportMimeType(file)) { + const resolved = await fs.realpath(file); + const parent = await fs.realpath(path.dirname(exports)); + inside(path.join(parent,path.basename(exports)),resolved); + return resolved; + } + return checked(file); + }; const read=(agent,requestScope)=>{ const worker=agent==='worker'; const workerSkills=worker?host.productionSkills:undefined; const tool=createReadTool(worker?workerSkills.filesRoot:cwd,{operations:{ + detectImageMimeType:async file=>worker ? undefined : exportMimeType(file), access:async file=>{ const normalized=path.normalize(file); if(workerSkills){ if(!await workerSkills.resolveFile(normalized))throw new UnlockedEnterpriseFile(normalized); - } else if(!host.localSkillFiles?.has(normalized)&&!await host.productionSkills?.resolveFile(normalized)) await checked(file); + } else if(!host.localSkillFiles?.has(normalized)&&!await host.productionSkills?.resolveFile(normalized)) await checkedRead(file); await fs.access(file); }, readFile:async file=>{ const normalized=path.normalize(file); const resource=(workerSkills??host.productionSkills)?.documents.get(normalized); - if(!resource) return fs.readFile(host.localSkillFiles?.has(normalized)?file:await checked(file)); + if(!resource) return fs.readFile(host.localSkillFiles?.has(normalized)?file:await checkedRead(file)); const bytes=await fs.readFile(file); await host.store.appendEvent({type:'enterprise_skill_resource_read',agent,requestScope, fileId:resource.fileId,revision:resource.revision,kind:resource.kind,path:resource.path}); diff --git a/apps/detail-agent-pi/src/screen-review.mjs b/apps/detail-agent-pi/src/screen-review.mjs index 9db68127..91df4810 100644 --- a/apps/detail-agent-pi/src/screen-review.mjs +++ b/apps/detail-agent-pi/src/screen-review.mjs @@ -64,7 +64,10 @@ export function screenFindings({overlayLayers,screenCopy,slots,templateFidelity} errors.push(`${group}[${index}].location 缺少画面位置,未填写 ${key} 时必填`); } if (id!==undefined && !allowed.has(id)) { - errors.push(`${group}[${index}].${key} ${JSON.stringify(id)} 不在本屏${inventory}清单中`); + const instruction = allowed.size + ? `请原样复制清单中的单个 ${key},或删除此字段并填写 location` + : `本屏没有可引用的${inventory},请删除 ${key} 并填写 location`; + errors.push(`${group}[${index}].${key} ${JSON.stringify(id)} 不在本屏${inventory}清单中。 ${instruction}。`); } }); } @@ -99,7 +102,7 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl const instructions = [ '复核整屏成片。第一张是整屏实际画面,如有模板原屏,它位于成片之后,再后面是本款实拍。', '用 review_output_screen 提交结论、画面依据和修改建议。图片问题填写 location 和已知 slotId,叠层问题填写 overlayLayers 中的 nativeLayerId,正文问题填写 screenCopy 中的 field。', - '找不到对应图位、叠层或文案字段时,省略编号并用 location 描述在画面中的具体位置。', + '每项问题只引用一个编号,从本屏对应清单原样复制。一个问题涉及多个字段时逐项填写。找不到对应图位、叠层或文案字段时,省略编号并用 location 描述画面位置。', OVERLAY_SCREEN_CRITERIA, TEMPLATE_REVIEW_GUIDANCE, '有问题时填写 needs_fix 和至少一项问题。通过时三组问题均为空。', diff --git a/apps/detail-agent-pi/src/store.mjs b/apps/detail-agent-pi/src/store.mjs index 4cc954d1..1fb209e3 100644 --- a/apps/detail-agent-pi/src/store.mjs +++ b/apps/detail-agent-pi/src/store.mjs @@ -1,4 +1,5 @@ import fs from 'node:fs/promises'; +import { createInterface } from 'node:readline'; import path from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import { createHash, randomUUID } from 'node:crypto'; @@ -141,10 +142,33 @@ export class ProjectStore { const record = executionEvent(event, {projectId:this.identity.project,...this.executionScope}, this.executionHealth ?? {}); await fs.appendFile(path.join(this.dir, 'events.jsonl'), JSON.stringify(redact(record)) + '\n', { mode: 0o600 }); } - readToolReceipt(manager, toolCallId, offset) { + async readToolReceipt(manager, toolCallId, offset) { const entry = manager.getBranch().findLast(row => row.type === 'message' && row.message.role === 'toolResult' && row.message.toolCallId === toolCallId); - if (!entry) return null; + if (!entry) { + let file; + try { file = await fs.open(path.join(this.dir,'events.jsonl')); } + catch (error) { + if (error.code === 'ENOENT') return null; + throw error; + } + const stream = file.createReadStream(); + const input = createInterface({ input:stream, crlfDelay:Infinity }); + try { + for await (const line of input) { + let event; + try { event = JSON.parse(line); } catch { continue; } + if (event.type === 'tool_execution_end' && event.toolCallId === toolCallId && event.isError) { + const text = event.message ?? event.error; + if (text) return {toolCallId,text:text.slice(offset),failureCategory:event.failureCategory,nextOffset:null}; + } + } + } finally { + input.close(); + stream.destroy(); + } + return null; + } const text = entry.message.content.filter(item => item.type === 'text').map(item => item.text).join('\n'); const preview = text.slice(offset, offset + 8000); const end = offset + preview.length; diff --git a/apps/detail-agent-pi/test/activity-event.test.mjs b/apps/detail-agent-pi/test/activity-event.test.mjs index 9ec28ce4..f15bb758 100644 --- a/apps/detail-agent-pi/test/activity-event.test.mjs +++ b/apps/detail-agent-pi/test/activity-event.test.mjs @@ -2,6 +2,18 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { activityScope, canvasPresence, toolActivity } from '../src/activity-event.mjs'; +test('accepted image work and unknown outcomes remain pending with distinct labels', () => { + const event={type:'tool_execution_end',toolName:'dispatch_image_request',toolCallId:'image-call'}; + const accepted=toolActivity({...event,result:{details:{phase:'accepted',operationId:'original'}}},{},100); + assert.equal(accepted.status,'pending'); + assert.equal(accepted.pendingKind,'active'); + assert.match(accepted.summary,/^进行中/u); + const unknown=toolActivity({...event,result:{details:{phase:'unknown',pendingOriginal:'original'}}},{},100); + assert.equal(unknown.status,'pending'); + assert.equal(unknown.pendingKind,undefined); + assert.match(unknown.summary,/^待核查/u); +}); + test('canvas presence projects only the live canvas address', () => { const event = { type: 'tool_execution_start', toolName: 'write_copy_fields', toolCallId: 'copy', args: { items: [{ layer: 54, text: '未提交的文案' }, { layer: 55, text: '第二行' }] } }; diff --git a/apps/detail-agent-pi/test/context-usage.test.mjs b/apps/detail-agent-pi/test/context-usage.test.mjs index 88a0539b..3777e0af 100644 --- a/apps/detail-agent-pi/test/context-usage.test.mjs +++ b/apps/detail-agent-pi/test/context-usage.test.mjs @@ -1,5 +1,8 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; import { foldSupersededProductionReads } from '../src/context-usage.mjs'; import { describeProductionOutput } from '../src/production-goal.mjs'; import { ProjectStore } from '../src/store.mjs'; @@ -11,6 +14,20 @@ const receipt = (id,name,details,args={},content=[text(JSON.stringify(details))] {role:'toolResult',toolName:name,toolCallId:id,content,details,...metadata}, ]; const original = (messages,id)=>messages.find(message=>message.toolCallId===id); + +test('a worker failure remains readable without a durable Pi session result',async t=>{ + const dir=await mkdtemp(path.join(tmpdir(),'xiaoyi-receipt-')); + t.after(()=>rm(dir,{recursive:true,force:true})); + const host={dir}; + const manager={getBranch:()=>[]}; + const read=id=>ProjectStore.prototype.readToolReceipt.call(host,manager,id,0); + assert.equal(await read('review-1'),null); + const event={type:'tool_execution_end',toolCallId:'review-1',isError:true, + failureCategory:'tool_failed',message:'本屏文案字段不匹配'}; + await writeFile(path.join(dir,'events.jsonl'),JSON.stringify(event)+'\n'); + assert.deepEqual(await read('review-1'),{toolCallId:'review-1',text:event.message, + failureCategory:event.failureCategory,nextOffset:null}); +}); const verify = (messages,foldedIds,fullIds)=>{ const projected=foldSupersededProductionReads(messages); for(const id of foldedIds) { @@ -22,7 +39,7 @@ const verify = (messages,foldedIds,fullIds)=>{ return projected; }; -test('opening the same output folds an older binding and retains its save result',()=>{ +test('opening the same output folds an older binding and retains its save result',async()=>{ const previousSave={saved:true,path:'saved.psd',revision:8}; const messages=[ ...receipt('old','open_production_output',{...target,previousSave}), @@ -33,7 +50,7 @@ test('opening the same output folds an older binding and retains its save result const projected=verify(messages,['old'],['other','new','denied']); assert.match(original(projected,'old').content[0].text,/saved\.psd/); const manager={getBranch:()=>messages.map(message=>({type:'message',message}))}; - assert.equal(ProjectStore.prototype.readToolReceipt(manager,'old',0).text, + assert.equal((await ProjectStore.prototype.readToolReceipt(manager,'old',0)).text, original(messages,'old').content[0].text); }); diff --git a/apps/detail-agent-pi/test/desktop-daemon.test.mjs b/apps/detail-agent-pi/test/desktop-daemon.test.mjs index e5e17c2d..e39e643f 100644 --- a/apps/detail-agent-pi/test/desktop-daemon.test.mjs +++ b/apps/detail-agent-pi/test/desktop-daemon.test.mjs @@ -18,6 +18,23 @@ import { BridgeError } from '../src/bridge-error.mjs'; const runId = '9a1ba294-f2c4-4e5f-91e0-ef6002f50e22'; const tick = () => new Promise(resolve => setImmediate(resolve)); +test('canvas failure receipts retain the cause and distinguish pending dispatch', async () => { + const records = []; + const store = { executionScope: {}, executionHealth: {}, async appendEvent(event) { records.push(event); } }; + const call = observeCanvasCalls(store, async (_action, input, accepted) => { + accepted(); + if (input.action === 'prepare') throw new BridgeError('同款原图编号无效', 'local_precondition_failed'); + return { status: 'pending', requestId: 'original' }; + }); + await assert.rejects(call('pi-image-request', { action: 'prepare' }), /同款原图编号无效/u); + await call('pi-image-request', { action: 'dispatch' }); + assert.deepEqual(records.map(({ status, failureCategory, message, requestId }) => + [status, failureCategory, message, requestId]), [ + ['failed', 'local_precondition_failed', '同款原图编号无效', undefined], + ['pending', undefined, undefined, 'original'], + ]); +}); + test('canvas observations save a single receipt and keep routine telemetry in memory',async()=>{ const records=[]; const executionScope={projectId:'project',runId,outputId:'detail',variantId:'oak',revision:7,documentKey:{variantId:'oak'}}; diff --git a/apps/detail-agent-pi/test/native-wire.test.mjs b/apps/detail-agent-pi/test/native-wire.test.mjs index 773404b8..6cbaf678 100644 --- a/apps/detail-agent-pi/test/native-wire.test.mjs +++ b/apps/detail-agent-pi/test/native-wire.test.mjs @@ -911,6 +911,13 @@ test('a retryable response at the worker limit does not trigger another Pi reque test('Pi project tools share the same file boundary',async()=>{ const x=await setup(()=>sse({content:'已核对。'},'stop')); try { + const exports=path.join(x.host.store.dir,'product-exports'); + x.host.store.projectExportRoot=exports; + await fs.mkdir(exports); + const image=path.join(exports,'sku.png'); + await fs.writeFile(image,Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==','base64')); + const metadata=path.join(exports,'manifest.json'); + await fs.writeFile(metadata,'{}'); const {cwd,tools}=await projectTools(x.host); const tool=name=>tools.find(row=>row.name===name); await tool('write').execute('1',{path:'notes.md',content:'品牌说明'}); @@ -919,6 +926,10 @@ test('Pi project tools share the same file boundary',async()=>{ assert.ok((await fs.readFile(path.join(cwd,'notes.md'),'utf8')).includes('品牌')); await assert.rejects(tool('write').execute('3',{path:'../outside.txt',content:'无'}),/工作目录之外/); await assert.rejects(tool('read').execute('4',{path:'../session.json'}),/工作目录之外/); + const exported=await tool('read').execute('5',{path:image}); + assert.equal(exported.content.find(block=>block.type==='image')?.mimeType,'image/png'); + await assert.rejects(tool('read').execute('6',{path:metadata}),/工作目录之外/); + await assert.rejects(tool('write').execute('7',{path:image,content:'无'}),/工作目录之外/); assert.ok(tool('bash')); } finally {await x.close();} }); diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index d5e79d45..4e765414 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -1724,6 +1724,14 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it assert.equal(mixedLookup.variantId,variantId); assert.deepEqual(mixedLookup.pictures.map(row=>row.id),['lamp-photo']); assert.deepEqual(mixedLookup.unmatched.map(row=>row.slotId),['main-only-field']); + slots[0].candidates.push({id:'large-receipt',status:'complete',instructions:'图'.repeat(220_000)}); + const compactReview=await actions.review_image_slots({slotIds:['lamp','switch']}); + assert.equal(compactReview.detailsOmitted,true); + assert.ok(JSON.stringify(compactReview).length<262_144); + assert.deepEqual(compactReview.pictures[0].candidates,[{id:'large-receipt',status:'complete'}]); + const focusedReview=await actions.review_image_slots({slotIds:['lamp']}); + assert.equal(focusedReview.pictures[0].candidates[0].instructions.length,220_000); + slots[0].candidates.pop(); const otherOutput=await actions.review_image_slots({slotIds:['main-only-field']}); assert.equal(otherOutput.outputId,outputId); assert.deepEqual(otherOutput.pictures,[]); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 8b593d5c..0dd9e580 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -218,11 +218,16 @@ fn identifier(s: &str) -> R<&str> { } } fn read_json(path: &Path) -> R { + read_json_with_missing(path, "本机记录无法读取,请保留文件") +} + +fn read_json_with_missing(path: &Path, missing: &'static str) -> R { let mut bytes = Vec::new(); fs::File::open(path).map_err(|error| { - if error.kind() != std::io::ErrorKind::NotFound { - log::warn!("local project record open failed: {}: {error}", path.display()); + if error.kind() == std::io::ErrorKind::NotFound { + return missing; } + log::warn!("local project record open failed: {}: {error}", path.display()); "本机记录无法读取,请保留文件" })?.take(2_000_001).read_to_end(&mut bytes).map_err(|_| "本机记录读取中断,请保留文件")?; if bytes.len() > 2_000_000 { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index edb798de..3b67ddc9 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -1078,7 +1078,7 @@ fn crop_product_photo(bytes: &[u8], region: &Value, frame: &Value, inside: bool) fn original_product_candidate(dir: &Path, state: Value, binding: Value, products: &Value, index: usize, frame: &Value, project_scoped: bool) -> R { let image = products.as_array().into_iter().flatten().filter(|row| row["purpose"] == "product") - .nth(index).ok_or("当前花色没有所选产品原图")?; + .nth(index).ok_or("当前花色没有所选产品原图。用 read_slot_images 查看当前图位的同款原图,再填写从 0 开始的 referenceIndex。")?; let id = uuid(&binding["candidateId"], "原图候选")?; let job = dir.join("image-jobs").join(&id); let mut bytes = local_product_photo(dir, image)?; @@ -2108,7 +2108,7 @@ impl Backend { } let index = request["referenceIndex"].as_u64().filter(|index| *index < reference_limit as u64) .ok_or("同款原图编号无效")? as usize; - let original = originals.get(index).ok_or("当前花色没有该同款原图")?; + let original = originals.get(index).ok_or("当前花色没有该同款原图。用 read_slot_images 查看当前图位的同款原图,再填写从 0 开始的 referenceIndex。")?; let frame = slot_frame(field, mapped_slot(&state, slot, &variant_id)).ok_or("找不到实际图框")?; let crop_mode = product_crop_mode(&state, output, field)?; let inside = matches!(crop_mode, Some("inside" | "cover")); @@ -4165,9 +4165,13 @@ impl Backend { // Sibling candidates change the workspace revision, not this document or slot. // The mapped layer and candidate are checked again below before reading any pixels. let browsing = method == "slot-product-view"; + // Production handoff binds to the workspace and resolves the requested + // output from its live configuration. Candidate receipts may advance it. + let handoff = method == "slot-skeleton" && input["continueProduct"] == true + && input["workspaceId"].is_string() && input["workspaceId"] == state["id"]; if !matches!(method, "slot-read" | "slot-recover" | "slot-adopted" | "slot-product-view") && input["slotRevision"].as_u64() != Some(revision(&state)) - && !batch && !(method == "slot-skeleton" && input["brief"].is_object()) { + && !batch && !handoff && !(method == "slot-skeleton" && input["brief"].is_object()) { return Err("画布项目已有新版本,请重新读取;原候选保留".into()); } if method == "slot-read" { @@ -5533,6 +5537,15 @@ mod tests { {"outputId":"sku_images","variantId":variant}, ])); assert_eq!(prepared["workflow"]["productionBlocks"][0]["outputId"], "main_images"); + let mut handoff = json!({ + "doc":doc,"baseRevision":7,"slotRevision":0,"continueProduct":true, + "workspaceId":prepared["workflow"]["workspaceId"],"outputId":"main_images", + }); + let error = backend.canvas_workspace_action("slot-skeleton", &handoff, &events, &egui::Context::default()).unwrap_err(); + assert_eq!(error, "主图原稿缺失"); + handoff["workspaceId"] = json!("previous-workspace"); + let error = backend.canvas_workspace_action("slot-skeleton", &handoff, &events, &egui::Context::default()).unwrap_err(); + assert!(error.contains("画布项目已有新版本"), "{error}"); assert!(receiver.try_recv().is_err()); assert_eq!(fs::read(dir.join(FILE)).unwrap(), before); assert!(!dir.join("template-outputs").exists()); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_image_transform.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_image_transform.rs index fc2b9b1c..f31d4a84 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_image_transform.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_image_transform.rs @@ -53,10 +53,10 @@ pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value) -> R { let products = generation_references(dir, &state, &variant)?; let photo = - products.as_array().into_iter().flatten().filter(|image| image["purpose"] == "product").nth(index as usize).ok_or("当前花色没有该同款原图")?; + products.as_array().into_iter().flatten().filter(|image| image["purpose"] == "product").nth(index as usize).ok_or("当前花色没有该同款原图。用 read_slot_images 查看当前图位的同款原图,再填写从 0 开始的 referenceIndex。")?; (local_product_photo(dir, photo)?, None, json!(index), json!([photo]), 1.0) } - _ => return Err("须指定一个候选号或本款原片编号".into()), + _ => return Err("用 read_slot_images 查看来源,再填写一个 sourceCandidateId 或一个 referenceIndex。".into()), }; let decoded = photocraft_codecs::decode_with( &bytes, diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs index 859c3bfd..774d24f0 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs @@ -58,7 +58,8 @@ fn image_request_file(dir: &Path, id: &str) -> R { } pub(super) fn read_image_request(dir: &Path, id: &str) -> R { - let request = read_json(&image_request_file(dir, id)?)?; + let request = read_json_with_missing(&image_request_file(dir, id)?, + "本项目没有该生图请求。请使用当前图位 prepare_image_request 返回的 requestId。")?; if request["id"] != id || !request["requestSpecHash"].is_string() { return Err("未找到此版本的生图请求".into()); } @@ -1481,6 +1482,8 @@ mod tests { task["protocol"] = json!({"parameters":{"quality":"medium"},"field":"images","route":"fixture-route", "path":"/v1/images/edits","multipart":true}); task["requestSpecHash"] = json!(hash(&image_spec(&task).to_string())); + assert_eq!(read_image_request(&fixture.dir, &Uuid::new_v4().to_string()).unwrap_err(), + "本项目没有该生图请求。请使用当前图位 prepare_image_request 返回的 requestId。"); job_save(&fixture.dir, &task).unwrap(); let read = image_request_receipt(&read_image_request(&fixture.dir, &id).unwrap()); assert_eq!(read["spec"]["prompt"], prompt); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs index c476bd48..07a7ecef 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -628,7 +628,8 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: let binary = std::env::current_exe().map_err(|_| "客户端位置不可用")?; let profile = b.root.parent().ok_or("配置位置无效")?; let scope = &input["context"]["requestScope"]; - let config = json!({"binary":binary,"profile":profile,"root":dir.join("agent"),"project":project,"scope":b.scope(),"documentId":doc, + let config = json!({"binary":binary,"profile":profile,"root":dir.join("agent"),"projectExportRoot":dir.join("product-exports"), + "project":project,"scope":b.scope(),"documentId":doc, "dispatchLease":b.access.dispatch_path(), "ruleCatalog":saved.as_ref().map(|rule|rule["catalog"].clone()),"ruleId":saved.as_ref().map(|rule|rule["id"].clone()), "projectEvidence":project_evidence(&super::creation::load(&dir)?,&b.scope(),&project,doc,&input["context"]["requestScope"]["variantId"]), diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs index ca6fc44e..0383970d 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs @@ -266,7 +266,7 @@ pub(super) fn guard_with_background_save(w: &Workspace, app: &PhotocraftApp, inp if w.pi_request_scope["productProduction"] == true { guard_production_access(w, input, current.2, read_only)?; if !read_only && current.2 != w.expected_revision { - return Err("写入修订已变化,请重新读取画布".into()); + return Err(format!("写入修订已变化,当前修订 {}。请用 canvas_read 核对目标图层后再提交。", current.2)); } return Ok(current); } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs index 722f3a60..44fb4cdf 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs @@ -94,6 +94,7 @@ fn tool_activity(w: &Workspace, event: &Value) -> Result { "started" => "开始", "completed" => "完成", "failed" => "失败", + "pending" if event["pendingKind"] == "active" => "进行中", "pending" => "待核查", "stopped" => "已停止", _ => return Err("工具状态无效".into()), @@ -118,8 +119,15 @@ fn tool_activity(w: &Workspace, event: &Value) -> Result { return Err("工具状态目标与原请求不一致".into()); } } + let mut summary = format!("{prefix}:{label}"); + if matches!(state, "failed" | "stopped") && id(&event["failureCategory"]).is_some() { + if let Some(message) = event["message"].as_str() { + summary.push_str(" · "); + summary.extend(message.chars().take(240)); + } + } let mut clean = json!({"version":1,"type":"tool","toolCallId":call,"toolName":name,"status":state, - "timestampMs":timestamp,"summary":format!("{prefix}:{label}"),"run":w.pi_run}); + "timestampMs":timestamp,"summary":summary,"run":w.pi_run}); if let Some(category) = event["category"].as_str().filter(|category| matches!(*category, "inference" | "canvas_read" | "canvas_write" | "disk_persist" | "remote_image" | "ui_ack" | "export")) { clean["category"] = json!(category); @@ -1292,6 +1300,8 @@ mod tests { let mut pending = input["event"].clone(); pending["status"] = json!("pending"); assert_eq!(tool_activity(&w, &pending).unwrap()["summary"], "待核查:读取画布"); + pending["pendingKind"] = json!("active"); + assert_eq!(tool_activity(&w, &pending).unwrap()["summary"], "进行中:读取画布"); for (field, value) in [("toolCallId", json!("private argument")), ("toolName", json!("secret")), ("status", json!("invalid")), ("timestampMs", json!(-1)), ("version", json!(2))] { let mut bad = input.clone(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs index 29773d26..6b6deb71 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs @@ -1395,7 +1395,8 @@ impl Workspace { && canvas_workspace::document_scope_matches(&canvas.doc, &self.template_workflow, &stage.output, &stage.variant)) { self.bind_production_canvas(app); } else if let Err(error) = self.slot_action(app, "slot-skeleton", json!({ - "outputId":stage.output,"variantId":stage.variant,"continueProduct":true + "outputId":stage.output,"variantId":stage.variant,"continueProduct":true, + "workspaceId":self.template_workflow["workspaceId"] })) { self.production_canvas_open_failed(app, "slot-skeleton", &error); } @@ -3513,6 +3514,7 @@ mod tests { let Request::Action(method, requested) = requests.try_recv().unwrap() else { panic!("load after save"); }; assert_eq!(method, "slot-skeleton"); assert_eq!(requested["outputId"], "main_images"); + assert_eq!(requested["workspaceId"], "workspace"); let workflow = json!({"workspaceId":"workspace","outputId":"main_images","variantId":"wood", "templateId":"catalog","templateVersion":"v1","templateHash":"main-hash","revision":2, "outputs":[{"outputId":"main_images","documentId":"M01"}]}); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs index 7d2cc8b4..8b895f8a 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs @@ -423,6 +423,8 @@ pub(super) fn known_tool_label(tool: &str) -> Option<&'static str> { "use_product_image" => "取用商品实拍", "transform_slot_image" => "调整候选图片", "prepare_image_request" => "准备生图请求", + "review_candidate" => "提交候选图复核", + "review_output_screen" => "提交整屏复核", "dispatch_image_request" | "generate_slot_image" => "生成候选图片", "retire_production_image" => "清理已退回的候选图", "check_page_copy" => "发起文案复核", diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs index 59f12f6a..af03efb6 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs @@ -1043,7 +1043,7 @@ fn template_input(w: &Workspace, intent: &str, proposal: &Value) -> Result '); + process.exit(2); +} + +async function* records(file) { + const input = createInterface({ input: createReadStream(file), crlfDelay: Infinity }); + let line = 0; + for await (const text of input) { + line++; + if (!text.trim()) continue; + try { + yield { line, data: JSON.parse(text) }; + } catch (error) { + console.error(`${file}:${line} ${error.name},该行未计入`); + } + } +} + +const results = new Map(); +const sizes = new Map(); +for (const file of await readdir(sessions)) { + if (!file.endsWith('.jsonl')) continue; + for await (const { line, data } of records(path.join(sessions, file))) { + if (data.type !== 'message' || data.message?.role !== 'toolResult') continue; + results.set(data.message.toolCallId, { file, line, ...data.message }); + const { toolName, content, toolCallId } = data.message; + const chars = content.filter(block => block.type === 'text').reduce((total, block) => total + block.text.length, 0); + if (chars > (sizes.get(toolName)?.chars ?? -1)) sizes.set(toolName,{chars,toolCallId,file,line}); + } +} + +const rows = []; +const terminalReceipts = new Map(); +const historicalReasons = [ + [/修订已变化/u, 'revision_conflict'], + [/nothing to transform/u, 'empty_transform_target'], + [/characters of JSON, more than the limit/u, 'result_too_large'], + [/路径在本项目工作目录之外/u, 'workspace_path'], + [/当前花色没有|同款原图编号无效|须指定一个候选号/u, 'image_source'], + [/expectedHash .*不一致|expectedRevision .*不一致/u, 'request_receipt_mismatch'], + [/生图请求编号无效/u, 'unknown_image_request'], + [/本机记录无法读取/u, 'record_unreadable'], + [/Validation failed for tool/u, 'tool_argument_schema'], + [/不在本.*清单中|三组问题列表均为空/u, 'review_evidence'], +]; +for await (const { line, data } of records(events)) { + if (!['tool_execution_end', 'canvas_receipt'].includes(data.type)) continue; + const original = data.requestId || data.operationId; + if (data.type === 'canvas_receipt' && original && ['complete','applied','failed','cancelled'].includes(data.status)) { + terminalReceipts.set(original,{status:data.status,line}); + } + const failed = data.isError || data.status === 'failed'; + if (!failed && !['pending', 'unknown', 'waiting_save'].includes(data.status)) continue; + const session = data.type === 'tool_execution_end' ? results.get(data.toolCallId) : undefined; + const failure = session?.details?.failure; + const message = data.message || data.error || failure?.message || + (failed ? session?.content?.findLast(item => item.type === 'text')?.text : ''); + const category = data.failureCategory || failure?.category || + (failed ? historicalReasons.find(([pattern]) => pattern.test(message ?? ''))?.[1] ?? '历史原因未结构化' : data.status); + rows.push({ + source: data.type, status: data.status ?? 'failed', category, + tool: data.toolName ?? data.action, line, id: data.toolCallId ?? data.operationId, requestId: data.requestId, + operationPhase: data.operationPhase, imageAction: data.imageAction, command: data.command, + session: session && `${session.file}:${session.line}`, + message: message?.replace(/\s+/gu, ' ').slice(0, 1000) || (failed ? '历史事件未记录失败原因' : ''), + }); +} +for (const row of rows) { + if (!['pending','unknown','waiting_save'].includes(row.status)) continue; + const terminal = terminalReceipts.get(row.requestId ?? row.id); + if (terminal?.line > row.line) row.laterReceipt = terminal; +} + +const totals = new Map(); +for (const { source, status, tool, category } of rows) { + const key = [source, status, tool, category].join('\t'); + totals.set(key, (totals.get(key) ?? 0) + 1); +} +console.log('事件类型\t状态\t工具\t原因分类\t次数'); +for (const [key, count] of totals) console.log(`${key}\t${count}`); +console.log('\n会话中各工具最大文本回执(JSONL)'); +for (const [tool, size] of [...sizes].sort((a,b)=>b[1].chars-a[1].chars)) console.log(JSON.stringify({tool,...size})); +console.log('\n逐条证据(JSONL)'); +for (const row of rows) console.log(JSON.stringify(row));