diff --git a/apps/detail-agent-pi/scripts/recover.mjs b/apps/detail-agent-pi/scripts/recover.mjs deleted file mode 100644 index 614c3b80..00000000 --- a/apps/detail-agent-pi/scripts/recover.mjs +++ /dev/null @@ -1,17 +0,0 @@ -import fs from 'node:fs/promises'; -import path from 'node:path'; -import { Native98kBroker } from '../src/native-bridge.mjs'; -import { NativeControlClient } from '../src/native-control-client.mjs'; -import { ProjectStore, atomic } from '../src/store.mjs'; -import { DetailPiAgent } from '../src/agent.mjs'; -const config = JSON.parse(await fs.readFile(process.argv[2], 'utf8')), id = process.argv[3]; -if (!id) throw Error('请提供原幂等键;仅查询原请求,不会发起推理'); -const broker = new Native98kBroker(config.broker), info = await broker.info(); -const store = await ProjectStore.open(config.output, { scope: info.accountScope, project: config.broker.project }, config.canvasBinding || config.binding); -const canvas = await NativeControlClient.connect(config.canvas); -const host = await DetailPiAgent.open({ store, broker, canvas, protocolMode: config.protocolMode }); -try { - const result = await host.recover(id, { executeReadOnly: true }); - await atomic(path.join(config.output, 'recovered-original-sse.json'), { id, ...result, checkedAt: new Date().toISOString() }); - console.log(JSON.stringify(result, null, 2)); -} finally { await host.dispose(); canvas.close(); } diff --git a/apps/detail-agent-pi/scripts/verify-recovery.mjs b/apps/detail-agent-pi/scripts/verify-recovery.mjs deleted file mode 100644 index 5d4d749d..00000000 --- a/apps/detail-agent-pi/scripts/verify-recovery.mjs +++ /dev/null @@ -1,23 +0,0 @@ -import fs from 'node:fs/promises'; -import path from 'node:path'; -import assert from 'node:assert/strict'; -import { Native98kBroker } from '../src/native-bridge.mjs'; -import { ProjectStore, atomic } from '../src/store.mjs'; -import { DetailPiAgent } from '../src/agent.mjs'; -const config = JSON.parse(await fs.readFile(process.argv[2], 'utf8')); -const broker = new Native98kBroker(config.broker), info = await broker.info(); -const store = await ProjectStore.open(config.output, { scope: info.accountScope, project: config.broker.project }, config.binding); -const dir = path.join(config.broker.profile, 'jiansun/accounts', info.accountScope, 'pi-validation', config.broker.project, 'requests'); -const before = (await fs.readdir(dir)).sort(); -const host = await DetailPiAgent.open({ store, broker, protocolMode: 'native-tools' }); -try { - const known = await host.recover('61616ad2-b1d4-4281-a63e-32a60876c5e2'); - assert.equal(known.alreadyApplied, true); assert.equal(known.reposted, false); - const unknown = await host.recover('0447b17b-1c45-4902-a6a5-18357a3e2a3f'); - assert.equal(unknown.phase, 'unknown'); assert.equal(unknown.reposted, false); - await assert.rejects(host.prompt('核查阻止重复发送的保护,不应真的发给模型'), /未知请求/); - const after = (await fs.readdir(dir)).sort(); assert.deepEqual(after, before); - const result = { known, unknown, newPromptBlocked: true, dispatchReceiptsBefore: before.length, dispatchReceiptsAfter: after.length, checkedAt: new Date().toISOString() }; - await atomic(path.join(config.output, 'readonly-recovery.json'), result); - console.log(JSON.stringify(result, null, 2)); -} finally { await host.dispose(); } diff --git a/apps/detail-agent-pi/src/activity-event.mjs b/apps/detail-agent-pi/src/activity-event.mjs index 70975f0b..66715dbc 100644 --- a/apps/detail-agent-pi/src/activity-event.mjs +++ b/apps/detail-agent-pi/src/activity-event.mjs @@ -9,7 +9,7 @@ const labels = Object.freeze({ canvas_candidate_image: '核对图位和候选', bash: '运行项目终端', open_production_output: '打开制作画布', produce_current_output: '制作并验收当前输出', generate_slot_image: '生成候选图片', - plan_production: '读取制作进度', start_production_strategy: '准备制作策划', read_production_knowledge: '读取制作规则', + 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: '调整候选图片', prepare_image_request: '准备生图请求', dispatch_image_request: '生成候选图片', diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index cf7cd21d..a27b79ed 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -1,5 +1,5 @@ import {setTimeout as delay} from 'node:timers/promises'; -import { confirmProductionResponse, recoverProductionResponse, confirmedProductionFailure, productRequestScope, ProductionOutputLimit, ProductionRequestFailed } from './production-recovery.mjs'; +import { productRequestScope } from './production-recovery.mjs'; import { enterpriseTools } from './enterprise-knowledge.mjs'; import { executeWorkflow } from './workflow-execute.mjs'; import { PresentationBatch, StreamOutputMeter, StreamPresentation, presentText, stripProductionToolText } from './stream-presentation.mjs'; @@ -11,29 +11,22 @@ import { productionLedger } from './production-repository.mjs'; import { CanvasOperations } from './canvas-operations.mjs'; import { BridgeError, stoppedCanvas } from './bridge-error.mjs'; import { protectSession, redactText } from './credentials.mjs'; -import { productionTools, callProductionTool, closeProductionTurn, runPiProductionGoal, unfinishedProductionTurn, - mayContinueProductionGoal } from './production-goal.mjs'; +import { productionTools, callProductionTool, closeProductionTurn, runPiProductionGoal, unfinishedProductionTurn } 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'; import { atomic } from './store.mjs'; import { jsonToolContext, decodeToolReply } from './json-tool-codec.mjs'; -import { parseReceipt } from './receipt.mjs'; -import { auditResponse, InvalidToolReply } from './response-audit.mjs'; import { createImageContextPruningExtension } from './image-context-pruning.mjs'; -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 { 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 +62,12 @@ memory_set只记录对话记忆,不修改产品资料。用户希望改资料 references是用户提交时冻结的本轮引用;component为pixelMask或vectorMask时指所属图层对应的蒙版。liveSelected只表示实时界面选择,不能替代本轮引用。没有references时,不要猜测用户明确指向了哪个对象。 只确认已执行的修改。工具失败要说明。生图和画布操作结果未确认时,只核查原编号。`; -const PRODUCTION_SYSTEM = `你是小壹的制作助手。先读取本项目适用的企业制作指引,按指引和模板在画布中制作和复核。由你决定要做什么、顺序、并行和返工。 +const PRODUCTION_SYSTEM = `你是小壹的制作助手。依据本项目发布的企业 Skill、商品实拍、资料和模板制作并复核。按需读取适用 Skill 和引用。由你决定工作范围内的顺序、并行和返工。 ${PRODUCT_VOICE} -用 plan_production 读取本轮目标及待交付项。open_production_output 指定当前可写的成品和花色,切换回执包含保存结果和各成品的在途工作。list_project_images 可查询本项目已完成的候选,供跨成品复用。用户查看的页面和制作画布独立。 -${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 切换可写画布,保留各成品在途工作。用 list_project_images 查询本项目可复用的候选。用户附带引用时,用其中的输出、花色、图位、候选或原生图层身份定位目标。 +读实时文案并使画面与对应卖点一致。子代理读取本屏实时文案,验图回执绑定当时的文案签名。文案更新后可按新文案复核。安排图位任务时写清需呈现的内容,避免把模板原文当成当前卖点。 +用 tool_search 查找按需工具。企业指引中的命令行编修可用等价的画布命令完成。通过 native_catalog 查原生命令与完整参数,复用已取得的 parameterDocs。连续的确定操作可用 codemode 依次 await,用真实回执衔接各步。 +按实际像素和企业 Skill 复核成片。结果未知的付费请求用 reconcile_image_slots 按原编号核查。以文件与版本回执确认交付,用简短中文汇报实际进展。`; const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value }); // Both shapes are native projections of the frozen request, never the live selection. @@ -92,6 +75,7 @@ const frozenReferences = context => Array.isArray(context?.requestScope?.referen ? context.requestScope.references : Array.isArray(context?.references) ? context.references : undefined; // Only the native owner's explicit inactive-document response detaches display. // Connection, account/authentication and all other failures must still surface. +const workflowBindingError = '品牌或品类已变化,请重新开始一轮对话以加载对应规则;未继续执行当前回合'; const inactiveDocument = error => error?.category === 'scope_changed'; const sequentialTools = new Set([ 'memory_set', 'canvas_edit', 'canvas_preview', 'copywriting_options', 'copywriting_fields', @@ -111,9 +95,14 @@ function toolsFor(host) { try { host.productionSignal?.throwIfAborted(); const value = await execute(args, signal, ctx); + if ((name==='finish_production'||name==='defer_production_output') && value.finalized) { + if (value.completed) await ctx.executeTool('update_goal',{status:'complete'}); + else await host.session.prompt('/goal pause'); + } return format(name==='canvas_read'&&args.revision!==undefined?{...value,changedSinceRevision:value.revision!==args.revision}:value); } catch(error) { if (!(error instanceof BridgeError)) throw error; + if (!host.productionGoal&&host.canvasOperations.writesBlocked) host.canvasOperations.stopReason=error.message; return {...plain({failure:error.wire()}),isError:true}; } } }); @@ -135,11 +124,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, @@ -170,7 +162,7 @@ function toolsFor(host) { if(host.canvasNotificationsDetached || host.canvasOperations.writesBlocked)throw Error('当前项目已切换或用户已接手,本轮画布写入已停止'); const permission = await host.canvas.requestWrite(revision); if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧画布编辑未派发'); - if (!permission.allowed) throw new BridgeError('用户已接手,本轮写入未获许可','write_revoked'); + if (!permission.allowed || permission.writeBlocked) throw new BridgeError('用户已接手,本轮写入未获许可','write_revoked'); if (permission.revision !== revision) throw new BridgeError('画布已修改,写入许可已过期,未执行','revision_conflict'); signal?.throwIfAborted(); if (host.canvasNotificationsDetached || host.canvasOperations.writesBlocked) throw Error('当前项目已切换或用户已接手,旧画布编辑未派发'); @@ -409,171 +401,119 @@ export class DetailPiAgent { const workerFields = worker && {slotId:worker.slotId,requestScope:worker.requestScope}; if (worker?.signal) options = {...options,signal:AbortSignal.any([options.signal,worker.signal].filter(Boolean))}; (async () => { - let requiredTool; - let round, sentAt; + let round; const purpose = worker ? 'whole-detail-worker' : host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation'; try { - options.signal?.throwIfAborted(); - if (host.compromised) throw Error('本地会话锁失效,已停止模型调用'); - if (host.workflowBindingChanged) throw Error('品牌或品类已变化,请重新开始一轮对话以加载对应规则'); - const liveCanvas = !worker && host.canvas && !host.compacting && !host.canvasNotificationsDetached ? await host.canvas.read() : null; - if (liveCanvas?.conversationActive === false) throw Error('当前项目已切换,本轮对话未应用到其他项目'); - if (!worker && !host.compacting && (host.canvasNotificationsDetached || !host.productionGoal && - !liveCanvas?.manualEdit && (host.canvasOperations.writesBlocked || liveCanvas?.writeBlocked && host.canvasOperations.writeRequested))) { - const text=host.canvasNotificationsDetached?'本机:原项目已切换,原回复保留在原项目,后续画布操作已停止。':host.canvasOperations.stopReason?`本次创作已停止:${host.canvasOperations.stopReason}`:'本机:已接手,剩余画布操作已停止。'; - const message = { role: 'assistant', api, provider: model.provider, model: model.id, content: [{ type: 'text', text }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } } }; - await store.appendEvent({ type: host.canvasNotificationsDetached?'inactive_project_stopped':host.canvasOperations.stopReason?'workflow_operation_stopped':'handover_stopped', modelCallSkipped: true }); - output.push({ type: 'start', partial: message }); - output.push({ type: 'done', reason: 'stop', message }); output.end(message); - return; - } - const completedProduction=!worker&&!host.compacting&&Boolean(host.productionCompletion?.receipt); - if (completedProduction) { - const text = host.productionCompletion.text; - await store.appendEvent({ type:'production_stage_submitted', modelCallSkipped: true }); - const message = { role: 'assistant', api, provider: model.provider, model: model.id, content: [{ type: 'text', text }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } } }; - output.push({ type: 'start', partial: message }); - output.push({ type: 'done', reason: 'stop', message }); output.end(message); - return; - } - const encoded = !worker && protocolMode === 'structured-json' && !host.compacting; - const wireContext = encoded ? jsonToolContext(context) : context; - if (!worker) { - host.currentCanvas = liveCanvas?.context; - const {textChars: inputChars, totalChars} = contextLengths(wireContext); - if (!host.compacting) await host.updateContextUsage(null, 'running'); - host.rounds++; - if (host.callBudget !== undefined && host.rounds > host.callBudget) throw Error(`本轮已达${host.callBudget}次调用预算,停止继续调用`); - await store.appendEvent({ type: 'context_budget', inputChars, originalChars: encoded ? contextLengths(context).totalChars : totalChars }); - } - if (transport?.stream) { - const stream = transport.stream(model, wireContext, options); - for await (const event of stream) output.push(event); - const result = await stream.result(); - if (!worker && !host.compacting && result.stopReason !== 'error' && result.stopReason !== 'aborted') { - const u = result.usage; - await host.updateContextUsage({ inputTokens: u.input + u.cacheRead + u.cacheWrite, outputTokens: u.output, cachedTokens: u.cacheRead, model: info.model.id, at: Date.now(), source: 'sdk-response' }, 'running'); - } - output.end(result); - return; - } - round = (worker ? worker.broker : host.goalBroker ?? broker).round({inference:true}); - await store.appendEvent({ type: 'provider_prepared', id: round.id, requestId:round.id, model: model.id, bindingHash: store.hash, - purpose, ...workerFields, - ...(worker ? {imageCount:context.messages.reduce((count,message)=>count+ - (Array.isArray(message.content)?message.content.filter(item=>item.type==='image').length:0),0)} : null) }); - if (!worker) { - if (!host.compacting) requiredTool = host.requiredTool; - } - let wireCapture; - let requestBytes, promptCacheKeyPresent, headersAt, firstThinkingAt, firstTextAt, firstToolAt; - const stream = apiImpl.streamSimple(model, wireContext, { ...options, - ...(worker ? {sessionId:worker.cacheKey} : null),maxRetries:0, - apiKey: 'native-broker-only', fetch: async (...args) => { - sentAt = Date.now(); - if (worker && typeof args[1]?.body === 'string') requestBytes = Buffer.byteLength(args[1].body); - await store.appendEvent({type:'provider_started',id:round.id,requestId:round.id,...workerFields}); - host.productionSignal?.throwIfAborted(); - const response = await round.fetch(...args); - headersAt = Date.now(); - wireCapture = response.clone().text().then(text => ({ text }), error => ({ error })); - return response; - }, - onPayload: async payload => { - applyOutputContract(payload); - if (!encoded && requiredTool) selectRequiredTool(payload, requiredTool); - if (!worker && !encoded && api === 'openai-completions' && payload.tools?.length) { - payload.tool_choice ||= 'auto'; - payload.parallel_tool_calls = false; - } - if (encoded && api === 'openai-completions') payload.response_format = { type: 'json_object' }; - if (encoded && api === 'openai-responses') payload.text = { format: { type: 'json_object' } }; - // Private project evidence: BODY ONLY, never the fetch headers or API Key. - promptCacheKeyPresent = typeof payload.prompt_cache_key === 'string'; - if (!worker && process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1') { - await atomic(path.join(store.dir, 'payloads', round.id + '.json'), payload); - } - return payload; - }, - }); - let finalEvent, partial, reply = ''; - for await (const event of stream) { - if (event.type === 'thinking_delta' && firstThinkingAt === undefined) firstThinkingAt = Date.now(); - if (event.type === 'toolcall_delta' && firstToolAt === undefined) firstToolAt = Date.now(); - if (event.type === 'text_delta' && firstTextAt === undefined) firstTextAt = Date.now(); - // Release the final event only after the transport and wire audit finish. - if (event.type === 'done' || event.type === 'error') finalEvent = event; - else if (options.signal?.aborted || host.productionSignal?.aborted) continue; - else if (!encoded) output.push(event); - else if (event.type === 'start') { - partial = { ...event.partial, content: [] }; - output.push({ type: 'start', partial }); - } else if (event.type === 'text_delta' && partial) { - const raw = event.partial.content.filter(c => c.type === 'text').map(c => c.text).join(''); - const current = parseStreamingJson(raw)?.reply; - if (typeof current === 'string' && current.startsWith(reply) && current !== reply) { - if (!reply) output.push({ type: 'text_start', contentIndex: 0, partial }); - const delta = current.slice(reply.length); reply = current; - partial.content = [{ type: 'text', text: current }]; - output.push({ type: 'text_delta', contentIndex: 0, delta, partial }); - } - } - } - const result = await stream.result(); - const valid = finalEvent?.type === 'done' && (worker - ? ['stop','toolUse'].includes(result.stopReason) : host.compacting - ? result.stopReason === 'stop' && !result.content.some(content => content.type === 'toolCall') - : ['stop', 'toolUse', 'length'].includes(result.stopReason)); - const settled = await round.finish(valid, result.stopReason); - await store.appendEvent({ type: 'provider_finished', id: round.id, requestId:round.id, ...settled, - ...(worker ? {...workerFields,requestBytes,promptCacheKeyPresent} : null), - ...(options.signal?.aborted || host.productionSignal?.aborted ? {consumption:'discarded_after_cancel'} : null), - ...(sentAt === undefined ? {} : { - ...(headersAt === undefined ? {} : {responseHeadersMs:headersAt-sentAt}), - ...(firstThinkingAt === undefined ? {} : {firstThinkingMs:firstThinkingAt-sentAt}), - ...(firstTextAt === undefined ? {} : {firstTextMs:firstTextAt-sentAt}), - ...(firstToolAt === undefined ? {} : {firstToolMs:firstToolAt-sentAt}), - }) }); - if (broker?.authority?.error) throw broker.authority.error; - const failure = confirmedProductionFailure(settled, round.id); - if (failure) throw failure; - if (result.stopReason==='length' && ['complete','rejected'].includes(settled.phase)) { - if (worker) throw new ProductionOutputLimit(); - host.productionSignal?.throwIfAborted(); - options.signal?.throwIfAborted(); - const message={...result,content:result.content.filter(block=>block.type!=='toolCall')}; - output.push({type:'done',reason:'length',message}); - output.end(message); - return; - } - if (!valid || settled.phase !== 'complete') throw Error(result.errorMessage ?? 'network error: inference stream did not complete'); - const wire = await wireCapture; - if (!wire || wire.error) throw Error('network error: incomplete inference receipt, tool was not executed'); - const usage = responseUsage(wire.text); - await store.appendEvent({ type: 'usage', id: round.id, model: model.id, purpose, ...workerFields, ...usage }); + options.signal?.throwIfAborted(); + if (host.compromised) throw Error('本地会话锁失效,已停止模型调用'); + const encoded = !worker && protocolMode === 'structured-json' && !host.compacting; + const wireContext = encoded ? jsonToolContext(context) : context; + if (!worker) { + const {textChars: inputChars, totalChars} = contextLengths(wireContext); + if (!host.compacting) await host.updateContextUsage(null, 'running'); + host.rounds++; + if (host.callBudget !== undefined && host.rounds > host.callBudget) throw Error(`本轮已达${host.callBudget}次调用预算,停止继续调用`); + await store.appendEvent({ type: 'context_budget', inputChars, originalChars: encoded ? contextLengths(context).totalChars : totalChars }); + } + if (transport?.stream) { + const stream = transport.stream(model, wireContext, options); + for await (const event of stream) output.push(event); + const result = await stream.result(); + if (!worker && !host.compacting && !['error','aborted'].includes(result.stopReason)) { + await host.recordUsage(result, {purpose}); + } + output.end(result); + return; + } + round = (worker ? worker.broker : host.goalBroker ?? broker).round(); + const requiredTool = !worker && !host.compacting ? host.requiredTool : null; + let requestBytes, promptCacheKeyPresent, sentAt, headersAt, firstTextAt; + const stream = apiImpl.streamSimple(model, wireContext, { ...options, + ...(worker ? {sessionId:worker.cacheKey} : null),maxRetries:0, + apiKey: 'native-broker-only', fetch: async (...args) => { + sentAt=Date.now(); + if (typeof args[1]?.body === 'string') requestBytes = Buffer.byteLength(args[1].body); + await store.appendEvent({type:'provider_started',id:round.id,...workerFields,requestBytes}); host.productionSignal?.throwIfAborted(); - options.signal?.throwIfAborted(); - await onEvent({ type: 'usage', id: round.id, model: model.id, ...usage }); - if (!worker && !host.compacting) await host.updateContextUsage({ ...usage, id: round.id, model: model.id, at: Date.now(), source: 'provider-response' }, 'running'); - const audit = auditResponse(wire.text, info.model.protocol); - if (worker && result.content.filter(item=>item.type==='toolCall').length!==audit.calls.length) throw new InvalidToolReply('原模型工具调用未完整返回'); - host.productionSignal?.throwIfAborted(); - options.signal?.throwIfAborted(); - if (!encoded && requiredTool && !audit.calls.some(c => c.name === requiredTool)) throw Error('模型未返回要求的标准函数调用;本轮操作未执行,不会自动改用其他协议'); - if (!host.compacting && requiredTool) host.requiredTool = null; - if (encoded) { - const content = decodeToolReply(result.content.filter(c => c.type === 'text').map(c => c.text).join(''), context, round.id); - const message = { ...result, content, stopReason: content.some(c => c.type === 'toolCall') ? 'toolUse' : 'stop' }; - if (!partial) output.push({ type: 'start', partial: message }); - if (reply) output.push({ type: 'text_end', contentIndex: 0, content: reply, partial: message }); - output.push({ type: 'done', reason: message.stopReason, message }); output.end(message); - } else { output.push(finalEvent); output.end(result); } + const response=await round.fetch(...args); + headersAt=Date.now(); + return response; + }, + onPayload: async payload => { + applyOutputContract(payload); + if (!encoded && requiredTool) selectRequiredTool(payload, requiredTool); + if (!worker && !encoded && api === 'openai-completions' && payload.tools?.length) { + payload.tool_choice ||= 'auto'; + payload.parallel_tool_calls = false; + } + if (encoded && api === 'openai-completions') payload.response_format = { type: 'json_object' }; + if (encoded && api === 'openai-responses') payload.text = { format: { type: 'json_object' } }; + // Private project evidence: BODY ONLY, never the fetch headers or API Key. + promptCacheKeyPresent = typeof payload.prompt_cache_key === 'string'; + if (!worker && process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1') { + await atomic(path.join(store.dir, 'payloads', round.id + '.json'), payload); + } + return payload; + }, + }); + let finalEvent, partial, reply = ''; + for await (const event of stream) { + if (event.type === 'text_delta') firstTextAt??=Date.now(); + if (event.type === 'done' || event.type === 'error') finalEvent = event; + else if (options.signal?.aborted || host.productionSignal?.aborted) continue; + else if (!encoded) output.push(event); + else if (event.type === 'start') { + partial = { ...event.partial, content: [] }; + output.push({ type: 'start', partial }); + } else if (event.type === 'text_delta' && partial) { + const raw = event.partial.content.filter(c => c.type === 'text').map(c => c.text).join(''); + const current = parseStreamingJson(raw)?.reply; + if (typeof current === 'string' && current.startsWith(reply) && current !== reply) { + if (!reply) output.push({ type: 'text_start', contentIndex: 0, partial }); + const delta = current.slice(reply.length); reply = current; + partial.content = [{ type: 'text', text: current }]; + output.push({ type: 'text_delta', contentIndex: 0, delta, partial }); + } + } + } + const result = await stream.result(); + const {stopReason}=result; + await store.appendEvent({type:'provider_finished',id:round.id,stopReason,...workerFields,requestBytes,promptCacheKeyPresent, + ...(headersAt===undefined?{}:{responseHeadersMs:headersAt-sentAt}), + ...(firstTextAt===undefined?{}:{firstTextMs:firstTextAt-sentAt}), + ...(options.signal?.aborted||host.productionSignal?.aborted?{consumption:'discarded_after_cancel'}:{})}); + if (broker?.authority?.error) throw broker.authority.error; + if (['error','aborted'].includes(stopReason)) { + result.errorMessage=redactText(result.errorMessage??''); + output.push(finalEvent); + output.end(result); + return; + } + host.productionSignal?.throwIfAborted(); + options.signal?.throwIfAborted(); + await host.recordUsage(result, {id:round.id,purpose,...workerFields}, !worker&&!host.compacting); + if (stopReason==='length') { + output.push(finalEvent); + output.end(result); + return; + } + if (requiredTool && !result.content.some(block=>block.type==='toolCall'&&block.name===requiredTool)) { + throw Error('模型未返回要求的标准函数调用;本轮操作未执行,不会自动改用其他协议'); + } + if (requiredTool) host.requiredTool = null; + if (encoded) { + const content = decodeToolReply(result.content.filter(c => c.type === 'text').map(c => c.text).join(''), context, round.id); + const message = { ...result, content, stopReason: content.some(c => c.type === 'toolCall') ? 'toolUse' : 'stop' }; + if (!partial) output.push({ type: 'start', partial: message }); + if (reply) output.push({ type: 'text_end', contentIndex: 0, content: reply, partial: message }); + output.push({ type: 'done', reason: message.stopReason, message }); output.end(message); + } else { output.push(finalEvent); output.end(result); } } catch (error) { const reason = redactText(String(error.message)); - const message = { role: 'assistant', api, provider: 'jiansun-native-98k', model: info.model.id, content: [], stopReason: 'error', errorMessage: error instanceof ProductionRequestFailed && error.httpStatus ? String(error.httpStatus)+' '+reason : reason, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } }, timestamp: Date.now() }; + const message = { role: 'assistant', api, provider: 'jiansun-native-98k', model: info.model.id, content: [], stopReason: options.signal?.aborted || host.productionSignal?.aborted ? 'aborted' : 'error', errorMessage: reason, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } }, timestamp: Date.now() }; await store.appendEvent({ type: 'provider_error', id: round?.id, ...workerFields, reason: message.errorMessage, ...(options.signal?.aborted || host.productionSignal?.aborted ? {status:'cancelled',consumption:'discarded_after_cancel'} : null) }); - output.push({ type: 'error', reason: 'error', error: message }); output.end(message); + output.push({ type: 'error', reason: message.stopReason, error: message }); output.end(message); } })(); return output; @@ -584,17 +524,18 @@ 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), + includeGoal: !!productionGoal, systemPrompt: productionGoal ? PRODUCTION_SYSTEM : SYSTEM, }); host.localSkillFiles = new Set(loader.getSkills().skills.map(skill=>path.normalize(skill.filePath))); const { session } = await createAgentSession({ cwd: files.cwd, agentDir: store.dir, modelRuntime: runtime, model: runtime.getModel('jiansun-native-98k', info.model.id), thinkingLevel: reasoning ? info.thinkingLevel ?? undefined : undefined, - resourceLoader: loader, customTools, tools: photoCraftToolAllowlist(customTools, productionGoal ? ['get_goal'] : []), + resourceLoader: loader, customTools, tools: photoCraftToolAllowlist(customTools, productionGoal ? ['get_goal','update_goal'] : []), settingsManager: SettingsManager.inMemory({retry}), sessionManager: host.manager, }); const workerSettings = SettingsManager.inMemory({retry,cacheWarming:'off',compaction:{enabled:false},enableSkillCommands:false}); @@ -652,6 +593,7 @@ export class DetailPiAgent { await workerSession.sendCustomMessage({customType:'photocraft-worker-task',content,display:false},{triggerTurn:true}); activeSignal?.throwIfAborted(); const result = workerSession.messages.findLast(message=>message.role==='assistant'); + if (result?.stopReason==='length') throw Error('模型回复达到单次输出长度,当前制作步骤未完成'); if (result?.stopReason==='error'||result?.stopReason==='aborted') { throw Error(result.errorMessage||'当前制作步骤未完成'); } @@ -663,6 +605,15 @@ export class DetailPiAgent { await scoped?.close(); } }; + const finishTurn=session.agent.finishTurn; + session.agent.finishTurn=async (turn, signal)=>{ + const decision=await finishTurn(turn,signal); + if (turn.message.stopReason==='length' || host.productionCompletion || !host.productionGoal && + (host.canvasNotificationsDetached||host.canvasOperations.writesBlocked||host.workflowBindingChanged)) { + return {action:'end'}; + } + return decision; + }; host.session = session; session.subscribe(event => { if (event.type === 'compaction_start') host.compacting = true; @@ -748,7 +699,7 @@ export class DetailPiAgent { } if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') { const activity = toolActivity(event, host.activityScope || activityScope(store.identity)); - if (canvas) void host.notifyCanvas('activity', activitySummary(event), + if (canvas) await host.notifyCanvas('activity', activitySummary(event), activity && {...activity, presence:canvasPresence(event, activity)}).catch(()=>{}); await recordToolEvent(event,activity); void Promise.resolve().then(() => onEvent({ type: event.type, toolName: event.toolName, isError: event.isError ?? false, ...(activity ? { activity } : {}) })).catch(()=>{}); @@ -779,7 +730,7 @@ export class DetailPiAgent { async readWorkflowContext(args) { const epoch = this.turnEpoch; if (this.canvasNotificationsDetached) throw Error('当前项目已切换,未读取其他项目工作流'); - if (this.workflowBindingChanged) throw Error('品牌或品类已变化,请重新开始一轮对话以加载对应规则;未继续执行当前回合'); + if (this.workflowBindingChanged) throw Error(workflowBindingError); const snapshot = await this.canvas.workflowRead(args); const latest = workflowContext(snapshot, this.productIdentity); if (this.turnEpoch !== epoch) throw Error('原回合已结束,旧工作流读取不更新当前回合'); @@ -809,12 +760,14 @@ export class DetailPiAgent { const {workflow,product}=(!this.productionGoal || this.productionGoal.outputId) && this.canvas?.workflowRead ? await this.readWorkflowContext({section:'overview'}) : {workflow:this.currentWorkflow,product:this.productEvidence}; - const value=await this.store.modelContext({workflow,canvas:this.currentCanvas,...options}); + const canvas=await this.canvas?.read(); + if (canvas?.conversationActive===false) throw Error('当前项目已切换,未读取其他项目画布'); + const value=await this.store.modelContext({workflow,canvas:canvas?.context,...options}); value.currentProduct=product; if (workflow) value.currentWorkflow=workflow; if (this.productionSkills && loadKnowledge) { - const {knowledge,documents}=this.productionSkills; - value.enterpriseKnowledge={execution:knowledge.execution,sources:[...documents.values()]}; + const {execution,files}=this.productionSkills; + value.enterpriseKnowledge={execution,sources:files}; value.snapshot.rules=value.snapshot.rules.filter(rule=>/原稿画布|源模板约束/.test(rule)); return value; } @@ -854,6 +807,15 @@ export class DetailPiAgent { if (this.canvasOperations.stopReason) reply += `\n\n后续操作已停止。${this.canvasOperations.stopReason}`; return reply; } + async recordUsage({model,usage}, fields, updateContext=true) { + const {input,output,cacheRead,cacheWrite,totalTokens}=usage; + const receipt={model,inputTokens:input+cacheRead+cacheWrite,outputTokens:output, + cachedTokens:cacheRead,totalTokens,source:'sdk-response'}; + const event={type:'usage',...fields,...receipt}; + await this.store.appendEvent(event); + await this.onEvent(event); + if (updateContext) await this.updateContextUsage({...receipt,id:fields.id,at:Date.now()},'running'); + } async updateContextUsage(receipt = null, phase = 'ready') { this.contextUsage = contextSnapshot(this.store.identity, this.info.model, this.session, this.contextUsage, receipt, phase); if (phase === 'ready') { @@ -866,7 +828,6 @@ export class DetailPiAgent { return this.contextUsage; } async promptTurn(text, { requiredTool, referenceContent = [], goalContinuation = false } = {}) { - if (this.needsReopen) throw Error('原响应已恢复,请重新打开此会话;未发起新请求'); if (typeof text !== 'string' || !text.trim()) throw Error('请输入本轮要求'); text = redactText(text); const latest = this.firstTurnBrokerInfo ?? (this.broker ? await this.broker.info() : this.info); @@ -922,6 +883,9 @@ export class DetailPiAgent { } try { const production=this.productionGoal; + if (!production && (await this.canvas?.read())?.conversationActive===false) { + throw Error('当前项目已切换,本轮对话未应用到其他项目'); + } if ((!production || production.outputId) && typeof this.canvas?.workflowRead === 'function') await this.readWorkflow({ section: 'overview' }); const template=production?.template??this.productionTemplate; if (this.productionGoal && template?.enterprise) { @@ -953,20 +917,20 @@ export class DetailPiAgent { ? undefined : await unfinishedProductionTurn(this); const remaining=await closeProductionTurn(this); this.productionSignal?.throwIfAborted(); + if (this.workflowBindingChanged) throw Error(workflowBindingError); await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() }); const last = this.session.messages.filter(m => m.role === 'assistant').at(-1); - const useCompletionReceipt = last?.stopReason === 'error' && this.productionCompletion && !this.canvasOperations.writesBlocked; - if (last?.stopReason === 'aborted' || last?.stopReason === 'error' && !useCompletionReceipt) { - throw Error(last.errorMessage || '本轮未完成;保留原请求'); + if (last?.stopReason === 'aborted' || last?.stopReason === 'error') { + throw Error(last.errorMessage || '本轮对话未完成'); } if (last?.stopReason==='length') throw Error('模型输出达到线路上限,未执行未完成的工具建议'); - const resultText = useCompletionReceipt ? this.productionCompletion.text : + const resultText = this.productionCompletion?.text ?? this.canvasOperations.stopReason ?? (this.previewCancelled&&!this.previewReceipt ? '已取消本次预览,没有应用这项修改。' - : presentText(this.session.getLastAssistantText() || this.productionCompletion?.text || '')); - const textResult=this.productionGoal - ? stripProductionToolText(resultText).trim()||this.productionCompletion?.text||'' - : resultText; + : presentText(this.session.getLastAssistantText() || this.generatedCandidateReply() || this.canvasOperations.stopReason || '')); + const textResult=this.productionGoal?stripProductionToolText(resultText).trim(): + this.canvasNotificationsDetached&&last?.stopReason==='toolUse' + ? resultText+'\n\n原项目已切换,后续画布操作已停止。' : resultText; if (!textResult.trim()) throw Error('模型没有返回正文,请更换模型后再试;本轮工具结果已保留'); await this.display.flush(); await this.updateContextUsage(null, 'ready'); @@ -1030,86 +994,6 @@ export class DetailPiAgent { return result; }); } - async recover(id, options = {}) { return this.exclusive(() => this.recoverTurn(id, options)); } - async recoverTurn(id, { executeReadOnly = false } = {}) { - if (this.session.isStreaming) throw Error('先等待当前操作结束'); - const purpose = await requestPurpose(this, id); - if (['whole-detail-worker','product-goal','whole-detail-review'].includes(purpose)) { - const original=await recoverProductionResponse(this.broker,id,this.session.model,[]); - const {requestId}=original; - const phase=['failed','rejected'].includes(original.phase)?'failed':original.phase==='complete'?'complete':'unknown'; - if (phase==='unknown' && original.recoveryError) { - await this.store.appendEvent({type:'recovery_unknown',id,requestId,reason:original.recoveryError.message}); - } - return {phase,requestId,reposted:false,canvasWrites:0,...(phase==='complete'&&purpose==='whole-detail-review' - ?{restoredText:'已核查原验图结果,制作会从对应图位继续。'}:null)}; - } - const internalCompaction = ['compaction','legacy-compaction'].includes(purpose); - let record = { id, ...await this.broker.read(id) }; - if (record.phase === 'unknown' || record.phase === 'dispatched') { - try { await this.broker.recover(id); } - catch (error) { - await this.store.appendEvent({ type: 'recovery_unknown', id, requestId: record.requestId, reason: error.message }); - return { phase: 'unknown', requestId: record.requestId, reason: error.message, reposted: false, internalCompaction }; - } - record = { id, ...await this.broker.read(id) }; - } - if (purpose === 'cancelled') { - const receipt = record.phase === 'received' - ? await confirmProductionResponse(this.broker, record, this.session.model, this.session.agent.state.tools, this.protocolMode) - : record; - const phase = ['failed','rejected'].includes(receipt.phase) ? 'failed' : receipt.phase === 'complete' ? 'complete' : 'unknown'; - return {phase,requestId:receipt.requestId,reposted:false,toolsExecuted:0,canvasWrites:0,consumption:'discarded_after_cancel'}; - } - if (internalCompaction) { - return {phase:['complete','received','failed','rejected'].includes(record.phase)?'complete':'unknown', - requestId:record.requestId,reposted:false,internalCompaction:true,toolsExecuted:0,canvasWrites:0}; - } - if (record.phase === 'failed') return { phase: 'failed', requestId: record.requestId, reposted: false }; - if (record.phase === 'unavailable') return {phase: 'unknown', requestId: record.requestId, reposted: false, - needsManualReview: true, reason: '原对话结果不可用,保留待核查,未自动放弃或重发', toolsExecuted: 0, canvasWrites: 0}; - const message = await parseReceipt(record, this.session.model, this.protocolMode, this.session.agent.state.tools); - if (record.phase === 'received') await this.broker.confirm(id, record.bodyHash, true, message.stopReason); - if (message.stopReason === 'length') return { phase: 'complete', usable: false, reason: 'output_limit', toolsExecuted: 0, reposted: false }; - const entries = this.manager.getEntries(), calls = message.content.filter(c => c.type === 'toolCall'); - const recorded = message.responseId && entries.some(e => e.type === 'message' && e.message.role === 'assistant' && e.message.responseId === message.responseId); - const completed = calls.every(call => entries.some(e => e.type === 'message' && e.message.role === 'toolResult' && e.message.toolCallId === call.id)); - if (recorded && completed) return { phase: 'complete', requestId: record.requestId, alreadyApplied: true, reposted: false }; - if (calls.length && executeReadOnly && calls.every(call => ['context_read', 'memory_search', 'canvas_read', 'workflow_read'].includes(call.name))) { - const last = this.manager.getEntries().filter(e => e.type === 'message').at(-1); - if (!recorded && last?.message.role === 'assistant' && ['error', 'aborted'].includes(last.message.stopReason)) this.manager.appendContextEdit(last.id, null); - if (!recorded) this.manager.appendMessage(message); - if (this.canvas) await this.canvas.begin('取回原请求,恢复只读步骤'); - let recovered = 0; - try { - for (const call of calls) { - if (entries.some(e => e.type === 'message' && e.message.role === 'toolResult' && e.message.toolCallId === call.id)) continue; - const outcome = await runToolCall(call, { tools: this.session.agent.state.tools, assistantMessage: message, context: { messages: this.session.messages, tools: this.session.agent.state.tools }, beforeToolCall: this.session.agent.beforeToolCall, afterToolCall: this.session.agent.afterToolCall }); - this.manager.appendMessage({ role: 'toolResult', toolCallId: call.id, toolName: call.name, content: outcome.result.content, isError: outcome.isError, timestamp: Date.now() }); - recovered++; - } - } finally { if (this.canvas) await this.canvas.end('原请求已取回,未重发;画布未被修改。'); } - const pending = await this.store.get('recovered-tools.json', []); - await atomic(path.join(this.store.dir, 'recovered-tools.json'), pending.map(t => t.id === id ? { ...t, phase: 'read-only-complete' } : t)); - await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() }); - this.needsReopen = true; - return { phase: 'complete', requestId: record.requestId, reposted: false, readOnlyToolsRecovered: recovered, canvasWrites: 0, reopenRequired: true }; - } - if (calls.length) { - const pending = await this.store.get('recovered-tools.json', []); - if (!pending.some(t => t.id === id)) pending.push({ id, requestId: record.requestId, phase: 'review', message }); - await atomic(path.join(this.store.dir, 'recovered-tools.json'), pending); - return { phase: 'complete', needsToolReview: true, requestId: record.requestId, reposted: false, toolsExecuted: 0 }; - } - const last = this.manager.getEntries().filter(e => e.type === 'message').at(-1); - if (last?.message.role === 'assistant' && ['error', 'aborted'].includes(last.message.stopReason)) this.manager.appendContextEdit(last.id, null); - this.manager.appendMessage(message); - this.manager.appendCustomEntry('pi-recovered-receipt', { id, requestId: record.requestId, restoredAt: Date.now() }); - await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() }); - this.needsReopen = true; - return { phase: 'complete', requestId: record.requestId, reposted: false, reopenRequired: true, toolsExecuted: 0, - restoredText: presentText(message.content.filter(c => c.type === 'text').map(c => c.text).join('\n')) }; - } async dispose() { this.disposed = true; if (this.nativeUI) this.nativeUI.active = false; diff --git a/apps/detail-agent-pi/src/candidate-review.mjs b/apps/detail-agent-pi/src/candidate-review.mjs index 67cbfcea..ebfbf195 100644 --- a/apps/detail-agent-pi/src/candidate-review.mjs +++ b/apps/detail-agent-pi/src/candidate-review.mjs @@ -25,7 +25,7 @@ export const canvasTransformArgs={ export async function reviewProductionCandidate({ canvas,runAgent,slot,candidateId,signal,copy,rule,source,adopted=false,fit,artDirection, - reviewKnowledge,liveScreenCopy, + liveScreenCopy, }) { const input=await canvas.detailImages(slot.id,candidateId,{ ...(adopted?{adopted:true}:null), @@ -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, 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, @@ -95,7 +95,6 @@ export async function reviewProductionCandidate({ '原件信息见 candidateFile,图框见 frame。requirements 是当前图位的要求,screenCopy 是实时文案。', '用 shownSubject 描述实际画面,用 shownFields 标明与文案对应的画面依据。mustRedo 和 canvasFixes 分别记录建议重做和能用画布处理的问题。裁切坐标以未裁切原图为准。', ...(guides.length?['模板要求的结构标注落点用图框内 [0,0] 到 [1000,1000] 的坐标。']:[]), - ...(reviewKnowledge.files.length?['用 read_production_knowledge 获取 knowledgeFiles 中适用的企业 Skill 和审稿规则。']:[]), '调用 review_candidate 提交结论。', ].join('\n'); const images=[input.images.at(-1),...originalImages,...layoutImages]; @@ -103,7 +102,7 @@ export async function reviewProductionCandidate({ '同款实拍 '+(originalReference??'P'+String(index+1).padStart(2,'0'))), ...layoutImages.map(()=> '模板构图参考')]; const scope=productRequestScope('review',candidateId); - await runAgent(slot.id,instructions,prompt,[review,...reviewKnowledge.tools],images,scope,captions,signal); + await runAgent(slot.id,instructions,prompt,[review],images,scope,captions,signal); signal?.throwIfAborted(); if(!receipt)throw new InvalidToolReply('独立验图未提交结论'); return {...receipt,referenceCount,...(input.candidateFile?{original:input.candidateFile}:null)}; diff --git a/apps/detail-agent-pi/src/context-usage.mjs b/apps/detail-agent-pi/src/context-usage.mjs index 73df7938..8edb2ffd 100644 --- a/apps/detail-agent-pi/src/context-usage.mjs +++ b/apps/detail-agent-pi/src/context-usage.mjs @@ -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 diff --git a/apps/detail-agent-pi/src/copy-image-alignment.mjs b/apps/detail-agent-pi/src/copy-image-alignment.mjs index c3522ff9..ac597780 100644 --- a/apps/detail-agent-pi/src/copy-image-alignment.mjs +++ b/apps/detail-agent-pi/src/copy-image-alignment.mjs @@ -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); @@ -16,15 +12,14 @@ function screenCopyRow(row) { return {field:fieldId(row),label:row.label,role:row.role,text:row.currentText,templateSample:Boolean(row.templateSample)}; } -export function resolveLiveSlotCopy({slot,copyFields=[],pages=[],journalCopy=[]}) { +export function resolveLiveSlotCopy({slot,copyFields=[],journalCopy=[]}) { const slotIds=[slot.fieldId,slot.id].filter(Boolean); const directJournal=journalCopy.filter(row=>slotIds.some(id=>belongsTo(row.pictures,id))); const journalByField=new Map(directJournal.map(row=>[fieldId(row),row])); const isDirect=row=>journalByField.has(fieldId(row))|| slotIds.some(id=>belongsTo(row.relatedFields,id))||belongsTo(slot.relatedFields,fieldId(row)); const directPage=copyFields.find(row=>isDirect(row)&&fieldPage(row)); - const page=slot.page??slot.pageId??slot.documentId??(directPage&&fieldPage(directPage))?? - pages.find(id=>slot.fieldId?.startsWith(id+'-')||slot.fieldId?.startsWith(id+'_')); + const page=slot.page??slot.pageId??slot.documentId??(directPage&&fieldPage(directPage)); const liveFields=new Set(copyFields.map(fieldId)); const resolved=new Map(); for(const row of copyFields){ diff --git a/apps/detail-agent-pi/src/desktop-host.mjs b/apps/detail-agent-pi/src/desktop-host.mjs index 1a0d1184..b6210b17 100644 --- a/apps/detail-agent-pi/src/desktop-host.mjs +++ b/apps/detail-agent-pi/src/desktop-host.mjs @@ -138,7 +138,6 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o } let host, broker, store, output, atomic, heartbeat; let releaseRecovery; - const historical = config.mode==='recover'||config.mode==='review'; const productionGoal=config.mode==='prompt'&&config.productProduction===true ? {outputId:config.outputId,variantId:config.variantId,requestedOutputs:config.requestedOutputs, pendingOutputs:config.pendingOutputs,drafts:config.productionDrafts,workspaceId:config.workspaceId,template:config.productionTemplate, @@ -156,7 +155,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o const blocked = productionGoalPreflight(productionGoal); if (blocked) return blocked; } - const modelRole=config.mode==='recover'?config.modelRole||'chat':productionGoal?'detail':'chat'; + const modelRole=productionGoal?'detail':'chat'; const bindingConfig={binary:config.binary,profile:config.profile,project:config.project,scope:config.scope,modelRole, dispatchLease:config.dispatchLease,onAuthorizationLost}; broker=sharedBroker??new Native98kBroker(bindingConfig); @@ -173,8 +172,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o store = await storage.ProjectStore.open(config.root, { scope: config.scope, project: config.project }, binding, { continuous:true }); signal?.throwIfAborted(); broker.bind(bindingConfig); - const info = await broker.info(config.mode==='recover'?{original:true,id:config.productionOriginals?.[0]} - :productionGoal&&!config.goalUserEntry?{reuseDetailSelection:true}:undefined); + const info = await broker.info(productionGoal&&!config.goalUserEntry?{reuseDetailSelection:true}:undefined); const brokerReadyAt = performance.now(); if (info.accountScope !== config.scope) throw authorityFailure('scope_changed'); store.executionScope={runId:config.runId ?? randomUUID(),outputId:config.outputId,variantId:config.variantId, @@ -197,47 +195,11 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o host.qaNativeTimeout = command => consumeQaNativeTimeout({scope:info.accountScope, project:config.project, documentId:config.documentId, accountId:host.canvas.identity?.accountId, origin:host.canvas.identity?.origin}, command); signal?.throwIfAborted(); - let result; - if(config.mode==='recover' && (config.productionOriginals?.length || - info.pending.length && info.pending.every(request=>typeof request.detailSlot==='string'))){ - const settled=[]; - const originals=config.productionOriginals ?? info.pending.map(request=>request.id); - for(const id of new Set(originals)){ - signal?.throwIfAborted(); - try { - const checked=await host.recover(id,{executeReadOnly:false}); - settled.push({id,phase:checked.phase}); - } catch (error) { - signal?.throwIfAborted(); - await store.appendEvent({type:'production_original_check_failed',id,category:BridgeError.from(error).category}); - settled.push({id,phase:'unknown'}); - } - } - const remaining=settled.filter(request=>request.phase==='unknown').length; - result={phase:remaining?'unknown':'complete',reposted:false,canvasWrites:0, - settledOriginalIds:settled.filter(request=>request.phase==='complete'||request.phase==='failed').map(request=>request.id), - text:'已核查 '+settled.length+' 条制作原请求,'+remaining+' 条仍待核查。'}; - } else if (config.mode === 'recover') { - const pending = info.pending; - if (pending.length !== 1) throw Error('待核查请求数量异常,请保留项目和请求号'); - result = await host.recover(pending[0].id, { executeReadOnly: false }); - result.text = result.phase === 'unknown' ? `原请求仍待核查(${result.requestId || pending[0].id}),未重发。` - : result.internalCompaction ? '已核对旧摘要的请求记录。需要时,小壹会整理这段对话。' - : result.phase === 'failed' ? '已确认这条请求失败。你可以在原对话发送新消息。' - : result.needsToolReview ? '原响应已取回。画布建议尚待核对,未自动执行。' : '原响应已取回,未重新调用模型。'; - if (result.restoredText) result.text += '\n\n' + result.restoredText; - } else if (config.mode === 'review') { - const pending = await store.get('recovered-tools.json', []); - // Acknowledge/discard recovered mutation proposals. Never replay them. - await atomic(path.join(store.dir, 'recovered-tools.json'), pending.map(t => t.phase === 'review' ? { ...t, phase: 'discarded', reviewedAt: Date.now() } : t)); - result = { text: '已放弃原响应中的未执行建议;已完成的修改保留。', reposted: false }; - } else result = await host.prompt(config.text, { referenceContent: config.referenceContent, goalContinuation: !!productionGoal&&!config.goalUserEntry }); + const result = await host.prompt(config.text, {referenceContent:config.referenceContent,goalContinuation:!!productionGoal&&!config.goalUserEntry}); signal?.throwIfAborted(); if (broker.authority?.error) throw broker.authority.error; - const pending = historical?(await broker.status()).pending:[]; - const reviews = historical?(await store.get('recovered-tools.json', [])).filter(t => t.phase === 'review'):[]; - output = { ...result, unknown: pending.length > 0, review: reviews.length > 0, usage, contextUsage: host.contextUsage, - pending, bindingHash: store.hash, sessionFile: host.manager.getSessionFile() }; + output = {...result,unknown:false,usage,contextUsage:host.contextUsage, + pending:[],bindingHash:store.hash,sessionFile:host.manager.getSessionFile()}; } catch (error) { const authority = [signal?.reason, broker?.authority?.error, error].find(authorityLost); if (authority) { @@ -252,15 +214,10 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o } catch { /* The paused receipt reports the actual draft write outcome. */ } } return {phase:'paused', draftSaved, error:authority.message, failure:authority.wire(), - unknown:broker?.hasUnconfirmedRequest ?? false, reposted:false}; - } - let pending = [], unknown = false; - if (historical && broker) { - try { pending = (await broker.status()).pending; unknown = pending.length > 0; } - catch { unknown = broker.hasUnconfirmedRequest; } + unknown:false,reposted:false}; } const failure = BridgeError.from(error).wire(); - output = { error:failure.message, failure, unknown, pending, reposted:false, contextUsage:host?.contextUsage }; + output = {error:failure.message,failure,unknown:false,pending:[],reposted:false,contextUsage:host?.contextUsage}; } finally { clearInterval(heartbeat); signal?.removeEventListener('abort',abort); diff --git a/apps/detail-agent-pi/src/enterprise-context.mjs b/apps/detail-agent-pi/src/enterprise-context.mjs index 79419765..8062da80 100644 --- a/apps/detail-agent-pi/src/enterprise-context.mjs +++ b/apps/detail-agent-pi/src/enterprise-context.mjs @@ -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; diff --git a/apps/detail-agent-pi/src/enterprise-skill-resources.mjs b/apps/detail-agent-pi/src/enterprise-skill-resources.mjs index 877cee14..d338fff8 100644 --- a/apps/detail-agent-pi/src/enterprise-skill-resources.mjs +++ b/apps/detail-agent-pi/src/enterprise-skill-resources.mjs @@ -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,19 @@ 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:'发布资源'}); + } + } + + for (const {path:relative} of knowledge.referenceSources ?? []) { + if (!validPath(relative)) throw Error('已发布的规则资源路径无效:' + relative); + if (!references.has(filePath(relative))) references.set(filePath(relative), {target:relative,from:'发布资源'}); + } const scriptSources = new Map(); for (const source of knowledge.scriptSources ?? []) { @@ -85,10 +100,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 +112,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 +140,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 +157,22 @@ 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, + execution:knowledge.execution, + get sources() { + return [...knowledge.skills,...knowledge.rules] + .map(({fileId,revision,path,kind})=>({fileId,revision,path,kind})); + }, + get files() { + const sources=new Map(this.sources.map(source=>[source.path,source])); + for (const source of knowledge.referenceSources ?? []) { + if (!sources.has(source.path)) sources.set(source.path,source); + } + return [...sources.values()].map(source=>({...source,path:filePath(source.path)})); + }, + resource, documents, resolveFile, shellFiles, + }; } diff --git a/apps/detail-agent-pi/src/native-bridge.mjs b/apps/detail-agent-pi/src/native-bridge.mjs index 8fda5d71..0a01195f 100644 --- a/apps/detail-agent-pi/src/native-bridge.mjs +++ b/apps/detail-agent-pi/src/native-bridge.mjs @@ -34,8 +34,6 @@ export class Native98kBroker { } if(!['chat','copy','detail'].includes(modelRole))throw Error('模型用途无效'); Object.assign(this, { binary, profile, project, modelRole, invocationHeaders, spawnProcess }); - this.potentiallyDispatched = new Set(); - this.dispatchScopes = new Map(); this.children = new Set(); this.authority = {}; } @@ -50,16 +48,13 @@ export class Native98kBroker { return worker; } bind({ binary, profile, project, scope, modelRole = 'chat', dispatchLease, onAuthorizationLost }) { - if (this.active || this.closed || this.failed) throw Error('模型桥状态不可复用,未派发新请求'); + if (this.active || this.closed) throw Error('模型桥状态不可复用,未派发新请求'); if (binary !== this.binary || profile !== this.profile || !/^[a-f0-9-]{36}$/i.test(project) || typeof scope !== 'string' || !scope) throw Error('模型桥账户或项目配置不匹配'); if(!['chat','copy','detail'].includes(modelRole))throw Error('模型用途无效'); this.project = project; this.scope = scope; this.modelRole=modelRole; this.invocationHeaders = {}; this.selectionId = undefined; this.authority = { onAuthorizationLost }; this.dispatchLease = dispatchLease; - const identity = JSON.stringify([scope, project]); - if (!this.dispatchScopes.has(identity)) this.dispatchScopes.set(identity, new Set()); - this.potentiallyDispatched = this.dispatchScopes.get(identity); } revoke(error, notify = true) { if (!this.authority.error) { @@ -68,7 +63,11 @@ export class Native98kBroker { } } async open(signal) { - if (this.failed) throw this.failed; + if (this.failed) { + await this.exited; + this.child = null; + this.failed = null; + } if (this.closed || this.parent?.closed) throw Error('模型桥已关闭'); if (this.child) return; let local; @@ -94,9 +93,8 @@ export class Native98kBroker { let value; try { value = JSON.parse(line); } catch { fail(); return; } const active = this.active; - if (!active || !value || !['headers', 'chunk', 'result', 'error'].includes(value.type) || (value.type === 'error' && typeof value.error !== 'string') || (value.type === 'result' && (!value.value || typeof value.value !== 'object')) || (['headers', 'chunk'].includes(value.type) && !['request', 'recover'].includes(active.method))) { fail(); return; } + if (!active || !value || !['headers', 'chunk', 'result', 'error'].includes(value.type) || (value.type === 'error' && typeof value.error !== 'string') || (value.type === 'result' && (!value.value || typeof value.value !== 'object')) || (['headers', 'chunk'].includes(value.type) && active.method !== 'request')) { fail(); return; } if (value.type === 'headers' && value.status === 401) { - if (active.method === 'request') this.potentiallyDispatched.delete(active.requestId); this.revoke(authorityFailure('auth_revoked', {dispatched:true})); } try { active.onEvent(value); } catch { fail(); return; } @@ -105,10 +103,7 @@ export class Native98kBroker { if (value.type === 'error') { const error = new BridgeError(value.error, value.category, value); if (authorityLost(error)) this.revoke(error); - if (active.method === 'request' && value.dispatched === false) { - this.potentiallyDispatched.delete(active.requestId); - error.retryPreparation = value.retryPreparation === true; - } + error.retryPreparation = value.retryPreparation === true; active.reject(error); } else if (value.value && typeof value.value === 'object') active.resolve(value.value); @@ -127,39 +122,30 @@ export class Native98kBroker { const authority = this.authority; const run = async () => { signal?.throwIfAborted(); - const needsAuthority = !['status','read','finish'].includes(method); if (authority !== this.authority) throw authorityFailure('scope_changed'); - if (needsAuthority && authority.error) throw authority.error; + if (authority.error) throw authority.error; await this.open(signal); signal?.throwIfAborted(); if (authority !== this.authority) throw authorityFailure('scope_changed'); - if (needsAuthority && authority.error) throw authority.error; + if (authority.error) throw authority.error; if (this.failed) throw this.failed; if (this.closed) throw Error('模型桥已关闭'); return new Promise((resolve, reject) => { this.active = { resolve, reject, onEvent, method, requestId: args.id }; - if (method === 'request' && args.id && args.inference !== true) this.potentiallyDispatched.add(args.id); try { this.child.stdin.write(JSON.stringify({ ...args, method, project: this.project, accountScope: this.scope, ...(this.modelRole==='chat'?{}:{modelRole:this.modelRole}), ...(this.detailSlot?{detailSlot:this.detailSlot}:{}), dispatchLease:this.dispatchLease }) + '\n', error => { - if (error && this.active) { this.failed = Error('模型桥连接中断;请核查原请求,不会重发'); const active = this.active; this.active = null; active.reject(this.failed); this.child.kill(); } - }); } catch { this.failed = Error('模型桥连接中断;请核查原请求,不会重发'); this.active = null; reject(this.failed); this.child.kill(); } + if (error && this.active) { this.failed = Error('network error: 模型桥连接中断'); const active = this.active; this.active = null; active.reject(this.failed); this.child.kill(); } + }); } catch { this.failed = Error('network error: 模型桥连接中断'); this.active = null; reject(this.failed); this.child.kill(); } }); }; const result = (this.queue || Promise.resolve()).then(run); this.queue = result.catch(() => {}); - const value = await result; - if ((['finish', 'recover'].includes(method) && ['complete', 'rejected', 'failed'].includes(value.phase)) - || (method === 'request' && value.phase === 'failed' && value.failureCode === 'rate_limit_exceeded')) { - this.potentiallyDispatched.delete(args.id); - } - return value; + return result; } - get hasUnconfirmedRequest() { return this.potentiallyDispatched.size > 0; } - isUnconfirmed(id) { return this.potentiallyDispatched.has(id); } async close({ force = false } = {}) { this.closed = true; const children = [...this.children].map(worker => worker.close({ force })); const active = this.active; - if (active) { this.active = null; active.reject(Error('模型桥已关闭,原请求需核查;不会重发')); } + if (active) { this.active = null; active.reject(Error('模型桥已关闭')); } if (this.child) { if (active || force) this.child.kill(); else this.child.stdin.end(); @@ -169,7 +155,6 @@ export class Native98kBroker { await Promise.all(children); this.parent?.children.delete(this); } - status() { return this.start('status'); } async info(args) { const info = await this.start('info', args); if (this.scope && info.accountScope !== this.scope) { @@ -182,12 +167,13 @@ export class Native98kBroker { this.selectionId = info.selectionId ?? undefined; return info; } - /** A new fetch object for ONE provider request. It refuses all implicit retries. */ - round({ inference = false } = {}) { + /** One native request per Pi attempt. */ + round() { const id = randomUUID(); - let calls = 0, metadata, completed; + let sent = false; const fetch = async (address, init = {}) => { - if (++calls !== 1) throw Error('禁止自动重发模型请求'); + if (sent) throw Error('每次模型调用只接受一个请求'); + sent = true; init.signal?.throwIfAborted(); const url = new URL(typeof address === 'string' || address instanceof URL ? address : address.url); if (url.origin !== 'https://api.vip98k.com' || !['/v1/messages', '/v1/chat/completions', '/v1/responses'].includes(url.pathname) || init.method?.toUpperCase() !== 'POST' || typeof init.body !== 'string') throw Error('模型请求边界无效'); @@ -197,23 +183,17 @@ export class Native98kBroker { let cancelled = false; const enqueue = data => { if (!cancelled) { try { controller.enqueue(data); } catch { cancelled = true; } } }; const request = () => this.start('request', { id, body: init.body, invocationPath: url.pathname, invocationHeaders: this.invocationHeaders, - selectionId: this.selectionId, ...(inference ? { inference:true } : {}) }, event => { + selectionId: this.selectionId }, event => { if (event.type === 'headers') { - metadata = event; resolveHeaders(new Response(body, { status: event.status, headers: event.headers })); } else if (event.type === 'chunk') enqueue(Buffer.from(event.data, 'base64')); }, init.signal); - if (inference && this.failed) { - await this.exited; - this.child = null; - this.failed = null; - } const abort = () => { if (!this.authority.error && this.active?.requestId === id) this.child?.kill(); }; init.signal?.addEventListener('abort', abort, {once:true}); - completed = request().catch(error=>{ - if (inference && (error.retryPreparation || /^98k(?:连接|响应)中断/u.test(error.message))) { + const completed = request().catch(error=>{ + if (error.retryPreparation || /^98k(?:连接|响应)中断$/u.test(error.message)) { throw Error('network error: '+error.message); } throw error; @@ -224,21 +204,8 @@ export class Native98kBroker { }); return ready; }; - return { - id, fetch, - finish: async (valid, reason) => { - if (!completed) return { phase: 'not_dispatched' }; - const result = await completed; - if (inference) return result; - if (result.phase === 'failed' && result.failureCode === 'rate_limit_exceeded') return result; - if (result.phase !== 'received') throw Error(`请求 ${id} 结果未知;不会重发`); - return this.start('finish', { id, bodyHash: metadata.bodyHash, valid, reason }); - }, - }; + return {id,fetch}; } - read(id) { return this.start('read', { id }); } - recover(id) { return this.start('recover', { id }); } - confirm(id, bodyHash, valid, reason) { return this.start('finish', { id, bodyHash, valid, reason }); } knowledge(brandId) { return this.start('knowledge', { brandId: brandId ?? null }); } } diff --git a/apps/detail-agent-pi/src/photocraft-extension.mjs b/apps/detail-agent-pi/src/photocraft-extension.mjs index de247f3f..6e7bcdc8 100644 --- a/apps/detail-agent-pi/src/photocraft-extension.mjs +++ b/apps/detail-agent-pi/src/photocraft-extension.mjs @@ -6,6 +6,8 @@ import { DefaultResourceLoader, SettingsManager, } from '@earendil-works/pi-coding-agent'; +import { foldSupersededProductionReads } from './context-usage.mjs'; +import { settleProductionGoal } from './production-goal.mjs'; import { createImageContextPruningExtension } from './image-context-pruning.mjs'; const sdkToolNames = Object.freeze(['codemode', 'tool_search']); @@ -30,7 +32,7 @@ export function nativeToolMetadata(name) { * Instantiate the official factories through the public SDK loader. */ export async function createPhotoCraftExtensions(host, existing = [], { - includeGoal = false, mayContinueGoal, systemPrompt = '', includeProjectResources = true, + includeGoal = false, systemPrompt = '', includeProjectResources = true, } = {}) { const cwd = host?.workingDirectory ?? host?.store?.dir; if (typeof cwd !== 'string' || !cwd) throw new TypeError('工作台未能找到制作工具的工作目录'); @@ -63,6 +65,19 @@ 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 => { + const messages = foldSupersededProductionReads(event.messages); + const isReminder = message => message.role === 'custom' && message.customType === 'pi-goal-event' && + ['active', 'resumed', 'continuation'].includes(message.details?.kind); + const latest = messages.findLast(isReminder); + if (!latest) return {messages}; + return {messages:messages.flatMap(message => message === latest + ? [{...message,content:'继续当前制作目标:'+latest.details.goal.objective}] + : isReminder(message)?[]:[message])}; + }); + if (host.productionGoal) pi.on('agent_end', event => settleProductionGoal(host,event)); + }}] : []), ], }); await loader.reload(); @@ -71,23 +86,6 @@ export async function createPhotoCraftExtensions(host, existing = [], { const cause = new Error(result.errors.map(error => `${error.path}: ${error.error}`).join('; ')); throw new Error('工作台未能加载制作工具,请重新打开客户端后重试', { cause }); } - 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沿用已完成的工作。需要事实或画布状态时按需读取,以实际文件回执确认交付。'}; - }), - })]); - // 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); - })); - } return {...result, resourceLoader: loader}; } diff --git a/apps/detail-agent-pi/src/product-copy-evidence.mjs b/apps/detail-agent-pi/src/product-copy-evidence.mjs deleted file mode 100644 index 8ee285cb..00000000 --- a/apps/detail-agent-pi/src/product-copy-evidence.mjs +++ /dev/null @@ -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 = /(? 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))])]; -} diff --git a/apps/detail-agent-pi/src/production-goal.mjs b/apps/detail-agent-pi/src/production-goal.mjs index 6828b89b..79957e79 100644 --- a/apps/detail-agent-pi/src/production-goal.mjs +++ b/apps/detail-agent-pi/src/production-goal.mjs @@ -1,12 +1,11 @@ import fs from 'node:fs/promises'; import path from 'node:path'; import lockfile from 'proper-lockfile'; -import { productionKnowledge } from './production-knowledge.mjs'; -import { SessionManager } from '@earendil-works/pi-coding-agent'; +import { createAgentSession, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent'; import { imageResult, openProductionOperations, productionOperationTools, reconcileProjectImageSlots } from './production-operations.mjs'; +import { createPhotoCraftExtensions } from './photocraft-extension.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) { @@ -31,10 +30,20 @@ export async function recordProductionExport(dir, goalId) { try { const saved = JSON.parse(await fs.readFile(path.join(dir, 'session.json'), 'utf8')); const manager = SessionManager.open(path.join(dir, 'sessions', path.basename(saved.file)), dir, dir); - const entry = manager.getBranch().findLast(row => row.type === 'custom' && row.customType === 'pi-goal'); - if (entry?.data?.goal?.id !== goalId) throw Error('导出回执与当前制作目标不一致'); - if (entry.data.goal.status !== 'complete') { - manager.appendCustomEntry('pi-goal', {...entry.data, goal:{...entry.data.goal, status:'complete', updatedAt:Date.now()}}); + const goal = piGoalState(manager); + if (goal?.id !== goalId) throw Error('导出回执与当前制作目标不一致'); + if (goal.status !== 'complete') { + const host = {store:{dir}}; + const {resourceLoader} = await createPhotoCraftExtensions(host, [], { includeGoal:true, includeProjectResources:false }); + const modelRuntime = await ModelRuntime.create({ modelsPath:null, allowModelNetwork:false, refreshOnCreate:false, + authPath:path.join(dir,'pi-runtime-auth.json'), modelsStorePath:path.join(dir,'pi-model-cache') }); + const {session} = await createAgentSession({cwd:dir, agentDir:dir, modelRuntime, resourceLoader, + settingsManager:SettingsManager.inMemory({}), sessionManager:manager, tools:['update_goal']}); + try { + await session.bindExtensions({mode:'rpc'}); + session.setActiveToolsByName(['update_goal']); + await session.agent.state.tools.find(tool=>tool.name==='update_goal').execute(goalId,{status:'complete'}); + } finally { session.dispose(); } } return {recorded:true, goalId}; } finally { await unlock(); } @@ -45,7 +54,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}); @@ -59,28 +68,34 @@ export async function runPiProductionGoal(host, text, continuation, images=[]) { await host.session.prompt('/goal resume'); } await host.session.waitForIdle(); - if (host.productionPause) await host.session.prompt('/goal pause'); - if (host.productionCompletion?.receipt.completed === true) { - const entry = host.manager.getBranch().findLast(row => row.type === 'custom' && row.customType === 'pi-goal'); - if (entry) host.manager.appendCustomEntry('pi-goal', {...entry.data, - goal:{...entry.data.goal,status:'complete',updatedAt:Date.now()}}); + const end = host.session.messages.findLast(message=>message.role==='assistant'); + if (['error','aborted','length'].includes(end?.stopReason) && piGoalState(host.manager)?.status==='active') { + await host.session.prompt('/goal pause'); } } -export async function mayContinueProductionGoal(host, event) { - const messages=event?.messages??[]; +export async function settleProductionGoal(host, {messages}) { + const active=piGoalState(host.manager)?.status==='active'; + if (host.productionCompletion) { + if (active) await host.session.prompt('/goal pause'); + host.session.clearQueue(); + return; + } + if (!active) return; const end=messages.findLast(message=>message.role==='assistant'); - if(end?.stopReason==='error'||end?.stopReason==='aborted')return false; - if(host.productionSignal?.aborted||host.compacting||host.canvasNotificationsDetached||host.productionCompletion)return false; + if (['error','aborted','length'].includes(end?.stopReason)) { + host.session.clearQueue(); + return; + } const start=messages.findLastIndex(message=>message.role==='custom'&&message.customType==='pi-goal-event' && ['continuation','resumed'].includes(message.details?.kind)); - if(start===-1||!end||piGoalState(host.manager)?.status!=='active')return true; - if(messages.slice(start+1).some(message=>message.role==='toolResult'))return true; + if(start===-1||!end||messages.slice(start+1).some(message=>message.role==='toolResult'))return; const blocker=host.productionGoal.drafts?.findLast(draft=>draft.blocker)?.blocker; host.productionPause=blocker ? {reason:blocker.reason,requiredAction:blocker.requiredAction} : {reason:end.content.filter(part=>part.type==='text').map(part=>part.text).join('\n').trim()}; - return false; + await host.session.prompt('/goal pause'); + host.session.clearQueue(); } export { productionOperationTools as productionTools }; @@ -91,20 +106,22 @@ export async function callProductionTool(host, name, args, signal) { const started=performance.now(); const previous=await currentProductionOperations(host)?.catch(()=>undefined); const switched=goal.outputId!==args.outputId||goal.variantId!==args.variantId; - if(switched)await previous?.suspendCanvas(); + let binding; try { - const previousImageRequests=switched?previous?.workStatus().inFlightImages:undefined; - const binding=await host.canvas.openProductionOutput(previousImageRequests?.length + const previousImageRequests=switched?await previous?.suspendCanvas():undefined; + binding=await host.canvas.openProductionOutput(previousImageRequests?.length ?{...args,previousImageRequests}:args,signal); - const switchMs=Math.round(performance.now()-started); - if(binding.accepted===false)previous?.resumeCanvas(); - else await bindProductionOutput(host,binding); - return {...binding,switchMs,work:(await productionWork(host)).map(operations=>operations.workStatus())}; } catch(error) { if (Object.hasOwn(error,'productionCanvas')) await bindProductionOutput(host,error.productionCanvas); else previous?.resumeCanvas(); throw error; } + const switchMs=Math.round(performance.now()-started); + if(binding.accepted===false)previous?.resumeCanvas(); + else await bindProductionOutput(host,binding); + const work=await productionWork(host); + const originals=work.length?await host.canvas.imageRequest('pending',{}):[]; + return {...binding,switchMs,work:work.map(operations=>operations.workStatus(originals))}; } if (name==='list_project_images') return {candidates:await host.canvas.detailHistory({projectImages:true,...args})}; @@ -118,7 +135,6 @@ export async function callProductionTool(host, name, args, signal) { const options={targetOutput:target,...(input.candidateId&&!input.includeReferences ?{includeProductReferences:false,includeTemplateReference:false}:null)}; return imageResult({...target,...await host.canvas.detailImages(input.slotId,input.candidateId,options)}); - } if(!working&&!['plan_production','review_image_slots','await_image_slots','reconcile_image_slots','check_image_slots'].includes(name)) return {...target,accepted:false,reason:'canvas_inactive',workingOutput:goal.outputId?{ @@ -133,14 +149,9 @@ export async function callProductionTool(host, name, args, signal) { if (name==='plan_production') { const {id,name,version,productionRoute}=goal.template??{}; const {product,dimensions,note}=host.productEvidence??{}; - const knowledge=productionKnowledge(host.productionSkills?.knowledge??host.knowledgeContext); return {requestedOutputs:goal.requestedOutputs,pendingOutputs:goal.pendingOutputs, workingOutput:null,template:{id,name,version,productionRoute},product:{...product,dimensions,note}, - knowledgeFiles:knowledge.files}; - } - if (name==='read_production_knowledge') { - const knowledge=productionKnowledge(host.productionSkills?.knowledge??host.knowledgeContext); - return knowledge.tools[0]? (await knowledge.tools[0].execute('',args,signal)).details:{files:[]}; + ...(args.includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null)}; } throw Error('请先用 open_production_output 打开本轮工作画布'); } diff --git a/apps/detail-agent-pi/src/production-knowledge.mjs b/apps/detail-agent-pi/src/production-knowledge.mjs deleted file mode 100644 index d60a6056..00000000 --- a/apps/detail-agent-pi/src/production-knowledge.mjs +++ /dev/null @@ -1,55 +0,0 @@ -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 必须取自 knowledgeFiles 列表,不能传模板编号。'; - -const pageSize = 6000; -export function productionKnowledge(knowledge, stage) { - 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))); - 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{ - signal?.throwIfAborted(); - const document=documents.find(entry=>entry.fileId===fileId); - if(!document)throw Error('该文件不属于当前制作阶段使用的知识资料'); - const details=await readPage(document,offset); - signal?.throwIfAborted(); - 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&§ions.length>1 - ? sections.filter(section=>headings.test(section.split('\n',1)[0])).join('\n') - : text; - return selected.trim().slice(0,limit)||undefined; -} diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 20f7616a..1f333798 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -1,26 +1,29 @@ +import { readFileSync } from 'node:fs'; 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 { formatDimensionNote, parseFrontmatter, resizeImage } from '@earendil-works/pi-coding-agent'; import { productionLedger, recordProductionInputs } from './production-repository.mjs'; import { PresentationBatch } from './stream-presentation.mjs'; 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'; import { reviewOutputScreen } from './screen-review.mjs'; import { createTailWatcher } from './tail-watcher.mjs'; +const {frontmatter: {maxGenerationAttempts: defaultGenerationLimit}} = parseFrontmatter( + readFileSync(new URL('./skills/product-image-sources/SKILL.md', import.meta.url), 'utf8'), +); + 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,9 +45,8 @@ const recoveryNotices={ expired:'原请求结果已过期', not_executed:'原操作已确认未执行', }; -const MAX_SLOT_GENERATIONS=4; const expiryFields=receipt=>receipt?.resultExpiry? - {requestId:receipt.requestId,retryable:false,resultExpiry:receipt.resultExpiry}:{}; + {requestId:receipt.resultExpiry.requestId??receipt.requestId,retryable:false,resultExpiry:receipt.resultExpiry}:{}; function rememberImageExpiry(item,candidateId,receipt){ const expiry=expiryFields(receipt); if(!expiry.resultExpiry)return; @@ -77,13 +79,12 @@ const outputScope={outputId:optional(text),variantId:optional(text)}; export const productionOperationTools = [ ['open_production_output','打开本轮指定输出和花色。切换前保存原工程,返回保存结果、新画布绑定及各成品的在途工作。已有工作会保留。',obj({outputId:text,variantId:text})], - ['plan_production','读取商品规格、模板、图位及成品进度。可指定输出和花色,省略时读取当前工作画布。按 slotIds 读取指定图位的规则和要求。模板规则从项目 Skill 及其引用读取。pictures 中的 copyReady 表示关联字段没有待写文案。调用图位工具时优先使用 pictures 中的 fieldId。',obj({...outputScope,slotIds:optional(ids)})], - ['read_production_knowledge','读取当前阶段固定版本的制作规则,按回执的 nextOffset 翻页。'+knowledgeFileIdInstruction,obj({fileId:text,offset:optional(page)})], - ['read_copy_fields','省略 pageId 和 fieldId 可一次读取全页文案字段、当前文字及修订号。需要模板样稿与发布要求时,指定 pageId 或 fieldId 读取对应范围。',obj({ + ['plan_production','读取当前商品规格与备注、模板、图位、成品进度和本轮其它待处理输出。可指定输出和花色,省略时读取当前工作画布。按 slotIds 获取指定图位及其发布要求;includeKnowledge=true 列出固定版本的规则路径,可用 read 读取。pictures 中的 copyReady 表示关联字段没有待写文案。图位工具优先使用 fieldId,重名时使用完整 id。',obj({...outputScope,slotIds:optional(ids),includeKnowledge:optional(Type.Boolean())})], + ['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','查看指定成品图位的同款实拍、模板构图和候选。adopted=true 读取当前可写画布上的实际回填。候选只返回候选画面;需要同时查看或重新查看参考时传 includeReferences=true。',obj({ ...outputScope,slotId:slotRef,candidateId:optional(Type.String()),adopted:optional(Type.Boolean()),includeReferences:optional(Type.Boolean()), @@ -91,13 +92,13 @@ export const productionOperationTools = [ ['use_product_image','用本款原片或裁切区域创建候选。通过 adopt_production_image 回填时,放置回执会列出覆盖图位的模板叠层。',obj({slotId:slotRef,...productImageArgs})], ['transform_slot_image','在本机裁切、镜像、旋转、缩放或位移本款实拍及任一成品的同花色候选,返回新候选和像素清晰度指标。',obj({...outputScope,slotId:slotRef,...transformImageArgs})], ['prepare_image_request','保存完整生图请求,返回正式文本、参考顺序、模型参数与请求编号。'+imagePromptGuidance,obj({...outputScope,slotId:slotRef,...preparationArgs})], - ['dispatch_image_request','审阅准备回执后填写 requestId 确认派发。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。'+DRAW_LIMIT_GUIDANCE,obj({...outputScope,...dispatchArgs})], + ['dispatch_image_request','审阅准备回执后填写 requestId 确认派发。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。',obj({...outputScope,...dispatchArgs})], ['delegate_image_slots','异步分派一批图位,空闲的制作助手立即开始,其余图位顺序排队。每个 goal 写明对应屏的核心卖点与画面要证明的细节。逐图位返回接收情况及待写文案字段。生图派发后宿主继续跟踪原请求,可用 await_image_slots 查看回执。',obj({ ...outputScope,jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})), })], ['await_image_slots','等待任一在途制作、验图或生图请求返回,并读取已有回执。省略 slotIds 时也关注按屏复核,结论见 screenChecks。已返回结果未知的原请求用 reconcile_image_slots 核查。可指定成品和花色,非当前可写成品直接返回已有回执和在途状态。',obj({...outputScope,slotIds:optional(ids)})], - ['review_image_slots','只读查看指定成品和花色的候选、验图、原请求、覆盖统计与整屏复核进度。默认逐图位返回状态和尝试次数。指定 slotIds 获取候选、退回原因、原请求、验图详细结论与提示词。',obj({...outputScope,slotIds:optional(Type.Array(Type.String()))})], - ['list_project_images','列出本项目已完成且可读的候选,包括有采纳记录的图。可按来源成品和花色筛选。用候选号在当前目标图位做本地变换或复用。',obj(outputScope)], + ['review_image_slots','只读查看指定成品和花色的候选、验图、原请求、覆盖统计与整屏复核进度。默认逐图位返回状态和尝试次数。指定 slotIds 获取候选、退回原因、原请求和验图详细结论。',obj({...outputScope,slotIds:optional(Type.Array(Type.String()))})], + ['list_project_images','列出本项目已完成且可读的候选,包括有采纳记录的图。可按来源成品和花色筛选,生图次数取自宿主已派发的记录。用候选号在当前目标图位做本地变换或复用。',obj(outputScope)], ['read_archived_images','只读查找其他本机项目同款的历史候选。可选 slotIds 查看有对应图位的结果。不同模板或花色的已完成候选也可放入当前图位复核。',obj({ slotIds:optional(Type.Array(Type.String())), })], @@ -110,7 +111,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({...outputScope,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({ @@ -186,15 +187,18 @@ function slotAttempts(slot, record) { function originalCandidate(item) { if(item?.heldOriginalId)return item.heldOriginalId; const operation=item?.pendingOperation; + if(operation?.kind==='frozen-image')return undefined; + if(!operation&&item?.pendingGenerations)return undefined; if(operation&&Object.hasOwn(operation,'candidateId'))return operation.candidateId; return item?.state==='unknown'&&(!operation||!item.reason)?item.candidateId:undefined; } function slotOriginals(item) { - const originals=Object.values(item?.pendingGenerations??{}).map(frozen=>({frozen,request:frozen})); + const originals=[]; const candidateId=originalCandidate(item); - if(item?.pendingOperation||candidateId){ - originals.push({request:{...item.pendingOperation,candidateId,projectId:item.heldOriginalProjectId}}); + const operation=item?.pendingOperation?.kind==='frozen-image'?undefined:item?.pendingOperation; + if(operation||candidateId){ + originals.push({request:{...operation,candidateId,projectId:item.heldOriginalProjectId}}); } if(item?.pendingAdoption)originals.push({adopting:true,request:item.pendingAdoption}); return originals; @@ -204,35 +208,22 @@ function imageOriginals({items}) { return Object.entries(items).flatMap(([slotId,item])=>{ const originals=slotOriginals(item).map(({request:{candidateId,operationId,projectId},adopting})=> ({slotId,candidateId,operationId,projectId,adoption:adopting})); - return !originals.length&&item.state==='unknown'?[{slotId,phase:'unknown'}]:originals; + return !originals.length&&item.state==='unknown'&&!item.pendingGenerations&&item.pendingOperation?.kind!=='frozen-image' + ?[{slotId,phase:'unknown'}]:originals; }); } +async function readNativeOriginal(canvas,original,scope) { + const {slotId,candidateId,operationId}=original; + const receipt=await canvas.detailRecover(slotId,{candidateId},scope); + if(receipt.id!==candidateId)throw Error('原生回执与请求号不一致'); + const phase=settledImagePhases.includes(receipt.status)?receipt.status:'unknown'; + return {slotId,candidateId,operationId,phase,reason:receipt.message,...expiryFields(receipt)}; +} + function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{projectScope,onAdopted,onError}={}) { const detailRecover=(slotId,original)=>canvas.detailRecover(slotId,original, typeof projectScope==='function'?projectScope():projectScope); - const reconcileImageRequest=async(slot,original,signal)=>{ - const {candidateId,operationId}=original; - signal?.throwIfAborted(); - const receipt=await detailRecover(slot.id,{candidateId}); - signal?.throwIfAborted(); - const phase=receipt?.id===candidateId&&settledImagePhases.includes(receipt.status)?receipt.status:'unknown'; - if(phase!=='unknown')await update(journal=>{ - signal?.throwIfAborted(); - const item=journal.items[slot.id]; - const attempts=item.attempts??=[]; - if(!attempts.some(row=>row.candidateId===candidateId))attempts.push({candidateId,source:'generate'}); - rememberImageExpiry(item,candidateId,receipt); - if(item.pendingGenerations?.[candidateId]){ - delete item.pendingGenerations[candidateId]; - Object.assign(item,{state:phase==='complete'?'candidate':phase,candidateId,source:'generate'}); - } - },{receipt:[candidateId,phase,receipt], - evidence:[slot.id,candidateId,'candidate',{requestId:candidateId,...receipt,operationId}]}); - return {slotId:slot.id,candidateId,operationId,phase,reason:receipt?.id===candidateId?receipt.message:undefined, - ...(receipt?.id===candidateId?expiryFields(receipt):null)}; - }; - const reconcile=async(slot,signal,adopting=false)=>{ const item=readJournal().items[slot.id]; const pendingKey=adopting?'pendingAdoption':'pendingOperation'; @@ -252,7 +243,6 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p pendingOperation:null,heldGeneration:false,heldOriginalId:null,heldOriginalProjectId:null, }); },{ - ...(original?.kind==='frozen-image'?{receipt:[archivedCandidate,phase,receipt]}:null), evidence:[slot.id,archivedCandidate,'candidate',{...receipt,sourceProjectId:item.heldOriginalProjectId}], }); const reason=receipt?.id===archivedCandidate?receipt.message:undefined; @@ -290,15 +280,15 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p const reason=receipt?.id===candidateId?receipt?.message??operation.message:operation.message; return {slotId:slot.id,phase,candidateId,operationId:original.operationId,reason,...expiry}; }; - return async (slot,adopting,original,signal)=>{ + return async (slot,adopting,signal)=>{ try { - return original?await reconcileImageRequest(slot,original,signal):await reconcile(slot,signal,adopting); + return await reconcile(slot,signal,adopting); } catch(error) { signal?.throwIfAborted(); onError?.(error); const item=readJournal().items[slot.id]; - const request=original??item?.[adopting?'pendingAdoption':'pendingOperation']; - const candidateId=original||adopting?request?.candidateId:originalCandidate(item); + const request=item?.[adopting?'pendingAdoption':'pendingOperation']; + const candidateId=adopting?request?.candidateId:originalCandidate(item); return {slotId:slot.id,operationId:request?.operationId,candidateId,phase:'unknown',reason:error.message}; } }; @@ -307,8 +297,13 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p export async function reconcileProjectImageSlots(host,{slotIds},signal) { const {canvas,store,productionGoal:goal}=host; const requested=new Set(slotIds); - const results=[]; - for(const {outputId,variantId} of goal.pendingOutputs??goal.requestedOutputs){ + const outputs=goal.pendingOutputs??goal.requestedOutputs; + const pending=(await canvas.imageRequest('pending',{})).filter(row=> + outputs.some(scope=>scope.outputId===row.outputId&&scope.variantId===row.variantId) + &&(!requested.size||requested.has(row.slotId))); + const results=await Promise.all(pending.map(async row=>({outputId:row.outputId,variantId:row.variantId, + ...await readNativeOriginal(canvas,row,{outputId:row.outputId,variantId:row.variantId})}))); + for(const {outputId,variantId} of outputs){ signal?.throwIfAborted(); const ledger=productionLedger(store,outputId,variantId); let journal=ledger.read(); @@ -319,8 +314,8 @@ export async function reconcileProjectImageSlots(host,{slotIds},signal) { await ledger.publishAudit(journal); },{projectScope:{outputId,variantId}}); for(const [id,item] of slots){ - for(const {adopting,frozen} of slotOriginals(item)){ - results.push({outputId,variantId,...await recover({id},adopting,frozen,signal)}); + for(const {adopting} of slotOriginals(item)){ + results.push({outputId,variantId,...await recover({id},adopting,signal)}); } } } @@ -331,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,{target=host.productionGoal,maxActiveDelegates=6,maxGenerationAttempts=MAX_SLOT_GENERATIONS, +export async function openProductionOperations(host,{target=host.productionGoal,maxActiveDelegates=6, 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}=host; const {outputId,variantId}=target; @@ -354,11 +348,13 @@ export async function openProductionOperations(host,{target=host.productionGoal, const byId=new Map(slots.map(slot=>[slot.id,slot])); const byField=Map.groupBy(slots,slot=>slot.fieldId); const binding=JSON.stringify([plan.template.contentHash,variantId]); + const templateLimit=plan.template.production?.maxGenerationAttempts; + const maxGenerationAttempts=(Number.isSafeInteger(templateLimit)&&templateLimit>0?templateLimit:undefined) + ??host.productionSkills?.maxGenerationAttempts??defaultGenerationLimit; const ledger=productionLedger(store,outputId,variantId); const {repository}=ledger; const previous=ledger.read(); let journal=previous?.binding===binding?previous:{binding,items:{}}; - if(previous)await ledger.publishAudit(previous); const evidenceMatches=(value,record=journal)=>Object.hasOwn(record,'copyInputs') ?record.copyInputs===productionInputs(value,variantId) :record.creationRevision===value.revisions?.creation; @@ -367,10 +363,6 @@ export async function openProductionOperations(host,{target=host.productionGoal, 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 findSlot=reference=>{ const id=reference.trim(); const named=byField.get(id); @@ -393,14 +385,6 @@ export async function openProductionOperations(host,{target=host.productionGoal, } 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(); @@ -484,22 +468,21 @@ export async function openProductionOperations(host,{target=host.productionGoal, return live.slots; }; const liveSlot=async slot=>(await liveSlots()).find(row=>row.id===slot.id)??slot; - const nativeGenerations=slot=>(slot.candidates??[]).filter(row=> - !row.sourceType&&!row.reusedFrom&&row.status!=='prepared').map(row=>row.id); + const nativeGenerations=slot=>[ + ...(slot.generationRequestIds??(slot.candidates??[]).filter(row=> + !row.sourceType&&!row.reusedFrom&&row.status!=='prepared').map(row=>row.id)), + ...[...dispatchingImages].filter(([,job])=>job?.slotId===slot.id).map(([id])=>id), + ]; const drawStatus=generationAttempts=>({ generationAttempts,maxGenerationAttempts, remainingGenerationAttempts:Math.max(0,maxGenerationAttempts-generationAttempts), drawLimitReached:generationAttempts>=maxGenerationAttempts, }); - const drawStatuses=selected=>{ - const ids=new Map(selected.map(slot=>[slot.id,nativeGenerations(slot)])); - const counts=repository.countImageGenerations(binding,ids,journal.items); - return new Map([...counts].map(([id,count])=>[id,drawStatus(count)])); - }; - const slotDrawStatus=slot=>drawStatuses([slot]).get(slot.id); + const slotDrawStatus=slot=>drawStatus(new Set(nativeGenerations(slot)).size); + const drawStatuses=selected=>new Map(selected.map(slot=>[slot.id,slotDrawStatus(slot)])); 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 (canvasReady?scopedPlan():canvas.workflowRead({section:'overview',outputId})); @@ -532,9 +515,9 @@ export async function openProductionOperations(host,{target=host.productionGoal, .map(({field,label,currentText})=>({fieldId:field,label,currentText}))])); }; const liveSlotCopy=async slot=>{ - const {fields:copyFields,pages}=await copySnapshot(); + const {fields:copyFields}=await copySnapshot(); const journalCopy=Object.values(evidenceMatches(plan)?journal.copyEvidence??{}:{}); - return resolveLiveSlotCopy({slot,copyFields,pages,journalCopy}); + return resolveLiveSlotCopy({slot,copyFields,journalCopy}); }; function screenReviewRevisions(){ const inputs=productionInputs(plan,variantId); @@ -591,8 +574,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, const jobProgress={total:slots.length,rendered:filled.size, copy:copyCells.filter(row=>row.state==='verified').length, copyPending:copyCells.filter(row=>row.state!=='verified').length, - unresolved:Object.values(journal.items).filter(item=>item.pendingOperation||item.pendingAdoption|| - Object.keys(item.pendingGenerations??{}).length).length}; + unresolved:Object.values(journal.items).filter(item=>item.pendingOperation||item.pendingAdoption).length}; const category=jobs.size?'remote_image':pendingReviews().length||runningScreens().length?'inference':'canvas_read'; await store.appendEvent({type:'production_progress',category,phase:'progress',status:'running',outputId,variantId,jobProgress}); const workers=new Map(); @@ -684,18 +666,6 @@ export async function openProductionOperations(host,{target=host.productionGoal, tailWatcher.refresh(); } } - const pendingGeneration=(slot,record=journal,requestId)=>{ - const item=record.items[slot.id]; - if(requestId){ - const original=item?.pendingGenerations?.[requestId]; - return original&&{slotId:slot.id,phase:'unknown',...original,pendingOriginal:requestId}; - } - const original=item?.pendingOperation; - if (!original&&!item?.heldOriginalId&&item?.state!=='unknown') return null; - const candidateId=originalCandidate(item); - return {slotId:slot.id,phase:'unknown',operationId:original?.operationId,candidateId, - pendingOriginal:candidateId??original?.operationId}; - }; const transformImage=async(slot,{sourceCandidateId,referenceIndex,...transform},signal)=>{ signal?.throwIfAborted(); await current(); @@ -704,7 +674,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, const result={...receipt,candidateId:receipt.id,phase:'complete'}; await update(journal=>{ const item=journal.items[slot.id]??={}; - if(item.state!=='applied'&&!item.pendingOperation&&!item.pendingAdoption&&!Object.keys(item.pendingGenerations??{}).length){ + if(item.state!=='applied'&&!item.pendingOperation&&!item.pendingAdoption){ Object.assign(item,{state:'candidate',candidateId:receipt.id,source:'transform'}); } },{evidence:[slot.id,receipt.id,'candidate',receipt]}); @@ -715,143 +685,93 @@ export async function openProductionOperations(host,{target=host.productionGoal, const prepareImageRequest=async(slot,{prompt,retryOf,useTemplateReference,prefer2k,geometryReferenceIndex, referenceIndexes,useSceneComposite,reworkCandidateId,reworkChange},signal)=>{ signal?.throwIfAborted(); - const input=await current(); + await current(); const live=await liveSlot(slot); const status=slotDrawStatus(live); if(status.drawLimitReached)return drawLimit(live,status); - const versions=recordProductionInputs(repository,input,slots); const receipt=await canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf:retryOf?.trim()||undefined,useTemplateReference, prefer2k,geometryReferenceIndex,reworkOf:reworkCandidateId,reworkChange, ...(referenceIndexes?{referenceIndexes}:null),...(useSceneComposite!==undefined?{useSceneComposite}:null)}); - const {request}=await update(()=>{},{prepared:{...receipt,binding,...versions,knowledge:knowledge.files}}); - return {...receipt,operationId:request.operationId}; + return {...receipt,operationId:receipt.requestId}; }; - const preparedRequest=(requestId,slot)=>{ - const saved=repository.readImageRequest(requestId); - const request=saved?.prepared.binding===binding - ? {...saved.prepared,prompt:saved.prepared.spec.prompt,operationId:saved.operationId} - : journal.preparedRequests?.[requestId]; - if (!request || slot && request.slotId!==slot.id) throw Error('生图请求不属于本轮工作画布或委托图位'); - return request; - }; - const claimDispatch=async(slot,approval,request,signal)=>{ - signal?.throwIfAborted(); - await current(); - const live=await liveSlot(slot); - approval={requestId:approval.requestId,expectedRevision:approval.expectedRevision??request.revision, - expectedHash:approval.expectedHash??request.requestSpecHash}; - let claimedOperationId, submission; - 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)}); - if(claim.claimed){ - claimedOperationId=claim.original.operationId; - submission=Promise.withResolvers(); - dispatchingImages.set(claimedOperationId,submission.promise); - } - return claim; - }).catch(error=>{ - submission?.resolve(); - dispatchingImages.delete(claimedOperationId); - tailWatcher.refresh(); - throw error; - }); - const {requestId:candidateId}=approval; - if(generationAttempts!==undefined){ - const status=drawStatus(generationAttempts); - return {receipt:drawLimit(await liveSlot(slot),status)}; + const preparedRequest=async(requestId,slot)=>{ + const receipt=await canvas.imageRequest('read',{requestId}); + if(receipt.requestId!==requestId||receipt.templateHash!==plan.template.contentHash|| + receipt.outputId!==outputId||receipt.variantId!==variantId||slot&&receipt.slotId!==slot.id){ + throw Error('生图请求不属于本轮工作画布或委托图位'); } - if(!claimed){ - if(pending)return {receipt:{phase:'unknown',...pending,pendingOriginal:pending.candidateId??pending.operationId}}; - const {state,operationId,receipt}=record; - const phase=settledImagePhases.includes(state)?state:'unknown'; - return {receipt:{phase,candidateId,operationId,reason:receipt?.message,...expiryFields(receipt), - ...(phase==='unknown'?{pendingOriginal:candidateId}:null)}}; - } - return {approval,original,onEnqueued:submission.resolve}; - }; - const dispatchImageRequest=async(slot,approval,request,original,workerNumber,onEnqueued)=>{ - const {requestId:candidateId}=approval; - const {operationId}=original; - let receipt; - try { receipt=await canvas.imageRequest('dispatch',{...approval,slotId:slot.id,workerNumber},{operationId,requestId:candidateId,onEnqueued}); } - catch(error) { - if (error.dispatched===false) { - await update(journal=>{delete journal.items[slot.id].pendingGenerations[candidateId];}, - {receipt:[candidateId,'prepared',{dispatched:false,message:error.message}]}); - return {phase:'failed',candidateId,operationId,reason:error.message}; - } - await update(()=>{},{receipt:[candidateId,'unknown',{message:error.message}]}); - throw error; - } - const phase=receipt.status??receipt.phase; - const settled=settledImagePhases.includes(phase); - const late=host.productionSignal?.aborted; - const evidence={...receipt,requestId:candidateId,operationId,reworkOf:request.reworkOf, - ...(late?{consumption:'archived_after_cancel'}:null)}; - await update(journal=>{ - const item=journal.items[slot.id]??={}; - if(settled)delete item.pendingGenerations[candidateId]; - const attempts=item.attempts??=[]; - if(!attempts.some(row=>row.candidateId===candidateId))attempts.push({candidateId,source:'generate', - prompt:request.prompt,reworkOf:request.reworkOf,change:request.reworkChange}); - if(late)return; - if(settled)Object.assign(item,{candidateId,state:phase==='complete'?'candidate':phase}); - Object.assign(item,{prompt:request.prompt,source:'generate'}); - rememberImageExpiry(item,candidateId,receipt); - },{receipt:[candidateId,settled?phase:'unknown',evidence], - evidence:[slot.id,candidateId,'candidate',evidence]}); - await store.appendEvent({type:'image_request_receipt',operationId,requestId:candidateId,outputId,variantId,slotId:slot.id, - category:'remote_image',phase:'archive',status:late?'cancelled':settled?phase:'unknown',consumption:evidence.consumption}) - .catch(error=>console.warn('小壹生图事件写入失败',error.code ?? error.name)); - if(late)return {candidateId,operationId,phase:'cancelled',consumption:evidence.consumption}; - return {candidateId,operationId,phase:settled?phase:'unknown',reason:receipt.message, - requestedSource:'generate',...expiryFields(receipt),...(request.reworkOf?{reworkOf:request.reworkOf}:null), - ...(!settled?{pendingOriginal:candidateId}:null), - ...(receipt.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:receipt.retryAfterSeconds}:null)}; - }; - const launchImage=(slot,key,operation,requestId,workerNumber)=>{ - if(jobs.has(key))return {...generation.get(key),phase:'already_running'}; - const pending=!requestId&&pendingGeneration(slot); - if(pending)return pending; - const receipt={slotId:slot.id,phase:'accepted',...(requestId?{candidateId:requestId,operationId:key}:null)}; - const row={number:workerNumber??nextWorkerNumber(),slotId:slot.id,label:slot.label,step:requestId?'正在生图':'生成',active:true}; - generation.delete(key); - generation.set(key,receipt); - const run=Promise.resolve().then(()=>operation(row.number)) - .catch(error=>({...pendingGeneration(slot,journal,requestId)??{phase:'failed',candidateId:requestId},reason:error.message})) - .then(result=>{ - const receipt={slotId:slot.id,...result}; - generation.set(key,receipt); - return receipt; - }) - .finally(()=>{jobs.delete(key);return notice('候选图片回执');}); - jobs.set(key,{row,run}); - if(workerNumber===undefined)notice(requestId?'正在生图':'正在制作候选图片'); return receipt; }; + const dispatchImageRequest=async(slot,approval,request,workerNumber,onEnqueued)=>{ + const {requestId:candidateId}=approval; + const receipt=await canvas.imageRequest('dispatch',{requestId:candidateId,slotId:slot.id,workerNumber, + expectedRevision:approval.expectedRevision??request.revision,expectedHash:approval.expectedHash??request.requestSpecHash}, + {operationId:candidateId,requestId:candidateId,onEnqueued}); + if(host.productionSignal?.aborted)return {candidateId,operationId:candidateId,phase:'cancelled'}; + const phase=receipt.status??receipt.phase; + return {candidateId,operationId:candidateId,phase:phase==='running'?'unknown':phase,reason:receipt.message, + requestedSource:'generate',...expiryFields(receipt),...(request.reworkOf?{reworkOf:request.reworkOf}:null), + ...(!settledImagePhases.includes(phase)?{pendingOriginal:candidateId}:null), + ...(receipt.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:receipt.retryAfterSeconds}:null)}; + }; const queueDispatch=async(slot,approval,request,signal,workerNumber)=>{ - const key=request.operationId??approval.requestId; - if(jobs.has(key))return {...generation.get(key),phase:'already_running'}; - const claim=await claimDispatch(slot,approval,request,signal).catch(error=>({error})); - if(claim.receipt?.limitReached)return claim.receipt; - if(claim.receipt?.pendingOriginal&&!jobs.has(key)){ - return {slotId:slot.id,...claim.receipt}; + await current(); + const pending=request.phase==='prepared'?await pendingNative():[]; + const live=await liveSlot(slot); + signal.throwIfAborted(); + const id=approval.requestId; + if(jobs.has(id))return {slotId:slot.id,candidateId:id,operationId:id,phase:'already_running'}; + if(request.phase!=='prepared'){ + const phase=request.phase==='applied'?'complete':settledImagePhases.includes(request.phase)?request.phase:'unknown'; + return {slotId:slot.id,candidateId:id,operationId:id,phase, + reason:request.message,...(!settledImagePhases.includes(phase)?{pendingOriginal:id}:null),...expiryFields(request)}; } - return launchImage(slot,key,number=>{ - if(claim.error)throw claim.error; - return claim.receipt??dispatchImageRequest(slot,claim.approval,request,claim.original,number,claim.onEnqueued).finally(()=>{ - claim.onEnqueued(); - dispatchingImages.delete(claim.original.operationId); - tailWatcher.refresh(); + const status=slotDrawStatus(live); + if(status.drawLimitReached)return drawLimit(live,status); + const original=pending.find(row=>row.slotId===slot.id); + if(original)return {...original,phase:'unknown',pendingOriginal:original.candidateId}; + const sending=[...dispatchingImages].find(([,job])=>job?.slotId===slot.id); + if(sending)return {slotId:slot.id,phase:'unknown',candidateId:sending[0],pendingOriginal:sending[0]}; + + const submission=Promise.withResolvers(); + dispatchingImages.set(id,{slotId:slot.id,enqueued:submission.promise}); + const row={number:workerNumber??nextWorkerNumber(),slotId:slot.id,label:slot.label,step:'正在生图',active:true}; + const run=Promise.resolve().then(()=>dispatchImageRequest(slot,approval,request,row.number,submission.resolve)) + .catch(error=>({candidateId:id,operationId:id,reason:error.message, + ...(error.dispatched===false?{phase:'failed'}:{phase:'unknown',pendingOriginal:id})})) + .then(result=>({slotId:slot.id,...result})) + .finally(()=>{ + submission.resolve(); + dispatchingImages.delete(id); + jobs.delete(id); + notice('候选图片回执'); }); - },approval.requestId,workerNumber); + jobs.set(id,{row,run,requestId:id}); + if(workerNumber===undefined)notice('正在生图'); + return {slotId:slot.id,phase:'accepted',candidateId:id,operationId:id}; }; const useProductImage=async(slot,options,signal)=>({ ...await operate(slot,'generate_candidate',{useProductReference:true,...options},signal,{source:'product'}), requestedSource:'product',sourceNote:'仅使用或裁切原片,保留原片的背景和光线。', }); + const launchProductImage=(slot,options,signal)=>{ + const key=slot.id; + if(jobs.has(key))return {...generation.get(key),phase:'already_running'}; + const receipt={slotId:key,phase:'accepted'}; + const row={number:nextWorkerNumber(),slotId:key,label:slot.label,step:'生成',active:true}; + generation.set(key,receipt); + const run=onCanvas(signal,()=>useProductImage(slot,options,signal)) + .catch(error=>({phase:'failed',reason:error.message})) + .then(result=>{ + const receipt={slotId:key,...result}; + generation.set(key,receipt); + return receipt; + }) + .finally(()=>{jobs.delete(key);return notice('候选图片回执');}); + jobs.set(key,{row,run}); + notice('正在制作候选图片'); + return receipt; + }; const reportRecoveryError=error=>console.warn('原图片请求核查失败',error.code??error.name); const recoverImage=createImageReconciler(canvas,{outputId,variantId},()=>journal,update,{ @@ -859,9 +779,13 @@ export async function openProductionOperations(host,{target=host.productionGoal, onAdopted:(id,candidateId)=>filled.set(id,candidateId), onError:reportRecoveryError, }); + const pendingNative=async()=> (await canvas.imageRequest('pending',{})).filter(row=> + row.outputId===outputId&&row.variantId===variantId); + const dispatchedImages=()=>[...dispatchingImages].flatMap(([candidateId,job])=> + job?[{slotId:job.slotId,candidateId,operationId:candidateId}]:[]); const outstanding=async()=>{ await journalWrite; - const requests=imageOriginals(journal); + const requests=[...imageOriginals(journal),...await pendingNative(),...dispatchedImages()]; const images=[...new Set(requests.filter(row=>!row.projectId&&!row.adoption&&row.candidateId).map(row=>row.candidateId))]; return {requests,originals:{models:[],images}}; }; @@ -882,10 +806,10 @@ export async function openProductionOperations(host,{target=host.productionGoal, async probe({slot,key},signal){ const tail=tailsFor(slot).find(tail=>tail.key===key); if(!tail)return {slotId:slot.id,phase:'none'}; - const {adopting,frozen,request:{candidateId,operationId}}=tail; + const {adopting,request:{candidateId,operationId}}=tail; if(dispatchingImages.has(operationId))return {slotId:slot.id,candidateId,operationId,phase:'unknown'}; const alreadyPlaced=adopting&&filled.get(slot.id)===candidateId; - const receipt=await recoverImage(slot,adopting,frozen,signal); + const receipt=await recoverImage(slot,adopting,signal); signal.throwIfAborted(); if(!adopting&&receipt.phase!=='none'){ const original=[...generation.entries()].find(([,row])=>row.slotId===slot.id&&row.phase==='unknown'&& @@ -910,15 +834,15 @@ export async function openProductionOperations(host,{target=host.productionGoal, }); async function check(slot,candidateId,adopted,signal){ const item=journal.items[slot.id]; - const request=repository.readImageRequest(candidateId); - const source=request?.slotId===slot.id?'generate':item?.candidateId===candidateId?item.source:undefined; + const live=await liveSlot(slot); + const source=nativeGenerations(live).includes(candidateId)?'generate':item?.candidateId===candidateId?item.source:undefined; try{ const liveScreenCopy=await liveSlotCopy(slot); const readCanvas={detailImages:(id,candidate,options)=>canvas.detailImages(id,candidate,{ ...options,...(canvasReady?{targetOutput:output}:null), })}; const {referenceCount,...review}=await reviewProductionCandidate({canvas:readCanvas,runAgent:host.runDetailAgent, - slot,candidateId,signal,liveScreenCopy,rule:slot.productionRule,source,adopted,reviewKnowledge:reviews}); + slot,candidateId,signal,liveScreenCopy,rule:slot.productionRule,source,adopted}); const {verdict,checks,reason,observation,recommendedAction,canvasTransform}=review; const row={candidateId,decision:verdict,checks,reason,observation,original:review.original,recommendedAction,canvasTransform, evidenceVersion:1,creationRevision:plan.revisions?.creation}; @@ -931,7 +855,8 @@ export async function openProductionOperations(host,{target=host.productionGoal, history.push({candidateId,verdict,reason,recommendedAction,canvasTransform,mustRedo:observation.mustRedo,generationFixes:observation.generationFixes}); },{evidence:[slot.id,candidateId,'review',row]}); candidates.set(candidateId,{slotId:slot.id,status:verdict==='pass'?'passed':'rejected',reason}); - const reworkOf=journal.items[slot.id]?.attempts?.find(row=>row.candidateId===candidateId)?.reworkOf; + const reworkOf=live.candidates?.find(row=>row.id===candidateId)?.reworkOf ?? + item?.attempts?.find(row=>row.candidateId===candidateId)?.reworkOf; await store.appendEvent({type:'whole_detail_review',outputId,variantId,slotId:slot.id,fieldId:slot.fieldId, ...review,...(reworkOf?{reworkOf}:null)}); return {slotId:slot.id,...review,...(reworkOf?{reworkOf}:null)}; @@ -949,21 +874,21 @@ export async function openProductionOperations(host,{target=host.productionGoal, await Promise.allSettled(canvasTasks); await canvasWrite; await journalWrite; - await Promise.all(dispatchingImages.values()); + await Promise.all([...dispatchingImages.values()].map(job=>job?.enqueued)); + return (await outstanding()).originals.images; }, resumeCanvas(){ const suspended=canvasReady; canvasReady=null; if(suspended){ - copyReads.clear(); suspended.resolve(); tailWatcher.refresh(); markProgressDirty(); } }, - workStatus(){ + workStatus(originals){ return {...output,slots:[...new Set(running().map(job=>job.row.slotId))], - inFlightImages:imageOriginals(journal).filter(row=>row.candidateId&&!row.projectId&&!row.adoption) + inFlightImages:originals.filter(row=>row.outputId===outputId&&row.variantId===variantId) .map(row=>row.candidateId), screens:runningScreens().map(job=>job.receipt.page)}; }, @@ -973,20 +898,24 @@ export async function openProductionOperations(host,{target=host.productionGoal, stageController.abort(); await canvasWrite; await journalWrite; + tailWatcher.close(); // Hand off only after admitted requests have entered the native transport. - await Promise.all(dispatchingImages.values()); - const inFlightImages=imageOriginals(journal) + const dispatches=dispatchedImages(); + await Promise.all([...dispatchingImages.values()].map(job=>job?.enqueued)); + const native=host.productionCompletion||host.productionSignal?.aborted?[]:await pendingNative(); + const originalImages=[...imageOriginals(journal),...native,...dispatches]; + const inFlightImages=[...new Map(originalImages.filter(row=>row.candidateId) + .map(row=>[row.candidateId,row])).values()] .filter(({candidateId,projectId,adoption})=>candidateId&&!projectId&&!adoption) .map(({slotId,candidateId,operationId})=>({slotId,requestId:candidateId,operationId})); const inFlightSlots=new Set(inFlightImages.map(image=>image.slotId)); const cancelledSlots=delegates.filter(([key,{row,dispatched}])=> !inFlightSlots.has(row.slotId)&&!dispatched.size&&!generation.get(key)?.candidateId).map(([,job])=>job.row.slotId); - tailWatcher.close(); return {outputId,variantId,cancelledSlots,inFlightImages}; }, screenReviewRevisions, async unfinished(){return unfinished((await outstanding()).originals);}, - async plan_production({slotIds}={}){ + async plan_production({slotIds,includeKnowledge=false}={}){ await current({refresh:true}); if(!canvasReady)recordProductionInputs(repository,plan,slots); const {requested,matched,unmatched}=readSelection(slotIds); @@ -1001,24 +930,24 @@ export async function openProductionOperations(host,{target=host.productionGoal, completedCandidates:candidates?.filter(row=>row.status==='complete').length??0,copyReady:canvasReady?undefined:!pendingCopy.get(id)?.length, ...(requested.size?{productionRule,requirements,sourcePolicy}:null)}; }); - const {production,...template}=plan.template; + const {production,skillSources,resourceSetId,...template}=plan.template; const {outputId:workingOutputId,variantId:workingVariantId}=host.productionGoal; return {outputId,variantId,workingOutput:workingOutputId?{outputId:workingOutputId,variantId:workingVariantId}:null, template,product:{name,dimensions,note,variant:variant&&{id:variant.id,colorName:variant.colorName}}, - pictures,inFlightImages:operations.workStatus().inFlightImages,knowledgeFiles:knowledge.files,requestedOutputs:host.productionGoal.requestedOutputs, + pictures,inFlightImages:(await pendingNative()).map(row=>row.candidateId), + ...(includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null), + requestedOutputs:host.productionGoal.requestedOutputs, 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:[]}; - }, 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()=>{ @@ -1033,37 +962,9 @@ export async function openProductionOperations(host,{target=host.productionGoal, 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)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); @@ -1071,7 +972,6 @@ export async function openProductionOperations(host,{target=host.productionGoal, 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??={}; @@ -1121,7 +1021,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, use_product_image({slotId,...options},signal){ signal?.throwIfAborted(); const slot=matches(slotId); - return launchImage(slot,slot.id,()=>onCanvas(signal,()=>useProductImage(slot,options,signal?AbortSignal.any([signal,stageSignal]):stageSignal))); + return launchProductImage(slot,options,signal?AbortSignal.any([signal,stageSignal]):stageSignal); }, transform_slot_image({slotId,...options},signal){ return serialize(()=>transformImage(matches(slotId),options,signal)); @@ -1130,7 +1030,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, return prepareImageRequest(matches(slotId),args,signal); }, async dispatch_image_request(approval,signal){ - const request=preparedRequest(approval.requestId); + const request=await preparedRequest(approval.requestId); const slot=matches(request.slotId); return queueDispatch(slot,approval,request,signal?AbortSignal.any([signal,stageSignal]):stageSignal); }, @@ -1174,12 +1074,12 @@ export async function openProductionOperations(host,{target=host.productionGoal, (args,activeSignal)=>onCanvas(activeSignal,()=>prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal))), workerTool('dispatch_image_request','审阅准备回执后填写 requestId 确认派发',dispatchArgs, (approval,activeSignal)=>onCanvas(activeSignal,async()=>{ - const request=preparedRequest(approval.requestId,slot); + const request=await preparedRequest(approval.requestId,slot); row.step='正在生图'; notice('子代理正在生图'); const receipt=await queueDispatch(slot,approval,request,activeSignal,row.number); if(receipt.operationId)dispatched.add(receipt.operationId); - await dispatchingImages.get(receipt.operationId); + await dispatchingImages.get(receipt.operationId)?.enqueued; return receipt; }),result=>!result.limitReached), ]; @@ -1218,14 +1118,11 @@ export async function openProductionOperations(host,{target=host.productionGoal, const live=await liveSlot(slot); const status=slotDrawStatus(live); const instructions='完成主代理委托的图位。goal 是本次任务,screenCopy 是画布实时文案。可用 transform_slot_image 调整已有图像并查看像素指标。派发回执会带原请求号,宿主继续跟踪结果。'+ - (rework?'\n先看随消息附上的退回图、验图回执和上次实发提示词。按发布规则处理,用 reworkChange 记录改动。':'')+ - (delegateKnowledge.files.length?'\n用 read_production_knowledge 获取 knowledgeFiles 中本任务适用的企业 Skill 和制作规则。':''); + (rework?'\n先看随消息附上的退回图、验图回执和上次实发提示词。按发布规则处理,用 reworkChange 记录改动。':''); const screenCopy=await liveSlotCopy(slot); - const taskGuidance=await delegateKnowledge.guidance(); 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, - taskGuidance,knowledgeFiles:delegateKnowledge.files}),[readTool,...makeTools(),...delegateKnowledge.tools], + JSON.stringify({rework,goal,screenCopy,...status,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements}),[readTool,...makeTools()], rejectedImage?[rejectedImage]:[],productRequestScope('slot',slot.id),undefined,delegateSignal); if(!produced)generation.set(workerId,{slotId:slot.id,phase:'no_candidate'}); }).catch(async error=>{ @@ -1253,9 +1150,14 @@ export async function openProductionOperations(host,{target=host.productionGoal, const scope=slotIds?.length||!selected.length?wanted:new Set(selected.map(job=>job.row.slotId)); const screens=slotIds?.length?[]:[...screenChecks.values()]; const pending=[...selected,...screens.filter(job=>job.run)].map(job=>job.run); - if(pending.length&&!canvasReady)await Promise.race(pending); + const receipt=pending.length&&!canvasReady?await Promise.race(pending):undefined; + const native=(await liveSlots()).filter(slot=>scope.has(slot.id)).flatMap(slot=> + (slot.candidates??[]).filter(row=>!row.sourceType&&!row.reusedFrom).map(row=> + ({...row,slotId:slot.id,candidateId:row.id,operationId:row.id,phase:row.status,reason:row.message??row.error}))) + .sort((a,b)=>(b.sequence??0)-(a.sequence??0)); + const completed=receipt?.operationId&&scope.has(receipt.slotId)?[receipt]:[]; return {...output,active:jobs.size,checking:pendingReviews().length, - generation:generationReceipts(scope), + generation:[...completed,...generationReceipts(scope),...native.filter(row=>row.candidateId!==completed[0]?.candidateId)], checks:[...reviewWork].filter(job=>scope.has(job.row.slotId)).map(job=>job.receipt), ...(screens.length?{screenChecks:screens.map(job=>job.receipt)}:null)}; }, @@ -1283,8 +1185,13 @@ export async function openProductionOperations(host,{target=host.productionGoal, const record=journal.items[id]; const {attemptCount,rejections}=slotAttempts(slot,record); const status=statuses.get(id); - const latest=candidates?.at(-1); - const generations=generationReceipts(new Set([id])); + const ordered=(candidates??[]).toSorted((a,b)=>(b.sequence??0)-(a.sequence??0)); + const latest=ordered[0]; + const sending=[...jobs.values()].filter(job=>job.requestId&&job.row.slotId===id) + .map(({requestId})=>({slotId:id,candidateId:requestId,operationId:requestId,phase:'accepted'})); + const generations=[...sending,...ordered.filter(row=>!row.sourceType&&!row.reusedFrom&& + !sending.some(receipt=>receipt.candidateId===row.id)) + .map(row=>({...row,candidateId:row.id,phase:row.status})),...generationReceipts(new Set([id]))]; const [generationReceipt]=generations; const latestCandidateId=latest?.id??generationReceipt?.candidateId??record?.candidateId; const reviews=checks.get(id)??[]; @@ -1293,7 +1200,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, const decision=record?.review?.candidateId===latestCandidateId?record?.review?.decision:undefined; const adopted=selectedCandidateId&&selectedCandidateId===latestCandidateId; const state=slotWorking(id)?'generating':reviews.some(job=>job.run)?'checking': - record?.pendingOperation||record?.pendingAdoption||originalCandidate(record)||Object.keys(record?.pendingGenerations??{}).length?'unknown': + slotOriginals(record).length?'unknown': adopted?'applied': decision??generationReceipt?.phase??latest?.status??record?.state??'empty'; return {id,fieldId,label,state,selectedCandidateId,latestCandidateId,attemptCount,...status,rejectionCount:rejections.length}; @@ -1360,21 +1267,16 @@ export async function openProductionOperations(host,{target=host.productionGoal, const generated=nativeGenerations(await liveSlot(slot)).includes(candidateId); const result=await serialize(()=>canvas.detailRetire(slot.id,candidateId,reason)); if(result.status==='retired'){ - const request=repository.readImageRequest(candidateId); await update(journal=>{ if(!journal.items[slot.id]&&!generated)return; const item=journal.items[slot.id]??={}; - if(generated&&!(item.attempts??[]).some(row=>row.candidateId===candidateId)){ - (item.attempts??=[]).push({candidateId,source:'generate'}); - } item.approvals=(item.approvals??[]).filter(row=>row.candidateId!==candidateId); if(item.candidateReviews)delete item.candidateReviews[candidateId]; if(item.candidateId===candidateId&&!item.pendingOperation&&!item.pendingAdoption){ item.state='retired'; if(result.canvasLayerId)filled.delete(slot.id); } - },{evidence:[slot.id,candidateId,'retirement',{...result,reason}], - ...(request?{receipt:[candidateId,'retired',result]}:null)}); + },{evidence:[slot.id,candidateId,'retirement',{...result,reason}]}); candidates.delete(candidateId); host.generatedCandidates?.delete(candidateId); markProgressDirty(); @@ -1392,8 +1294,14 @@ export async function openProductionOperations(host,{target=host.productionGoal, if(tails.every(tail=>tail.adopting))receipts.unshift({slotId:slot.id,phase:'none'}); return receipts; })); + const pending=await pendingNative(); signal?.throwIfAborted(); - return results; + const ids=new Set(selected.map(slot=>slot.id)); + const originals=await Promise.all(pending.filter(row=>ids.has(row.slotId)) + .map(row=>readNativeOriginal(canvas,row,canvasReady?output:undefined))); + signal?.throwIfAborted(); + const pendingSlots=new Set(originals.map(row=>row.slotId)); + return [...originals,...results.filter(row=>row.phase!=='none'||!pendingSlots.has(row.slotId))]; }, async read_output_screen({page=0,pages},signal){ const render=async page=>{ @@ -1410,7 +1318,6 @@ export async function openProductionOperations(host,{target=host.productionGoal, 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); @@ -1481,7 +1388,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, const screenSlots=slots.filter(slot=>screen.details.fields?.includes(slot.fieldId)) .map(({id,fieldId,label,nativeLayerId})=>({id,fieldId,label,nativeLayerId})); const receipt=await reviewOutputScreen({runAgent:host.runDetailAgent,page,screen,references, - slots:screenSlots,outputId,variantId,signal:activeSignal,reviewKnowledge:reviews}); + slots:screenSlots,outputId,variantId,signal:activeSignal}); job.inputSignature=(await references()).inputSignature; if(receipt.verdict==='pass'){ await onCanvas(activeSignal,()=>operations.record_screen_check({page:page-1,revision,issues:[]},activeSignal,job.inputSignature)); @@ -1533,15 +1440,11 @@ export async function openProductionOperations(host,{target=host.productionGoal, }); }, 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; diff --git a/apps/detail-agent-pi/src/production-recovery.mjs b/apps/detail-agent-pi/src/production-recovery.mjs index e10e4d0e..4d364fe6 100644 --- a/apps/detail-agent-pi/src/production-recovery.mjs +++ b/apps/detail-agent-pi/src/production-recovery.mjs @@ -1,89 +1,3 @@ -import { parseReceipt } from './receipt.mjs'; -import { retryDelayMs } from '@earendil-works/pi-ai'; -import { SettingsManager } from '@earendil-works/pi-coding-agent'; - -export const piRetryPolicy = SettingsManager.inMemory().getRetrySettings(); - -export function gatewayImageRetryDelay(retries, retryAfterSeconds) { - if (!piRetryPolicy.enabled || retries >= piRetryPolicy.maxRetries) return null; - return Math.max(retryDelayMs(piRetryPolicy, retries + 1), - Number.isFinite(retryAfterSeconds) ? retryAfterSeconds * 1000 : 0); -} - -export class ProductionRequestFailed extends Error { - constructor(requestId, httpStatus) { - super('模型服务已确认请求失败(原请求 '+requestId+(httpStatus?',HTTP '+httpStatus:'')+')'); - this.httpStatus=httpStatus; - this.retryable=![400,401,403,404,422].includes(httpStatus); - } -} - -export function confirmedProductionFailure(receipt, id) { - if (receipt.phase !== 'failed') return null; - if (receipt.failureCode === 'rate_limit_exceeded') { - return new ProductionRequestFailed(receipt.requestId ?? id, 429); - } - return receipt.confirmedFailure - ? new ProductionRequestFailed(receipt.requestId ?? id, receipt.httpStatus) - : null; -} - -export class ProductionOutputLimit extends Error { - constructor() { super('模型回复达到单次输出长度,当前制作步骤未完成'); } -} - export function productRequestScope(step, variant, output) { return ['product',step,variant,output].filter(Boolean).join('/'); } - -// Model refusal is a terminal reply, but it authorizes no tools or canvas writes. -async function closeProductRefusal(broker,record){ - if(record.phase!=='received'||record.terminal!==true||typeof record.raw!=='string')return false; - const protocol=record.model?.protocol; - if(!['anthropic-messages','openai-chat'].includes(protocol))return false; - const raw=Buffer.from(record.raw,'base64').toString('utf8'); - const refused=raw.split(/\r?\n/u).some(line=>{ - if(!line.startsWith('data:'))return false; - try{ - const event=JSON.parse(line.slice(5)); - return protocol==='anthropic-messages' - ? event?.type==='message_delta'&&event.delta?.stop_reason==='refusal' - : event?.choices?.some(choice=>(choice.index??0)===0&&choice.finish_reason==='content_filter')===true; - }catch{return false;} - }); - if(!refused)return false; - const receipt=await broker.confirm(record.id,record.bodyHash,false,'refusal'); - return receipt.phase==='rejected'; -} - -export async function confirmProductionResponse(broker,record,model,tools,protocolMode='native-tools'){ - const {id,requestId}=record; - if(await closeProductRefusal(broker,record))return {phase:'rejected',requestId}; - const message=await parseReceipt(record,model,protocolMode,tools); - if(record.phase==='received'){ - const receipt=await broker.confirm(id,record.bodyHash,message.stopReason!=='length',message.stopReason); - if(receipt.phase!=='complete')return {phase:receipt.phase,requestId}; - } - return message.stopReason==='length'?{phase:'rejected',requestId}:{phase:'complete',requestId,message}; -} - -export async function recoverProductionResponse(broker,id,model,tools) { - let record=await broker.read(id); - let recoveryError; - if (['unknown','dispatched'].includes(record.phase)) { - try { await broker.recover(id); } - catch (error) { - recoveryError=error; - } - // The native broker can settle the original journal even when the GET fails. - record=await broker.read(id); - } - if (!['received','complete'].includes(record.phase)) { - const confirmedFailure=record.phase==='failed'&&record.originalLookup?.verified===true&& - record.originalLookup.status==='failed'&&record.originalLookup.requestId===record.requestId; - return {phase:record.phase,requestId:record.requestId,failureCode:record.failureCode, - ...(recoveryError?{recoveryError}:null), - ...(confirmedFailure?{confirmedFailure,httpStatus:record.failureHttpStatus??record.httpStatus}:null)}; - } - return confirmProductionResponse(broker,{id,...record},model,tools); -} diff --git a/apps/detail-agent-pi/src/production-repository.mjs b/apps/detail-agent-pi/src/production-repository.mjs index a3622bd4..2bda0d37 100644 --- a/apps/detail-agent-pi/src/production-repository.mjs +++ b/apps/detail-agent-pi/src/production-repository.mjs @@ -18,7 +18,11 @@ export function productionLedger(store, outputId, variantId) { // PhotoCraft consumes this view for adoption, archives and .xiaoyi saves. // On the original project, SQLite owns all changes after the first import. const publishAudit = async journal => { - const view = repository.exportLedger(journal); + const {preparedRequests, ...audit} = journal; + const view = {...audit, items:Object.fromEntries(Object.entries(journal.items).map(([id, item])=>{ + const {pendingGenerations, ...record} = item; + return [id, record]; + }))}; const encoded = JSON.stringify(view, null, 2); if (published === undefined) { try { published = await fs.readFile(legacyFile, 'utf8'); } diff --git a/apps/detail-agent-pi/src/project-repository.mjs b/apps/detail-agent-pi/src/project-repository.mjs index a720ab04..938e326a 100644 --- a/apps/detail-agent-pi/src/project-repository.mjs +++ b/apps/detail-agent-pi/src/project-repository.mjs @@ -38,6 +38,7 @@ const schema = ` value_json TEXT NOT NULL, PRIMARY KEY (${scopeColumns}, kind, record_id, revision) ) STRICT; + -- Historical R2/R3 request records. The host owns new image requests. CREATE TABLE image_requests ( ${scopeDefinition}, request_id TEXT NOT NULL, @@ -170,30 +171,14 @@ export class ProjectRepository { }); } - exportLedger(journal) { - return this.#open(db => { - const rows = db.prepare(`SELECT request_id, prepared_json FROM image_requests WHERE ${scopeWhere}`).all(...this.scope); - const requests = rows.map(row => [row.request_id, JSON.parse(row.prepared_json)]) - .filter(([, draft]) => draft.binding === journal.binding); - if (!requests.length) return journal; - const preparedRequests = { ...journal.preparedRequests, ...Object.fromEntries( - requests.map(([id, { slotId, spec, reworkOf, reworkChange }]) => - [id, { slotId, prompt: spec.prompt, reworkOf, reworkChange }]), - ) }; - return { ...journal, preparedRequests }; - }); - } - - updateLedger(binding, change, { prepared, policy, candidateSetId, receipt, evidence } = {}) { + updateLedger(binding, change, { evidence } = {}) { return this.#open(db => transaction(db, () => { const previous = this.#readLedger(db); const journal = previous?.binding === binding ? structuredClone(previous) : { binding, items: {} }; const result = change(journal); this.#writeLedger(db, journal, previous); - const request = prepared && this.#saveImageRequest(db, prepared, policy, candidateSetId); - if (receipt) this.#recordImageReceipt(db, ...receipt); if (evidence) this.#recordCandidate(db, ...evidence); - return { journal, result, request }; + return { journal, result }; })); } @@ -231,39 +216,6 @@ export class ProjectRepository { }); } - #saveImageRequest(db, receipt, policy, candidateSetId) { - const { requestId, operationId = requestId, slotId, requestSpecHash, revision } = receipt; - if (policy || candidateSetId) { - const original = this.#readRequest(db, requestId); - let candidateSet = original?.prepared.candidateSet; - if (!candidateSet) { - const first = candidateSetId && this.#readRequest(db, candidateSetId); - if (candidateSetId && (first?.prepared.candidateSet?.id !== candidateSetId || - first.slotId !== slotId || first.prepared.binding !== receipt.binding || - first.requestSpecHash !== requestSpecHash || first.prepared.planRevision !== receipt.planRevision || - first.prepared.productFactsRevision !== receipt.productFactsRevision)) { - throw Error('同批候选须使用相同的正式请求和制作依据'); - } - const setPolicy = first?.prepared.candidateSet.policy ?? policy; - const position = first ? this.#candidateSet(db, slotId, candidateSetId).length : 0; - if (position >= setPolicy.candidateCount) throw Error('此批候选已准备齐全'); - candidateSet = { id: candidateSetId ?? requestId, position, policy: setPolicy }; - } - receipt = { ...receipt, candidateSet }; - } - db.prepare(`INSERT INTO image_requests (${scopeColumns}, request_id, operation_id, slot_id, request_spec_hash, - revision, state, prepared_json) VALUES (${scopeValues}, ?, ?, ?, ?, ?, 'prepared', ?) - ON CONFLICT (${scopeColumns}, request_id) DO NOTHING`).run( - ...this.scope, requestId, operationId, slotId, requestSpecHash, revision, json(receipt)); - const saved = this.#readRequest(db, requestId); - if (json(saved.prepared) !== json(receipt)) throw Error('生图请求内容已变化,请重新准备新版本'); - return saved; - } - - saveImageRequest(receipt) { - return this.#open(db => transaction(db, () => this.#saveImageRequest(db, receipt))); - } - #readRequest(db, requestId) { const row = db.prepare(`SELECT * FROM image_requests WHERE ${scopeWhere} AND request_id = ?`).get(...this.scope, requestId); if (!row) return null; @@ -277,113 +229,6 @@ export class ProjectRepository { return this.#open(db => this.#readRequest(db, requestId)); } - #candidateSet(db, slotId, id) { - return db.prepare(`SELECT request_id FROM image_requests WHERE ${scopeWhere} AND slot_id = ? - AND json_extract(prepared_json, '$.candidateSet.id') = ? ORDER BY rowid`) - .all(...this.scope, slotId, id).map(row => this.#readRequest(db, row.request_id)); - } - - candidateSet(slotId, id) { - return this.#open(db => this.#candidateSet(db, slotId, id)); - } - - #countImageGenerations(requests, nativeIds, item) { - const ids = new Set(nativeIds); - for (const {request_id, state, receipt_json} of requests) { - if (state !== 'prepared') ids.add(request_id); - else if (receipt_json && JSON.parse(receipt_json).dispatched === false) ids.delete(request_id); - } - for (const row of item?.attempts ?? []) if (row.source === 'generate' && row.candidateId) ids.add(row.candidateId); - for (const id of Object.keys(item?.pendingGenerations ?? {})) ids.add(id); - const originalId = item?.pendingOperation?.candidateId; - if (originalId && !item.attempts?.some(row => row.candidateId === originalId && row.source === 'product')) { - ids.add(originalId); - } - return ids.size; - } - - #generationRequests(db, binding, slotId) { - return db.prepare(`SELECT slot_id, request_id, state, receipt_json FROM image_requests - WHERE ${scopeWhere} AND json_extract(prepared_json, '$.binding') = ?${slotId ? ' AND slot_id = ?' : ''}`) - .all(...this.scope, binding, ...(slotId ? [slotId] : [])); - } - - countImageGenerations(binding, nativeIdsBySlot, items) { - if (!nativeIdsBySlot.size) return new Map(); - return this.#open(db => { - const slotId = nativeIdsBySlot.size === 1 ? nativeIdsBySlot.keys().next().value : undefined; - const requests = Map.groupBy(this.#generationRequests(db, binding, slotId), row => row.slot_id); - return new Map([...nativeIdsBySlot].map(([id, nativeIds]) => - [id, this.#countImageGenerations(requests.get(id) ?? [], nativeIds, items[id])])); - }); - } - - claimImageRequest({ requestId, expectedRevision, expectedHash }, binding, pendingGeneration, generationLimit) { - return this.#open(db => transaction(db, () => { - const request = this.#readRequest(db, requestId); - if (request && (request.prepared.binding !== binding || - request.revision !== expectedRevision || request.requestSpecHash !== expectedHash)) { - throw Error('生图请求版本已变化,请重新准备'); - } - const previous = this.#readLedger(db); - const journal = previous?.binding === binding ? structuredClone(previous) : { binding, items: {} }; - const slotId = request?.slotId ?? journal.preparedRequests?.[requestId]?.slotId; - if (!slotId) throw Error('生图请求不属于本轮工作画布或委托图位'); - const item = journal.items[slotId] ??= {}; - const sameOperation = item.pendingGenerations?.[requestId]; - const expired = !request && item.attempts?.find(attempt => attempt.candidateId === requestId && attempt.phase === 'expired'); - if (expired) return { journal, request: { state: 'expired', operationId: requestId, receipt: expired }, claimed: false }; - if (sameOperation || request && request.state !== 'prepared') { - return { journal, pending: sameOperation, request, claimed: false }; - } - if (generationLimit) { - const {maxGenerationAttempts, nativeIds} = generationLimit; - const requests = this.#generationRequests(db, binding, slotId); - const generationAttempts = this.#countImageGenerations(requests, nativeIds, item); - if (generationAttempts >= maxGenerationAttempts) return { journal, claimed: false, generationAttempts }; - const set = request?.prepared.candidateSet; - if (set && this.#candidateSet(db, slotId, set.id).length !== set.policy.candidateCount) { - throw Error('请先按政策准备齐全同批候选,再分别确认派发'); - } - } - const priorGeneration = Object.values(item.pendingGenerations ?? {}).find(original => { - const prior = this.#readRequest(db, original.candidateId); - return !request?.prepared.candidateSet || - prior?.prepared.candidateSet?.id !== request.prepared.candidateSet.id; - }); - const priorState = priorGeneration && this.#readRequest(db, priorGeneration.candidateId)?.state; - const pending = pendingGeneration?.(journal, priorGeneration) ?? - (priorState !== 'dispatching' ? priorGeneration : undefined); - if (pending) return { journal, pending, request, claimed: false }; - const operationId = request?.operationId ?? requestId; - if (request) { - const set = request.prepared.candidateSet; - if (set && this.#candidateSet(db, slotId, set.id).every(candidate => candidate.frozenAt === null)) { - item.autoCandidateSetId = set.id; - } - db.prepare(`UPDATE image_requests SET state = 'dispatching', frozen_at = COALESCE(frozen_at, ?) - WHERE ${scopeWhere} AND request_id = ?`).run(Date.now(), ...this.scope, requestId); - } - // Old drafts carry only the prompt and still rely on the native revision/hash check. - const original = { candidateId: requestId, operationId, kind: 'frozen-image' }; - (item.pendingGenerations ??= {})[requestId] = original; - this.#writeLedger(db, journal, previous); - return { journal, original, claimed: true }; - })); - } - - #recordImageReceipt(db, requestId, state, receipt) { - // Expiration is a terminal failure to retrieve the result. Its receipt carries - // the exact outcome, with the same durable schema as earlier projects. - db.prepare(`UPDATE image_requests SET state = ?, receipt_json = ? - WHERE ${scopeWhere} AND request_id = ? AND json_extract(receipt_json, '$.resultExpiry') IS NULL`) - .run(state === 'expired' ? 'failed' : state, json(receipt), ...this.scope, requestId); - } - - recordImageReceipt(requestId, state, receipt) { - this.#open(db => this.#recordImageReceipt(db, requestId, state, receipt)); - } - #recordCandidate(db, slotId, candidateId, kind, detail) { db.prepare(`INSERT INTO candidate_evidence (${scopeColumns}, slot_id, candidate_id, kind, detail_json) VALUES (${scopeValues}, ?, ?, ?, ?)`).run(...this.scope, slotId, candidateId, kind, json(detail)); diff --git a/apps/detail-agent-pi/src/request-purpose.mjs b/apps/detail-agent-pi/src/request-purpose.mjs deleted file mode 100644 index 9f262898..00000000 --- a/apps/detail-agent-pi/src/request-purpose.mjs +++ /dev/null @@ -1,20 +0,0 @@ -import fs from 'node:fs/promises'; -import path from 'node:path'; - -export async function requestPurpose(host, id) { - const text = await fs.readFile(path.join(host.store.dir, 'events.jsonl'), 'utf8').catch(error => {if (error.code === 'ENOENT') return ''; throw error;}); - const events = text.split('\n').filter(Boolean).map(line => { try { return JSON.parse(line); } catch { return null; } }); - let legacyCompacting = false; - for (const event of events) { - if (event?.type === 'automatic_compaction_started') legacyCompacting = true; - if (event?.type === 'automatic_compaction_completed') legacyCompacting = false; - if (event?.type !== 'provider_prepared' || event.id !== id || - (event.bindingHash && event.bindingHash !== host.store.hash)) continue; - if (events.some(row => row?.id === id && row.consumption === 'discarded_after_cancel')) return 'cancelled'; - const {purpose} = event; - if (['conversation','compaction','whole-detail-review','whole-detail-worker','product-goal'].includes(purpose)) return purpose; - // Old automatic summaries have no durable cut point. - return legacyCompacting ? 'legacy-compaction' : 'conversation'; - } - throw Error('原请求不属于当前店铺/品类会话,未查询或恢复'); -} diff --git a/apps/detail-agent-pi/src/screen-review.mjs b/apps/detail-agent-pi/src/screen-review.mjs index cfb4f069..f41d24cc 100644 --- a/apps/detail-agent-pi/src/screen-review.mjs +++ b/apps/detail-agent-pi/src/screen-review.mjs @@ -25,7 +25,7 @@ const assessment = object({ copyFixes:finding({field:text(200)}), }); -export async function reviewOutputScreen({runAgent, page, screen, references, slots, outputId, variantId, signal, reviewKnowledge}) { +export async function reviewOutputScreen({runAgent, page, screen, references, slots, outputId, variantId, signal}) { const {revision,copyRevision,overlayLayers,screenCopy=[]} = screen.details; const images = screen.content.filter(item => item.type === 'image'); if (!Number.isSafeInteger(revision) || images.length !== 1) throw Error('未读取到当前屏的实际画面和修订号'); @@ -59,14 +59,12 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl const scope = screenReviewScope(variantId,outputId,page); const instructions = [ '复核整屏成片。第一张是整屏实际画面,后续是本款实拍。', - ...(reviewKnowledge.files.length?['用 read_production_knowledge 获取 knowledgeFiles 中适用的企业 Skill 和审稿规则。']:[]), '用 review_output_screen 提交结论、画面依据和修改建议。图片问题填写 location 和已知 slotId,叠层问题填写 overlayLayers 中的 nativeLayerId,正文问题填写 screenCopy 中的 field。', '有问题时填写 needs_fix 和至少一项问题。通过时三组问题均为空。', ].join('\n'); - const prompt = JSON.stringify({page,revision,product,slots,screenCopy,overlayLayers,productReferenceCount:photos.length, - taskGuidance:await reviewKnowledge.guidance(),knowledgeFiles:reviewKnowledge.files}); + const prompt = JSON.stringify({page,revision,product,slots,screenCopy,overlayLayers,productReferenceCount:photos.length}); const captions = ['当前整屏成片', ...photos.map((_,index) => `本款实拍 ${index + 1}`)]; - await runAgent(`screen-${page}`, instructions, prompt, [tool,...reviewKnowledge.tools], [...images,...photos], scope, captions,signal); + await runAgent(`screen-${page}`, instructions, prompt, [tool], [...images,...photos], scope, captions,signal); signal?.throwIfAborted(); if (!receipt) throw new InvalidToolReply('整屏复核未提交结论'); return receipt; diff --git a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md index 962d6a7c..3382c8da 100644 --- a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md +++ b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md @@ -1,11 +1,12 @@ --- name: product-image-sources description: Use product image sources and Image Request tools in PhotoCraft. +maxGenerationAttempts: 4 --- # 商品配图工具 -从本项目企业 Skill 及其引用取得图位制作、素材选择、审稿和返工规则。用 `read_production_knowledge` 回读已锁定的文件,工具回执会注明版次。 +从本项目企业 Skill 及其引用取得图位制作、素材选择、审稿和返工规则。用 `read` 按路径查看已锁定的文件。 - `read_slot_images` 读取实拍、模板参考和候选。`use_product_image` 可直接用原片或指定裁切区域。 - transform_slot_image 可在本地裁切、旋转、镜像、缩放或位移同图位或跨图位候选及本款实拍,并返回像素清晰度指标。仅有构图问题时可复用现有图片。近景和特写可裁切现有或用 prefer2k: true 请求的 2K 中景,担心模板参考影响商品结构时可用 useTemplateReference: false。 diff --git a/apps/detail-agent-pi/src/template-mapping.mjs b/apps/detail-agent-pi/src/template-mapping.mjs index 81a01b6a..bda012f5 100644 --- a/apps/detail-agent-pi/src/template-mapping.mjs +++ b/apps/detail-agent-pi/src/template-mapping.mjs @@ -65,6 +65,8 @@ function compact(raw,original,key,component) { const canvas=[template.canvas.width,template.canvas.height]; if(!canvas.every(n=>Number.isInteger(n)&&n>0))fail('字段映射的原稿尺寸无效'); const page=[0,0,...canvas]; + // Compact mappings publish rules against these generated IDs. Canonical + // mappings declare their own screen and field IDs. const screen=component==='sku_images'?'K01':'M01'; const fields=[]; const append=(id,reference,slot,kind)=>{ diff --git a/apps/detail-agent-pi/test/account-authorization.test.mjs b/apps/detail-agent-pi/test/account-authorization.test.mjs index 0396d12b..44e0f5c1 100644 --- a/apps/detail-agent-pi/test/account-authorization.test.mjs +++ b/apps/detail-agent-pi/test/account-authorization.test.mjs @@ -50,11 +50,10 @@ test('native HTTP 401 revokes the bound broker and all workers without another d try { const response = await round.fetch(address, options); assert.equal(response.status, 401); - await assert.rejects(round.finish(false), {category:'auth_revoked',dispatched:true}); + await assert.rejects(response.text(), {category:'auth_revoked',dispatched:true}); await assert.rejects(broker.round().fetch(address, options), {category:'auth_revoked'}); await assert.rejects(formerWorker.round().fetch(address, options), {category:'auth_revoked'}); assert.equal(requests.length, 1); - assert.equal(broker.hasUnconfirmedRequest, false); assert.equal(paused.length, 1); assert.doesNotMatch(JSON.stringify(paused), /never-log-auth-fixture/); } finally { diff --git a/apps/detail-agent-pi/test/conversation.test.mjs b/apps/detail-agent-pi/test/conversation.test.mjs index 8ce57c3b..66995303 100644 --- a/apps/detail-agent-pi/test/conversation.test.mjs +++ b/apps/detail-agent-pi/test/conversation.test.mjs @@ -18,7 +18,7 @@ function canvas(){ return {revision:1,allowed:false,writeBlocked:false,writes:0,requests:0,text:'原始标题', async begin(){this.allowed=false;this.writeBlocked=false;}, async read(){return {conversationActive:true,allowed:this.allowed,writeBlocked:this.writeBlocked,revision:this.revision,context:{id:7,name:'test',width:1440,height:1800,layers:[{id:1,name:'S01 title',kind:'Type',text:this.text,locked:{}}],product:{mustNotDuplicate:'private'}}};}, - async requestWrite(revision){this.requests++;if(this.writeBlocked||revision!==this.revision)throw Error('用户已接手,写入未获许可');this.allowed=true;return this.read();}, + async requestWrite(revision){this.requests++;if(this.writeBlocked||revision!==this.revision)throw new BridgeError('用户已接手,写入未获许可','write_revoked');this.allowed=true;return this.read();}, async edit(edit,revision){assert.ok(this.allowed&&!this.writeBlocked);assert.equal(revision,this.revision);this.writes++;this.text=edit.params.text;this.revision++;return this.read();}, async delta(){},async activity(){},async end(){this.allowed=false;}}; } @@ -164,14 +164,11 @@ test('a model response arriving after cancellation keeps its receipt and cannot await assert.rejects(first,/停止/); const journal=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(JSON.parse); const finished=journal.find(e=>e.type==='provider_finished'); - assert.equal(finished.phase,'complete'); + assert.equal(finished.stopReason,'toolUse'); assert.equal(finished.status,'cancelled'); assert.equal(finished.consumption,'discarded_after_cancel'); - assert.equal(finished.operationId,finished.requestId); x.host.productionSignal=new AbortController().signal; - x.broker.read=async id=>({phase:'complete',requestId:id}); - assert.equal((await x.host.recover(finished.id,{executeReadOnly:true})).consumption,'discarded_after_cancel'); assert.equal((await x.host.prompt('新回合')).text,'新一轮正常完成。'); assert.equal(x.native.writes,0); assert.equal(x.requests.length,2); @@ -268,7 +265,7 @@ test('switching projects in the middle of the original SSE detaches UI delivery assert.ok(replies.some(m=>m.stopReason==='stop'&&m.content.filter(c=>c.type==='text').map(c=>c.text).join('')===full)); assert.ok(!replies.some(m=>m.stopReason==='error'),'an inactive display is not an incomplete model result'); const journal=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).split('\n').filter(Boolean).map(JSON.parse); - assert.equal(journal.filter(e=>e.type==='provider_prepared').length,1);assert.ok(journal.some(e=>e.type==='provider_finished'&&e.phase==='complete')); + assert.equal(journal.filter(e=>e.type==='provider_started').length,1);assert.ok(journal.some(e=>e.type==='provider_finished'&&e.stopReason==='stop')); assert.ok(journal.some(e=>e.type==='inactive_ui_delivery'&&e.method==='delta'));assert.ok(journal.some(e=>e.type==='inactive_ui_delivery'&&e.method==='end')); assert.equal(x.events.filter(e=>e.type==='text_delta').map(e=>e.delta).join(''),full); }finally{await x.close();} @@ -290,7 +287,7 @@ test('inactive activity delivery preserves the original assistant/tool transcrip assert.ok(messages.some(m=>m.role==='assistant'&&m.stopReason==='toolUse'&&m.content.some(c=>c.type==='text'&&c.text==='A的完整规则解释,随后只读查询原历史。'))); assert.ok(messages.some(m=>m.role==='toolResult'&&m.toolCallId==='read-old-a'&&!m.isError)); assert.ok(!messages.some(m=>m.role==='assistant'&&m.stopReason==='error')); - const log=await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8');assert.ok(log.includes('inactive_project_stopped')); + const log=await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8');assert.ok(log.includes('inactive_ui_delivery')); }finally{await x.close();} }); @@ -408,8 +405,7 @@ test('legacy transcript migration retains originals and a new conversation can p let posts=0; host=await DetailPiAgent.open({store:stable,broker:{ info:async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-chat'},pending:[{id:'original-unknown'}]}), - round:({inference})=>{ - assert.equal(inference,true); + round:()=>{ return {id:randomUUID(),fetch:async()=>{ posts++; return new Response(sse({content:'当前对话可以继续。'}),{headers:{'content-type':'text/event-stream'}}); diff --git a/apps/detail-agent-pi/test/copy-image-alignment.test.mjs b/apps/detail-agent-pi/test/copy-image-alignment.test.mjs index 7d8a15cd..78ba1436 100644 --- a/apps/detail-agent-pi/test/copy-image-alignment.test.mjs +++ b/apps/detail-agent-pi/test/copy-image-alignment.test.mjs @@ -34,13 +34,13 @@ test('live text replaces stale journal copy and includes all supported selling p assert.deepEqual(resolveLiveSlotCopy({slot,copyFields:[{...fields[0],currentText:''}],journalCopy}),[]); }); -test('slot page, native document ID and known field prefixes locate a screen without direct copy',()=>{ +test('declared page and native document IDs locate a screen without guessing the field prefix',()=>{ const copyFields=fields.slice(0,2); - for(const location of [{page:'P02'},{pageId:'P02'},{documentId:'P02'},{fieldId:'P02_leg'},{}]){ + for(const location of [{page:'P02'},{pageId:'P02'},{documentId:'P02'}]){ const result=resolveLiveSlotCopy({slot:{...slot,...location},copyFields,pages}); assert.deepEqual(result.map(row=>row.binding),['same_screen','same_screen']); } - assert.deepEqual(resolveLiveSlotCopy({slot,copyFields}),[]); + assert.deepEqual(resolveLiveSlotCopy({slot,copyFields,pages}),[]); assert.deepEqual(resolveLiveSlotCopy({slot,journalCopy}).map(row=>row.text),['圆润桌面']); const repeated={...fields[0],page:'P01',currentText:'另一屏的同名文字格'}; const result=resolveLiveSlotCopy({slot:{...slot,page:'P02'},copyFields:[...copyFields,repeated],journalCopy}); @@ -65,7 +65,7 @@ test('candidate review records the observed subject and alignment while acceptin canvas:{detailImages:async()=>({candidateId:'candidate',referenceCount:1,images:[image,image], relatedCopy:[{fieldId:'tag',text:'实木横梁'}]})}, host:{},slot,candidateId:'candidate',copy:journalCopy, - liveScreenCopy:[{field:'title',text:'加厚桌腿',binding:'direct'}],reviewKnowledge:{files:[],tools:[],guidance:()=>undefined}, + liveScreenCopy:[{field:'title',text:'加厚桌腿',binding:'direct'}], async runAgent(_slot,instructions,prompt,[tool]){ assert.match(instructions,/shownSubject.*shownFields/u); const {screenCopy}=JSON.parse(prompt); @@ -94,12 +94,10 @@ test('candidate review sends the candidate, same-product photo and template comp const result=await reviewProductionCandidate({ canvas:{detailImages:async(_slot,_candidate,options)=>{assert.deepEqual(options,{});return source;}}, host:{},slot,candidateId:'candidate',rule:{crop:true,actionReviewRegion:[0,0,50,50]}, - reviewKnowledge:{files:[{fileId:'special-rule'}],tools:[],guidance:()=>({fileId:'special-rule',text:'企业审稿标准'})}, - async runAgent(_slot,instructions,prompt,[tool],images,_scope,captions){ + async runAgent(_slot,_instructions,prompt,[tool],images,_scope,captions){ assert.deepEqual(images,[candidate,photo,layout]); assert.deepEqual(captions,['受审候选图框','同款实拍 P02','模板构图参考']); - assert.match(instructions,/read_production_knowledge.*企业 Skill/u); - assert.equal(JSON.parse(prompt).taskGuidance.text,'企业审稿标准'); + assert.equal(JSON.parse(prompt).taskGuidance,undefined); assert.doesNotMatch(prompt,/pixelFindings|hasWhiteTopBand|extraViews/u); await tool.execute('review',{candidateId:'candidate',verdict:'pass',reason:'清楚呈现桌腿', checks:{structure:true,color:true,composition:true,evidence:true}}); @@ -120,6 +118,7 @@ test('production delegation and screen rendering use live copy after a direct ca {nativeLayerId:42,mapped:true,text:null,bounds:[32,40,90,130],overlapsSlots:[slot.id]}, ]; const host={store:productionStore(dir),productionGoal:{outputId:'detail',variantId:'oak'},canvas:{ + imageRequest:async()=>[], workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak', template:{contentHash:'fixture'},totalSlots:1,slots:[slot]}), detailCopyFields:async options=>{ @@ -134,7 +133,7 @@ test('production delegation and screen rendering use live copy after a direct ca delegated=JSON.parse(prompt); }}; const actions=await openProductionOperations(host); - await actions.write_copy_fields({recordOnly:true,items:[ + await actions.write_copy_fields({revision:2,recordOnly:true,items:[ {layer:1,text:'圆润桌面',pictures:[slot.fieldId],sources:['P01']}, ]}); live[0].currentText='加厚桌腿'; @@ -169,8 +168,9 @@ test('switching outputs discards the prior canvas copy reads and uses the new li outputId=binding.outputId; return binding; }, + imageRequest:async()=>[], workflowRead:async()=>({available:true,canvasFirst:true,outputId,productVariantId:variantId, - template:{contentHash:'fixture'},totalSlots:1,slots:[slot]}), + template:{contentHash:'fixture'},totalSlots:1,slots:[{...slot,documentId:pages[1]}]}), detailCopyFields:async()=>({revision,pages,fields:[{...fields[0],currentText:copyByOutput[outputId]}]}), detailRender:async({page})=>({page,revision,images:[]}), detailImages:async()=>({candidateId:'candidate',referenceCount:1,images:[image,image]}), @@ -191,18 +191,16 @@ test('switching outputs discards the prior canvas copy reads and uses the new li await action('open_production_output',{outputId:'detail',variantId}); const detail=await action('read_copy_fields'); assert.equal(detail.fields[0].currentText,'加厚桌腿'); - await action('write_copy_fields',{recordOnly:true,items:[ + await action('write_copy_fields',{revision,recordOnly:true,items:[ {layer:1,text:'加厚桌腿',pictures:[slot.fieldId],sources:['仅详情图使用']}, ]}); 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'}]}); diff --git a/apps/detail-agent-pi/test/enterprise-context.test.mjs b/apps/detail-agent-pi/test/enterprise-context.test.mjs index 88f767f1..3efbd78d 100644 --- a/apps/detail-agent-pi/test/enterprise-context.test.mjs +++ b/apps/detail-agent-pi/test/enterprise-context.test.mjs @@ -1,9 +1,11 @@ +import {projectTools} from '../src/project-tools.mjs'; import test from 'node:test'; import assert from 'node:assert/strict'; 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 {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,32 @@ 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.maxGenerationAttempts,3); + assert.equal(binding.resource.skills[0].name,'lighting'); + const {files}=binding; + assert.deepEqual(files.map(({fileId,revision})=>[fileId,revision]),[['workflow','7'],['rules','11']]); + const reviewPath=files[1].path; + const {read}=await projectTools({store,productionSkills:binding}); + const [result]=await Promise.all([ + read('main').execute('',{path:reviewPath}), + binding.resolveFile(reviewPath), + ]); + assert.equal(result.content[0].text,'rules body'); 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(await fs.readFile(reopened.files[1].path,'utf8'),'rules body'); await assert.rejects(ctx.load(input),/尚未发布制作 Skill/u); }); diff --git a/apps/detail-agent-pi/test/json-codec.test.mjs b/apps/detail-agent-pi/test/json-codec.test.mjs index 0bb4175c..50d4ac79 100644 --- a/apps/detail-agent-pi/test/json-codec.test.mjs +++ b/apps/detail-agent-pi/test/json-codec.test.mjs @@ -25,7 +25,7 @@ test('strict JSON never executes prose, unknown tools, extra fields or malformed test('actual Pi SDK consumes JSON codec through real OpenAI parser and validates/executes tools', async () => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-json-sdk-')); const scope = 'c'.repeat(64), store = await ProjectStore.open(dir, { scope, project: randomUUID() }, { brandId: 'qa', shopId: 'qa', categoryId: 'qa', platform: 'qa', version: '1', source: 'qa-fixture', rules: [] }); - let calls = 0, finishes = 0; + let calls = 0; const broker = { info: async () => ({ accountScope: scope, model: { id: 'qa-model', protocol: 'openai-chat', maxTokens: 65536, contextWindow: 131072, contextWindowSource: 'pi-model-catalog:qa/qa-model' }, pending: [] }), @@ -39,13 +39,13 @@ test('actual Pi SDK consumes JSON codec through real OpenAI parser and validates const chunk = { id, model: 'qa-model', choices: [{ index: 0, delta: { role: 'assistant', content: JSON.stringify(answer) }, finish_reason: null }] }; const finish = { id, model: 'qa-model', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }; return new Response(`data: ${JSON.stringify(chunk)}\n\ndata: ${JSON.stringify(finish)}\n\ndata: [DONE]\n\n`, { headers: { 'content-type': 'text/event-stream' } }); - }, finish: async valid => { assert.equal(valid, true); finishes++; return { phase: 'complete' }; } }; + } }; }, }; const host = await DetailPiAgent.open({ store, broker, protocolMode: 'structured-json' }); const result = await host.prompt('这个测试颜色是浅灰色,请记住。'); assert.equal((await store.context()).confirmedMemory.color.value, '浅灰色'); - assert.equal(result.text, '浅灰色已记录'); assert.equal(calls, 2); assert.equal(finishes, 2); + assert.equal(result.text, '浅灰色已记录'); assert.equal(calls, 2); await host.dispose(); await cleanup(dir); }); test('output length stop never executes even a syntactically complete JSON tool prefix', async () => { diff --git a/apps/detail-agent-pi/test/native-wire.test.mjs b/apps/detail-agent-pi/test/native-wire.test.mjs index e2fb8be7..0bc88b4c 100644 --- a/apps/detail-agent-pi/test/native-wire.test.mjs +++ b/apps/detail-agent-pi/test/native-wire.test.mjs @@ -99,7 +99,6 @@ test('native request validation can prove that no model was dispatched', async t try { const round=broker.round(); await assert.rejects(round.fetch('https://api.vip98k.com/v1/chat/completions',{method:'POST',body:'{}'}),/本机拒绝该操作/); - assert.equal(broker.hasUnconfirmedRequest,!rejectedBeforeDispatch); } finally { await broker.close(); } } }); @@ -125,12 +124,10 @@ test('the native bridge reports a retryable preflight to Pi without replaying it const broker=new Native98kBroker({project:randomUUID(),profile,spawnProcess:()=>child}); broker.scope='fixture'; try { - const round=broker.round({inference:true}); + const round=broker.round(); await assert.rejects(round.fetch('https://api.vip98k.com/v1/chat/completions',{method:'POST',body:'{}'}),/network error/); assert.equal(requests.length,1); assert.equal(requests[0].id,round.id); - assert.equal(requests[0].inference,true); - assert.equal(broker.hasUnconfirmedRequest,false); } finally {await broker.close();} }); @@ -147,7 +144,7 @@ test('the native bridge posts only to the endpoint bound to the selected route', await round.fetch('https://api.vip98k.com/v1/responses', {method:'POST',body:'{}'}); assert.equal(requests[0].input.invocationPath,'/v1/responses'); assert.deepEqual(requests[0].input.invocationHeaders,{'X-Relay-Route-Option':route}); - await assert.rejects(round.fetch('https://api.vip98k.com/v1/responses',{method:'POST',body:'{}'}),/禁止自动重发/); + await assert.rejects(round.fetch('https://api.vip98k.com/v1/responses',{method:'POST',body:'{}'}),/只接受一个请求/); assert.equal(requests.length,1); }); @@ -199,7 +196,6 @@ test('an exit signal during native broker startup prevents the original request admit(); await assert.rejects(pending, /退出已停止接单/); assert.deepEqual(requests, []); - assert.equal(broker.hasUnconfirmedRequest, false); }); test('forcing the daemon model bridge closed also closes its goal and slot processes', async t => { @@ -286,19 +282,6 @@ test('a retained Responses function call is audited and decoded without a networ await assert.rejects(parseReceipt({...record,raw:Buffer.from(JSON.stringify(response)).toString('base64')},model,'native-tools',[])); }); -test('an explicit stream rate limit settles the attempt without confirm or replay', async () => { - const broker = new Native98kBroker({project:randomUUID()}); - const calls = []; - broker.start = async (method, _input, event) => { - calls.push(method); - event({type:'headers',status:200,headers:{'content-type':'text/event-stream'}}); - return {phase:'failed',failureCode:'rate_limit_exceeded'}; - }; - const round = broker.round(); - await round.fetch('https://api.vip98k.com/v1/chat/completions', {method:'POST',body:'{}'}); - assert.deepEqual(await round.finish(false,'error'),{phase:'failed',failureCode:'rate_limit_exceeded'}); - assert.deepEqual(calls,['request']); -}); const sse = (delta, finish) => `data: ${JSON.stringify({ id: 'wire', model: 'qa', choices: [{ index: 0, delta, finish_reason: finish }] })}\n\ndata: [DONE]\n\n`; async function setup(reply, finish = async valid => { assert.equal(valid, true); return {phase:'complete'}; }, production, recovery = production) { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-')); @@ -311,7 +294,8 @@ async function setup(reply, finish = async valid => { assert.equal(valid, true); const id=randomUUID(); return { id, fetch: async (_url, init) => { const p = JSON.parse(init.body); requests.push(p); ids.push(id); - return new Response(reply(p, requests.length), { headers: { 'content-type': 'text/event-stream' } }); + const result=reply(p,requests.length); + return result instanceof Response ? result : new Response(result,{headers:{'content-type':'text/event-stream'}}); }, finish }; } }; const canvas=(production||recovery?.canvas)&&{begin:async()=>({}),read:async()=>({conversationActive:true}),detailImages(){}, @@ -371,6 +355,7 @@ test('Pi loads the Skill and opens a project-selected output with the same sessi } return sse({content:'已核对画册。'},'stop'); },undefined,{outputs,template,callBudget:8,canvas:{ + imageRequest:async()=>[], workflowRead:async()=>({available:true,canvasFirst:true,version:1,outputId:'gallery',productVariantId:outputs[1].variantId, template:{contentHash:'fixture'},totalSlots:0,slots:[]}), requestWrite(){assert.fail('selection should not ask for canvas write access');}, @@ -405,9 +390,9 @@ test('Pi loads the Skill and opens a project-selected output with the same sessi }finally{await x.close();} }); -test('ordinary chat resumes the same turn through Pi after a confirmed rate limit', async () => { +test('ordinary chat resumes the same turn through Pi after a rate limit', async () => { const x = await setup((_p, n) => n === 1 - ? 'data: {"error":{"code":"rate_limit_exceeded","type":"server_error"}}\n\n' + ? new Response(JSON.stringify({error:{message:'Rate limit exceeded'}}),{status:429,headers:{'retry-after':'0'}}) : sse({content:'可以继续处理。'}, 'stop'), async valid => valid ? {phase:'complete'} : {phase:'failed',failureCode:'rate_limit_exceeded'}); try { @@ -443,7 +428,7 @@ test('an HTTP 503 native inference receipt reaches Pi retry in the same one-clic if(method==='finish'){finished.push(input.id);return {phase:'complete'};} assert.equal(method,'request'); requests.push(input); - const success=input.inference===true && requests.length>1; + const success=requests.length>1; emit({type:'headers',status:success?200:503,requestId:success?randomUUID():originalId, headers:{'content-type':success?'text/event-stream':'application/json'},bodyHash:'native-wire'}); const error=JSON.stringify({error:{code:'service_unavailable',type:'server_error',message:'Service temporarily unavailable'}}); @@ -466,9 +451,6 @@ test('an HTTP 503 native inference receipt reaches Pi retry in the same one-clic assert.deepEqual(finished,[]); assert.notEqual(requests[0].id,requests[1].id); assert.equal(requests[0].body,requests[1].body); - const guarded=broker.round(); - await guarded.fetch('https://api.vip98k.com/v1/responses',{method:'POST',body:'{}'}); - await assert.rejects(guarded.finish(false,'error'),/结果未知;不会重发/u); }); test('the one-click goal resumes on changed fields at the same count without naming the next tool',async()=>{ @@ -479,16 +461,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)/); } @@ -520,6 +506,21 @@ test('a managed inference interruption retries without executing its partial too } finally {await x.close();} }); +test('a broken model stream stops after the three native retries', async t => { + const x=await setup(()=>new Response(new ReadableStream({ + start(controller) { controller.error(new TypeError('network error: mock stream disconnected')); }, + }),{headers:{'content-type':'text/event-stream'}})); + x.host.callBudget=10; + t.after(()=>x.close()); + const settings=x.host.session.settingsManager; + const retry=settings.getRetrySettings(); + settings.getRetrySettings=()=>({...retry,baseDelayMs:1,maxDelayMs:1}); + await assert.rejects(x.host.prompt('核对进度'),/network error|network connection|connection error/i); + assert.equal(retry.maxRetries,3); + assert.equal(x.requests.length,4); + assert.equal(new Set(x.ids).size,4); +}); + test('actual native Pi wire sends function schemas, executes typed call and accepts a plain final reply', async () => { const x = await setup((_p, n) => n === 1 ? sse({ tool_calls: [{ index: 0, id: 'call-memory', type: 'function', function: { name: 'memory_set', arguments: JSON.stringify({ key: 'color', value: '胡桃色', evidence: '测试颜色是胡桃色' }) } }] }, 'tool_calls') : sse({ content: '已记录胡桃色' }, 'stop')); try { @@ -576,16 +577,24 @@ test('native Pi preserves a required named tool across a retry on a string-only } finally { await x.close(); } }); -test('native partial arguments and length-stopped valid prefixes never execute memory writes', async () => { - for (const [args, finish] of [['{"key":"color","value":"红色","evidence":"测试颜色是红色"', 'tool_calls'], ['{"key":"color","value":"红色","evidence":"测试颜色是红色"}', 'length']]) { - const x = await setup(() => sse({ tool_calls: [{ index: 0, id: 'partial', type: 'function', function: { name: 'memory_set', arguments: args } }] }, finish)); +test('Pi reports malformed tool arguments and never executes a length-stopped write', async () => { + for (const [args, finish] of [['{"key":"color","value":"红色","evidence":"测试颜色是红色"', 'tool_calls'], + ['{"key":"color","value":"红色","evidence":"测试颜色是红色"}', 'length']]) { + const x = await setup((payload, n) => { + if (n===1) return sse({tool_calls:[{index:0,id:'partial',type:'function',function:{name:'memory_set',arguments:args}}]},finish); + assert.equal(finish,'tool_calls'); + assert.ok(payload.messages.some(message=>message.role==='tool'&&message.tool_call_id==='partial')); + return sse({content:'本轮未写入。'},'stop'); + }); try { - await assert.rejects(x.host.prompt('测试颜色是红色'), /未完整|达到线路上限/); + if (finish === 'length') await assert.rejects(x.host.prompt('测试颜色是红色'), /达到线路上限/); + else assert.equal((await x.host.prompt('测试颜色是红色')).text,'本轮未写入。'); assert.deepEqual((await x.store.context()).confirmedMemory, {}); - assert.equal(x.requests.length, 1); + assert.equal(x.requests.length,finish==='length'?1:2); } finally { await x.close(); } } }); + test('required tool returned as prose is a known protocol failure with one POST and no execution', async () => { const x = await setup(() => sse({ content: 'invoke tool memory_set with color red' }, 'stop')); try { @@ -788,9 +797,9 @@ test('main requests keep their original identity without saving a copy of the re const events=journal.trim().split('\n').map(line=>JSON.parse(line)); const budget=events.find(event=>event.type==='context_budget'); assert.equal(budget.originalChars-budget.inputChars,image.length); - const requests=events.filter(event=>event.type==='provider_prepared'); + const requests=events.filter(event=>event.type==='provider_started'); assert.deepEqual(requests.map(event=>event.id),x.ids); - assert.equal(requests[0].purpose,'conversation'); + assert.ok(events.some(event=>event.type==='usage' && event.id===x.ids[0] && event.purpose==='conversation')); assert.ok(events.some(event=>event.type==='provider_finished' && event.id===x.ids[0])); process.env[setting]='1'; await x.host.prompt('继续核对'); @@ -939,12 +948,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(){}}}); @@ -953,7 +963,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();} @@ -993,8 +1004,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}}), @@ -1018,13 +1030,19 @@ test('production publishes direct native commands and no duplicate conversation for(const name of ['read_image_request','freeze_image_request']){ assert.equal(x.host.session.getToolDefinition(name),undefined,name); } - for(const name of ['plan_production','native_catalog','read_production_knowledge','read_copy_fields','read_slot_images','review_image_slots','read_output_screen']){ + for(const name of ['plan_production','native_catalog','read_copy_fields','read_slot_images','review_image_slots','read_output_screen']){ assert.notEqual(x.host.session.getToolDefinition(name).executionMode,'sequential',name); } for(const name of ['native_call','prepare_image_request','dispatch_image_request','transform_slot_image','finish_production']){ 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); @@ -1220,6 +1238,7 @@ test('reading a fresh production goal never starts the strategy, image workers, fields:[{layer:6,page:'intro'},{layer:9,page:'specs'}].filter(field=>!pageId||field.page===pageId), }), read:async()=>({revision:3}), + imageRequest: async stage => {assert.equal(stage,'pending');return [];}, detailRender: async () => ({page:0,revision:3,images:[]}), }, }; diff --git a/apps/detail-agent-pi/test/pi.test.mjs b/apps/detail-agent-pi/test/pi.test.mjs index 169bc80c..998fbfaf 100644 --- a/apps/detail-agent-pi/test/pi.test.mjs +++ b/apps/detail-agent-pi/test/pi.test.mjs @@ -13,7 +13,6 @@ import { piGoalState, recordProductionExport } from '../src/production-goal.mjs' import { EnterpriseContext } from '../src/enterprise-context.mjs'; import { projectTools } from '../src/project-tools.mjs'; import { openEnterpriseSkills } from '../src/enterprise-skill-resources.mjs'; -import { mayContinueProductionGoal } from '../src/production-goal.mjs'; import { cleanup } from './cleanup.mjs'; const identity = () => ({ scope: 'a'.repeat(64), project: randomUUID() }); @@ -36,6 +35,7 @@ test('historical screen images are pruned from model context and retained in the documentId, detailImages() {}, finishProduction:async input=>productionExportReceipt(input), begin: async () => ({}), read: async () => ({conversationActive: true, revision: 3}), delta: async () => {}, activity: async () => {}, end: async () => {}, + imageRequest:async()=>[], workflowRead: async () => ({available: true, canvasFirst: true, version: 1, outputId: 'detail', productVariantId: variantId, template: {contentHash: 'fixture'}, totalSlots: 1, slots: [{id: 'cover', fieldId: 'cover', label: '主视觉', candidates: []}], @@ -90,6 +90,7 @@ test('Pi production and its worker read the same locked Skill and its relative r const canvas={run:'skill-fixture',documentId,detailImages(){},finishProduction:async input=>productionExportReceipt(input),begin:async()=>({run:'skill-fixture',conversationActive:true}), read:async()=>({conversationActive:true,revision:1}),delta:async()=>{},activity:async()=>{},reply:async()=>{},end:async()=>{}, detailCopyFields:async()=>({fields:[]}), + imageRequest:async()=>[], workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:'detail',productVariantId:variantId,totalSlots:1, slots:[{id:'lighting-slot',fieldId:'lamp',label:'灯罩近景'}], template:{id:'two-outputs',version:'v4',contentHash:'v4',enterprise:true,resourceSetId:'lighting'}, @@ -166,7 +167,7 @@ test('Pi production and its worker read the same locked Skill and its relative r assert.equal([...reads.values()].filter(body=>body.includes('PINNED_FINISH')).length,2); assert.deepEqual(documents,[['finish','r7']]); const second=await openEnterpriseSkills(store,selection,()=>{throw Error('run must use the first locked version');}); - assert.equal(second.knowledge.rules[0].revision,'r7'); + assert.equal(second.files.find(file=>file.fileId==='finish').revision,'r7'); const mainSelection={...selection,outputId:'main_images',releaseId:'main-v4'}; const mainBinding=await openEnterpriseSkills(store,mainSelection,pins=>{ assert.equal(pins.get(knowledge.skills[0].path).revision,'r4'); @@ -225,21 +226,6 @@ test('native read reports an unavailable linked document and can read it once pu assert.deepEqual([searchCalls,reads],[2,1]); }); -test('Pi continues the goal without a host readiness gate', async () => { - const host={productionGoal:{deadline:Date.now()/1000+60}}; - for(let turn=0;turn<4;turn++)assert.equal(await mayContinueProductionGoal(host),true); - for(const stopReason of ['error','aborted']){ - assert.equal(await mayContinueProductionGoal(host,{messages:[{role:'assistant',stopReason}]}),false); - } - host.productionCompletion={receipt:{completed:true}}; - assert.equal(await mayContinueProductionGoal(host),false); - host.productionCompletion=null; - host.productionGoal.deadline=Date.now()/1000-1; - assert.equal(await mayContinueProductionGoal(host),true); - host.productionSignal=AbortSignal.abort(); - assert.equal(await mayContinueProductionGoal(host),false); -}); - test('Pi pauses after a continuation without tools and resumes on a new user request', {timeout:10000}, async t=>{ const dir=await root(), id=identity(), documentId=13, variantId=randomUUID(); const store=await ProjectStore.open(dir,id,binding('pause')); @@ -251,6 +237,7 @@ test('Pi pauses after a continuation without tools and resumes on a new user req run:'pause-fixture',documentId,detailImages(){}, begin:async()=>({conversationActive:true}),read:async()=>({conversationActive:true,revision:1}), delta:async()=>{},activity:async()=>{},end:async()=>{}, + imageRequest:async()=>[], workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:stage, productVariantId:variantId,totalSlots:0,slots:[],template:{contentHash:stage}, productEvidence:{accountScope:id.scope,project:id.project,documentId,brief:{}}}), @@ -301,13 +288,14 @@ test('explicit tools share one Pi transcript and submit each real canvas revisio begin:async()=>({run:'goal-fixture',conversationActive:true,context:null}), read:async()=>({conversationActive:true,revision}),delta:async()=>{},end:async()=>{}, activity:async(_label,event)=>publicActivity.push(event), + imageRequest:async()=>[], workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:stage, productVariantId:variantId,totalSlots:0,slots:[],template:{contentHash:stage}, productEvidence:{accountScope:id.scope,project:id.project,documentId:13,brief:{}}}), 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 +304,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(); @@ -371,6 +359,8 @@ test('explicit tools share one Pi transcript and submit each real canvas revisio const completed=entries.findLast(e=>e.type==='custom'&&e.customType==='pi-goal'); assert.equal(completed.data.goal.status,'complete'); savedGoal=completed.data.goal.id; + await host.session.prompt('/goal pause'); + assert.equal(piGoalState(host.manager).status,'paused'); }finally{await host.dispose();} assert.equal(copyWrites,1); assert.ok(publicActivity.every(row=>row.scope.documentId===canvas.documentId&&row.scope.run===canvas.run)); diff --git a/apps/detail-agent-pi/test/production-goal.test.mjs b/apps/detail-agent-pi/test/production-goal.test.mjs index 5c03f313..d1b890c4 100644 --- a/apps/detail-agent-pi/test/production-goal.test.mjs +++ b/apps/detail-agent-pi/test/production-goal.test.mjs @@ -7,6 +7,7 @@ test('an elapsed legacy production deadline allows the goal and its local tool t let called=0,aborted=0; const host={manager:{getBranch:()=>[]},productionGoal:{deadline:1,requestedOutputs:[{outputId:'detail'}]}, session:{ + messages:[], sendCustomMessage:async()=>{}, prompt:async()=>{called++}, waitForIdle:()=>idle.promise, diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index b3545a83..a97178e7 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -5,35 +5,81 @@ import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; -import { openProductionOperations } from '../src/production-operations.mjs'; -import { callProductionTool, closeProductionTurn, currentProductionOperations, mayContinueProductionGoal } from '../src/production-goal.mjs'; +import { openProductionOperations as openOperations } from '../src/production-operations.mjs'; +import { callProductionTool, closeProductionTurn, currentProductionOperations } from '../src/production-goal.mjs'; import { cleanup } from './cleanup.mjs'; import { bindRecovery } from '../src/desktop-host.mjs'; +import { openEnterpriseSkills } from '../src/enterprise-skill-resources.mjs'; import { productionStore } from './production-store-fixture.mjs'; +const imageBridges=new WeakSet(); + +// The fixture models the host journal. Each Pi operations instance reads it anew. function imageBridge(host,dispatch,id=()=>randomUUID()) { const prepared=new Map(); - host.canvas.imageRequest=async(action,args,execution)=>{ + const canvas=host.canvas; + imageBridges.add(canvas); + const workflowRead=canvas.workflowRead.bind(canvas); + const originalRecovery=canvas.detailRecover?.bind(canvas); + canvas.workflowRead=async input=>{ + const view=await workflowRead(input); + const matching=[...prepared.values()].filter(({receipt})=> + receipt.outputId===view.outputId&&receipt.variantId===view.productVariantId&&receipt.phase!=='prepared'); + return {...view,slots:view.slots?.map(slot=>({...slot,candidates:[ + ...(slot.candidates??[]),...matching.filter(({receipt})=>receipt.slotId===slot.id&& + !slot.candidates?.some(row=>row.id===receipt.requestId)) + .map(({receipt,result},index)=>({...result,id:receipt.requestId,status:receipt.phase,sequence:(slot.candidates?.length??0)+index+1, + reworkOf:receipt.reworkOf,instructions:receipt.spec.prompt})), + ]}))}; + }; + const settle=(receipt,result)=>{ + Object.assign(receipt,{phase:result.status,resultExpiry:result.resultExpiry,message:result.message}); + prepared.get(receipt.requestId).result=result; + }; + canvas.detailRecover=async(slot,options,scope)=>{ + const result=await originalRecovery(slot,options,scope); + const {receipt}=prepared.get(options.candidateId)??{}; + if(receipt)settle(receipt,result); + return result; + }; + canvas.imageRequest=async(action,args,execution)=>{ + if(action==='pending')return [...prepared.values()].filter(({receipt})=> + ['dispatched','running','unknown'].includes(receipt.phase)).map(({receipt})=>({ + slotId:receipt.slotId,candidateId:receipt.requestId,operationId:receipt.requestId, + phase:receipt.phase,outputId:receipt.outputId,variantId:receipt.variantId, + })); if(action==='prepare'){ const requestId=id(); - const receipt={requestId,revision:1,requestSpecHash:'fixture-digest',frozen:false, + const receipt={requestId,revision:1,requestSpecHash:'fixture-digest',frozen:false,phase:'prepared', + templateHash:(await workflowRead({section:'overview',outputId:host.productionGoal.outputId})).template.contentHash, outputId:host.productionGoal.outputId,variantId:host.productionGoal.variantId,slotId:args.slotId, reworkOf:args.reworkOf,reworkChange:args.reworkChange,spec:{prompt:args.instructions}}; prepared.set(requestId,{receipt,args}); return structuredClone(receipt); } - assert.equal(action,'dispatch'); - assert.deepEqual(Object.keys(args),['requestId','expectedRevision','expectedHash','slotId','workerNumber']); const request=prepared.get(args.requestId); - assert.ok(request); + if(!request)throw Error('未找到原生生图请求'); + if(action==='read')return structuredClone(request.receipt); + assert.equal(action,'dispatch'); assert.equal(args.slotId,request.receipt.slotId); if(args.expectedHash!==request.receipt.requestSpecHash||args.expectedRevision!==request.receipt.revision){ - throw new BridgeError('生图请求版本已变化,请重新准备'); + throw Object.assign(new BridgeError('生图请求版本已变化,请重新准备'),{dispatched:false}); } if(dispatch.length<4)execution?.onEnqueued?.(); - return dispatch(request.args,args.requestId,args.workerNumber,execution?.onEnqueued); + request.receipt.phase='dispatched'; + const result=await dispatch(request.args,args.requestId,args.workerNumber,execution?.onEnqueued); + settle(request.receipt,result); + return result; }; + return {prepared,settle}; } +function openProductionOperations(host,options){ + const canvas=host.canvas; + const original=canvas.imageRequest?.bind(canvas); + canvas.imageRequest=async(action,...args)=> action==='pending'&&!imageBridges.has(canvas) ? [] : original(action,...args); + return openOperations(host,options); +} + function approve({requestId,revision,requestSpecHash}) { return {requestId,expectedRevision:revision,expectedHash:requestSpecHash}; } @@ -73,7 +119,7 @@ async function tailFixture(t,ids,items={}){ const host={store,productionGoal:{outputId:'detail',variantId:'oak'},canvas:{ workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak', template:{contentHash:'studio'},totalSlots:slots.length,slots}), - detailCopyFields:async()=>({fields:[]}), + imageRequest:async()=>[],detailCopyFields:async()=>({fields:[]}), async delta(_text,_thinking,{heading}){notices.get(heading)?.resolve();}, }}; if(Object.keys(items).length)ledger.repository.replaceLedger({binding:JSON.stringify(['studio','oak']),items}); @@ -84,50 +130,56 @@ async function tailFixture(t,ids,items={}){ }}; } -test('a newly uncertain dispatch and a restored frozen request are watched without posting again',{timeout:5000},async t=>{ - for(const reopen of [false,true])await t.test(reopen?'restored from the ledger':'reported during production',async t=>{ - const {dir,host,ledger,clock,notice}=await tailFixture(t,['hero']); - const posted=[],reads=[]; - const recovered=notice('原请求结果已取回'); - const result=Promise.withResolvers(); - imageBridge(host,async(_args,id)=>{ - posted.push(id); - return {id,status:'unknown'}; - }); - host.canvas.detailRecover=async(slotId,{candidateId})=>{ - reads.push({slotId,candidateId}); - return result.promise; - }; - let actions=await openProductionOperations(host,{tailWatchClock:clock}); - assert.equal(clock.nextDue,undefined); - const original=await generateAndWait(actions,{slotId:'hero',prompt:'保留同款结构'}); - assert.equal(original.phase,'unknown'); - if(reopen){ - await actions.close(); - assert.equal(clock.nextDue,undefined); - actions=await openProductionOperations(host,{tailWatchClock:clock}); - } - t.after(()=>actions.close()); - assert.equal(clock.nextDue,0); - await clock.advance(); - const manual=actions.reconcile_image_slots({slotIds:['hero']}); - assert.deepEqual(reads,[{slotId:'hero',candidateId:original.candidateId}]); - const localImage=path.join(dir,'recovered-image.png'); - await fs.writeFile(localImage,'native image fixture'); - result.resolve({id:original.candidateId,status:'complete',path:localImage}); - const [receipt]=await manual; - await recovered; - assert.equal(receipt.phase,'complete'); - assert.equal(receipt.operationId,original.operationId); - assert.deepEqual(reads,[{slotId:'hero',candidateId:original.candidateId}]); - assert.deepEqual(posted,[original.candidateId]); - assert.deepEqual((await actions.await_image_slots({slotIds:['hero']})).generation,[receipt]); - assert.equal(ledger.repository.readImageRequest(original.candidateId).receipt.path,localImage); - const saved=JSON.parse(await fs.readFile(path.join(dir,'production-detail-oak.json'),'utf8')); - assert.deepEqual(saved.items.hero.pendingGenerations,{}); - assert.equal(saved.items.hero.state,'candidate'); - assert.equal(clock.nextDue,undefined); +test('a host-owned original survives a Pi restart and is recovered without another POST',async t=>{ + const {dir,host,ledger,clock}=await tailFixture(t,['hero']); + const posted=[],reads=[]; + host.canvas.detailRecover=async(slotId,{candidateId})=>{ + reads.push({slotId,candidateId}); + return {id:candidateId,status:'complete'}; + }; + imageBridge(host,async(_args,id)=>{ + posted.push(id); + return {id,status:'unknown'}; }); + let actions=await openProductionOperations(host,{tailWatchClock:clock}); + const original=await generateAndWait(actions,{slotId:'hero',prompt:'保留同款结构'}); + assert.equal(original.phase,'unknown'); + const closed=await actions.close(); + assert.deepEqual(closed.inFlightImages,[{slotId:'hero',requestId:original.candidateId,operationId:original.operationId}]); + actions=await openProductionOperations(host,{tailWatchClock:clock}); + t.after(()=>actions.close()); + assert.equal(clock.nextDue,undefined); + assert.equal((await actions.dispatch_image_request({requestId:original.candidateId})).pendingOriginal,original.candidateId); + const [receipt]=await actions.reconcile_image_slots({slotIds:['hero']}); + assert.equal(receipt.phase,'complete'); + assert.equal(receipt.operationId,original.operationId); + assert.deepEqual(reads,[{slotId:'hero',candidateId:original.candidateId}]); + assert.deepEqual(posted,[original.candidateId]); + assert.equal(ledger.repository.readImageRequest(original.candidateId),null); + assert.equal(ledger.read(),null); + await assert.rejects(fs.stat(path.join(dir,'production-detail-oak.json')),{code:'ENOENT'}); +}); + +test('a candidate reserved before POST neither owns the slot nor spends its draw budget',async t=>{ + const {host}=await tailFixture(t,['hero'],{ + hero:{state:'unknown',pendingGenerations:{'reserved-before-send':{candidateId:'reserved-before-send'}}}, + }); + const workflowRead=host.canvas.workflowRead; + host.canvas.workflowRead=async input=>{ + const view=await workflowRead(input); + return {...view,template:{...view.template,production:{maxGenerationAttempts:1}},slots:view.slots.map(slot=>({...slot,generationRequestIds:[], + candidates:[{id:'reserved-before-send',status:'dispatched'}]}))}; + }; + const posted=[]; + imageBridge(host,async(_args,id)=>{ + posted.push(id); + return {id,status:'complete'}; + }); + const actions=await openProductionOperations(host); + const receipt=await generateAndWait(actions,{slotId:'hero',prompt:'本款正面'}); + assert.equal(receipt.phase,'complete'); + assert.deepEqual(posted,[receipt.candidateId]); + await actions.close(); }); test('six original lookups run while all six generation delegates are posting',{timeout:8000},async t=>{ @@ -287,8 +339,9 @@ for(const stop of ['abort','close'])test(`${stop} stops queued lookups and ignor 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=4)=>({generationAttempts:attempts, + 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-')); @@ -427,7 +480,7 @@ test('a late image settles its original request after cancellation without selec detailCopyFields:async()=>({fields:[]}),delta:async()=>{}, workflowExecute:async()=>assert.fail('a cancelled candidate cannot be adopted'), }}; - imageBridge(host,async(_args,id)=>{started.resolve();await done.promise;return {id,status:'complete'};}); + const native=imageBridge(host,async(_args,id)=>{started.resolve();await done.promise;return {id,status:'complete'};}); const old=await openProductionOperations(host); const prepared=await old.prepare_image_request({slotId:'photo',prompt:'保留桌面轮廓'}); assert.equal((await old.dispatch_image_request(approve(prepared),abort.signal)).phase,'accepted'); @@ -436,17 +489,10 @@ test('a late image settles its original request after cancellation without selec done.resolve(); await old.await_image_slots({}); await old.close(); - const receipt=ledger.repository.readImageRequest(prepared.requestId); - assert.equal(receipt.state,'complete'); - assert.equal(receipt.operationId,prepared.operationId); - assert.equal(receipt.receipt.consumption,'archived_after_cancel'); - assert.equal(ledger.read().items.photo.candidateId,undefined); - assert.equal(ledger.read().items.photo.pendingAdoption,undefined); - assert.deepEqual(events.find(event=>event.type==='image_request_receipt'),{ - type:'image_request_receipt',operationId:prepared.operationId,requestId:prepared.requestId, - outputId:'detail',variantId:'oak',slotId:'photo',category:'remote_image',phase:'archive', - status:'cancelled',consumption:'archived_after_cancel', - }); + assert.equal(native.prepared.get(prepared.requestId).receipt.phase,'complete'); + assert.equal(ledger.repository.readImageRequest(prepared.requestId),null); + assert.equal(ledger.read(),null); + assert.equal(events.some(event=>event.type==='image_request_receipt'),false); const fresh=await openProductionOperations({...host,productionSignal:new AbortController().signal}); assert.equal((await fresh.plan_production()).outputId,'detail'); await fresh.close(); @@ -456,12 +502,6 @@ test('switch keeps other output workers and their original requests without wait const {host,ledger,clock}=await tailFixture(t,['active','queued']); const posted=Promise.withResolvers(), remote=Promise.withResolvers(), queuedStarted=Promise.withResolvers(); const workerStarts=[]; - const archived=Promise.withResolvers(); - const appendEvent=host.store.appendEvent.bind(host.store); - host.store.appendEvent=async event=>{ - await appendEvent(event); - if(event.type==='image_request_receipt')archived.resolve(); - }; const localTransport=Promise.withResolvers(); imageBridge(host,async(_args,id,_number,onEnqueued)=>{ posted.resolve(id); @@ -470,6 +510,13 @@ test('switch keeps other output workers and their original requests without wait await remote.promise; return {id,status:'complete'}; }); + const archived=Promise.withResolvers(); + const imageRequest=host.canvas.imageRequest; + host.canvas.imageRequest=async (action,...args)=>{ + const receipt=await imageRequest(action,...args); + if(action==='dispatch')archived.resolve(); + return receipt; + }; host.runDetailAgent=async(slotId,_instructions,_prompt,tools,_images,_scope,_captions,signal)=>{ workerStarts.push(slotId); assert.equal(signal.aborted,false); @@ -523,9 +570,10 @@ test('switch keeps other output workers and their original requests without wait await queuedStarted.promise; assert.deepEqual(workerStarts,['active','queued']); remote.resolve(); - await archived.promise; assert.equal(host.productionGoal.outputId,'main_images'); - assert.equal(ledger.read().items.active.candidateId,requestId); + await archived.promise; + assert.equal((await host.canvas.imageRequest('read',{requestId})).phase,'complete'); + assert.equal(ledger.repository.readImageRequest(requestId),null); const reopened=await callProductionTool(host,'open_production_output',{outputId:'detail',variantId:'oak'}); assert.equal(reopened.outputId,'detail'); assert.equal(await currentProductionOperations(host),operations); @@ -538,7 +586,7 @@ test('project image discovery can stage a completed image on another output with const target={outputId:'detail',variantId:'oak'}; host.productionGoal.requestedOutputs=[source,target]; const candidate={...source,slotId:'source',fieldId:'M01',candidateId:'completed',width:1600,height:1200, - adoptionRecorded:true,reviewDecision:'pass'}; + adoptionRecorded:true,reviewDecision:'pass',generationAttempts:2,sourceRequestId:'original'}; const staged=[]; host.canvas.detailHistory=async options=>{ if(options.projectPlan){ @@ -549,7 +597,7 @@ test('project image discovery can stage a completed image on another output with assert.deepEqual(options,{projectImages:true,...source}); return [candidate]; }; - host.canvas.imageRequest=()=>assert.fail('本地复用不应派发生图'); + host.canvas.imageRequest=async action=>{assert.equal(action,'pending','本地复用不应派发生图');return [];}; host.canvas.detailArchive=async(slotId,args)=>{ staged.push({slotId,...args}); return {id:'reused',status:'complete',reusedFrom:{candidateId:args.candidateId}}; @@ -566,7 +614,7 @@ test('project image discovery can stage a completed image on another output with assert.deepEqual(staged,[{slotId:'target',projectId:undefined,candidateId:candidate.candidateId,forReview:true}]); }); -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'; @@ -574,10 +622,12 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr const worker=Promise.withResolvers(); const ledger=store.ledger(outputId,variantId); const binding=JSON.stringify(['template',variantId]); + let pending=[]; const host={ store,productionGoal:{outputId,variantId}, runDetailAgent:()=>worker.promise, canvas:{ + imageRequest:async()=>pending, workflowRead:async()=>({available:true,canvasFirst:true,outputId,productVariantId:variantId, template:{contentHash:'template'},totalSlots:1,slots:[{id:slotId,fieldId:'M01'}]}), detailCopyFields:async()=>({fields:[]}),delta:async()=>{},read:async()=>({revision:1}), @@ -587,20 +637,22 @@ 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',{}); await closeProductionTurn(host); const original={candidateId:'original-image',operationId:'original-operation'}; - ledger.repository.replaceLedger({binding,items:{[slotId]:{state:'unknown', - pendingGenerations:{[original.candidateId]:original}}}}); + pending=[{...original,outputId,variantId,slotId,phase:'unknown'}]; host.productionWork?.clear(); - 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}); @@ -609,12 +661,12 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr assert.deepEqual(receipt.originals,deferred.originals); assert.equal(host.productionCompletion,undefined); + pending=[]; ledger.repository.replaceLedger({binding,items:{[slotId]:{state:'candidate', review:{candidateId:'rejected-image',decision:'revise',reason:'主体构图需要调整'}}}}); host.productionWork?.clear(); 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); }); @@ -641,7 +693,6 @@ test('deferral records a hard blocker even when the production operations cannot blocker:{...blocker,requiredAction:' '}, },signal), error=>error===unavailable); assert.deepEqual(submissions,[]); - assert.equal(await mayContinueProductionGoal(host),true); const receipt=await callProductionTool(host,'defer_production_output',{blocker,scope:'current'},signal); assert.deepEqual(submissions,[{outputId,variantId,complete:false,stageStatus:'hard-blocked',blocker, @@ -649,7 +700,6 @@ test('deferral records a hard blocker even when the production operations cannot assert.equal(currentProductionOperations(host),undefined); assert.deepEqual(host.productionGoal.pendingOutputs,[]); assert.equal(host.productionCompletion.receipt,receipt); - assert.equal(await mayContinueProductionGoal(host),false); }); test('an unbound production turn checks project originals without opening any working canvas',async t=>{ @@ -660,12 +710,14 @@ test('an unbound production turn checks project originals without opening any wo const main={outputId:'main_images',variantId:'white'}; const ledger=store.ledger(main.outputId,main.variantId); const goal={requestedOutputs:[detail,main],pendingOutputs:[detail,main]}; - const calls=[]; + const calls=[],pending=[]; const host={store,productionGoal:goal,canvas:{ openProductionOutput(){assert.fail('project reconciliation must leave canvas selection unchanged');}, - workflowRead(){assert.fail('project reconciliation must use the saved ledger');}, + workflowRead(){assert.fail('project reconciliation must use the original host records');}, + imageRequest:async()=>pending, async detailRecover(slot,request,scope){ calls.push({slot,request,scope}); + pending.length=0; return {id:request.candidateId,status:'complete'}; }, }}; @@ -674,6 +726,7 @@ test('an unbound production turn checks project originals without opening any wo ledger.repository.replaceLedger({binding:JSON.stringify(['main-template','white']),items:{ 'original-slot':{state:'unknown',pendingGenerations:{original:{candidateId:'original',operationId:'operation'}}}, }}); + pending.push({...main,slotId:'original-slot',candidateId:'original',operationId:'operation'}); assert.equal((await callProductionTool(host,'plan_production',{})).workingOutput,null); assert.deepEqual(await reconcile({slotIds:['other-slot']}),{scope:'project',results:[]}); const result=await reconcile({}); @@ -682,7 +735,7 @@ test('an unbound production turn checks project originals without opening any wo {...main,slotId:'original-slot',candidateId:'original',operationId:'operation',phase:'complete'}, ]); assert.deepEqual(calls,[{slot:'original-slot',request:{candidateId:'original'},scope:main}]); - assert.deepEqual(ledger.read().items['original-slot'].pendingGenerations,{}); + assert.deepEqual(ledger.read().items['original-slot'].pendingGenerations,{original:{candidateId:'original',operationId:'operation'}}); assert.deepEqual(await reconcile({}),{scope:'project',results:[]}); assert.equal(goal.outputId,undefined); }); @@ -691,18 +744,16 @@ test('the unbound production plan lists the same readable knowledge files as the const {host}=await tailFixture(t,['hero']); const boundGoal=host.productionGoal; host.productionGoal={requestedOutputs:[boundGoal],pendingOutputs:[boundGoal]}; - host.productionSkills={knowledge:{skills:[{ - fileId:'released-file',revision:'r3',path:'production/SKILL.md',kind:'skill',loadText:async()=>'以本款事实为依据', - }]}}; - const plan=await callProductionTool(host,'plan_production',{}); + host.productionSkills={files:[{fileId:'released-file',revision:'r3',path:'production/SKILL.md',kind:'skill'}]}; + assert.equal((await callProductionTool(host,'plan_production',{})).knowledgeFiles,undefined); + const plan=await callProductionTool(host,'plan_production',{includeKnowledge:true}); assert.equal(plan.workingOutput,null); assert.deepEqual(plan.knowledgeFiles,[{fileId:'released-file',revision:'r3',path:'production/SKILL.md',kind:'skill'}]); - const {text}=await callProductionTool(host,'read_production_knowledge',{fileId:plan.knowledgeFiles[0].fileId}); - assert.equal(text,'以本款事实为依据'); 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=>{ @@ -766,7 +817,7 @@ test('candidate review leaves placement to the main agent, even with an old temp }; imageBridge(host,async(_request,id)=>{ posts.push(id); - assert.ok(ledger.read().items[slotId].pendingGenerations[id]); + assert.equal(ledger.repository.readImageRequest(id),null); firstStarted.resolve(); await complete.promise; return {status:recoverA&&id===posts[0]?'unknown':'complete',id}; @@ -783,7 +834,7 @@ test('candidate review leaves placement to the main agent, even with an old temp await actions.dispatch_image_request(approve(a)); await firstStarted.promise; assert.equal((await actions.dispatch_image_request(approve(a))).phase,'already_running'); - assert.deepEqual(Object.keys(ledger.read().items[slotId].pendingGenerations),[a.requestId]); + assert.equal(ledger.repository.readImageRequest(a.requestId),null); complete.resolve(); while(actions.active)await actions.await_image_slots({}); await actions.close(); @@ -976,8 +1027,9 @@ test('a rework delegate sees the rejected image, exact previous prompt and revie assert.equal(exact.attemptCount,3); assert.equal(overview.rejectionCount,2); assert.equal(overview.rejections,undefined); - assert.deepEqual(exact.record.attempts.at(-1),{candidateId:'replacement',source:'generate', - prompt:'以同款原片直杆为准,改为单张自然光近景',reworkOf:'old',change:'去掉模板构图并以原片确认支撑形状'}); + assert.equal(exact.generations?.find(row=>row.candidateId==='replacement')?.reworkOf ?? + exact.generation.reworkOf,'old'); + assert.equal(exact.record.attempts.at(-1).candidateId,'old'); await ops.delegate_image_slots({jobs:[{slotId:'front',goal:'核对指定候选',reworkCandidateId:'missing'}]}); await ops.await_image_slots({}); @@ -1129,9 +1181,9 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca variants[1].colorName='暖白色'; creation++; const prepare=canvas.imageRequest; - canvas.imageRequest=(action,args)=>{ + canvas.imageRequest=(action,args,execution)=>{ if(action==='prepare')assert.equal(args.retryOf,undefined); - return prepare(action,args); + return prepare(action,args,execution); }; const draft=await actions.prepare_image_request({...request,retryOf:''}); assert.equal(draft.spec.prompt,request.prompt); @@ -1146,7 +1198,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'); @@ -1208,9 +1259,7 @@ test('a lost native acknowledgement can be recovered with the saved generation o const host={canvas,store,productionGoal:{outputId:'detail',variantId:'ink'}}; imageBridge(host,async(_args,operationId)=>{ submissions.push(operationId); - const pending=journal().items[slotId].pendingGenerations[operationId]; - assert.equal(pending.operationId,operationId); - assert.equal(pending.candidateId,operationId); + assert.equal(journal(),null); throw new BridgeError('画布连接中断,原操作不会重发','transport_interrupted',{dispatched:true}); }); let actions=await openProductionOperations(host,{tailWatchClock}); @@ -1232,91 +1281,44 @@ test('a lost native acknowledgement can be recovered with the saved generation o assert.equal(recovered.operationId,originalId); assert.deepEqual(recoveries,[{slot:slotId,candidateId:originalId},{slot:slotId,candidateId:originalId}]); assert.deepEqual(submissions,[originalId]); - assert.deepEqual(journal().items[slotId].pendingGenerations,{}); + assert.equal(journal(),null); + await actions.close(); }); -test('410 settles only the original result and permits an explicitly prepared replacement',async t=>{ - for(const legacy of [false,true])await t.test(legacy?'imported R28 ledger':'frozen SQLite request',async t=>{ - const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-expiry-')); - t.after(()=>cleanup(dir)); - const store=productionStore(dir); - const ledger=store.ledger('main_images','ink'); - const {repository}=ledger; - const slotId='main-photo'; - const originalId=randomUUID(), remoteRequestId=randomUUID(); - const resultExpiry={httpStatus:410,source:'retained-result',requestId:remoteRequestId,observedAt:1795685081}; - const expiry={id:originalId,status:'expired',requestId:remoteRequestId,retryable:false,resultExpiry,message:'原生图结果已过期'}; - let response='timeout'; +test('the host can settle 410, failure and exhausted unresolved, then Pi can prepare another request',async t=>{ + for(const terminal of ['expired','failed','unresolved'])await t.test(terminal,async t=>{ + const {host,ledger}=await tailFixture(t,['hero']); + let status='unknown'; const posted=[], reads=[]; - const host={store,productionGoal:{outputId:'main_images',variantId:'ink'},canvas:{ - workflowRead:async()=>({available:true,canvasFirst:true,outputId:'main_images',productVariantId:'ink', - template:{contentHash:'fixture'},totalSlots:1,slots:[{id:slotId,fieldId:'M02-I01'}]}), - detailCopyFields:async()=>({fields:[]}),delta:async()=>{}, - async detailRecover(slot,{candidateId}){ - reads.push({slot,candidateId}); - if(response==='timeout'||response==='connection lost')throw Error(response); - return response==='410'?expiry:{id:originalId,status:'unknown',message:'HTTP '+response}; - }, - }}; - if(legacy){ - await fs.writeFile(path.join(dir,'production-main_images-ink.json'),JSON.stringify({ - binding:JSON.stringify(['fixture','ink']),preparedRequests:{[originalId]:{slotId,prompt:'旧提示词'}}, - items:{[slotId]:{state:'unknown',candidateId:originalId,source:'generate', - pendingOperation:{candidateId:originalId,operationId:originalId,kind:'frozen-image'}, - attempts:[{candidateId:originalId,prompt:'旧提示词',source:'generate'}]}}, - })); - } + const resultExpiry={httpStatus:410,requestId:'original-remote'}; + host.canvas.detailRecover=async(slotId,{candidateId})=>{ + reads.push([slotId,candidateId]); + return {id:candidateId,status,...(status==='expired'?{resultExpiry}:null)}; + }; imageBridge(host,async(_args,id)=>{ posted.push(id); - return {id,status:id===originalId?'unknown':'complete'}; - },()=>!legacy&&!posted.length?originalId:randomUUID()); - - let actions=await openProductionOperations(host); - const input={slotId:'M02-I01',source:'generate',prompt:'旧提示词'}; - if(!legacy)assert.equal((await generateAndWait(actions,input)).phase,'unknown'); - const before=legacy?[]:[originalId]; - await actions.close(); - actions=await openProductionOperations(host); - for(response of ['timeout','connection lost','429','503']){ - const [receipt]=await actions.reconcile_image_slots({slotIds:[slotId]}); - assert.equal(receipt.phase,'unknown'); - assert.equal(receipt.candidateId,originalId); - assert.equal((await generateAndWait(actions,{...input,prompt:'新提示词'})).pendingOriginal,originalId); - assert.deepEqual(posted,before); - if(!legacy)assert.equal(repository.readImageRequest(originalId).state,'unknown'); - } - - response='410'; - const [expired]=await actions.reconcile_image_slots({slotIds:[slotId]}); - assert.deepEqual(expired,{slotId,candidateId:originalId,operationId:originalId,phase:'expired', - reason:expiry.message,requestId:remoteRequestId,retryable:false,resultExpiry}); - assert.deepEqual(posted,before); - const replacements=reads.length; - assert.ok(reads.every(read=>read.slot===slotId&&read.candidateId===originalId)); - if(!legacy)assert.equal(repository.readImageRequest(originalId).state,'expired'); - await actions.close(); - - actions=await openProductionOperations(host); - assert.equal((await actions.reconcile_image_slots({slotIds:[slotId]}))[0].phase,'none'); - assert.equal(reads.length,replacements); - const same=await actions.dispatch_image_request({requestId:originalId,expectedRevision:1,expectedHash:'fixture-digest'}); - assert.equal(same.phase,'accepted'); - assert.equal((await actions.await_image_slots({slotIds:[slotId]})).generation[0].phase,'expired'); - assert.deepEqual(posted,before); - - const replacement=await generateAndWait(actions,{...input,prompt:'新提示词'}); - assert.equal(replacement.phase,'complete'); - assert.notEqual(replacement.candidateId,originalId); - assert.deepEqual(posted,[...before,replacement.candidateId]); - const {items}=JSON.parse(await fs.readFile(path.join(dir,'production-main_images-ink.json'),'utf8')); - assert.equal(items[slotId].candidateId,replacement.candidateId); - assert.equal(items[slotId].pendingOperation??null,null); - assert.deepEqual(items[slotId].pendingGenerations,{}); - assert.deepEqual(items[slotId].attempts.find(item=>item.candidateId===originalId),{ - candidateId:originalId,source:'generate',prompt:'旧提示词',phase:'expired', - requestId:remoteRequestId,retryable:false,resultExpiry, + return {id,status:posted.length===1?'unknown':'complete'}; }); - assert.deepEqual(repository.candidateEvidence(slotId,originalId).at(-1).detail.resultExpiry,resultExpiry); + const actions=await openProductionOperations(host); + const input={slotId:'hero',prompt:'原提示词'}; + const original=await generateAndWait(actions,input); + assert.equal(original.phase,'unknown'); + assert.equal((await actions.reconcile_image_slots({}))[0].candidateId,original.candidateId); + assert.equal((await generateAndWait(actions,{...input,prompt:'新提示词'})).pendingOriginal,original.candidateId); + assert.deepEqual(posted,[original.candidateId]); + // Exhaustion is a terminal receipt supplied by the Rust recovery owner. + status=terminal==='unresolved'?'failed':terminal; + const [settled]=await actions.reconcile_image_slots({}); + assert.equal(settled.phase,status); + if(terminal==='expired')assert.deepEqual(settled.resultExpiry,resultExpiry); + assert.equal((await actions.dispatch_image_request({requestId:original.candidateId})).phase,status); + const next=await generateAndWait(actions,{...input,prompt:'新提示词'}); + assert.equal(next.phase,'complete'); + assert.notEqual(next.candidateId,original.candidateId); + assert.deepEqual(reads,[['hero',original.candidateId],['hero',original.candidateId]]); + assert.deepEqual(posted,[original.candidateId,next.candidateId]); + assert.equal(ledger.repository.readImageRequest(original.candidateId),null); + assert.equal(ledger.repository.readImageRequest(next.candidateId),null); await actions.close(); }); }); @@ -1369,7 +1371,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]}; @@ -1455,19 +1457,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,'用户手改'); @@ -1479,12 +1480,12 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it assert.match(submissions[0].instructions,/场景桌面上的一盏灯$/u); assert.equal(submissions[0].prefer2k,true); const overview=(await actions.review_image_slots({slotIds:[]})).pictures.find(row=>row.id==='lamp-photo'); - const exact=(await actions.review_image_slots({slotIds:['lamp']})).pictures[0].record; + const exact=(await actions.review_image_slots({slotIds:['lamp']})).pictures[0]; assert.equal(overview.state,'unknown'); assert.equal(overview.record,undefined); assert.equal(overview.candidates,undefined); - assert.equal(exact.pendingGenerations[first.candidateId].operationId,first.operationId); - assert.match(exact.prompt,/场景桌面上的一盏灯/u); + assert.equal(exact.generation.candidateId,first.candidateId); + assert.match(exact.generation.instructions,/场景桌面上的一盏灯/u); assert.equal((await generateAndWait(actions,{slotId:'lamp',source:'generate',prompt:'更换灯罩角度'})).phase,'unknown'); assert.equal(submissions.length,1); const ledger=host.store.ledger(outputId,variantId); @@ -1580,7 +1581,7 @@ test('worker progress shares a number with delegated image dispatch and reuses r detailImages:async()=>{await reviewRelease.promise; throw Error('测试候选不提供像素');}, async delta(_text,_thinking,progress){ if(progress.heading==='子代理正在制作'&&progress.workers.length===5)started.resolve(progress); - if(progress.heading==='子代理正在生图')generating.resolve(progress); + if(progress.workers.some(row=>row.slotId===first.id&&row.step==='正在生图'))generating.resolve(progress); if(progress.heading==='子代理正在验图')checking.resolve(progress); if(progress.heading==='验图已有回执')reviewed.resolve(progress); }, @@ -1795,7 +1796,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; @@ -1813,21 +1814,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++; @@ -1839,19 +1843,40 @@ 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(); }); -test('the fourth draw occupies the last slot while in flight and a rejected candidate can still be exported',async t=>{ +test('template draw limits override the lowest published enterprise Skill limit',async t=>{ + const {host}=await tailFixture(t,['hero']); + host.productionSkills=await openEnterpriseSkills(host.store,host.productionGoal,async()=>({ + skills:[6,5].map((limit,index)=>({ + fileId:`guide-${index}`,revision:'1',kind:'skill',path:`guides/guide-${index}/SKILL.md`, + text:`---\nname: guide-${index}\ndescription: Production guide.\nmaxGenerationAttempts: ${limit}\n---\n`, + })), + rules:[], + })); + const workflowRead=host.canvas.workflowRead; + for(const [production,expected] of [[{},5],[{maxGenerationAttempts:7},7]]){ + host.canvas.workflowRead=async()=>{ + const page=await workflowRead(); + return {...page,template:{...page.template,production}}; + }; + const ops=await openProductionOperations(host); + const {pictures:[picture]}=await ops.plan_production({}); + assert.equal(picture.maxGenerationAttempts,expected); + await ops.close(); + } +}); + +test('the bundled draw limit applies in flight and a rejected candidate can still be exported',async t=>{ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-draw-limit-')); t.after(()=>cleanup(dir)); const store=productionStore(dir); @@ -1905,6 +1930,7 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand dispatches.push(id); if(dispatches.length===3){fourthStarted.resolve();await fourthDone.promise;} slot.candidates.push({id,status:'complete',sourceType:null}); + slot.generationRequestIds?.push(id); return {id,status:'complete'}; }); const ops=await openProductionOperations(host); @@ -1912,9 +1938,10 @@ 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)); + slot.generationRequestIds=['existing']; + 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:'同款侧面'}); @@ -1922,7 +1949,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:'同款低机位'}); @@ -1931,28 +1958,28 @@ 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,{phase:'draw_limit_reached',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),{phase:'draw_limit_reached',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.productionWork=new Map([[JSON.stringify(["detail","oak"]),Promise.resolve(ops)]]); assert.deepEqual((await callProductionTool(host,'finish_production',{revision:3})).files,['detail.png']); assert.equal(exported[0].canvasRevision,3); await ops.close(); - const reopened=await openProductionOperations(host,{maxGenerationAttempts:5}); - assertStatus((await reopened.plan_production()).pictures[0],drawStatus(4,5)); + const reopened=await openProductionOperations(host); + assertStatus((await reopened.plan_production()).pictures[0],drawStatus(4,4)); await reopened.close(); }); diff --git a/apps/detail-agent-pi/test/production-store-fixture.mjs b/apps/detail-agent-pi/test/production-store-fixture.mjs index d26ad7d5..9225d265 100644 --- a/apps/detail-agent-pi/test/production-store-fixture.mjs +++ b/apps/detail-agent-pi/test/production-store-fixture.mjs @@ -27,9 +27,10 @@ export function productionExportReceipt({outputId,variantId,canvasRevision,compl export function stubProductionOperations(host, target, operations) { const {outputId,variantId}=target; const status={outputId,variantId,inFlightImages:[]}; + host.canvas.imageRequest??=async()=>[]; const work=host.productionWork??=new Map(); work.set(JSON.stringify([outputId,variantId]),Promise.resolve({ - suspendCanvas:async()=>{},resumeCanvas(){},workStatus:()=>status, + suspendCanvas:async()=>[],resumeCanvas(){},workStatus:()=>status, unfinished:async()=>({}),close:async()=>status,...operations, })); } diff --git a/apps/detail-agent-pi/test/project-repository.test.mjs b/apps/detail-agent-pi/test/project-repository.test.mjs index 86fec589..409ee75c 100644 --- a/apps/detail-agent-pi/test/project-repository.test.mjs +++ b/apps/detail-agent-pi/test/project-repository.test.mjs @@ -5,7 +5,6 @@ import os from 'node:os'; import path from 'node:path'; import { DatabaseSync } from 'node:sqlite'; import test from 'node:test'; -import { Worker } from 'node:worker_threads'; import { openProductionOperations } from '../src/production-operations.mjs'; import { ProjectRepository } from '../src/project-repository.mjs'; import { recordProductionInputs } from '../src/production-repository.mjs'; @@ -22,7 +21,16 @@ const request = (requestId = 'image-a', spec = { prompt: '用同款实拍约束 const approve = draft => ({ requestId: draft.requestId, expectedHash: draft.requestSpecHash, expectedRevision: draft.revision, }); -const pending = journal => journal.items.front?.pendingOperation; +function seedLegacyRequest(repo, draft, state='prepared', receipt=null) { + repo.readLedger(); + const db=new DatabaseSync(repo.file); + try { + db.prepare(`INSERT INTO image_requests + (account_id,project_id,output_id,variant_id,request_id,operation_id,slot_id,request_spec_hash,revision,state,prepared_json,receipt_json) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`).run(...repo.scope,draft.requestId,draft.operationId,draft.slotId,draft.requestSpecHash, + draft.revision,state,JSON.stringify(draft),receipt&&JSON.stringify(receipt)); + } finally { db.close(); } +} async function fixture(t) { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-project-repository-')); @@ -114,11 +122,11 @@ test('P01 local facts, document evidence and delivery reopen without a collabora assert.deepEqual(open().readDelivery(), delivery); }); -test('P02 stores the exact complete prompt and rejects changes at the same revision', async t => { +test('P02 reopens the exact complete prompt from a legacy request', async t => { const { file, open, repo } = await fixture(t); const draft = request('long', { prompt: '自然光与质感。\n'.repeat(300) + '末尾必需限制:只保留一件。\r\n' }); assert.ok(draft.spec.prompt.length > 2000); - repo.saveImageRequest(draft); + seedLegacyRequest(repo, draft); assert.equal(open().readVersion('prompt', 'long', 1).prompt, draft.spec.prompt); assert.equal(open().readImageRequest('long').prepared.spec.prompt, draft.spec.prompt); const db = new DatabaseSync(file, { readOnly:true }); @@ -127,46 +135,40 @@ test('P02 stores the exact complete prompt and rejects changes at the same revis } finally { db.close(); } - assert.throws(() => repo.saveImageRequest(request('long', { prompt: 'changed' })), /新版本/); }); -test('P03 the production bridge sends reviewed identity and the display number after an atomic local freeze', async t => { +test('P03 dispatches a host-confirmed request once without a Pi request row', async t => { const { dir } = await fixture(t); const store = productionStore(dir, { scope: scope.accountId, project: scope.projectId }); const repo = store.ledger('detail', 'oak').repository; - const draft = request('frozen', { prompt: '原始完整文字\n保留边缘', modelId: 'actual-model', - parameters: { size: '2048x2048' }, references: [{ position: 1, role: 'product', sha256: hash('reference') }] }); - const calls = []; - const host = { store, productionGoal: { outputId: 'detail', variantId: 'oak' }, canvas: { - workflowRead: async () => ({ available: true, canvasFirst: true, outputId: 'detail', productVariantId: 'oak', - template: { contentHash: 'template' }, totalSlots: 1, slots: [{ id: 'front', fieldId: 'cover' }] }), - detailCopyFields: async () => ({ fields: [] }), - delta: async () => {}, - async imageRequest(action, args) { - if (action === 'prepare') return draft; + const draft = {...request('frozen'),phase:'prepared',outputId:'detail',variantId:'oak',templateHash:'template'}; + const slot={id:'front',fieldId:'cover',candidates:[]}; + const calls=[]; + const host={store,productionGoal:{outputId:'detail',variantId:'oak'},canvas:{ + workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak', + template:{contentHash:'template'},totalSlots:1,slots:[slot]}), + detailCopyFields:async()=>({fields:[]}),delta:async()=>{}, + async imageRequest(action,args,execution){ + if(action==='pending')return []; + if(action==='read'||action==='prepare')return {...draft}; calls.push(args); - const saved = repo.readImageRequest(draft.requestId); - assert.equal(saved.state, 'dispatching'); - assert.equal(typeof saved.frozenAt, 'number'); - assert.deepEqual(saved.prepared.spec, draft.spec); - assert.equal(repo.readLedger().items.front.pendingGenerations[draft.requestId].operationId, draft.operationId); - const portable = JSON.parse(await fs.readFile(path.join(dir, 'production-detail-oak.json'), 'utf8')); - assert.equal(portable.items.front.pendingGenerations[draft.requestId].operationId, draft.operationId); - assert.equal(portable.preparedRequests[draft.requestId].prompt, draft.spec.prompt); - return { status: 'complete', id: draft.requestId, materialTaskId: draft.requestId }; + assert.equal(args.expectedRevision,draft.revision); + assert.equal(args.expectedHash,draft.requestSpecHash); + execution.onEnqueued(); + draft.phase='complete'; + slot.candidates.push({id:draft.requestId,status:'complete'}); + return {status:'complete',id:draft.requestId}; }, }}; - const tools = await openProductionOperations(host); - const prepared = await tools.prepare_image_request({ slotId: 'cover', prompt: draft.spec.prompt }); - await tools.dispatch_image_request({ ...approve(prepared), expectedRevision: 2 }); - assert.equal((await tools.await_image_slots({ slotIds: ['cover'] })).generation[0].phase, 'failed'); - assert.equal(calls.length, 0); - for (let attempt = 0; attempt < 2; attempt++) { - await tools.dispatch_image_request({ requestId: prepared.requestId }); - assert.equal((await tools.await_image_slots({ slotIds: ['cover'] })).generation[0].phase, 'complete'); - } - assert.deepEqual(calls, [{ ...approve(draft), slotId: 'front', workerNumber: 1 }]); - assert.equal(repo.readImageRequest(draft.requestId).receipt.status, 'complete'); + const tools=await openProductionOperations(host); + const prepared=await tools.prepare_image_request({slotId:'cover',prompt:draft.spec.prompt}); + assert.equal((await tools.dispatch_image_request(approve(prepared))).phase,'accepted'); + assert.equal((await tools.await_image_slots({})).generation[0].phase,'complete'); + assert.equal((await tools.dispatch_image_request({requestId:prepared.requestId})).phase,'complete'); + assert.deepEqual(calls,[{...approve(draft),slotId:'front',workerNumber:1}]); + assert.equal(repo.readImageRequest(draft.requestId),null); + assert.equal(repo.readLedger(),null); + await assert.rejects(fs.stat(path.join(dir,'production-detail-oak.json')),{code:'ENOENT'}); await tools.close(); }); @@ -180,7 +182,7 @@ test('P04 keeps original and normalized references, asset identities and send or position: index + 1, role: 'product', source: 'P1', originalAssetId: original.assetId, sourceSha256: original.sha256, assetId: input.assetId, sha256: input.sha256, })); - repo.saveImageRequest(request('p1', { prompt: '同款两视角。', references })); + seedLegacyRequest(repo, request('p1', { prompt: '同款两视角。', references })); assert.deepEqual(open().readImageRequest('p1').prepared.spec.references, references); assert.equal(open().readAsset(references[0].originalAssetId).path, original.path); assert.equal(open().readAsset(references[1].assetId).path, wide.path); @@ -190,8 +192,8 @@ test('P05 a prompt edit cannot relabel a candidate generated by the old request' const { repo } = await fixture(t); const first = request('old', { prompt: '第一版' }); const corrected = { ...request('rework', { prompt: '新取景' }), reworkOf: 'old', reworkChange: '修改机位' }; - repo.saveImageRequest(first); - repo.saveImageRequest(corrected); + seedLegacyRequest(repo, first); + seedLegacyRequest(repo, corrected); repo.recordCandidate('front', 'old', 'candidate', { requestId: 'old', requestSpecHash: first.requestSpecHash }); repo.recordCandidate('side', 'reuse', 'candidate', { reusedFrom: { projectId: 'project', candidateId: 'old' } }); assert.equal(repo.candidateEvidence('front', 'old')[0].detail.requestSpecHash, first.requestSpecHash); @@ -219,48 +221,22 @@ test('P07 two intentionally equivalent samples keep distinct operations and actu const b = request('sample-b'); assert.equal(a.requestSpecHash, b.requestSpecHash); for (const draft of [a, b]) { - repo.saveImageRequest(draft); - assert.equal(repo.claimImageRequest(approve(draft), binding, pending).claimed, true); + seedLegacyRequest(repo, draft); } - assert.deepEqual(Object.keys(open().readLedger().items.front.pendingGenerations), [a.requestId, b.requestId]); for (const draft of [a, b]) { - repo.updateLedger(binding, journal => { delete journal.items[draft.slotId].pendingGenerations[draft.requestId]; }, { - receipt: [draft.requestId, 'complete', { status: 'complete' }], - evidence: [draft.slotId, draft.requestId, 'review', { candidateId: draft.requestId, decision: 'pass' }], - }); + repo.recordCandidate(draft.slotId,draft.requestId,'review',{candidateId:draft.requestId,decision:'pass'}); } assert.notEqual(open().readImageRequest(a.requestId).operationId, open().readImageRequest(b.requestId).operationId); assert.deepEqual(repo.candidateEvidence('front', b.requestId).map(row => row.kind), ['review']); }); -test('P08 concurrent workers claim one operation and a restarted worker retains the original', async t => { - const { file, open, repo } = await fixture(t); - const draft = request('interrupted'); - repo.saveImageRequest(draft); - const start = new SharedArrayBuffer(4); - const run = () => new Promise((resolve, reject) => { - const worker = new Worker(` - const { parentPort, workerData } = require('node:worker_threads'); - (async () => { - const { ProjectRepository } = await import(workerData.module); - const repo = new ProjectRepository(workerData.file, workerData.scope); - const barrier = new Int32Array(workerData.start); - Atomics.add(barrier, 0, 1); - Atomics.notify(barrier, 0); - Atomics.wait(barrier, 0, 1, 5000); - parentPort.postMessage(repo.claimImageRequest(workerData.approval, workerData.binding, - journal => journal.items.front?.pendingOperation).claimed); - })().catch(error => { throw error; }); - `, { eval: true, workerData: { start, file, scope, binding, approval: approve(draft), - module: new URL('../src/project-repository.mjs', import.meta.url).href } }); - worker.once('message', resolve); - worker.once('error', reject); - }); - assert.deepEqual((await Promise.all([run(), run()])).sort(), [false, true]); - const resumed = open().claimImageRequest(approve(draft), binding, pending); - assert.equal(resumed.claimed, false); - assert.equal(resumed.pending.operationId, draft.operationId); - assert.equal(open().readImageRequest(draft.requestId).state, 'dispatching'); +test('P08 reads the original dispatching state from a historical database after reopening', async t => { + const {repo,open}=await fixture(t); + const draft=request(); + seedLegacyRequest(repo,draft,'dispatching'); + const saved=open().readImageRequest(draft.requestId); + assert.equal(saved.state,'dispatching'); + assert.equal(saved.operationId,draft.operationId); }); test('P09 output, variant, project and account are independent even when their IDs overlap', async t => { @@ -268,15 +244,13 @@ test('P09 output, variant, project and account are independent even when their I const neighbors = [open({ variantId: 'walnut' }), open({ outputId: 'main_images' }), open({ projectId: 'other' }), open({ accountId: 'other' })]; const draft = request(); - repo.saveImageRequest(draft); - repo.claimImageRequest(approve(draft), binding, pending); + seedLegacyRequest(repo, draft); for (const other of neighbors) { assert.equal(other.readImageRequest(draft.requestId), null); assert.equal(other.readLedger(), null); other.replaceLedger({ binding: 'independent', items: { front: { candidateId: 'other' } } }); } - repo.updateLedger(binding, journal => { journal.items.front.candidateId = draft.requestId; }, - { receipt: [draft.requestId, 'complete', { status: 'complete' }] }); + repo.updateLedger(binding, journal => { journal.items.front = {candidateId:draft.requestId}; }); for (const other of neighbors) assert.equal(other.readLedger().items.front.candidateId, 'other'); }); @@ -301,7 +275,7 @@ test('P11 records the actual background request separately from local compositin const { repo } = await fixture(t); const draft = request('background', { prompt: '移除模板中的旧商品。', sceneComposite: true, references: [{ position: 1, role: 'scene', sha256: hash('template scene') }] }); - repo.saveImageRequest(draft); + seedLegacyRequest(repo,draft,'complete',{status:'complete'}); repo.recordCandidate('front', 'composite', 'candidate', { requestId: 'background', processing: { kind: 'composite', productAssetId: 'actual-product-cutout', placement: [10, 20, 900, 1200] } }); assert.deepEqual(repo.readImageRequest('background').prepared.spec.references.map(row => row.role), ['scene']); @@ -329,7 +303,7 @@ test('P13 reloads full facts, plan, formal prompt and locked rule from stable ve }, [{ id: 'front', fieldId: 'cover', requirements: '展示圆角' }]); const draft = { ...request(), productFactsRevision, planRevision, knowledge: [{ fileId: 'image-prompt', revision: 'r7' }] }; - repo.saveImageRequest(draft); + seedLegacyRequest(repo, draft); const { prepared } = open().readImageRequest(draft.requestId); assert.equal(open().readVersion('product_facts', 'product', prepared.productFactsRevision).facts.items[0].source, 'P1'); assert.equal(open().readVersion('plan', 'production', prepared.planRevision).slots[0].requirements, '展示圆角'); @@ -337,37 +311,16 @@ test('P13 reloads full facts, plan, formal prompt and locked rule from stable ve assert.deepEqual(prepared.knowledge, draft.knowledge); }); -test('P14 reads the locked rule on demand and surfaces an unavailable reference', async t => { - const { dir } = await fixture(t); - const store = productionStore(dir); - let available = false; - const tools = await openProductionOperations({ store, productionGoal: { outputId: 'detail', variantId: 'oak' }, - canvas: { workflowRead: async () => ({ available: true, canvasFirst: true, outputId: 'detail', productVariantId: 'oak', - template: { contentHash: 'template' }, totalSlots: 0, slots: [] }) }, - productionSkills: { knowledge: { rules: [{ fileId: 'prompt-framework', revision: 'locked', kind: 'image-prompt', - loadText: async () => { - if (!available) throw Error('锁定版本引用暂不可读取'); - return '正式提示词结构'; - } }] } }, - }); - await assert.rejects(tools.read_production_knowledge({ fileId: 'prompt-framework' }), /锁定版本引用暂不可读取/); - available = true; - const rule = await tools.read_production_knowledge({ fileId: 'prompt-framework' }); - assert.deepEqual(rule, { fileId: 'prompt-framework', revision: 'locked', text: '正式提示词结构', nextOffset: null }); -}); - test('P15 execution success and a failed pixel check remain independently traceable', async t => { const { open, repo } = await fixture(t); const draft = request('undersize', { prompt: '输出 4K,保留产品结构。' }); - repo.saveImageRequest(draft); - repo.claimImageRequest(approve(draft), binding, pending); - repo.recordImageReceipt(draft.requestId, 'complete', { status: 'complete' }); + seedLegacyRequest(repo,draft,'complete',{status:'complete'}); repo.recordCandidate('front', draft.requestId, 'review', { decision: 'revise', actualPixels: [1024, 1024], reason: '尺寸不足且接合结构错误', }); const next = { ...request('corrected'), reworkOf: draft.requestId }; - repo.saveImageRequest(next); - assert.equal(open().readImageRequest(draft.requestId).state, 'complete'); + seedLegacyRequest(repo, next); + assert.equal(open().readImageRequest(draft.requestId).prepared.spec.prompt,draft.spec.prompt); assert.equal(open().candidateEvidence('front', draft.requestId)[0].detail.decision, 'revise'); assert.equal(open().readImageRequest(next.requestId).prepared.reworkOf, draft.requestId); }); diff --git a/apps/detail-agent-pi/test/recovery.test.mjs b/apps/detail-agent-pi/test/recovery.test.mjs index ea2f0ff4..b712c46f 100644 --- a/apps/detail-agent-pi/test/recovery.test.mjs +++ b/apps/detail-agent-pi/test/recovery.test.mjs @@ -1,5 +1,5 @@ -import { stubProductionOperations } from './production-store-fixture.mjs'; -import { productionExportReceipt } from './production-store-fixture.mjs'; +import { BridgeError } from '../src/bridge-error.mjs'; +import { productionExportReceipt, stubProductionOperations } from './production-store-fixture.mjs'; import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; @@ -8,7 +8,6 @@ import os from 'node:os'; import { randomUUID } from 'node:crypto'; import { ProjectStore } from '../src/store.mjs'; import { DetailPiAgent } from '../src/agent.mjs'; -import { recoverProductionResponse } from '../src/production-recovery.mjs'; import { cleanup } from './cleanup.mjs'; const setup = async () => { @@ -26,69 +25,6 @@ test('project lease rejects another process/session before opening transcript or const b = await DetailPiAgent.open({ store, transport }); await b.dispose(); await cleanup(root); }); -test('received final reply recovers from bytes, persists and reopens without inference', async () => { - const { root, scope, store } = await setup(); - let confirmations = 0, posts = 0; - const id = randomUUID(); - await store.appendEvent({ type: 'provider_prepared', id, bindingHash: store.hash }); - const original = { id: 'qa-original-response', model: 'qa', choices: [{ message: { role: 'assistant', content: '{"reply":"草稿已保留"}' }, finish_reason: 'stop' }] }; - const broker = { - info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: [] }), - read: async () => ({ phase: 'received', terminal: true, model: { id: 'qa', protocol: 'openai-chat' }, raw: Buffer.from(JSON.stringify(original)).toString('base64'), bodyHash: 'qa', requestId: 'retained-qa' }), - confirm: async () => { confirmations++; return { phase: 'complete' }; }, - round() { posts++; throw Error('must never post'); }, - }; - let host = await DetailPiAgent.open({ store, broker, protocolMode: 'structured-json' }); - const result = await host.recover(id); - assert.equal(result.reposted, false); assert.equal(result.reopenRequired, true); assert.equal(confirmations, 1); assert.equal(posts, 0); - await host.dispose(); - host = await DetailPiAgent.open({ store, broker, protocolMode: 'structured-json' }); - assert.equal(host.session.getLastAssistantText(), '草稿已保留'); - const again = await host.recover(id); - assert.equal(again.alreadyApplied, true); assert.equal(posts, 0); - await host.dispose(); await cleanup(root); -}); - -test('recovers structured image review for the original slot without adding it to chat',async()=>{ - const {root,scope,store}=await setup(); - const id=randomUUID(); - const review=JSON.stringify({decision:'generate',reason:'同款产品依据齐备'}); - await store.appendEvent({type:'provider_prepared',id,purpose:'whole-detail-review',bindingHash:store.hash}); - let phase='unknown',posts=0,lookups=0; - const model={id:'qa',protocol:'openai-chat'}; - const original={id:'review-original',model:'qa',choices:[{message:{role:'assistant',content:review},finish_reason:'stop'}]}; - const broker={info:async()=>({accountScope:scope,model,pending:[]}), - read:async()=>({phase,terminal:true,model,raw:Buffer.from(JSON.stringify(original)).toString('base64'),bodyHash:'qa',requestId:'review-original'}), - recover:async request=>{assert.equal(request,id);lookups++;phase='received';}, - confirm:async()=>{phase='complete';return {phase};},round(){posts++;throw Error('must not post');}}; - const host=await DetailPiAgent.open({store,broker,protocolMode:'structured-json'}); - try{ - const result=await host.recover(id); - assert.equal(result.phase,'complete'); - assert.equal(result.canvasWrites,0); - assert.equal(lookups,1); - assert.equal(host.session.messages.length,0); - assert.match(result.restoredText,/已核查原验图结果/); - assert.equal(result.reposted,false); - assert.equal(posts,0); - }finally{await host.dispose();await cleanup(root);} -}); -test('explicit text recovery queries the original without submitting inference', async () => { - const { root, scope, store } = await setup(); - let queries = 0, posts = 0; - await store.appendEvent({ type: 'provider_prepared', id: 'original', bindingHash: store.hash }); - const broker = { - info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: [{ id: 'original', phase: 'unknown' }] }), - read: async () => ({ phase: 'unknown', requestId: 'original-qa' }), - recover: async () => { queries++; throw Error('原请求查询HTTP 410,结果未知;不会重发'); }, - round() { posts++; throw Error('must not post'); }, - }; - const host = await DetailPiAgent.open({ store, broker }); - const result = await host.recover('original'); - assert.equal(result.phase, 'unknown'); assert.equal(result.reposted, false); - assert.equal(queries, 1); assert.equal(posts, 0); - await host.dispose(); await cleanup(root); -}); test('a waiting detail original does not hold independent main image and SKU goals',async t=>{ const {root,scope,store}=await setup(); t.after(()=>cleanup(root)); @@ -182,92 +118,6 @@ test('DeepSeek Flash 1017 can receive an optional strategy tool and product imag } }); -test('a retained terminal model refusal unblocks production without reposting or running tools', async t => { - for(const [protocol,body] of [ - ['anthropic-messages','data: {"type":"message_delta","delta":{"stop_reason":"refusal"}}\n\ndata: {"type":"message_stop"}\n\n'], - ['openai-chat','data: {"choices":[{"index":0,"finish_reason":"content_filter"}]}\n\ndata: [DONE]\n\n'], - ]){ - const {root,scope,store}=await setup(); - t.after(()=>cleanup(root)); - const id=randomUUID(),requestId=randomUUID(); - const model={id:'fixture',protocol}; - const raw=Buffer.from(body).toString('base64'); - await store.appendEvent({type:'provider_prepared',purpose:'product-goal',id,bindingHash:store.hash}); - const confirmed=[]; - const broker={ - info:async()=>({accountScope:scope,model,pending:[]}), - read:async originalId=>{ - assert.equal(originalId,id); - return {phase:'received',terminal:true,model,raw,bodyHash:'same',requestId}; - }, - confirm:async(...args)=>{confirmed.push(args);return {phase:'rejected'};}, - }; - const host=await DetailPiAgent.open({store,broker}); - try { - assert.deepEqual(await host.recover(id),{phase:'failed',requestId,reposted:false,canvasWrites:0}); - assert.deepEqual(confirmed,[[id,'same',false,'refusal']]); - } finally {await host.dispose();} - } -}); - -test('original production recovery waits for the durable finish and releases confirmed terminal truncation',async t=>{ - const {root,scope,store}=await setup(); - t.after(()=>cleanup(root)); - const model={id:'qa',protocol:'openai-chat'}; - for(const [finishReason,finishPhase,wanted] of [ - ['length','rejected','failed'], - ['stop','received','unknown'], - ['stop','complete','complete'], - ]){ - const id=randomUUID(),requestId=randomUUID(); - await store.appendEvent({type:'provider_prepared',id,purpose:'product-goal',bindingHash:store.hash}); - const bytes='data: '+JSON.stringify({id:requestId,model:'qa',choices:[{index:0, - delta:{role:'assistant',content:'部分制作回复'},finish_reason:finishReason}]})+'\n\ndata: [DONE]\n\n'; - let phase='unknown',checks=0; - const broker={ - info:async()=>({accountScope:scope,model,pending:[]}), - read:async original=>{ - assert.equal(original,id); - return {phase,terminal:phase==='received',model,bodyHash:'same',requestId,raw:Buffer.from(bytes).toString('base64')}; - }, - recover:async original=>{assert.equal(original,id);checks++;phase='received';}, - confirm:async(original,hash,valid,reason)=>{ - assert.deepEqual([original,hash,valid,reason],[id,'same',finishReason==='stop',finishReason]); - return {phase:finishPhase}; - }, - round:()=>assert.fail('recovery must not post'), - }; - const host=await DetailPiAgent.open({store,broker}); - try { - assert.deepEqual(await host.recover(id),{phase:wanted,requestId,reposted:false,canvasWrites:0}); - assert.equal(checks,1); - }finally{await host.dispose();} - } -}); - -test('production recovery reads the original result after the selected chat model changes', async t => { - const {root,scope,store}=await setup(); - t.after(()=>cleanup(root)); - const id=randomUUID(), requestId=randomUUID(); - const selected={id:'new-text-choice',protocol:'openai-chat',supportsImageInput:false}; - const model={id:'previous-visual-choice',protocol:'openai-chat'}; - const raw=Buffer.from(JSON.stringify({model:model.id,choices:[{ - index:0,message:{role:'assistant',content:'已核对首屏原图。'},finish_reason:'stop', - }]})).toString('base64'); - await store.appendEvent({type:'provider_prepared',purpose:'whole-detail-worker',id,bindingHash:store.hash}); - const broker={ - info:async()=>({accountScope:scope,model:selected,pending:[]}), - read:async originalId=>{ - assert.equal(originalId,id); - return {phase:'complete',terminal:true,model,requestId,raw}; - }, - }; - const host=await DetailPiAgent.open({store,broker}); - try { - assert.deepEqual(await host.recover(id),{phase:'complete',requestId,reposted:false,canvasWrites:0}); - } finally {await host.dispose();} -}); - test('the main Anthropic session serializes short cache markers through the native broker', async t => { const {root,scope,store}=await setup(); t.after(()=>cleanup(root)); @@ -370,32 +220,6 @@ test('Opus 5.5 planning and review use automatic tools while preserving their im } }); -test('an original request confirmed failed can be closed without replay and followed by a new message', async () => { - const { root, scope, store } = await setup(); - const id = randomUUID(), requestId = randomUUID(); - let phase = 'unknown', queries = 0, posts = 0; - await store.appendEvent({ type: 'provider_prepared', id, bindingHash: store.hash }); - const broker = { - info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: phase === 'unknown' ? [{ id, phase }] : [] }), - read: async () => ({ phase, requestId }), - recover: async original => { assert.equal(original, id); queries++; phase = 'failed'; }, - round() { - return { id: randomUUID(), fetch: async () => { - posts++; - const reply = { id: 'next', model: 'qa', choices: [{ index: 0, delta: { content: '可以接着聊。' }, finish_reason: 'stop' }] }; - return new Response(`data: ${JSON.stringify(reply)}\n\ndata: [DONE]\n\n`, { headers: { 'content-type': 'text/event-stream' } }); - }, finish: async () => ({ phase: 'complete' }) }; - }, - }; - const host = await DetailPiAgent.open({ store, broker }); - try { - assert.deepEqual(await host.recover(id), { phase: 'failed', requestId, reposted: false }); - assert.equal(queries, 1); - assert.equal(posts, 0); - assert.equal((await host.prompt('继续讨论已有图片')).text, '可以接着聊。'); - assert.equal(posts, 1); - } finally { await host.dispose(); await cleanup(root); } -}); test('handover stops the next model step locally rather than spending another call', async () => { const { root, scope, store } = await setup(); let posts = 0, ended; const broker = { info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: [] }), round() { @@ -404,45 +228,9 @@ test('handover stops the next model step locally rather than spending another ca const raw=`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{tool_calls:[call]},finish_reason:'tool_calls'}]})}\n\ndata: [DONE]\n\n`; return {id:randomUUID(),fetch:async()=>new Response(raw,{headers:{'content-type':'text/event-stream'}}),finish:async()=>({phase:'complete'})}; } }; - const canvas = { async begin() {}, async read() { return { conversationActive:true,allowed:false,writeBlocked:true,revision:1 }; },async activity(){},async requestWrite(){throw Error('用户已接手,写入未获许可');},async edit(){throw Error('must never edit');}, async end(text) { ended = text; } }; + const canvas = { async begin() {}, async read() { return { conversationActive:true,allowed:false,writeBlocked:true,revision:1 }; },async activity(){},async requestWrite(){throw new BridgeError('用户已接手,写入未获许可','write_revoked');},async edit(){throw Error('must never edit');}, async end(text) { ended = text; } }; const host = await DetailPiAgent.open({ store, broker, canvas }); const result = await host.prompt('开始后立即接手'); - assert.match(result.text, /本机:已接手/); assert.match(ended, /停止/); assert.equal(posts, 1); + assert.match(result.text, /用户已接手/); assert.equal(ended,result.text); assert.equal(posts, 1); await host.dispose(); await cleanup(root); }); -test('original SSE restores read-only tool through SDK schema/hook pipeline, without inference', async () => { - const { root, scope, store } = await setup(); let phase = 'unknown', posts = 0, queries = 0; - const id = randomUUID(), answer = JSON.stringify({ toolCalls: [{ name: 'context_read', arguments: {} }] }); - await store.appendEvent({ type: 'provider_prepared', id, bindingHash: store.hash }); - const raw = `data: ${JSON.stringify({ id: 'qa-sse', model: 'qa', choices: [{ index: 0, delta: { content: answer }, finish_reason: null }] })}\n\ndata: ${JSON.stringify({ id: 'qa-sse', model: 'qa', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`; - const broker = { - info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: phase === 'complete' ? [] : [{ id, phase }] }), - read: async () => ({ phase, terminal: phase !== 'unknown', raw: Buffer.from(raw).toString('base64'), model: { id: 'qa', protocol: 'openai-chat' }, requestId: 'qa-request', bodyHash: 'qa' }), - recover: async () => { queries++; phase = 'received'; }, confirm: async () => { phase = 'complete'; }, - round() { posts++; throw Error('must not post'); }, - }; - let host = await DetailPiAgent.open({ store, broker, protocolMode: 'structured-json' }); - const result = await host.recover(id, { executeReadOnly: true }); - assert.equal(result.readOnlyToolsRecovered, 1); assert.equal(result.canvasWrites, 0); assert.equal(queries, 1); assert.equal(posts, 0); - await host.dispose(); - host = await DetailPiAgent.open({ store, broker, protocolMode: 'structured-json' }); - assert.ok(host.session.messages.some(m => m.role === 'toolResult' && m.toolName === 'context_read')); - assert.equal((await host.recover(id)).alreadyApplied, true); - await host.dispose(); await cleanup(root); -}); -test('a result from another shop cannot be restored or queried into this conversation', async () => { - const { root, scope, store } = await setup(); let reads = 0; - const broker = { info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: [] }), read: async () => { reads++; } }; - const host = await DetailPiAgent.open({ store, broker }); - await assert.rejects(host.recover(randomUUID()), /不属于当前/); - assert.equal(reads, 0); - await host.dispose(); await cleanup(root); -}); - -test('production recovery verifies the original request identity before confirming failure',async()=>{ - const requestId='confirmed-failed-review'; - const settled={phase:'failed',requestId,originalLookup:{verified:true,status:'failed',requestId}}; - assert.equal((await recoverProductionResponse({read:async()=>settled},'local',null,[])).confirmedFailure,true); - assert.equal((await recoverProductionResponse({read:async()=>({...settled,originalLookup:{...settled.originalLookup, - requestId:'another-request'}})},'local',null,[])).confirmedFailure,undefined); -}); diff --git a/apps/detail-agent-pi/test/screen-review.test.mjs b/apps/detail-agent-pi/test/screen-review.test.mjs index 2af2724d..aca5b7ad 100644 --- a/apps/detail-agent-pi/test/screen-review.test.mjs +++ b/apps/detail-agent-pi/test/screen-review.test.mjs @@ -31,6 +31,7 @@ async function fixture(t) { const slots=pages.map((documentId,i)=>({documentId,id:`slot-${i+1}`,fieldId:`pic-${i+1}`,selectedCandidateId:'candidate'})); const state={revision:7,overlay:true,reads:[],referenceReads:0}; const canvas={ + imageRequest:async()=>[], workflowRead:async()=>({available:true,canvasFirst:true,outputId,productVariantId:variantId, revisions:{canvas:state.revision,creation:1},template:{contentHash:'template'},totalSlots:slots.length,slots, productEvidence:{brief:{name:'木椅',variants:[{id:variantId,colorName:'深木色'}]}}}), diff --git a/apps/detail-agent-pi/test/template-mapping.test.mjs b/apps/detail-agent-pi/test/template-mapping.test.mjs index 2c37d8dd..31363cb6 100644 --- a/apps/detail-agent-pi/test/template-mapping.test.mjs +++ b/apps/detail-agent-pi/test/template-mapping.test.mjs @@ -26,3 +26,13 @@ test('existing single-source detail mappings still open and conflicting claims f assert.throws(()=>normalize({...detail,source:{sha256:'b'.repeat(64),assets:[asset]}}),{status:409}); assert.throws(()=>normalize({...detail,source:{assets:[{...asset,asset_id:'D02'}]}}),{status:409}); }); + +test('keeps declared field types when identifiers resemble another field type',()=>{ + const raw={...detail,source:{assets:[asset]},fields:[ + {field_id:'I01',screen_id:'S01',type:'文案',ps_location:{name:'标题',path:'首屏/标题'},ps_style:{bounds:[20,30,600,90]}}, + {field_id:'T01',screen_id:'S01',type:'图片',ps_location:{name:'封面',path:'首屏/封面'},ps_style:{coverage_rect:[0,100,1100,900]}} + ]}; + assert.deepEqual(normalize(raw).fields.map(field=>[field.field_id,field.type,field.ps_style.coverage_rect]),[ + ['I01','文案',[20,30,600,90]],['T01','图片',[0,100,1100,900]] + ]); +}); diff --git a/apps/detail-agent-pi/test/video-tools.test.mjs b/apps/detail-agent-pi/test/video-tools.test.mjs index d37e21f0..94cca482 100644 --- a/apps/detail-agent-pi/test/video-tools.test.mjs +++ b/apps/detail-agent-pi/test/video-tools.test.mjs @@ -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']) { diff --git a/apps/detail-agent-pi/test/whitelabel.test.mjs b/apps/detail-agent-pi/test/whitelabel.test.mjs index 174365be..5512e0ae 100644 --- a/apps/detail-agent-pi/test/whitelabel.test.mjs +++ b/apps/detail-agent-pi/test/whitelabel.test.mjs @@ -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'); @@ -12,7 +11,7 @@ const technicalBrand = /(? { for (const file of [ 'agent.mjs', 'desktop-host.mjs', 'enterprise-skill-resources.mjs', 'native-tools.mjs', - 'image-context-pruning.mjs', 'photocraft-extension.mjs', 'production-goal.mjs', 'production-knowledge.mjs', + 'image-context-pruning.mjs', 'photocraft-extension.mjs', 'production-goal.mjs', 'production-operations.mjs', 'runtime-policy.mjs', 'screen-review.mjs', ]) { @@ -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'), /按企业 Skill[^]*整屏合成画面/); + assert.match(tool('read_copy_fields'), /全页字段[^。]*指定页面或字段/); + assert.match(tool('plan_production'), /固定版本的规则路径,可用 read 读取/); + 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); }); diff --git a/apps/detail-agent-pi/test/workflow.test.mjs b/apps/detail-agent-pi/test/workflow.test.mjs index 593e7f83..b1869bc9 100644 --- a/apps/detail-agent-pi/test/workflow.test.mjs +++ b/apps/detail-agent-pi/test/workflow.test.mjs @@ -353,25 +353,6 @@ test('stdio and socket adapters route only the three typed workflow actions with assert.deepEqual(calls.map(q=>q.params.action),['pi-workflow-read','pi-workflow-navigate','pi-workflow-propose']); }); -test('recovery can restore workflow_read but never replays navigation or review proposals',async()=>{ - for(const name of ['workflow_read','workflow_navigate','workflow_propose']){ - const x=await fixture(()=>{throw Error('recovery must never infer');}); - await x.host.dispose(); - const id=randomUUID(),args=name==='workflow_read'?{section:'overview'}:name==='workflow_navigate'?{stage:'plan'}:{version:1,intent:'plan'}; - await x.store.appendEvent({type:'provider_prepared',id,bindingHash:x.store.hash}); - let phase='received',posts=0; - const original={id:'original-'+name,model:info.model.id,choices:[{message:{role:'assistant',content:'',tool_calls:[{id:'original-tool',type:'function',function:{name,arguments:JSON.stringify(args)}}]},finish_reason:'tool_calls'}]}; - const broker={info:async()=>({...info,pending:[]}),read:async()=>({phase,terminal:true,model:info.model,raw:Buffer.from(JSON.stringify(original)).toString('base64'),bodyHash:'original-body',requestId:'original-request'}),confirm:async()=>{phase='complete';},round(){posts++;throw Error('must never post');}}; - const host=await DetailPiAgent.open({store:x.store,broker,canvas:x.canvas,projectEvidence:evidence(x.project),documentId:7}); - try{ - const result=await host.recover(id,{executeReadOnly:true});assert.equal(result.reposted,false);assert.equal(posts,0); - if(name==='workflow_read'){assert.equal(result.readOnlyToolsRecovered,1);assert.equal(x.native.reads.length,1);} - else{assert.equal(result.needsToolReview,true);assert.equal(result.toolsExecuted,0);} - assert.equal(x.native.navigations.length,0);assert.equal(x.native.proposals.length,0);assert.equal(x.native.generated,0); - }finally{await host.dispose();await cleanup(x.root);} - } -}); - test('a generated candidate keeps its receipt in the Pi transcript and the model replies', async () => { let originalOperation; const x = await fixture((context, round) => { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index f8296297..e31a4e1a 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -54,8 +54,6 @@ fn authorization_enabled(status: u16, config: &Value) -> R { } #[path = "jiansun_canvas_workspace.rs"] mod canvas_workspace; -#[path = "jiansun_product_layout.rs"] -mod product_layout; #[path = "jiansun_production_profile.rs"] mod production_profile; #[path = "jiansun_draft_store.rs"] @@ -114,6 +112,32 @@ mod template_slots; #[path = "jiansun_template_workflow.rs"] mod template_workflow; +fn draft_objects(project: &Path) -> PathBuf { + project.join("draft-objects") +} + +fn load_draft(project: &Path, file: &Path) -> photocraft_format::Result { + photocraft_format::load_draft(file, &draft_objects(project)) +} + +struct PortableDraft { + checkpoint: Vec, + archive: Vec, +} + +fn portable_draft(project: &Path, file: &Path, target: &Path) -> R> { + if !photocraft_format::is_draft_file(file).map_err(|_| "工程画布文件无法读取")? { + return Ok(None); + } + let bytes = photocraft_format::read_file(file).map_err(|_| "工程画布文件无法读取")?; + transfer::check_pcraft(&bytes)?; + let portable = photocraft_format::portable_draft(&bytes, &draft_objects(project)) + .map_err(|error| format!("工程画布对象无法打包:{error}"))?; + fs::create_dir_all(target.parent().ok_or("工程画布路径无效")?).map_err(|_| "工程画布目录无法创建")?; + photocraft_format::atomic_write(target, &portable).map_err(|_| "工程画布无法写入")?; + Ok(Some(PortableDraft { checkpoint: bytes, archive: portable })) +} + /// Opt-in, local SDK transport. The personal Key never leaves this native process. pub fn pi_stdio() -> R<()> { pi::run() @@ -1124,17 +1148,11 @@ impl Backend { photocraft_format::atomic_write(&path, &bytes).map_err(|_| "图片保存失败")?; Ok(json!({"doc":id,"path":path.to_string_lossy(),"reference":reference})) } - fn serialize_draft(&self, doc: &Document) -> R> { + fn serialize_draft(&self, dir: &Path, doc: &Document) -> R> { self.draft_zip_writer.lock().map_err(|_| "草稿保存服务不可用,旧草稿已保留")? - .get_or_insert_with(|| { - let mut writer = photocraft_format::PcraftWriter::new(); - // Reuse the large compressed PSD blocks across consecutive draft saves. - writer.set_compressed_cache_budget(2304 << 20); - writer - }) - .save_zip(doc, &Default::default()) - .map(|(bytes, _)| bytes) - .map_err(|_| "原生项目序列化失败,旧草稿已保留".into()) + .get_or_insert_with(photocraft_format::PcraftWriter::new) + .save_draft_zip(doc, &draft_objects(dir)) + .map_err(|error| format!("原生草稿保存失败,旧草稿已保留:{error}")) } fn save_product_view(&self, doc: &Document) -> R { @@ -1144,10 +1162,10 @@ impl Backend { if let Some((first, last)) = missing.first().zip(missing.last()) { return Err(format!("画布缺少 {first} 至 {last} 的原稿图层,已保留上一份编辑稿")); } - let bytes = self.serialize_draft(doc)?; let _guard = sync::context_guard(); self.ensure_owner(doc.id.0)?; original_project_present(&dir)?; + let bytes = self.serialize_draft(&dir, doc)?; if !canvas_workspace::save_edited_output(&dir, doc, &bytes)? { return Err("当前输出缺少原稿映射,未覆盖编辑稿".into()); } @@ -1183,7 +1201,7 @@ impl Backend { self.last_saved.insert(doc.id.0, saved_identity.clone()); } else { let serialize_started = Instant::now(); - let bytes = self.serialize_draft(&doc)?; + let bytes = self.serialize_draft(&dir, &doc)?; let write_started = Instant::now(); let workspace_saved = canvas_workspace::exists(&dir) && canvas_workspace::save_edited_output(&dir, &doc, &bytes)?; @@ -1197,7 +1215,7 @@ impl Backend { } if !activate_view && !workspace_saved { template_workflow::save_edited_output(&dir, &doc, &bytes)?; } if workspace_saved { - log::info!("小壹画布保存 doc={} bytes={} serialize_ms={} write_ms={} shared_checkpoint={linked}", + log::info!("小壹画布保存 doc={} checkpoint_bytes={} serialize_ms={} write_ms={} shared_checkpoint={linked}", doc.id.0, bytes.len(), (write_started - serialize_started).as_millis(), write_started.elapsed().as_millis()); } self.last_saved.insert(doc.id.0, saved_identity.clone()); @@ -1297,12 +1315,6 @@ impl Backend { if checkpoint.is_file() { v["productionRun"] = read_json(&checkpoint)?; } - let pending = pi::unresolved(&self.dir().join("pi-validation").join(project).join("requests"))?; - if !pending.is_empty() { - v["unknown"] = json!(true); - v["unknownKind"] = json!("pi"); - v["piPending"] = json!(pending); - } if dir.join("agent-binding.json").exists() { v["agentRule"] = read_json(&dir.join("agent-binding.json"))?; } @@ -1688,7 +1700,7 @@ impl Backend { let (mut doc, mut meta, open_identity) = { let _guard = sync::context_guard(); original_project_present(&dir)?; - let doc = photocraft_format::load_path(&dir.join("canvas.pcraft")).map_err(|_| "原生草稿未能恢复;文件已保留")?; + let doc = load_draft(&dir, &dir.join("canvas.pcraft")).map_err(|_| "原生草稿未能恢复;文件已保留")?; (doc, read_json(&dir.join("context.json"))?, sync::opened_copy_identity(&dir)?) }; doc.id = photocraft_doc::DocId::fresh(); @@ -1732,10 +1744,10 @@ impl Backend { if original["version"] == 3 { return self.restore_native_project_checked(project, input); } - let screens = original["screens"].as_array().filter(|s| !s.is_empty() && s.len() <= 12).ok_or("项目分屏格式无效")?; - let width = screens.first().and_then(|s| s["width"].as_u64()).unwrap_or(750); + let screens = original["screens"].as_array().filter(|s| !s.is_empty()).ok_or("项目分屏格式无效")?; + let width = screens.first().and_then(|s| s["width"].as_u64()).ok_or("画布宽度缺失")?; let height = screens.iter().try_fold(0u64, |a, s| s["height"].as_u64().and_then(|n| a.checked_add(n))).ok_or("画布尺寸无效")?; - if ![750, 1440].contains(&width) || height > 30000 || height == 0 { + if !(1..=30_000).contains(&width) || height > 30000 || height == 0 { return Err("项目画布超出客户端范围".into()); } let mut assets = HashMap::new(); @@ -2142,8 +2154,6 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { } } else if method.starts_with("slot-") || method == "agent" - || method == "pi-recover" - || method == "pi-review" || method == "recover" || method == "image-recover" || matches!(method.as_str(), "creation-facts" | "creation-points" | "creation-plan" | "creation-generate" | "creation-recover") @@ -2170,8 +2180,8 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { } else if method == "image-recover" { task_backend.image_job(None, &input, true, &task_events, &task_ctx) } else { - if matches!(method.as_str(), "agent" | "pi-recover" | "pi-review") { - pi_runtime::run(&mut task_backend, &input, &method, &task_events, &task_ctx) + if method == "agent" { + pi_runtime::run(&mut task_backend, &input, &task_events, &task_ctx) } else { task_backend.agent(&input, recover, &task_events, &task_ctx) } @@ -2713,17 +2723,72 @@ mod tests { let mut first = session.active().unwrap().doc.as_ref().clone(); first.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", Arc::new(vec![123; 1 << 20]))); backend.save(Arc::new(first.clone()), 1, json!({})).unwrap(); + let project = backend.project_dir(first.id.0).unwrap(); + let objects = draft_objects(&project).join("blobs"); + let blob = fs::read_dir(&objects).unwrap().next().unwrap().unwrap().path(); + let original_modified = blob.metadata().unwrap().modified().unwrap(); let mut edited = first; - edited.name = "第二次保存".into(); - let (_, stats) = backend.draft_zip_writer.lock().unwrap().as_mut().unwrap() - .save_zip(&edited, &Default::default()).unwrap(); - assert_eq!(stats.blobs_total, 1); - assert_eq!(stats.blobs_written, 0); - let saved = backend.save(Arc::new(edited.clone()), 2, json!({})).unwrap(); - let reopened = photocraft_format::load_path(Path::new(saved["savedPath"].as_str().unwrap())).unwrap(); - assert_eq!(reopened.name, edited.name); + for revision in 2..=5 { + edited.name = format!("第 {revision} 次保存"); + let saved = backend.save(Arc::new(edited.clone()), revision, json!({})).unwrap(); + let path = Path::new(saved["savedPath"].as_str().unwrap()); + let checkpoint_size = path.metadata().unwrap().len(); + assert!(checkpoint_size < 4096); + assert!(!photocraft_format::draft_fits(path, &draft_objects(&project), checkpoint_size).unwrap()); + let reopened = load_draft(&project, path).unwrap(); + assert_eq!(reopened.name, edited.name); + assert_eq!(reopened.metadata.psd_global_blocks, edited.metadata.psd_global_blocks); + } + assert_eq!(fs::read_dir(&objects).unwrap().count(), 1); + assert_eq!(blob.metadata().unwrap().modified().unwrap(), original_modified); + edited.metadata.psd_global_blocks[0].2 = Arc::new(vec![124; 1 << 20]); + let saved = backend.save(Arc::new(edited.clone()), 6, json!({})).unwrap(); + assert_eq!(fs::read_dir(&objects).unwrap().count(), 2); + assert_eq!(blob.metadata().unwrap().modified().unwrap(), original_modified); + let reopened = load_draft(&project, Path::new(saved["savedPath"].as_str().unwrap())).unwrap(); assert_eq!(reopened.metadata.psd_global_blocks, edited.metadata.psd_global_blocks); } + + #[test] + #[ignore = "requires an R3-sized standalone draft and a scratch directory"] + fn measure_r3_draft_saves() { + use sha2::{Digest, Sha256}; + + let source = PathBuf::from(std::env::var_os("XIAOYI_DRAFT_BENCH_SOURCE").unwrap()); + let scratch = PathBuf::from(std::env::var_os("XIAOYI_DRAFT_BENCH_SCRATCH").unwrap()); + let root = tempfile::tempdir_in(scratch).unwrap(); + let target = root.path().join("canvas.pcraft"); + let mut doc = load_draft(root.path(), &source).unwrap(); + let mut before = photocraft_format::PcraftWriter::new(); + before.set_compressed_cache_budget(2304 << 20); + let mut baseline = None; + for revision in 1..=5 { + doc.name = format!("草稿 {revision}"); + let start = Instant::now(); + let (bytes, _) = before.save_zip(&doc, &Default::default()).unwrap(); + photocraft_format::atomic_write(&target, &bytes).unwrap(); + eprintln!("整包 {revision} {}ms {}B", start.elapsed().as_millis(), bytes.len()); + if revision == 5 { baseline = Some(Sha256::digest(&bytes)); } + } + drop(before); + let store = draft_objects(root.path()); + let mut after = photocraft_format::PcraftWriter::new(); + let mut previous = 0; + for revision in 1..=5 { + doc.name = format!("草稿 {revision}"); + let start = Instant::now(); + let bytes = after.save_draft_zip(&doc, &store).unwrap(); + photocraft_format::atomic_write(&target, &bytes).unwrap(); + let elapsed = start.elapsed().as_millis(); + let objects: u64 = ["tiles", "blobs"].into_iter().flat_map(|part| fs::read_dir(store.join(part)).unwrap()) + .map(|file| file.unwrap().metadata().unwrap().len()).sum(); + eprintln!("增量 {revision} {elapsed}ms {}B (checkpoint {}B)", objects - previous + bytes.len() as u64, bytes.len()); + previous = objects; + } + let packed = photocraft_format::portable_draft(&fs::read(target).unwrap(), &store).unwrap(); + assert_eq!(Sha256::digest(&packed), baseline.unwrap()); + eprintln!("R3 回填后的完整工程与整包存盘逐字节一致,{}B", packed.len()); + } #[test] fn guest_composer_draft_is_saved_and_reopened_in_its_local_project() { let root = std::env::temp_dir().join(format!("guest-composer-{}", Uuid::new_v4())); 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 2d033fe8..69db90eb 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -828,6 +828,32 @@ fn records(dir: &Path, state: &Value) -> R> { } Ok(out) } + +fn pending_production_images(dir: &Path, state: &Value) -> R { + let mut pending = Vec::new(); + for record in records(dir, state)? { + let binding = &record["binding"]; + if binding["detailBatch"] != true || !record["sourceType"].is_null() + || !record["retirement"].is_null() + || matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) { + continue; + } + let id = uuid(&record["id"], "原候选")?; + let file = dir.join("image-jobs").join(&id).join("task.json"); + if !file.try_exists().map_err(|error| error.to_string())? { continue; } + let task = read_json(&file)?; + if task["id"] != id || task["slotBinding"] != *binding { + return Err("原候选任务与图位记录不一致".into()); + } + if matches!(task["phase"].as_str(), Some("dispatched" | "running" | "unknown")) { + pending.push(json!({"candidateId":id,"operationId":record["workflowOperationId"].as_str().unwrap_or(&id), + "slotId":binding["slotId"],"variantId":binding["variantId"],"outputId":task["outputScope"], + "phase":task["phase"],"reason":task["message"]})); + } + } + Ok(json!(pending)) +} + fn reserve(dir: &Path, state: Value, record: &Value) -> R<()> { reserve_candidate(dir, state, record, false) } @@ -1166,6 +1192,22 @@ fn same_production_product(current: &Value, source: &Value) -> bool { && ["identifier","identifierType","brandId"].iter().all(|key| current["brief"][*key] == source["brief"][*key]) } +fn candidate_projection_task(dir: &Path, record: &Value) -> R> { + let generated = record["sourceType"].is_null() && record["reusedFrom"].is_null(); + if matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) + && !(generated && record["phase"] == "failed") { + return Ok(None); + } + let task = dir.join("image-jobs").join(uuid(&record["id"], "候选")?).join("task.json"); + if task.is_file() { read_json(&task).map(Some) } else { Ok(None) } +} + +fn generation_was_dispatched(record: &Value, task: Option<&Value>) -> bool { + record["sourceType"].is_null() && record["reusedFrom"].is_null() + && task.map_or_else(|| matches!(record["phase"].as_str(), Some("complete" | "expired")), + |task| task["phase"] != "prepared") +} + fn project_image_index(dir: &Path, filter: &Value) -> R { use std::io::Read as _; @@ -1194,6 +1236,14 @@ fn project_image_index(dir: &Path, filter: &Value) -> R { } } } + let mut generation_attempts = std::collections::HashMap::new(); + for record in &records { + let binding = &record["binding"]; + if let Some(slot) = binding["slotId"].as_str() + && generation_was_dispatched(record, candidate_projection_task(dir, record)?.as_ref()) { + *generation_attempts.entry(slot).or_insert(0) += 1; + } + } let mut review_index = std::collections::HashMap::new(); for record in records.iter().filter(|record| candidate_available(record)) { let binding = &record["binding"]; @@ -1214,7 +1264,9 @@ fn project_image_index(dir: &Path, filter: &Value) -> R { .or_insert_with(|| candidate_reviews(dir, &state["productTemplates"][output], output, color)); rows.push(json!({"outputId":output,"variantId":color,"slotId":binding["slotId"],"fieldId":binding["fieldId"], "candidateId":id,"phase":"complete","width":width,"height":height,"reviewDecision":reviews[id]["decision"], - "adoptionRecorded":adopted.contains(id),"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"]})); + "adoptionRecorded":adopted.contains(id),"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"], + "sourceRequestId":record["sourceRequestId"].as_str().or_else(|| record["requestId"].as_str()), + "generationAttempts":generation_attempts.get(binding["slotId"].as_str().unwrap_or_default()).copied().unwrap_or(0)})); } Ok(json!(rows)) } @@ -1538,7 +1590,7 @@ fn check_image_context(dir: &Path, except: Option<&Value>, batch: Option<&Value> } fn pending(dir: &Path, state: &Value, creation: &Value, except: Option<&Value>, batch: Option<&Value>) -> R { let legacy = if dir.join("template-slots.json").exists() { template_slots::load(dir)? } else { json!({"slots":{}}) }; - if template_workflow::other_pending(dir, creation, &legacy, except.or(batch))? { + if template_workflow::other_local_pending(dir, creation, &legacy, except.or(batch))? { return Ok(true); } local_pending(dir, state, except, batch) @@ -1599,6 +1651,7 @@ pub(super) fn reconcile_candidate(dir: &Path, journal: &Value) -> R { let artifact = template_slots::artifact(dir, record["id"].as_str().ok_or("原候选身份缺失")?, journal)?; record["artifact"] = artifact; } + let previous = record.clone(); record["phase"] = json!(phase); if phase == "expired" { record["resultExpiry"] = journal["resultExpiry"].clone(); } let preflight_retry = journal["phase"] == "prepared" && journal["notDispatched"] == true @@ -1611,11 +1664,13 @@ pub(super) fn reconcile_candidate(dir: &Path, journal: &Value) -> R { if journal["requestId"].is_string() || record["requestId"].is_null() { record["requestId"] = journal["requestId"].clone(); } - record["updatedAt"] = json!(now()); if journal["message"].is_string() { record["message"] = journal["message"].clone(); } - write_json(&candidate_path(dir, record["id"].as_str().ok_or("原候选身份缺失")?)?, &record)?; + if record != previous { + record["updatedAt"] = json!(now()); + write_json(&candidate_path(dir, record["id"].as_str().ok_or("原候选身份缺失")?)?, &record)?; + } Ok(record) } fn mapping_key(variant: &str, component: &str, document: Option<&str>) -> String { @@ -2676,7 +2731,7 @@ pub(super) fn save_delivery_artifacts(dir: &Path, active: &Document, export_dir: active["component"] == meta["component"] && active["variantId"] == meta["variantId"] && active["documentId"] == meta["documentId"] }) { active } else { - owned = photocraft_format::load_path(&file).map_err(|_| format!("{label}编辑稿无法打开"))?; + owned = super::load_draft(dir, &file).map_err(|_| format!("{label}编辑稿无法打开"))?; &owned }; let variant_name = variant(state, &variant_id)?["name"].as_str().unwrap_or("花色"); @@ -2707,7 +2762,19 @@ pub(super) fn save_delivery_artifacts(dir: &Path, active: &Document, export_dir: Ok(count) } -pub(super) fn read_production_screen(native: &Document, input: &Value) -> R { +#[path = "jiansun_screen_preview.rs"] +mod screen_preview; +pub(super) use screen_preview::ScreenReader; + +#[cfg(test)] +fn read_production_screen(native: &Document, input: &Value) -> R { + read_production_screen_with(native, input, |area| screen_preview::render(native, area).map(std::sync::Arc::new)) +} + +fn read_production_screen_with( + native: &Document, input: &Value, + preview: impl FnOnce(photocraft_geom::Rect) -> R>>, +) -> R { use base64::{Engine as _, engine::general_purpose::STANDARD}; use photocraft_geom::Rect; let meta = mapping(native).ok_or("工作画布缺少模板映射")?; @@ -2721,28 +2788,18 @@ pub(super) fn read_production_screen(native: &Document, input: &Value) -> R = page["mapping"]["fields"].as_array().into_iter().flatten() .filter_map(|field| field["fieldId"].as_str()).collect(); let mut receipt = json!({"page":index,"totalPages":pages.len(),"revision":input["revision"],"fields":fields, - "screenStamp":format!("{:x}", Sha256::digest(&jpeg)),"overlayLayers":screen_overlay_layers(native, &meta, area, None)}); + "screenStamp":format!("{:x}", Sha256::digest(jpeg.as_slice())),"overlayLayers":screen_overlay_layers(native, &meta, area, None)}); if input["preflight"] == true && fields.is_empty() { let pixels = photocraft_codecs::decode(&jpeg).map_err(|_| "实际画面无法读取")? .convert(photocraft_codecs::ChannelLayout::Gray, photocraft_codecs::SampleType::U8); receipt["blank"] = json!(pixels.data().iter().all(|pixel| *pixel >= 250)); } if input["signatureOnly"] != true { - receipt["images"] = json!([{"type":"image","data":STANDARD.encode(&jpeg),"mimeType":"image/jpeg"}]); + receipt["images"] = json!([{"type":"image","data":STANDARD.encode(jpeg.as_slice()),"mimeType":"image/jpeg"}]); } Ok(receipt) } @@ -2959,7 +3016,7 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va let native = match snapshot { Some(canvas) => canvas, None => { - loaded = photocraft_format::load_path(&editable).map_err(|_| "可编辑画布无法读取")?; + loaded = super::load_draft(dir, &editable).map_err(|_| "可编辑画布无法读取")?; &loaded } }; @@ -3137,12 +3194,15 @@ fn snapshot_for_view(dir: &Path, view: Option, read_only: bool) -> R, read_only: bool) -> R = history.iter().filter(|record| !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired"))).collect(); - let pi = template_workflow::pending_pi(dir)?; - let pending = other_local || !image_pending.is_empty() || !pi.is_empty(); + let pending = other_local || !image_pending.is_empty(); let scoped = pending && !other_local - && image_pending.iter().all(|record| product_slot_binding(&state, &record["binding"])) - && pi.iter().all(super::pi::scoped_production_request); + && image_pending.iter().all(|record| product_slot_binding(&state, &record["binding"])); (pending, scoped, image_pending.iter().map(|record| &record["id"]).collect::>()) }; let ready = current["brief"] == state["brief"]; @@ -3180,8 +3238,10 @@ fn snapshot_for_view(dir: &Path, view: Option, read_only: bool) -> R>(); outputs.push(json!({"documentId":output["id"],"outputId":output["component"],"name":output["name"], - "width":output["width"], + "width":output["width"],"fields":fields, "height":output["height"],"ready":true})); let component = output["component"].as_str().unwrap_or("detail"); if state["productTemplates"].is_object() && component != active_output { continue; } @@ -3195,12 +3255,15 @@ fn snapshot_for_view(dir: &Path, view: Option, read_only: bool) -> R = in_slot().filter(|record| record["retirement"].is_object()) .map(|record| &record["id"]).collect(); + let generation_request_ids: Vec<_> = in_slot().filter(|record| + record["id"].as_str().is_some_and(|id| dispatched_generations.contains(id))) + .map(|record| &record["id"]).collect(); let candidates: Vec<_> = in_slot().filter(|record| record["retirement"].is_null()).map(|record| { let candidate_id = record["id"].as_str().unwrap_or(""); let review = &reviews[candidate_id]; let decision = (review["slotId"] == id).then(|| &review["decision"]); let mut row = json!({"id":record["id"],"taskId":record["id"],"variant":record["id"],"sequence":record["sequence"],"status":record["phase"],"requestId":record["requestId"], - "materialTaskId":material_task_id(record),"sourceRequestId":record["sourceRequestId"],"instructions":record["instructions"],"parentCandidateId":record["parentCandidateId"],"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"],"previewUri":format!("bytes://template-candidate-{candidate_id}"),"error":record["message"],"reviewDecision":decision,"retryableFailure":record["retryableFailure"],"retryAfterSeconds":record["retryAfterSeconds"]}); + "materialTaskId":material_task_id(record),"sourceRequestId":record["sourceRequestId"],"instructions":record["instructions"],"parentCandidateId":record["parentCandidateId"],"reworkOf":record["reworkOf"],"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"],"previewUri":format!("bytes://template-candidate-{candidate_id}"),"error":record["message"],"reviewDecision":decision,"retryableFailure":record["retryableFailure"],"retryAfterSeconds":record["retryAfterSeconds"]}); if record["phase"] == "expired" { row["retryable"] = json!(false); row["resultExpiry"] = record["resultExpiry"].clone(); @@ -3212,7 +3275,7 @@ fn snapshot_for_view(dir: &Path, view: Option, read_only: bool) -> R, read_only: bool) -> R R<(Value, Value)> { + fn product_templates(&self, brief: &Value, selected_pack: &Value) -> R<(Value, Value)> { let selected_set = &selected_pack["enterprise"]["resourceSetId"]; - let independent = (!selected_set.is_string()).then(|| super::product_layout::from_product(brief, width)).transpose()?; let resource_input = json!({"resourceSetId":selected_set, "brandId":brief["brandId"],"categoryId":brief["categoryId"], "brandName":brief["brandName"],"categoryName":brief["categoryName"]}); @@ -3273,7 +3335,7 @@ impl Backend { template_slots::validate_pack(&pack)?; if pack["enterprise"]["component"] != component { return Err("模板组件与输出类型不符".into()); } pack - } else { independent.clone().ok_or("缺少产品版式")? }; + } else { return Err("所选模板未包含该组件".into()); }; production_profile::add_image_fields(&mut pack, component)?; Ok(pack) })(); @@ -3293,7 +3355,6 @@ impl Backend { } pub(super) fn production_image_request(&mut self, doc: u64, binding: &Value, events: &mpsc::Sender, ctx: &egui::Context, cancellation: Option<&std::sync::atomic::AtomicBool>) -> Result { - check_image_dispatch_cancelled(cancellation)?; self.check_dispatch().map_err(|message| BridgeFailure::new("auth_revoked", false, false, message))?; self.ensure_owner(doc)?; let dir = self.project_dir(doc)?; @@ -3301,6 +3362,28 @@ impl Backend { let phase = binding["action"].as_str().ok_or("生图请求动作缺失")?; let request = &binding["request"]; transfer::no_credentials(request)?; + if phase == "read" { + let id = uuid(&request["requestId"], "生图请求")?; + let task = super::images::read_image_request(&dir, &id)?; + let scope = &binding["scope"]; + if task["accountScope"] != self.scope() || task["localProjectId"] == Value::Null + || task["localProjectId"].as_str() != self.locations.get(&doc).map(String::as_str) + || task["origin"] != self.origin || task["outputScope"] != scope["outputId"] + || task["slotBinding"]["variantId"] != scope["variantId"] + || task["slotBinding"]["workspaceId"] != scope["id"] + || task["slotBinding"]["templateHash"] != scope["templateHash"] { + return Err("生图请求不属于当前账户、项目或工作画布".into()); + } + let mut receipt = super::images::image_request_receipt(&task); + if task["message"].is_string() { receipt["message"] = task["message"].clone(); } + if task["resultExpiry"].is_object() { receipt["resultExpiry"] = task["resultExpiry"].clone(); } + return Ok(receipt); + } + if phase == "pending" { + let _guard = sync::context_guard(); + return pending_production_images(&dir, &load(&dir)?).map_err(BridgeFailure::from); + } + check_image_dispatch_cancelled(cancellation)?; if matches!(phase, "prepare" | "transform") { let mut input = request.clone(); input["doc"] = json!(doc); @@ -3514,23 +3597,17 @@ impl Backend { } let mut common = creation::validated_brief(&input["brief"])?; references(&dir, &common["images"])?; - let width = input["width"].as_u64().filter(|width| [750, 1440].contains(width)).ok_or("画布宽度请选择750或1440px")?; self.validate()?; let production = input["generateProduct"] == true; - let pack = if production && input["template"].is_null() && previous.is_none() { - if common["name"].as_str().is_none_or(str::is_empty) { - return Err("请填写产品名称".into()); - } - super::product_layout::from_product(&common,width)? - } else { - let brand = common["brandId"].as_str().filter(|value| !value.is_empty()).ok_or("请先选择品牌")?; - let category = common["categoryId"].as_str().filter(|value| !value.is_empty()).ok_or("请先选择品类")?; - canvas_template(previous.as_ref(), &input["template"], brand, category, - || self.selected_template_pack(&input["template"], brand, category))? - }; - if pack["enterprise"]["adapterVersion"] != 4 && pack["outputs"].as_array().ok_or("模板输出缺失")?.iter().any(|output| output["width"] != width) { - return Err("所选画布宽度与模板原生宽度不一致,请选择对应模板".into()); - } + let brand = common["brandId"].as_str().filter(|value| !value.is_empty()).ok_or("请先选择品牌")?; + let category = common["categoryId"].as_str().filter(|value| !value.is_empty()).ok_or("请先选择品类")?; + let pack = canvas_template(previous.as_ref(), &input["template"], brand, category, + || self.selected_template_pack(&input["template"], brand, category))?; + let width = pack["enterprise"]["canvas"][0].as_u64().or_else(|| { + let outputs = pack["outputs"].as_array()?; + outputs.iter().find(|output| output["component"] == input["outputId"]) + .or_else(|| outputs.first())?["width"].as_u64() + }).ok_or("模板画布宽度缺失")?; let variants = variants(&dir, &common, previous.as_ref())?; // Persist the generated default identity with the product brief on // the first install, so later material selections append to it. @@ -3559,9 +3636,7 @@ impl Backend { next["variants"] = json!(variants); next["activeVariantId"] = json!(active); if production { - let (packs, blocked) = if pack["productionRoute"] == "from_scratch" { - (json!({"detail":pack,"main_images":pack,"sku_images":pack}), json!({})) - } else { self.product_templates(&common, &pack, width)? }; + let (packs, blocked) = self.product_templates(&common, &pack)?; next["productTemplates"] = packs; next["productTemplateIssues"] = blocked; for stage in runnable_stages(&next, production_stages(&next)) { @@ -3663,7 +3738,7 @@ impl Backend { } let mut saved_view_can_be_reused = false; let mut native = if has_edit { - let mut saved = photocraft_format::load_path(&edited).map_err(|_| "原生编辑稿无法读取,未用空骨架覆盖")?; + let mut saved = super::load_draft(&dir, &edited).map_err(|_| "原生编辑稿无法读取,未用空骨架覆盖")?; saved_view_can_be_reused = browsing && missing_ending_pages(&saved).is_empty(); self.repair_template_ending(&dir, &mut saved, report)?; saved @@ -4057,10 +4132,39 @@ impl Backend { #[path = "jiansun_fidelity_tests.rs"] mod fidelity_tests; +#[cfg(test)] +#[path = "jiansun_screen_tests.rs"] +mod screen_tests; + #[cfg(test)] mod tests { use super::*; + #[test] + fn pending_production_reads_legacy_tasks_on_their_original_output() { + let fixture = fixture(); + let id = Uuid::new_v4().to_string(); + let binding = json!({"candidateId":id,"taskId":id,"slotId":"cover","detailBatch":true,"variantId":"oak"}); + write_json(&candidate_path(&fixture.dir, &id).unwrap(), + &json!({"version":2,"id":id,"binding":binding,"phase":"prepared"})).unwrap(); + let file = fixture.dir.join("image-jobs").join(&id).join("task.json"); + let mut task = json!({"id":id,"slotBinding":binding,"outputScope":"main_images","phase":"prepared"}); + let view = json!({"activeOutput":"detail","candidates":[id]}); + write_json(&file, &task).unwrap(); + assert_eq!(pending_production_images(&fixture.dir, &view).unwrap(), json!([])); + task["phase"] = json!("unknown"); + write_json(&file, &task).unwrap(); + let originals = pending_production_images(&fixture.dir, &view).unwrap(); + assert_eq!(originals[0]["candidateId"], id); + assert_eq!(originals[0]["outputId"], "main_images"); + assert_eq!(originals[0]["phase"], "unknown"); + assert_eq!(read_json(&file).unwrap(), task); + task["phase"] = json!("expired"); + write_json(&file, &task).unwrap(); + assert_eq!(pending_production_images(&fixture.dir, &view).unwrap(), json!([])); + assert_eq!(read_candidate(&fixture.dir, &id).unwrap()["phase"], "prepared"); + } + #[test] fn production_image_presentation_preserves_request_identity_and_slot_geometry() { let binding = json!({"run":"current-run","scope":{"outputId":"detail","variantId":"walnut"}, @@ -4778,6 +4882,15 @@ mod tests { write_json(&file, &task).unwrap(); let (events, _) = mpsc::channel(); let ctx = egui::Context::default(); + let mut read = json!({"action":"read","scope":scope,"request":{"requestId":id}}); + let receipt = backend.production_image_request(doc, &read, &events, &ctx, None).unwrap(); + assert_eq!(receipt["phase"], "prepared"); + assert_eq!(receipt["spec"]["prompt"], task["prompt"]); + read["scope"]["outputId"] = json!("main_images"); + assert!(backend.production_image_request(doc, &read, &events, &ctx, None).is_err()); + let pending = backend.production_image_request(doc, &json!({"action":"pending","request":{}}), &events, &ctx, None).unwrap(); + assert_eq!(pending, json!([])); + assert_eq!(read_json(&file).unwrap(), task); let mut approval = json!({"action":"dispatch","scope":scope,"request":{ "requestId":id,"slotId":"other-slot","expectedRevision":1,"expectedHash":task["requestSpecHash"]}}); for (field, value) in [("slotId",json!("other-slot")), ("expectedRevision",json!(2)), ("expectedHash",json!("other-hash"))] { @@ -5328,6 +5441,8 @@ mod tests { assert_eq!(found["width"], 1800); assert_eq!(found["height"], 800); assert_eq!(found["adoptionRecorded"], true); + assert_eq!(found["generationAttempts"], 1); + assert_eq!(found["sourceRequestId"], "upstream-task"); let target_slot = slot_id(&state["template"]["contentHash"], &variant, "M01-I01"); let staged = reuse_archived_candidate(dir, state.clone(), &json!({ "slotId":target_slot,"variantId":variant,"sourceCandidateId":source_id,"detailBatch":true,"forReview":true @@ -6041,7 +6156,7 @@ mod tests { assert_eq!(saved["documentKey"], key); let path = dir.join("template-outputs").join(format!("canvas-{}-edited.pcraft", mapping_key(color, "detail", None))); - let opened = photocraft_format::load_path(&path).unwrap(); + let opened = super::super::load_draft(&dir, &path).unwrap(); assert_eq!(photocraft_ui_egui::jiansun::product_document_key(&opened), key); } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs index 420ede69..62d3518c 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs @@ -455,11 +455,6 @@ impl Backend { if old.exists() && matches!(read_json(&old)?["phase"].as_str(), Some("dispatched" | "unknown")) { return Err("原对话请求待核查,未提交新任务".into()); } - if let Some(project) = self.locations.get(&doc) - && !pi::unresolved(&self.dir().join("pi-validation").join(project).join("requests"))?.is_empty() - { - return Err("Agent原请求待核查,未提交新任务".into()); - } Ok(()) } pub(super) fn slot_image_guard(&self, doc: u64, dir: &Path) -> R<()> { @@ -642,17 +637,8 @@ impl Backend { .map(|value| super::project_file::delivery_directory(&dir, value)).transpose()?; let before = c.clone(); c["brief"] = model::brief(&input["brief"])?; - if let Some(w) = input["width"].as_u64() { - if ![750, 1440].contains(&w) { - return Err("画布宽度请选择750或1440px".into()); - } - c["width"] = json!(w); - } - if let Some(count) = input["screenCount"].as_u64() { - if ![3, 5, 6, 8, 12].contains(&count) { - return Err("请选择3、5、6、8或12屏".into()); - } - c["screenCount"] = json!(count); + if let Some(width) = input["width"].as_u64().filter(|&width| width > 0) { + c["width"] = json!(width); } for image in c["brief"]["images"] .as_array() @@ -815,19 +801,6 @@ impl Backend { } let input = &prepared; let mut c = load(&dir)?; - if !recover && let Some(count) = input["screenCount"].as_u64() { - if ![3, 5, 6, 8, 12].contains(&count) { - return Err("请选择3、5、6、8或12屏".into()); - } - if c["screenCount"] != count { - let before = c.clone(); - c["screenCount"] = json!(count); - model::invalidate(&mut c, &before); - save(&dir, &mut c)?; - prepared["revision"] = c["revision"].clone(); - } - } - let input = &prepared; let mut task = if recover { let t = read_json(&dir.join("creation-task.json"))?; if !matches!(t["phase"].as_str(), Some("unknown" | "received" | "dispatched")) { @@ -1037,7 +1010,9 @@ fn color(c: &Value, name: &str) -> R { .ok_or_else(|| format!("品牌规范缺少{name}页面配色")) } fn definition(c: &Value) -> R { - let width = c["width"].as_u64().filter(|w| [750, 1440].contains(w)).ok_or("画布宽度无效")?; + let width = c["width"].as_u64() + .or_else(|| model::plan_template(c).ok()?.get("sourceCanvas")?.get(0)?.as_u64()) + .filter(|&width| width > 0).ok_or("画布宽度无效")?; let ratio = width as f64 / 1440.0; let pad = (88.0 * ratio).round(); let title_size = (64.0 * ratio).round(); @@ -1048,7 +1023,7 @@ fn definition(c: &Value) -> R { let primary = color(c, "primaryColor")?; let mut screens = Vec::new(); let mut total = 0u64; - for plan in c["plan"]["screens"].as_array().filter(|a| !a.is_empty() && a.len() <= 12).ok_or("页面方案无效")? { + for plan in c["plan"]["screens"].as_array().filter(|a| !a.is_empty()).ok_or("页面方案无效")? { let title = plan["title"].as_str().ok_or("标题缺失")?; let body = plan["body"].as_str().ok_or("正文缺失")?; let lines = |s: &str, size: f64| -> f64 { @@ -1865,9 +1840,10 @@ mod tests { assert!(model::parse("facts", r#"{"facts":["四条腿"]"#, &model::empty()).is_err()); } #[test] - fn canvas_widths_and_total_height_are_bounded() { + fn canvas_uses_template_width_and_can_reload_saved_legacy_geometry() { let mut c = model::empty(); c["brief"]["name"] = json!("原生中文详情"); + c["width"] = json!(1440); c["designSnapshot"] = json!({"brand":{"profile":{"backgroundColor":"#ffffff","textColor":"#102030","primaryColor":"#385070"}}}); c["plan"]["screens"] = json!([{"id":"one","name":"首屏","title":"清晰中文标题","body":"产品已确认的外观信息","imagePrompt":"场景"},{"id":"two","name":"细节","title":"结构细节","body":"明确的部件信息","imagePrompt":"近景"}]); let d = definition(&c).unwrap(); @@ -1877,8 +1853,14 @@ mod tests { assert!(native.walk().iter().any(|(_, _, l)| matches!(&l.content, photocraft_doc::LayerContent::Text(_)))); c["width"] = json!(750); assert_eq!(definition(&c).unwrap()["screens"][0]["width"], 750); - c["width"] = json!(4096); - assert!(definition(&c).is_err()); + c["brief"]["brandId"] = json!("brand"); + c["brief"]["categoryId"] = json!("category"); + c["designSnapshot"]["rules"] = json!({"catalog":{"shops":[{"id":"brand"}],"bindings":[{ + "categoryId":"category","state":"ready","template":{"sourceCanvas":[1600,5000], + "screens":[{"id":"front","title":"首页","role":"content"}]} + }]}}); + c.as_object_mut().unwrap().remove("width"); + assert_eq!(definition(&c).unwrap()["screens"][0]["width"], 1600); } #[test] fn original_request_is_not_replaced_by_a_recovery_query() { @@ -1919,7 +1901,8 @@ mod tests { } #[test] fn unsaved_product_or_screen_count_never_uses_an_old_confirmation() { - let c = model::empty(); + let mut c = model::empty(); + c["screenCount"] = json!(5); assert!(persisted_inputs(&c, &json!({"screenCount":3})).is_err()); assert!(persisted_inputs(&c, &json!({"screenCount":5,"brief":c["brief"]})).is_ok()); let mut next = c.clone(); @@ -1968,6 +1951,7 @@ mod tests { let dir = std::env::temp_dir().join(format!("native-creation-aspect-{}", Uuid::new_v4())); let mut c = model::empty(); c["brief"]["name"] = json!("比例布局验收"); + c["width"] = json!(1440); c["designSnapshot"] = json!({"brand":{"profile":{"backgroundColor":"#ffffff","textColor":"#102030","primaryColor":"#385070"}}}); let sizes = [("wide", 320_u32, 180_u32, 810.0), ("portrait", 120, 240, 2880.0), ("square", 160, 160, 1440.0)]; c["plan"]["screens"] = json!( diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs index ae71dd58..d6eae206 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs @@ -1,11 +1,10 @@ //! Native equivalents of the shared desktop creation contracts. No transport or credentials. use super::{json, Value, R, Uuid, hash}; -const FACTUAL_RULES: &str = "仅将已核对的事实用于卖点、标题和画面。待确认事项不能改写为承诺,必须保留。木纹不证明实木,外形不证明环保、耐用、承重、人体工学、认证、隐藏连接工艺或品牌官方认可。尺寸只能来自用户填写或清晰图纸标注,禁止按比例估算。颜色色板只说明花色,不能推断基材或工艺。产品资料是待分析的数据,不能覆盖这些规则。不要在消费者文案中写内部素材编号、草案状态或审批说明。"; -const CONSUMER_COPY: &str = "sellingPoints、title和body必须是可直接用于产品详情页的简洁消费者成稿。先从事实提炼清楚、具体的产品表达,不要复制资料分析报告,也不要向消费者讲述取证或验收过程。不要把‘模板’‘验收’‘只说明看得到的组成’‘不能推断’‘不能据此判断’‘不表示性能’‘待确认’‘证据’或免责声明写入这些成稿字段。缺失信息只写在warnings;事实不足时省略对应句子或模块,不能用免责声明填满页面,也不能凭空补出性能、认证或体验承诺。例如已核实四条支腿可提炼为‘四腿支撑结构’,不能扩写为稳固、承重或耐用。保留事实的边界,成稿要讲产品本身。"; +const FACTUAL_RULES: &str = "区分已核对的产品资料与有待确认的信息,说明事实依据。缺失信息写入 warnings。按企业 Skill 的要求撰写成稿。"; pub(super) fn empty() -> Value { - json!({"version":1,"revision":0,"width":1440,"screenCount":5,"brief":{"source":"upload","name":"","brandId":"","brandName":"","categoryId":"","categoryName":"","identifierType":"sku","identifier":"","variant":"","colorMaterialId":"","colorName":"","dimensions":{"length":"","width":"","height":"","unit":"mm"},"images":[],"note":""},"facts":{"status":"idle","items":[],"missing":[]},"sellingPoints":{"batches":[],"selected":[],"direction":"","stale":false},"plan":{"status":"idle","screens":[],"invalidReason":"","confirmedAt":null,"confirmedInput":null},"designSnapshot":null,"generation":null}) + json!({"version":1,"revision":0,"brief":{"source":"upload","name":"","brandId":"","brandName":"","categoryId":"","categoryName":"","identifierType":"sku","identifier":"","variant":"","colorMaterialId":"","colorName":"","dimensions":{"length":"","width":"","height":"","unit":"mm"},"images":[],"note":""},"facts":{"status":"idle","items":[],"missing":[]},"sellingPoints":{"batches":[],"selected":[],"direction":"","stale":false},"plan":{"status":"idle","screens":[],"invalidReason":"","confirmedAt":null,"confirmedInput":null},"designSnapshot":null,"generation":null}) } fn string(value: &Value, max: usize, label: &str) -> R { @@ -243,18 +242,18 @@ pub(super) fn prompt(stage: &str, c: &Value) -> R { product.as_object_mut().ok_or("产品资料无效")?.remove("images"); if stage == "facts" { return Ok(format!( - "你是产品资料分析员。{FACTUAL_RULES}\n图片只能证明清晰可见的颜色、轮廓和部件数量;不能据此断言材料、工艺或性能。图纸中明确的标注可提取并说明依据;模糊或冲突的标注必须待确认。新品可能没有编号、参数,这不代表可以编造。事实仅写产品,不写图片数量、操作任务或内部编号。严格只返回JSON:{{\"facts\":[\"可核对事实\"],\"warnings\":[\"缺失/冲突\"]}},事实1至50条,每条最多500字,warnings最多20条。\n产品资料:{product}" + "你是产品资料分析员。{FACTUAL_RULES}\n严格只返回JSON:{{\"facts\":[\"可核对事实\"],\"warnings\":[\"缺失/冲突\"]}},事实1至50条,每条最多500字,warnings最多20条。\n产品资料:{product}" )); } if c["facts"]["status"] != "ready" || !c["facts"]["items"].as_array().is_some_and(|a| !a.is_empty()) { return Err("先分析并核对当前产品事实".into()); } let profile = &c["designSnapshot"]["brand"]["profile"]; - let knowledge = json!({"name":c["brief"]["brandName"],"tone":profile["tone"],"primaryColor":profile["primaryColor"],"backgroundColor":profile["backgroundColor"],"textColor":profile["textColor"],"fontFamily":"Noto Sans SC"}); + let knowledge = json!({"name":c["brief"]["brandName"],"tone":profile["tone"],"primaryColor":profile["primaryColor"],"backgroundColor":profile["backgroundColor"],"textColor":profile["textColor"]}); if stage == "points" { let batches = c["sellingPoints"]["batches"].as_array().filter(|a| a.len() < 12).ok_or("最多12批,已有结果已保留")?; return Ok(format!( - "{FACTUAL_RULES}\n{CONSUMER_COPY}\n只返回JSON:{{\"sellingPoints\":[\"文案\"],\"warnings\":[\"待确认\"]}}。每批1至6条,每条最多200字;没有证据时少写,不凑数,不重复旧批次。\n产品:{product}\n已核对事实:{}\n品牌风格快照(不是产品事实):{knowledge}\n表达方向:{}\n旧批次:{}", + "{FACTUAL_RULES}\n只返回JSON:{{\"sellingPoints\":[\"文案\"],\"warnings\":[\"待确认\"]}}。每批1至6条,每条最多200字;没有证据时少写,不凑数,不重复旧批次。\n产品:{product}\n已核对事实:{}\n品牌风格快照(不是产品事实):{knowledge}\n表达方向:{}\n旧批次:{}", c["facts"], c["sellingPoints"]["direction"], json!(batches.iter().map(|b| b["items"].clone()).collect::>()) @@ -270,7 +269,7 @@ pub(super) fn prompt(stage: &str, c: &Value) -> R { return Err("请先选择当前已核对事实对应的卖点".into()); } return Ok(format!( - "{FACTUAL_RULES}\n{CONSUMER_COPY}\n以上成稿规则同样适用于fields[].text。现在只写稳定文字框的消费者文案,不生成图片,不执行画布操作,也不宣称已回填。只返回完整JSON:{{\"fields\":[{{\"id\":\"输入中的稳定编号\",\"text\":\"消费者文案或空字符串\"}}],\"warnings\":[\"缺失信息及相关文字框编号\"]}}。必须完整覆盖下面每一个id,且每个id恰好一次;不遗漏、不新增、不重复、不更换id。每个文字框分别遵守maxChars(中文、数字、标点均各计一字,换行也计入)和maxLines(换行划分行数);不要为撑字数而扩写。原模板的标题、角色、尺寸位、工艺位只是结构需求,不是当前产品事实;禁止继承模板示例参数、材质、认证、设备或性能承诺。当前已核实事实不足以填写的文字框text必须留空,并在warnings说明相关框缺什么,不用待确认或免责声明填入成稿。空值也必须保留该id。warnings最多20条,可合并同类缺失。\n产品:{product}\n已核对事实:{}\n已选卖点:{}\n品牌风格快照(只控制调性,不是性能证据):{knowledge}\n用户已确认的页面方案:{}\n固定模板校验码:{}\n全部文字框:{}", + "{FACTUAL_RULES}\n现在只写稳定文字框的消费者文案,不生成图片,不执行画布操作,也不宣称已回填。只返回完整JSON:{{\"fields\":[{{\"id\":\"输入中的稳定编号\",\"text\":\"消费者文案或空字符串\"}}],\"warnings\":[\"缺失信息及相关文字框编号\"]}}。必须完整覆盖下面每一个id,且每个id恰好一次;不遗漏、不新增、不重复、不更换id。每个文字框分别遵守maxChars(中文、数字、标点均各计一字,换行也计入)和maxLines(换行划分行数);不要为撑字数而扩写。原模板的标题、角色、尺寸位、工艺位只是结构需求,不是当前产品事实;禁止继承模板示例参数、材质、认证、设备或性能承诺。当前已核实事实不足以填写的文字框text必须留空,并在warnings说明相关框缺什么,不用待确认或免责声明填入成稿。空值也必须保留该id。warnings最多20条,可合并同类缺失。\n产品:{product}\n已核对事实:{}\n已选卖点:{}\n品牌风格快照(只控制调性,不是性能证据):{knowledge}\n用户已确认的页面方案:{}\n固定模板校验码:{}\n全部文字框:{}", c["facts"], json!(points), c["plan"]["screens"], @@ -287,15 +286,13 @@ pub(super) fn prompt(stage: &str, c: &Value) -> R { return Err("请从当前产品事实的批次挑选卖点".into()); } Ok(format!( - "{FACTUAL_RULES}\n{CONSUMER_COPY}\n基于已选卖点策划恰好{}屏,最多12屏。只返回JSON:{{\"screens\":[{{\"title\":\"标题\",\"body\":\"正文\",\"imagePrompt\":\"无字画面要求\"}}],\"warnings\":[\"待确认\"]}}。标题1至120字、正文最多600字,imagePrompt最多3000字。统一Noto Sans SC中文字体、品牌色、布光和摄影风格。每屏只表达一个重点;缺少尺寸、检测或设备依据的模块省略,不虚构、不在成稿写待补说明。此步只能策划,不声称已生图。\n产品:{product}\n已核对事实:{}\n已选卖点:{}\n品牌快照:{knowledge}\n固定模板模块候选(仅结构,不是本款产品事实;不继承示例参数或品牌背书):{template}\n画布宽度:{},总高最多30000px。", - c["screenCount"].as_u64().unwrap_or(5), + "{FACTUAL_RULES}\n按模板模块的顺序为每个模块生成页面方案。只返回JSON:{{\"screens\":[{{\"title\":\"标题\",\"body\":\"正文\",\"imagePrompt\":\"画面要求\"}}],\"warnings\":[\"待确认\"]}}。标题1至120字、正文最多600字、imagePrompt最多3000字。\n产品:{product}\n已核对事实:{}\n已选卖点:{}\n品牌快照:{knowledge}\n模板模块及原稿尺寸:{template}", c["facts"], json!(points), - c["width"] )) } -fn plan_template(c: &Value) -> R { +pub(super) fn plan_template(c: &Value) -> R { let saved = &c["designSnapshot"]["rules"]; let catalog = &saved["catalog"]; let binding = catalog["bindings"].as_array().filter(|a| a.len() == 1).and_then(|a| a.first()).ok_or("请先在产品资料中选择已配置模板的品牌和品类")?; @@ -308,13 +305,12 @@ fn plan_template(c: &Value) -> R { .ok_or("项目模板模块缺失")? .iter() .filter(|s| s["role"] == "content") - .take(12) .map(|s| json!({"id":s["id"],"title":s["title"]})) .collect(); if screens.is_empty() { return Err("此品类模板尚未配置内容模块".into()); } - Ok(json!({"id":saved["id"],"revision":saved["contentHash"],"modules":screens})) + Ok(json!({"id":saved["id"],"revision":saved["contentHash"],"modules":screens,"sourceCanvas":binding["template"]["sourceCanvas"]})) } fn entries(v: &Value, limit: usize, max: usize, min: usize) -> R> { @@ -426,7 +422,7 @@ pub(super) fn parse(stage: &str, text: &str, c: &Value) -> R { .collect::>>()?; return Ok(json!({"fields":fields,"warnings":warnings})); } - let screens = v["screens"].as_array().filter(|a| !a.is_empty() && a.len() <= 12).ok_or("方案必须含1至12屏")?; + let screens = v["screens"].as_array().filter(|a| !a.is_empty()).ok_or("页面方案缺少模板模块")?; let mut out = Vec::new(); for screen in screens { let title = string(&screen["title"], 120, "标题")?; @@ -808,16 +804,13 @@ mod tests { c["designSnapshot"] = json!({"brand":{"id":"brand","profile":{"tone":"简洁"}}}); c["facts"] = json!({"status":"ready","items":[{"text":"四条支腿","source":"实拍"}],"missing":["承重待确认"]}); let points = prompt("points", &c).unwrap(); - assert!(points.contains("可直接用于产品详情页的简洁消费者成稿")); - assert!(points.contains("缺失信息只写在warnings")); - assert!(points.contains("不能扩写为稳固、承重或耐用")); + assert!(points.contains("按企业 Skill 的要求撰写成稿")); c["sellingPoints"]["batches"] = json!([{"id":"batch","items":["四腿支撑结构"],"factsHash":facts_hash(&c)}]); c["sellingPoints"]["selected"] = json!(["batch:0"]); assert!(prompt("plan", &c).unwrap_err().contains("选择已配置模板")); c["designSnapshot"]["rules"] = json!({"id":"qa-template","contentHash":"a".repeat(64),"catalog":{"shops":[{"id":"brand"}],"bindings":[{"categoryId":"category","state":"ready","template":{"screens":[{"id":"first","title":"首屏","role":"content"}]}}]}}); let plan = prompt("plan", &c).unwrap(); - assert!(plan.contains("不要复制资料分析报告")); - assert!(plan.contains("不在成稿写待补说明")); + assert!(plan.contains("按模板模块的顺序为每个模块生成页面方案")); assert!(plan.contains("qa-template")); assert!(!points.contains("qa-template")); // Tone is guidance for the model, not a regex rejection of an otherwise complete response. @@ -838,7 +831,7 @@ mod tests { c["brief"]["categoryId"] = json!("category"); c["designSnapshot"] = json!({"rules":{"id":"template","contentHash":"a".repeat(64),"catalog":{"shops":[{"id":"brand"}],"bindings":[{"state":"ready","categoryId":"category","rules":["do not inject this whole original file"],"template":{"screens":(0..22).map(|i|json!({"id":format!("S{i}"),"title":"模块","role":"content","purpose":"a".repeat(2000)})).collect::>()}}]}}}); let template = plan_template(&c).unwrap(); - assert_eq!(template["modules"].as_array().unwrap().len(), 12); + assert_eq!(template["modules"].as_array().unwrap().len(), 22); assert!(template.to_string().len() < 2000); assert!(!template.to_string().contains("purpose")); c["brief"]["categoryId"] = json!("other"); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs index 5d16b9cb..27bf187f 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs @@ -194,7 +194,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu let project_file = package_root.join(format!("{name}.xiaoyi")); let mut package = json!({"version":2,"localId":policy.project,"scope":policy.scope, "snapshot":Uuid::new_v4().to_string(),"sourceRoot":project,"resources":format!("{name} 资源")}); - project_file::write_project(project, &project_file, &mut package, policy, true)?; + let portable_digests = project_file::write_project(project, &project_file, &mut package, policy, true)?; let reopened = read_json(&project_file)?; if reopened != package { return Err("小壹工程清单读回不一致".into()); @@ -209,11 +209,16 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu let format = file.extension().and_then(|extension| extension.to_str()).unwrap_or(""); let size = artifact_size(&file, format)?; let record = file_record(root, &file, "工程资源", size)?; - // The portable checkpoint normalizes its context. - if relative != "context.json" - && record["sha256"] != canvas_workspace::file_digest(&project.join(relative)).map_err(disk)? - { - return Err("工程资源与本机草稿内容不一致".into()); + // Context is normalized, and compact drafts are embedded before delivery. + if relative != "context.json" { + let source = canvas_workspace::file_digest(&project.join(relative)).map_err(disk)?; + let matches_source = match portable_digests.get(relative) { + Some(digests) => source == digests.checkpoint && record["sha256"] == digests.archive, + None => record["sha256"] == source, + }; + if !matches_source { + return Err("工程资源与本机草稿内容不一致".into()); + } } files.push(record); } @@ -338,8 +343,10 @@ mod tests { let local = Uuid::new_v4().to_string(); let project = root.path().join("drafts").join(&local); fs::create_dir_all(&project).unwrap(); - let canvas = Document::new("天青椅", Size::new(8, 10), ColorMode::Rgb, SampleType::U8); - photocraft_format::PcraftWriter::new().save_path(&canvas, &project.join("canvas.pcraft"), &Default::default()).unwrap(); + let mut canvas = Document::new("天青椅", Size::new(8, 10), ColorMode::Rgb, SampleType::U8); + canvas.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", std::sync::Arc::new(vec![123; 1 << 20]))); + let draft = photocraft_format::PcraftWriter::new().save_draft_zip(&canvas, &super::super::draft_objects(&project)).unwrap(); + fs::write(project.join("canvas.pcraft"), draft).unwrap(); write_json(&project.join("context.json"), &json!({"localId":local,"owner":"owner"})).unwrap(); let variant = Uuid::new_v4().to_string(); write_json(&project.join("creation.json"), &json!({"version":1,"brief":{"name":"天青椅", @@ -436,11 +443,15 @@ mod tests { fs::copy(final_dir.join("工程文件").join(format!("{name}.pcraft")), &native).unwrap(); let doc = photocraft_format::load_path(&native).unwrap(); assert_eq!(doc.size, Size::new(8, 10)); + assert_eq!(doc.metadata.psd_global_blocks[0].2.as_slice(), vec![123; 1 << 20]); let filename = format!("{name}.psd"); let layered = clean.join(&filename); fs::copy(final_dir.join("PSD").join(&filename), &layered).unwrap(); let bytes = fs::read(layered).unwrap(); assert_eq!(canvas_workspace::layered_size(&filename, &bytes).unwrap(), (8, 10)); + let layered = photocraft_io::import(&filename, &bytes).unwrap().document; + assert!(layered.metadata.psd_global_blocks.iter().any(|(_, key, bytes)| + key == b"lnk2" && bytes.len() == 1 << 20 && bytes.iter().all(|&byte| byte == 123))); } let packaged = clean.join("天青椅.xiaoyi"); fs::copy(final_dir.join("工程文件/天青椅.xiaoyi"), &packaged).unwrap(); @@ -453,6 +464,8 @@ mod tests { } fs::rename(&project, root.path().join("hidden-source")).unwrap(); assert_eq!(project_file::open(&packaged, &clean.join("drafts"), "owner").unwrap(), local); + let reopened = photocraft_format::load_path(&clean.join("drafts").join(&local).join("canvas.pcraft")).unwrap(); + assert_eq!(reopened.metadata.psd_global_blocks[0].2.as_slice(), vec![123; 1 << 20]); fs::rename(root.path().join("hidden-source"), &project).unwrap(); let original = fs::read(manifest_path).unwrap(); assert_eq!(deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap()["path"], delivered["path"]); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_document.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_document.rs index 6757af74..d1738002 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_document.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_document.rs @@ -146,10 +146,10 @@ fn shape(s: &mut Session, layer: &Value, top: f64) -> R { } pub fn import(original: &Value, assets: &HashMap>) -> R { - let screens = original["screens"].as_array().filter(|s| !s.is_empty() && s.len() <= 12).ok_or("此项目尚未生成画布,请先准备页面内容")?; + let screens = original["screens"].as_array().filter(|s| !s.is_empty()).ok_or("此项目尚未生成画布,请先准备页面内容")?; let width = screens[0]["width"].as_u64().ok_or("画布宽度无效")?; let height = screens.iter().try_fold(0u64, |sum, s| s["height"].as_u64().and_then(|h| sum.checked_add(h))).ok_or("画布高度无效")?; - if ![750, 1440].contains(&width) || height == 0 || height > 30000 || screens.iter().any(|s| s["width"] != width) { + if !(1..=30_000).contains(&width) || height == 0 || height > 30000 || screens.iter().any(|s| s["width"] != width) { return Err("项目画布超出客户端范围".into()); } let mut s = Session::new(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs index 29c70aa5..6b9382ef 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs @@ -836,10 +836,10 @@ impl Backend { if !dir.join("context.json").exists() { // A brand-new unsaved document can invoke image generation before // the normal autosave tick. Persist it once, never over a newer save. - let bytes = photocraft_format::save_to_bytes(&doc, &Default::default()).map_err(|_| "原画布无法保存,未提交生图")?; let _guard = sync::context_guard(); project_not_trashed(&dir)?; if !dir.join("context.json").exists() { + let bytes = self.serialize_draft(&dir, &doc)?; photocraft_format::atomic_write(&dir.join("canvas.pcraft"), &bytes).map_err(|_| "原画布无法保存,未提交生图")?; write_json( &dir.join("context.json"), diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs index 1ef61658..5f182600 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs @@ -79,261 +79,6 @@ fn write_task(path: &Path, task: &Value) -> R<()> { photocraft_format::atomic_write(path, &bytes).map_err(|_| "原SDK任务保存失败,请保留文件;不会重发".into()) } -fn append_response(raw: &mut Vec, part: &[u8]) -> R<()> { - if raw.len().saturating_add(part.len()) > RESPONSE_LIMIT { - return Err("98k响应超限,结果待核查;不会重发".into()); - } - raw.extend_from_slice(part); - Ok(()) -} - -fn retain_incomplete(task: &mut Value, raw: &[u8], recovering: bool) -> R<()> { - if raw.is_empty() { - return Ok(()); - } - if raw.len() > RESPONSE_LIMIT { - return Err("SDK不完整响应超限,原记录保留;不会重发".into()); - } - // The first interrupted stream is evidence. A later GET must never replace - // that original prefix, even when the GET itself breaks or exceeds its cap. - if task["partialRaw"].is_null() { - task["partialRaw"] = json!(STANDARD.encode(raw)); - task["partialBytes"] = json!(raw.len()); - } - if recovering { - task["recovery"] = json!({"status":task["lastQueryHttpStatus"],"at":now(),"raw":STANDARD.encode(raw),"complete":false}); - } - Ok(()) -} - -fn lookup_binding(task: &Value) -> R { - let id = uuid(task, "id")?; - let request = uuid(task, "requestId")?; - for key in ["bodyHash", "keyFingerprint"] { - if !task[key].as_str().is_some_and(|s| s.len() == 64 && s.bytes().all(|byte| byte.is_ascii_hexdigit())) { - return Err("原SDK请求身份摘要无效,保留未知状态;不会重发".into()); - } - } - Ok(hash(&json!({"id":id,"requestId":request,"bodyHash":task["bodyHash"],"keyFingerprint":task["keyFingerprint"]}).to_string())) -} - -/// Called only behind the original-scope/original-Key GET transport below. -/// Neither HTTP 410 nor a provider error body is evidence of a terminal status. -fn original_lookup(task: &Value, code: u16, response: &Value) -> R { - if code != 200 || !super::images::original_lookup_fields(response) || response["result_available"] != false { - return Err("原SDK请求尚无明确的不可取回证明,保留未知状态;不会重发".into()); - } - let request = uuid(task, "requestId")?; - if response["request_id"].as_str().and_then(|id| Uuid::parse_str(id).ok()) != Uuid::parse_str(&request).ok() - || response["result_path"] != format!("/api/external/requests/{request}/result") - { - return Err("原SDK请求号或结果路径不一致,保留未知状态;不会重发".into()); - } - let status = response["status"].as_str().filter(|status| ["failed", "succeeded"].contains(status)).ok_or("原SDK请求仍未确认终态,保留未知状态")?; - let expiry = &response["result_expires_at"]; - let valid_expiry = expiry.is_null() - || status == "succeeded" - && expiry.as_str().is_some_and(|s| { - (20..=40).contains(&s.len()) && s.contains('T') && s.ends_with('Z') && s.bytes().all(|b| b.is_ascii_digit() || b"-:.TZ".contains(&b)) - }); - if !valid_expiry { - return Err("原SDK请求保留期限格式尚未确认,保留未知状态;不会重发".into()); - } - let evidence = json!({"request_id":response["request_id"],"status":status,"result_available":false, - "result_path":response["result_path"],"result_expires_at":expiry}); - Ok(json!({"verified":true,"method":"GET","path":"/api/external/requests/by-idempotency-key","httpStatus":200, - "idempotencyKey":uuid(task,"id")?,"requestId":request,"status":status,"resultAvailable":false, - "resultPath":response["result_path"],"resultExpiresAt":expiry,"lookupSha256":hash(&evidence.to_string()), - "bodyHash":task["bodyHash"],"bindingHash":lookup_binding(task)?,"keyFingerprintMatches":true})) -} - -fn checked_lookup(task: &Value) -> R { - let proof = &task["originalLookup"]; - let response = json!({"request_id":proof["requestId"],"status":proof["status"],"result_available":proof["resultAvailable"], - "result_path":proof["resultPath"],"result_expires_at":proof["resultExpiresAt"]}); - let expected = original_lookup(task, proof["httpStatus"].as_u64().and_then(|v| u16::try_from(v).ok()).unwrap_or(0), &response)?; - if *proof != expected { - return Err("原SDK请求不可取回证明与原身份不一致,尚未确认放弃使用".into()); - } - Ok(expected) -} - -fn public_lookup(task: &Value) -> Value { - checked_lookup(task).unwrap_or(Value::Null) -} - -fn settle_lookup(task: &mut Value, proof: Value, mut persist: impl FnMut(&Value) -> R<()>) -> R<()> { - if matches!(task["phase"].as_str(), Some("complete" | "rejected" | "failed")) { - return Err("原SDK请求已结算,未覆盖终态".into()); - } - let mut witnessed = task.clone(); - witnessed["originalLookup"] = proof; - checked_lookup(&witnessed)?; - witnessed["phase"] = json!("unknown"); - persist(&witnessed)?; // An authenticated proof is durable before settlement. - *task = witnessed; - let mut settled = task.clone(); - let failed = settled["originalLookup"]["status"] == "failed"; - settled["phase"] = json!(if failed { "failed" } else { "unavailable" }); - settled["terminal"] = json!(false); - settled["lastError"] = json!(if failed { - "网关确认原SDK请求已终止且无可取回结果;不会重发" - } else { - "网关记录原SDK请求已成功,但原结果不可取回;尚未使用该结果,不会重发" - }); - persist(&settled)?; - *task = settled; - Ok(()) -} - -fn refused_model_response(task: &Value) -> bool { - let Some(protocol @ ("anthropic-messages" | "openai-chat")) = task["model"]["protocol"].as_str() else { return false; }; - let Some(bytes) = task["raw"].as_str().and_then(|raw| STANDARD.decode(raw).ok()) else { return false; }; - let Ok(text) = std::str::from_utf8(&bytes) else { return false; }; - text.lines().filter_map(|line| line.trim().strip_prefix("data:")).any(|data| { - serde_json::from_str::(data).is_ok_and(|frame| { - if protocol == "anthropic-messages" { - frame["type"] == "message_delta" && frame["delta"]["stop_reason"] == "refusal" - } else { - frame["choices"].as_array().is_some_and(|choices| choices.iter().any(|choice| - choice["index"].as_u64().unwrap_or(0) == 0 && choice["finish_reason"] == "content_filter")) - } - }) - }) -} - -fn finish_task(task: &mut Value, input: &Value) -> R<()> { - if task["bodyHash"] != input["bodyHash"] { - return Err("原请求身份不一致,不会重发".into()); - } - let phase = if task["phase"] == "received" { - if input["valid"] == true && task["terminal"] == true { - "complete" - } else if input["valid"] == false && task["terminal"] == true && task["detailSlot"].is_string() - && (input["reason"] == "length" || refused_model_response(task)) { - // A terminal truncation or refusal ends this step without executing a tool. - "rejected" - } else { - "unknown" - } - } else if task["phase"] == "unavailable" { - if input["valid"] != false || checked_lookup(task)?["status"] != "succeeded" { - return Err("不可取回结果只能明确确认不使用,不能当作成功回答或网关失败".into()); - } - "rejected" - } else { - return Err("原请求尚未完成或已结算,不会重发".into()); - }; - task["phase"] = json!(phase); - task["finishReason"] = input["reason"].clone(); - task["finishedAt"] = json!(now()); - Ok(()) -} - -fn response_metadata(task: &mut Value, method: &str, status: u16, content_type: &str) { - if method == "request" { - task["httpStatus"] = json!(status); - task["contentType"] = json!(content_type); - } else { - if task["lastQueryHttpStatus"].is_null() && task["recovery"]["status"].is_number() && !task["httpStatus"].is_null() { - task["legacyHttpMetadata"] = json!(true); - } - task["lastQueryHttpStatus"] = json!(status); - task["lastQueryContentType"] = json!(content_type); - } -} - -#[cfg(test)] -fn lookup_unavailable(task: &Value, get: impl FnOnce(&str, &str) -> R<(u16, Value)>) -> R { - if matches!(task["phase"].as_str(), Some("complete" | "rejected" | "failed")) { - return Err("原SDK请求已结算,未重复查询".into()); - } - let id = uuid(task, "id")?; - let (status, response) = get("/api/external/requests/by-idempotency-key", &id)?; - original_lookup(task, status, &response) -} - -fn lookup_original( - task: &mut Value, - get: impl FnOnce(&str, &str) -> R<(u16, Value)>, - mut persist: impl FnMut(&Value) -> R<()>, -) -> R { - let id = uuid(task, "id")?; - let (status, response) = get("/api/external/requests/by-idempotency-key", &id)?; - task["lastOriginalLookup"] = super::images::lookup_observation(status, &response); - persist(task)?; - if status != 200 || !super::images::original_lookup_fields(&response) { - return Ok(false); - } - let request = uuid(&response, "request_id")?; - if response["result_path"] != format!("/api/external/requests/{request}/result") - || (task["requestId"].is_string() && uuid(task, "requestId")? != request) - { - return Ok(false); - } - let Some(available) = response["result_available"].as_bool() else { return Ok(false) }; - if task["requestId"].is_null() { - task["requestId"] = json!(request); - persist(task)?; - } - if !available && matches!(response["status"].as_str(), Some("failed" | "succeeded")) { - let proof = original_lookup(task, status, &response)?; - settle_lookup(task, proof, persist)?; - } - Ok(available) -} - -pub(super) const RATE_LIMIT_MESSAGE: &str = "模型服务暂时限流,这条回复没有完成。稍后可继续对话。"; - -fn confirmed_rate_limit(status: u16, content_type: &str, text: &str) -> bool { - let mime = content_type.split(';').next().unwrap_or("").trim(); - if status == 429 && mime.eq_ignore_ascii_case("application/json") { - return serde_json::from_str::(text).is_ok_and(|value| { - value["error"]["code"] == "rate_limit_exceeded" - || (value["type"] == "error" && value["error"]["type"] == "rate_limit_error") - }); - } - if status != 200 || !mime.eq_ignore_ascii_case("text/event-stream") { - return false; - } - // Relay can send comment-only keepalives before its single error event. - let mut lines = text.lines().filter(|line| !line.is_empty() && !line.starts_with(':')); - let first = lines.next().unwrap_or(""); - let named_error = first == "event: error"; - let data_line = if named_error { lines.next().unwrap_or("") } else { first }; - let Some(data) = data_line.strip_prefix("data:") else { return false; }; - let Ok(value) = serde_json::from_str::(data.trim()) else { return false; }; - lines.next().is_none() - && if named_error { - value["type"] == "error" && value["error"]["type"] == "rate_limit_exceeded" - } else { - value.as_object().is_some_and(|object| object.len() == 1) && value["error"]["code"] == "rate_limit_exceeded" - } -} - -fn mark_rate_limited(task: &mut Value) { - task["phase"] = json!("failed"); - task["terminal"] = json!(false); - task["failureCode"] = json!("rate_limit_exceeded"); - task["lastError"] = json!(RATE_LIMIT_MESSAGE); -} - -pub(super) fn settle_recorded_rate_limit(dir: &Path) -> R> { - let pending = unresolved(dir)?; - let [pending] = pending.as_slice() else { return Ok(None); }; - let id = uuid(pending, "id")?; - let file = dir.join(format!("{id}.json")); - let mut task = read_task(&file)?; - if task["id"] != id || task["phase"] != "unknown" { return Ok(None); } - let raw = task["raw"].as_str().and_then(|raw| STANDARD.decode(raw).ok()).unwrap_or_default(); - let text = std::str::from_utf8(&raw).unwrap_or(""); - let status = task["httpStatus"].as_u64().and_then(|status| u16::try_from(status).ok()).unwrap_or_default(); - if !confirmed_rate_limit(status, task["contentType"].as_str().unwrap_or(""), text) { return Ok(None); } - mark_rate_limited(&mut task); - write_task(&file, &task)?; - Ok(Some(id)) -} - fn emit(value: Value) -> R<()> { let stdout = std::io::stdout(); let mut out = stdout.lock(); @@ -345,98 +90,9 @@ fn uuid(v: &Value, field: &str) -> R { fn scope_matches(method: &str, input: &Value, actual: &str) -> bool { match input["accountScope"].as_str() { Some(scope) => scope == actual, - None => method == "info" && input["original"] != true, + None => method == "info", } } -fn record_request_header(task: &mut Value, method: &str, request: &str) { - if method == "request" { - task["requestId"] = json!(request); - } else { - task["lastQueryRequestId"] = json!(request); - } -} -fn stream_complete(text: &str, anthropic: bool, expected_model: Option<&str>) -> bool { - let mut terminal = !anthropic && text.lines().any(|l| l.trim() == "data: [DONE]"); - let mut model_seen = false; - let mut finish_seen = false; - for data in text.lines().filter_map(|l| l.trim().strip_prefix("data:").map(str::trim)).filter(|data| !data.is_empty() && *data != "[DONE]") { - let Ok(value) = serde_json::from_str::(data) else { return false }; - if !value.is_object() { - return false; - } - if anthropic && value["type"] == "message_stop" { - terminal = true; - } - if anthropic && value["delta"]["stop_reason"].is_string() { - finish_seen = true; - } - if !anthropic - && value["choices"] - .as_array() - .is_some_and(|choices| choices.iter().any(|c| c["index"].as_u64().unwrap_or(0) == 0 && c["finish_reason"].is_string())) - { - finish_seen = true; - } - if let Some(model) = value["model"].as_str().or(value["message"]["model"].as_str()) { - model_seen = true; - if expected_model.is_some_and(|expected| expected != model) { - return false; - } - } - } - terminal && finish_seen && (expected_model.is_none() || model_seen) -} -fn responses_terminal(value: &Value, expected_model: &Value, bound_stream: bool) -> bool { - (value["model"] == *expected_model || bound_stream && value.get("model").is_none()) - && matches!(value["status"].as_str(), Some("completed" | "incomplete")) - && value["output"].is_array() -} - -fn stream_terminal(text: &str, model: &Value, bound_stream: bool) -> bool { - if model["protocol"] != "openai-responses" { - return stream_complete(text, model["protocol"] == "anthropic-messages", model["id"].as_str()); - } - let mut terminal = false; - for frame in text.lines().filter_map(|line| line.trim().strip_prefix("data:")) - .filter_map(|data| serde_json::from_str::(data.trim()).ok()) - { - let response = &frame["response"]; - if response.get("model").is_some_and(|id| id != &model["id"]) { - return false; - } - if matches!(frame["type"].as_str(), Some("response.completed" | "response.incomplete")) { - terminal = responses_terminal(response, &model["id"], bound_stream); - } - } - terminal -} - -#[cfg(test)] -fn validate_payload(value: &Value, model: &Value) -> R<()> { - validate_provider_payload(value, model) -} - -fn production_request_scope(scope: &str) -> bool { - if scope == "production-strategy" { return true; } - let Some(scope) = scope.strip_prefix("product/") else { return false }; - let mut parts = scope.split('/'); - let (Some(step), Some(id)) = (parts.next(), parts.next()) else { return false }; - if matches!(step, "slot" | "compare") { - return parts.next().is_none() && id.len() == 64 && id.bytes().all(|byte| byte.is_ascii_hexdigit()); - } - Uuid::parse_str(id).is_ok() && match (step, parts.next(), parts.next()) { - ("goal" | "copy" | "copy-audit", Some(output), None) => - output.as_bytes().first().is_some_and(u8::is_ascii_lowercase) - && output.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_-".contains(&b)), - ("run" | "strategy" | "strategy-audit" | "review" | "first-canvas", None, None) => true, - _ => false, - } -} - -pub(super) fn scoped_production_request(request: &Value) -> bool { - request["modelRole"] == "detail" && request["detailSlot"].as_str().is_some_and(production_request_scope) -} - fn validate_provider_payload(value: &Value, model: &Value) -> R<()> { if value["model"] != model["id"] || value["stream"] != true { return Err("只能调用当前账户已选择的流式对话模型".into()); @@ -562,8 +218,7 @@ pub(super) fn unresolved(dir: &Path) -> R> { } if v["inference"] != true && matches!(v["phase"].as_str(), Some("dispatched" | "unknown" | "received" | "unavailable")) { pending.push(json!({"id":v["id"],"requestId":v["requestId"],"phase":v["phase"],"detailSlot":v["detailSlot"], - "modelRole":v["modelRole"].as_str().unwrap_or("chat"),"retryOf":v["retryOf"],"createdAt":v["createdAt"], - "originalLookup":public_lookup(&v)})); + "modelRole":v["modelRole"].as_str().unwrap_or("chat"),"retryOf":v["retryOf"],"createdAt":v["createdAt"]})); } } } @@ -571,21 +226,6 @@ pub(super) fn unresolved(dir: &Path) -> R> { Ok(pending) } -fn request_conflicts(pending: &[Value], detail_slot: Option<&str>, scoped: bool, retry_of: Option<&str>) -> bool { - let mut conflicts = pending.iter().filter(|item| detail_slot.is_none() - || item["detailSlot"].as_str() == detail_slot || !scoped && !item["detailSlot"].is_string()); - if let Some(original) = retry_of { - // Replace only a model reply within the exact production scope. - let matches_scope = scoped && detail_slot.is_some_and(|slot| - ["product/goal/", "product/slot/", "product/review/"].into_iter().any(|prefix| slot.starts_with(prefix))) - && conflicts.next().is_some_and(|item| item["id"] == original - && matches!(item["phase"].as_str(), Some("dispatched" | "unknown" | "unavailable"))); - !matches_scope || conflicts.next().is_some() - } else { - conflicts.next().is_some() - } -} - pub(super) fn run() -> R<()> { let mut bytes = Vec::new(); std::io::stdin().take((LIMIT + 32769) as u64).read_to_end(&mut bytes).map_err(|_| "SDK输入无法读取")?; @@ -632,7 +272,6 @@ fn rpc_error_frame(error: &str, new_request_preflight: bool) -> Value { let safe = match error { "工具未授权" | "工具数量超限" | "工具名称无效" | "工具名称不一致" | "工具名称重复" => "客户端工具配置不匹配,本次未发送模型请求", "只能调用当前账户已选择的流式对话模型" | "会话条数无效" | "会话角色无效" | "必须限制输出长度" | "输出长度或候选数量超限" | "模型输入过大" | "模型输入不是JSON" => "客户端请求格式不匹配,本次未发送模型请求", - "网关确认原SDK请求已终止且无可取回结果;不会重发" => "服务端确认本次请求失败,没有可取回的结果", "98k暂时无法连接(请求超时);个人Key已保留" => "98k暂时无法连接(请求超时);个人Key已保留", "98k暂时无法连接(代理连接失败);个人Key已保留" => "98k暂时无法连接(代理连接失败);个人Key已保留", "98k暂时无法连接(TLS连接失败);个人Key已保留" => "98k暂时无法连接(TLS连接失败);个人Key已保留", @@ -647,16 +286,11 @@ fn rpc_error_frame(error: &str, new_request_preflight: bool) -> Value { | "当前对话模型已停用,请在小壹设置中重新选择" | "个人 Key 未开放所选对话模型,请在小壹设置中重新选择" | crate::jiansun_models::DETAIL_ROUTE_UNVERIFIED => error, - "98k连接中断,结果未知;不会重发" => "98k连接中断,结果未知;不会重发", - "98k响应中断,结果未知;不会重发" => "98k响应中断,结果未知;不会重发", - "原SDK请求只读定位连接中断,保留未知状态;不会重发" => "原SDK请求只读定位连接中断,保留未知状态;不会重发", - ACCOUNT_CHANGED | AUTH_REVOKED => error, + "98k连接中断" | "98k响应中断" | ACCOUNT_CHANGED | AUTH_REVOKED => error, "个人Key校验失败(HTTP 401)" => AUTH_REVOKED, - "原请求待核查或已提交,禁止重发" => "原请求待核查或已提交,禁止重发", - "原创作或生图请求待核查,禁止从Agent重新派发" => "原创作或生图请求待核查,禁止从Agent重新派发", "SDK输入过大" => "SDK输入过大", "SDK输入无效" => "SDK输入无效", - _ => "本地SDK操作失败;请检查原请求状态,勿重发", + _ => "本地模型连接操作失败", }; let mut frame = json!({"type":"error","error":safe}); if safe == ACCOUNT_CHANGED { @@ -667,7 +301,7 @@ fn rpc_error_frame(error: &str, new_request_preflight: bool) -> Value { frame["dispatched"] = json!(!new_request_preflight); } if new_request_preflight { - if safe == "本地SDK操作失败;请检查原请求状态,勿重发" { + if safe == "本地模型连接操作失败" { frame["error"] = json!("客户端准备模型请求失败,本次未发送"); frame["retryPreparation"] = json!(true); } @@ -735,33 +369,13 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m *selection = None; return Err(ACCOUNT_CHANGED.into()); } - if !matches!(method, "status" | "read" | "finish") - && let Err(error) = check_dispatch_lease(&input["dispatchLease"]) { + if let Err(error) = check_dispatch_lease(&input["dispatchLease"]) { *new_request_preflight = method == "request"; return Err(error); } let project_records = backend.dir().join("pi-validation").join(&project); - let dir = project_records.join("requests"); let selection_file = project_records.join("detail-selection.json"); - if method == "status" { - return emit(json!({"type":"result","value":{"accountScope":backend.scope(),"pending":unresolved(&dir)?}})); - } if method == "info" { - if input["original"] == true { - let pending = unresolved(&dir)?; - let id = if input["id"].is_string() { - uuid(&input, "id")? - } else { - uuid(pending.first().ok_or("没有待核查的原请求")?, "id")? - }; - let original = read_task(&dir.join(format!("{id}.json")))?; - if original["id"] != id || original["model"]["id"].as_str().is_none() { - return Err("原请求缺少模型记录".into()); - } - backend.validate()?; - return emit(json!({"type":"result","value":{"accountScope":backend.scope(),"accountId":backend.auth["account"]["id"], - "origin":backend.origin,"model":original["model"],"pending":pending}})); - } let role = input["modelRole"].as_str().unwrap_or("chat"); let continuation = if role == "detail" && input["reuseDetailSelection"] == true { let settings = backend.settings()?; @@ -789,7 +403,7 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m } else { None }; *selection = Some((backend.scope(), role.to_owned(), settings, model.clone(), invocation.clone())); return emit( - json!({"type":"result","value":{"accountScope":backend.scope(),"accountId":backend.auth["account"]["id"],"origin":backend.origin,"model":model,"thinkingLevel":thinking,"invocationHeaders":invocation["headers"],"pending":unresolved(&dir)?,"selectionTimings":selection_timings,"selectionId":selection_id}}), + json!({"type":"result","value":{"accountScope":backend.scope(),"accountId":backend.auth["account"]["id"],"origin":backend.origin,"model":model,"thinkingLevel":thinking,"invocationHeaders":invocation["headers"],"selectionTimings":selection_timings,"selectionId":selection_id}}), ); } if method == "knowledge" { @@ -798,42 +412,12 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m let value = backend.json(&path)?; return emit(json!({"type":"result","value":value})); } - let id = uuid(&input, "id")?; - let file = dir.join(format!("{id}.json")); - let inference = method == "request" && input["inference"] == true; - if method == "request" { - if !inference && file.try_exists().map_err(|_| "本机原请求记录无法核对")? { - return Err("原请求待核查或已提交,禁止重发".into()); - } - *new_request_preflight = true; - } - if method == "finish" { - let mut task = read_task(&file)?; - if uuid(&task, "id")? != id { - return Err("原SDK请求记录不属于当前请求,未确认使用".into()); - } - finish_task(&mut task, &input)?; - write_task(&file, &task)?; - return emit(json!({"type":"result","value":{"phase":task["phase"],"requestId":task["requestId"],"originalLookup":public_lookup(&task)}})); - } - if method == "read" { - let task = read_task(&file)?; - let proof = public_lookup(&task); - let observation = &task["lastOriginalLookup"]; - let failure_status = (proof["status"] == "failed" && observation["status"] == "failed" - && observation["requestId"] == proof["requestId"]).then(|| &observation["errorHTTPStatus"]); - return emit( - json!({"type":"result","value":{"phase":task["phase"],"requestId":task["requestId"],"bodyHash":task["bodyHash"],"model":task["model"],"terminal":task["terminal"],"raw":task["raw"],"httpStatus":task["httpStatus"],"failureHttpStatus":failure_status,"failureCode":task["failureCode"],"recovery":task["recovery"],"originalLookup":proof}}), - ); - } - if !matches!(method, "request" | "recover") { + if method != "request" { return Err("SDK操作未授权".into()); } - let (settings, model, selection_source) = if method == "recover" { - backend.validate()?; - let original = read_task(&file)?; - (backend.settings()?, original["model"].clone(), "original") - } else { + let id = uuid(&input, "id")?; + *new_request_preflight = true; + let (settings, model) = { let role = input["modelRole"].as_str().unwrap_or("chat"); let settings = backend.settings()?; let scoped_model = if role == "detail" && input["selectionId"].is_string() { @@ -846,7 +430,7 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m }; if let Some(model) = scoped_model { backend.validate()?; - (settings, model, "run") + (settings, model) } else { let (settings, mut model, invocation, _) = selected(&mut backend, role)?; pi_runtime::apply_invocation_capacity(&mut model, &invocation)?; @@ -855,281 +439,61 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m return Err("模型调用路由已更新,本次尚未提交".into()); } *selection = Some((backend.scope(), role.to_owned(), settings.clone(), model.clone(), invocation)); - (settings, model, "refresh") + (settings, model) } }; let key = settings["key"].as_str().ok_or("个人Key缺失")?; - let persist = |task: &Value| -> R<()> { - if inference { Ok(()) } else { write_task(&file, task) } - }; - let lookup = |task: &mut Value| { - lookup_original(task, |path, original_id| { - let response = backend.http.get(format!("{UPSTREAM}{path}")) - .bearer_auth(key) - .header("Idempotency-Key", original_id) - .timeout(Duration::from_secs(30)) - .send() - .map_err(|_| "原SDK请求只读定位连接中断,保留未知状态;不会重发")?; - body(response, 64 * 1024) - }, |task| write_task(&file, task)) - }; - let mut task; - let response = if method == "recover" { - task = read_task(&file)?; - if task["keyFingerprint"] != hash(key) { - return Err("必须使用原账户、原Key只读核查".into()); - } - if uuid(&task, "id")? != id { - return Err("原SDK请求记录不属于当前请求,未发起查询".into()); - } - if matches!(task["phase"].as_str(), Some("complete" | "rejected" | "failed")) { - return emit( - json!({"type":"result","value":{"phase":task["phase"],"requestId":task["requestId"],"bodyHash":task["bodyHash"],"terminal":task["terminal"],"originalLookup":public_lookup(&task)}}), - ); - } - if task["requestId"].is_null() && !lookup(&mut task)? { - return emit(json!({"type":"result","value":{"phase":task["phase"],"requestId":task["requestId"],"originalLookup":public_lookup(&task)}})); - } - let request = uuid(&task, "requestId")?; - backend.http.get(format!("{UPSTREAM}/api/external/requests/{request}/result")).bearer_auth(key).send() - } else { - let native = backend.dir().join("projects").join(&project); - let scoped = scoped_production_request(&input); - if !inference && !scoped && (super::creation::unresolved(&native)? || super::images::pending(&native)?) { - return Err("原创作或生图请求待核查,禁止从Agent重新派发".into()); - } - let detail_slot = input.get("detailSlot").map(|slot| slot.as_str().filter(|slot| !slot.is_empty() && slot.len() <= 240 && !slot.chars().any(char::is_control)).ok_or("详情页图位身份无效")).transpose()?; - let retry_of = input.get("retryOf").map(|_| uuid(&input, "retryOf")).transpose()?; - if !inference && request_conflicts(&unresolved(&dir)?, detail_slot, scoped, retry_of.as_deref()) { - return Err("原请求待核查或已提交,禁止重发".into()); - } - let payload = input["body"].as_str().filter(|s| s.len() <= LIMIT).ok_or("模型输入过大")?; - let value: Value = serde_json::from_str(payload).map_err(|_| "模型输入不是JSON")?; - if detail_slot.is_some() && input["modelRole"] != "detail" { - return Err("工具未授权".into()); - } - validate_provider_payload(&value, &model)?; - let headers = invocation_headers(&input)?; - let model_path = model["path"].as_str().ok_or("模型路径无效")?; - let timeout = Duration::from_secs(600); - task = if inference { json!({"requestId":null}) } else { - json!({"id":id,"requestId":null,"phase":"dispatched","detailSlot":detail_slot,"modelRole":input["modelRole"].as_str().unwrap_or("chat"),"model":model,"bodyHash":hash(payload),"keyFingerprint":hash(key),"createdAt":now(),"invocationHeaders":headers,"selectionSource":selection_source,"timeoutMs":timeout.as_millis() as u64}) - }; - if let Some(original) = retry_of { - task["retryOf"] = json!(original); - } - *new_request_preflight = false; - persist(&task)?; - let mut request = backend - .http - .post(format!("{UPSTREAM}{model_path}")) - .timeout(timeout) - .header("Idempotency-Key", &id) - .header("Content-Type", "application/json") - .body(payload.to_owned()); - for (name, value) in headers { - request = request.header(name, value); - } - if model["protocol"] == "anthropic-messages" { - request = request.header("Anthropic-Version", "2023-06-01").header("X-Api-Key", key); - } else { - request = request.bearer_auth(key); - } - if let Err(error) = check_dispatch_lease(&input["dispatchLease"]) { - task["phase"] = json!("not_dispatched"); - persist(&task)?; - *new_request_preflight = true; - return Err(error); - } - request.send() - }; - let mut raw = Vec::new(); - let result = (|| -> R<()> { - let mut response = response.map_err(|_| if inference { "98k连接中断" } else { "98k连接中断,结果未知;不会重发" })?; - if let Some(request) = response.headers().get("x-request-id").and_then(|s| s.to_str().ok()).filter(|s| Uuid::parse_str(s).is_ok()) { - record_request_header(&mut task, method, request); - persist(&task)?; - } - let status = response.status().as_u16(); - if method == "request" && matches!(status, 401 | 403) { - *selection = None; - if input["selectionId"].is_string() - && read_task(&selection_file).is_ok_and(|record| record["id"] == input["selectionId"]) { - let _ = fs::remove_file(&selection_file); - } - } - let content_type = response.headers().get("content-type").and_then(|s| s.to_str().ok()).unwrap_or("application/octet-stream").to_owned(); - response_metadata(&mut task, method, status, &content_type); - persist(&task)?; - if status == 401 { - if method == "request" { - task["phase"] = json!("failed"); - task["failureCode"] = json!("auth_revoked"); - persist(&task)?; - } - emit(json!({"type":"headers","status":401,"headers":{"content-type":"application/json"},"requestId":task["requestId"],"bodyHash":task["bodyHash"]}))?; - // Refresh the model authorization catalogue for a subsequent turn. - // The rejected request is terminal and is never replayed. - backend.refresh_model_authority(key); - return Err(AUTH_REVOKED.into()); - } - emit(json!({"type":"headers","status":status,"headers":{"content-type":content_type},"requestId":task["requestId"],"bodyHash":task["bodyHash"]}))?; - let mut chunk = [0u8; 8192]; - loop { - let n = response.read(&mut chunk).map_err(|_| if inference { "98k响应中断" } else { "98k响应中断,结果未知;不会重发" })?; - if n == 0 { - break; - } - let part = chunk.get(..n).ok_or("响应长度无效")?; - if !inference { - append_response(&mut raw, part)?; - } - emit(json!({"type":"chunk","data":STANDARD.encode(part)}))?; - } - if inference { - return emit(json!({"type":"result","value":{"phase":"complete","requestId":task["requestId"]}})); - } - transfer::check_wire(&raw)?; - let text = std::str::from_utf8(&raw).map_err(|_| "98k响应编码无效,结果未知;不会重发")?; - if method == "recover" { - task["recovery"] = json!({"status":status,"at":now(),"raw":STANDARD.encode(&raw)}); - write_task(&file, &task)?; - if status != 200 { - lookup(&mut task)?; - emit( - json!({"type":"result","value":{"phase":task["phase"],"requestId":task["requestId"],"bodyHash":task["bodyHash"],"originalLookup":public_lookup(&task)}}), - )?; - return Ok(()); - } - } - let sse = content_type.to_ascii_lowercase().starts_with("text/event-stream") - || text.trim_start().starts_with("data:") - || text.trim_start().starts_with("event:"); - if method == "request" && confirmed_rate_limit(status, &content_type, text) { - mark_rate_limited(&mut task); - task["raw"] = json!(STANDARD.encode(&raw)); - task["receivedAt"] = json!(now()); - write_task(&file, &task)?; - emit(json!({"type":"result","value":{"phase":"failed","failureCode":task["failureCode"],"requestId":task["requestId"]}}))?; - return Ok(()); - } - // A few Responses streams omit the model in every frame. The authenticated - // POST or GET for the recorded Relay request binds that stream to this model. - let bound_stream = status == 200 && uuid(&task, "requestId").is_ok(); - let terminal = if method == "recover" && sse { - // The public retained-result endpoint can return the ORIGINAL SSE body. - stream_terminal(text, &model, bound_stream) - } else if method == "recover" { - let v: Value = serde_json::from_slice(&raw).map_err(|_| "原响应无效,继续保留未知状态")?; - let v = retained_body(v)?; - if model["protocol"] == "openai-responses" { - responses_terminal(&v, &model["id"], false) - } else { - v["model"] == model["id"] - && (v["stop_reason"].is_string() || v["choices"].as_array().is_some_and(|a| a.iter().any(|c| c["finish_reason"].is_string()))) - } - } else { - stream_terminal(text, &model, bound_stream) - }; - if method == "recover" && !terminal { - lookup(&mut task)?; - return emit(json!({"type":"result","value":{"phase":task["phase"],"requestId":task["requestId"],"originalLookup":public_lookup(&task)}})); - } - task["terminal"] = json!(terminal); - task["phase"] = json!(if status == 200 && terminal { "received" } else { "unknown" }); - task["raw"] = json!(STANDARD.encode(&raw)); - task["receivedAt"] = json!(now()); - write_task(&file, &task)?; - emit(json!({"type":"result","value":{"phase":task["phase"],"requestId":task["requestId"],"bodyHash":task["bodyHash"]}})) - })(); - if let Err(e) = result { - if inference { return Err(e); } - if matches!(task["phase"].as_str(), Some("failed" | "unavailable")) - && (checked_lookup(&task).is_ok() || task["failureCode"] == "rate_limit_exceeded" || task["failureCode"] == "auth_revoked") { - // The proof and outcome already landed. A broken SDK output pipe - // must not erase that authenticated result or reopen a terminal job. - return Err(e); - } - task["phase"] = json!("unknown"); - if transfer::check_wire(&raw).is_ok() { - retain_incomplete(&mut task, &raw, method == "recover")?; - } - task["lastError"] = json!(transfer::redact_text(&e)); - write_task(&file, &task)?; - return Err(e); + let payload = input["body"].as_str().filter(|body| body.len() <= LIMIT).ok_or("模型输入过大")?; + let value: Value = serde_json::from_str(payload).map_err(|_| "模型输入不是JSON")?; + validate_provider_payload(&value, &model)?; + let model_path = model["path"].as_str().ok_or("模型路径无效")?; + let mut request = backend.http + .post(format!("{UPSTREAM}{model_path}")) + .timeout(Duration::from_secs(600)) + .header("Idempotency-Key", &id) + .header("Content-Type", "application/json") + .body(payload.to_owned()); + for (name, value) in invocation_headers(&input)? { + request = request.header(name, value); } - Ok(()) + if model["protocol"] == "anthropic-messages" { + request = request.header("Anthropic-Version", "2023-06-01").header("X-Api-Key", key); + } else { + request = request.bearer_auth(key); + } + check_dispatch_lease(&input["dispatchLease"])?; + *new_request_preflight = false; + let mut response = request.send().map_err(|_| "98k连接中断")?; + let status = response.status().as_u16(); + if matches!(status, 401 | 403) { + *selection = None; + if input["selectionId"].is_string() + && read_task(&selection_file).is_ok_and(|record| record["id"] == input["selectionId"]) { + let _ = fs::remove_file(&selection_file); + } + } + let content_type = response.headers().get("content-type").and_then(|value| value.to_str().ok()) + .unwrap_or("application/octet-stream"); + let retry_after = response.headers().get("retry-after").and_then(|value| value.to_str().ok()); + let mut headers = json!({"content-type":content_type}); + if let Some(retry_after) = retry_after { headers["retry-after"] = json!(retry_after); } + emit(json!({"type":"headers","status":status,"headers":headers}))?; + if status == 401 { + backend.refresh_model_authority(key); + return Err(AUTH_REVOKED.into()); + } + let mut chunk = [0u8; 8192]; + loop { + let count = response.read(&mut chunk).map_err(|_| "98k响应中断")?; + if count == 0 { break; } + emit(json!({"type":"chunk","data":STANDARD.encode(&chunk[..count])}))?; + } + emit(json!({"type":"result","value":{}})) } #[cfg(test)] mod tests { - #[test] - fn production_recovery_is_limited_to_original_production_steps() { - let variant = Uuid::new_v4(); - let copy = format!("product/copy/{variant}/detail"); - let audit = format!("product/copy-audit/{variant}/detail"); - let strategy_audit = format!("product/strategy-audit/{variant}"); - let slot = format!("product/slot/{}", "a".repeat(64)); - let compare = format!("product/compare/{}", "a".repeat(64)); - let goal = format!("product/goal/{variant}/detail"); - for scope in ["production-strategy", &strategy_audit, ©, &audit, &slot, &compare, &goal] { - assert!(scoped_production_request(&json!({"modelRole":"detail","detailSlot":scope}))); - assert!(!scoped_production_request(&json!({"modelRole":"chat","detailSlot":scope}))); - } - for scope in ["supervisor", "product/copy/invalid/detail", "product/copy/invalid/other", - "product/compare/invalid", "product/strategy-audit/invalid", "canvas-chat"] { - assert!(!scoped_production_request(&json!({"modelRole":"detail","detailSlot":scope}))); - } - } - - #[test] - fn recorded_error_only_rate_limit_can_settle_without_a_network_request() { - use super::*; - let content_type = "text/event-stream; charset=utf-8"; - let text = "data: {\"error\":{\"code\":\"rate_limit_exceeded\",\"type\":\"server_error\"}}\r\n\r\n"; - assert!(confirmed_rate_limit(200, content_type, text)); - assert!(!confirmed_rate_limit(200, content_type, &format!("data: {{\"choices\":[]}}\n\n{text}"))); - assert!(!confirmed_rate_limit(200, content_type, "data: {\"error\":{\"code\":\"server_error\"}}")); - let dir = std::env::temp_dir().join(format!("pcraft-rate-limit-{}", Uuid::new_v4())); - let id = Uuid::new_v4().to_string(); - let file = dir.join(format!("{id}.json")); - let raw = STANDARD.encode(text); - write_task(&file, &json!({"id":id,"phase":"unknown","raw":raw,"httpStatus":200,"contentType":content_type})).unwrap(); - assert_eq!(unresolved(&dir).unwrap().len(), 1); - assert_eq!(settle_recorded_rate_limit(&dir).unwrap().as_deref(), Some(id.as_str())); - let task = read_task(&file).unwrap(); - assert_eq!(task["raw"], raw); - assert_eq!(task["phase"], "failed"); - assert!(unresolved(&dir).unwrap().is_empty()); - fs::remove_file(file).unwrap(); - fs::remove_dir(dir).unwrap(); - } - - #[test] - fn confirmed_rate_limits_clear_old_journals_in_both_gateway_formats() { - use super::*; - let dir = std::env::temp_dir().join(format!("pcraft-rate-limit-formats-{}", Uuid::new_v4())); - let id = Uuid::new_v4().to_string(); - let file = dir.join(format!("{id}.json")); - let cases = [ - (200, "text/event-stream", ": keep-alive\r\n\r\n: keep-alive\r\n\r\n: keep-alive\r\n\r\ndata: {\"error\":{\"code\":\"rate_limit_exceeded\",\"type\":\"server_error\"}}\r\n\r\n", true), - (200, "text/event-stream; charset=utf-8", ": keep-alive\n\nevent: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"rate_limit_exceeded\"}}\n\n", true), - (429, "application/json; charset=utf-8", "{\"error\":{\"code\":\"rate_limit_exceeded\",\"type\":\"rate_limit_error\"},\"request_id\":\"\"}", true), - (429, "application/json", "{\"type\":\"error\",\"error\":{\"type\":\"rate_limit_error\"},\"request_id\":\"\"}", true), - (429, "application/json", "{\"error\":{\"code\":\"insufficient_quota\",\"type\":\"insufficient_quota\"}}", false), - (429, "text/plain", "Too Many Requests", false), - (200, "text/event-stream", "data: {\"choices\":[]}\n\ndata: {\"error\":{\"code\":\"rate_limit_exceeded\"}}\n\n", false), - (200, "text/event-stream", ": keep-alive\n\ndata: {\"error\":{\"code\":\"rate_limit_exceeded\"", false), - ]; - for (status, mime, response, confirmed) in cases { - let raw = STANDARD.encode(response); - write_task(&file, &json!({"id":id,"phase":"unknown","raw":raw,"httpStatus":status,"contentType":mime})).unwrap(); - assert_eq!(settle_recorded_rate_limit(&dir).unwrap().is_some(), confirmed, "{status} {response}"); - assert_eq!(unresolved(&dir).unwrap().is_empty(), confirmed); - assert_eq!(read_task(&file).unwrap()["raw"], raw); - } - std::fs::remove_dir_all(dir).unwrap(); - } + use super::*; #[test] fn production_worker_uses_only_the_verified_selection_for_its_bound_turn() { @@ -1186,20 +550,19 @@ mod tests { assert_eq!(rpc_error_frame(&message), json!({"type":"error", "error":message})); } let raw = "TLS连接失败 https://user:secret@example.test Authorization: Bearer secret"; - assert_eq!(rpc_error_frame(raw), json!({"type":"error", "error":"本地SDK操作失败;请检查原请求状态,勿重发"})); + assert_eq!(rpc_error_frame(raw), json!({"type":"error", "error":"本地模型连接操作失败"})); assert_eq!(super::rpc_error_frame(raw, true), json!({"type":"error","error":"客户端准备模型请求失败,本次未发送","dispatched":false,"retryPreparation":true})); assert_eq!(super::rpc_error_frame("工具未授权", true), json!({"type":"error","error":"客户端工具配置不匹配,本次未发送模型请求","dispatched":false})); let appended = "98k暂时无法连接(TLS连接失败);个人Key已保留 secret"; assert_eq!(rpc_error_frame(appended), rpc_error_frame(raw)); - assert_eq!(rpc_error_frame("98k连接中断,结果未知;不会重发")["error"], "98k连接中断,结果未知;不会重发"); assert_eq!(rpc_error_frame("工具未授权")["error"], "客户端工具配置不匹配,本次未发送模型请求"); let text_only = crate::jiansun_models::DETAIL_ROUTE_UNVERIFIED; assert_eq!(rpc_error_frame(text_only)["error"], text_only); assert_eq!(rpc_error_frame("输出长度或候选数量超限")["error"], "客户端请求格式不匹配,本次未发送模型请求"); - assert_eq!(rpc_error_frame("网关确认原SDK请求已终止且无可取回结果;不会重发")["error"], "服务端确认本次请求失败,没有可取回的结果"); } + #[test] fn rpc_lines_are_bounded_and_keep_alignment() { use super::*; @@ -1218,40 +581,22 @@ mod tests { } #[test] - fn rpc_status_requires_matching_scope() { - use super::*; - assert!(!scope_matches("status", &json!({}), "account-a")); - assert!(!scope_matches("status", &json!({"accountScope":"account-b"}), "account-a")); - assert!(scope_matches("status", &json!({"accountScope":"account-a"}), "account-a")); - } - use super::*; - #[test] - fn interrupted_goal_retry_preserves_original_receipt_and_only_blocks_on_latest_attempt() { + fn archived_goal_attempts_keep_the_original_file_and_report_the_latest_state() { let dir = std::env::temp_dir().join(format!("xiaoyi-goal-retry-{}", Uuid::new_v4())); fs::create_dir_all(&dir).unwrap(); let scope = format!("product/goal/{}/detail", Uuid::new_v4()); - let other = format!("product/goal/{}/main_images", Uuid::new_v4()); let original = Uuid::new_v4().to_string(); let retry = Uuid::new_v4().to_string(); let file = dir.join(format!("{original}.json")); let retry_file = dir.join(format!("{retry}.json")); let entry = json!({"id":original,"detailSlot":scope,"modelRole":"detail","phase":"unknown"}); write_task(&file, &entry).unwrap(); - let pending = unresolved(&dir).unwrap(); - assert!(request_conflicts(&pending, Some(&scope), true, None)); - assert!(!request_conflicts(&pending, Some(&scope), true, Some(&original))); - assert!(request_conflicts(&pending, Some(&other), true, Some(&original))); - assert!(request_conflicts(&pending, None, false, Some(&original))); - let worker = format!("product/slot/{}", "a".repeat(64)); - let slot_pending = vec![json!({"id":original,"detailSlot":worker,"modelRole":"detail","phase":"unknown"})]; - assert!(!request_conflicts(&slot_pending, Some(&worker), true, Some(&original))); - assert!(request_conflicts(&slot_pending, Some(&scope), true, Some(&original))); + assert_eq!(unresolved(&dir).unwrap()[0]["id"], original); let mut attempt = json!({"id":retry,"detailSlot":scope,"modelRole":"detail","phase":"dispatched","retryOf":original}); write_task(&retry_file, &attempt).unwrap(); let pending = unresolved(&dir).unwrap(); assert_eq!(pending.len(), 1); assert_eq!(pending[0]["id"], retry); - assert!(request_conflicts(&pending, Some(&scope), true, Some(&original))); attempt["phase"] = json!("complete"); write_task(&retry_file, &attempt).unwrap(); assert!(unresolved(&dir).unwrap().is_empty()); @@ -1261,231 +606,6 @@ mod tests { fs::remove_dir(dir).unwrap(); } - fn lookup_task() -> Value { - json!({"id":"50f20cf3-e1dc-4cce-b7ee-0f84cde746c1","requestId":"a7fbb894-ad84-4c6a-a56a-29f7d8260bf8","phase":"unknown", - "bodyHash":hash("original-payload"),"keyFingerprint":hash("original-personal-key"),"httpStatus":200,"contentType":"text/event-stream", - "raw":STANDARD.encode(b"original raw"),"partialRaw":STANDARD.encode(b"original partial"),"partialBytes":16}) - } - fn lookup_body(status: &str) -> Value { - json!({"request_id":"a7fbb894-ad84-4c6a-a56a-29f7d8260bf8","status":status,"result_available":false, - "result_path":"/api/external/requests/a7fbb894-ad84-4c6a-a56a-29f7d8260bf8/result","result_expires_at":null}) - } - #[test] - fn original_model_lookup_can_recover_missing_request_id_without_authorizing_a_new_post() { - let mut task = lookup_task(); - task["requestId"] = Value::Null; - let mut location = lookup_body("succeeded"); - location["result_available"] = json!(true); - let mut writes = Vec::new(); - assert!(lookup_original(&mut task, |path, id| { - assert_eq!(path, "/api/external/requests/by-idempotency-key"); - assert_eq!(id, "50f20cf3-e1dc-4cce-b7ee-0f84cde746c1"); - Ok((200, location.clone())) - }, |saved| { writes.push(saved.clone()); Ok(()) }).unwrap()); - assert_eq!(writes.last().unwrap()["requestId"], location["request_id"]); - assert_eq!(task["phase"], "unknown"); - let different = Uuid::new_v4(); - location["request_id"] = json!(different); - location["result_path"] = json!(format!("/api/external/requests/{different}/result")); - assert!(!lookup_original(&mut task, |_, _| Ok((200, location)), |_| Ok(())).unwrap()); - assert_eq!(task["requestId"], "a7fbb894-ad84-4c6a-a56a-29f7d8260bf8"); - } - - #[test] - fn pi_result_lookup_uses_one_fixed_original_get_and_persists_proof_before_gateway_failure() { - let mut task = lookup_task(); - let original = task.clone(); - let mut gets = 0; - let proof = lookup_unavailable(&task, |path, idempotency| { - gets += 1; - assert_eq!(path, "/api/external/requests/by-idempotency-key"); - assert_eq!(idempotency, original["id"].as_str().unwrap()); - Ok((200, lookup_body("failed"))) - }) - .unwrap(); - assert_eq!(gets, 1); - let mut writes = Vec::new(); - settle_lookup(&mut task, proof, |value| { - writes.push(value.clone()); - Ok(()) - }) - .unwrap(); - assert_eq!(writes.len(), 2); - assert_eq!(writes[0]["phase"], "unknown"); - assert_eq!(writes[0]["originalLookup"]["verified"], true); - assert_eq!(writes[1]["phase"], "failed"); - assert_eq!(task["phase"], "failed"); - for key in ["id", "requestId", "bodyHash", "keyFingerprint", "raw", "partialRaw", "partialBytes", "httpStatus", "contentType"] { - assert_eq!(task[key], original[key], "{key}"); - } - assert_eq!(public_lookup(&task)["status"], "failed"); - assert!(!task["lastError"].as_str().unwrap().contains("从未执行")); - } - #[test] - fn succeeded_without_retained_result_stays_pending_until_explicit_invalid_finish_rejects_usage() { - let dir = std::env::temp_dir().join(format!("pi-unavailable-ack-{}", Uuid::new_v4())); - let file = dir.join("task.json"); - let mut task = lookup_task(); - let original = task.clone(); - let proof = original_lookup(&task, 200, &lookup_body("succeeded")).unwrap(); - settle_lookup(&mut task, proof, |value| write_task(&file, value)).unwrap(); - assert_eq!(task["phase"], "unavailable"); - let pending = unresolved(&dir).unwrap(); - assert_eq!(pending.len(), 1); - assert_eq!(pending[0]["originalLookup"]["status"], "succeeded"); - assert_eq!(pending[0]["originalLookup"]["resultAvailable"], false); - assert!(!task["lastError"].as_str().unwrap().contains("已失败")); - let before = task.clone(); - assert!(finish_task(&mut task, &json!({"bodyHash":original["bodyHash"],"valid":true})).is_err()); - assert_eq!(task, before); - assert!(finish_task(&mut task, &json!({"bodyHash":hash("different-payload"),"valid":false})).is_err()); - assert_eq!(task, before); - finish_task(&mut task, &json!({"bodyHash":original["bodyHash"],"valid":false,"reason":"compaction_original_result_unavailable"})).unwrap(); - assert_eq!(task["phase"], "rejected"); - assert_eq!(task["terminal"], false); - assert_eq!(task["originalLookup"]["status"], "succeeded"); - for key in ["requestId", "bodyHash", "keyFingerprint", "raw", "partialRaw"] { - assert_eq!(task[key], original[key]); - } - write_task(&file, &task).unwrap(); - assert!(unresolved(&dir).unwrap().is_empty()); - assert!(finish_task(&mut task, &json!({"bodyHash":original["bodyHash"],"valid":false})).is_err()); - assert!(dir.is_absolute() && dir.parent() == Some(std::env::temp_dir().as_path())); - fs::remove_dir_all(dir).unwrap(); - } - #[test] - fn pi_lookup_never_converts_unconfirmed_http_status_identity_or_envelopes_to_terminal() { - let task = lookup_task(); - for code in [201, 202, 401, 403, 404, 410, 429, 500, 502, 503, 504] { - assert!(original_lookup(&task, code, &lookup_body("failed")).is_err()); - } - for (field, value) in [ - ("request_id", json!(Uuid::new_v4().to_string())), - ("request_id", Value::Null), - ("status", json!("processing")), - ("status", json!("unknown")), - ("result_available", json!(true)), - ("result_available", Value::Null), - ("result_path", json!("https://api.vip98k.com/api/external/requests/a7fbb894-ad84-4c6a-a56a-29f7d8260bf8/result")), - ("result_path", Value::Null), - ("result_expires_at", json!("unconfirmed expiry")), - ("error", json!({"message":"provider body must not be retained"})), - ] { - let mut body = lookup_body("failed"); - body[field] = value; - assert!(original_lookup(&task, 200, &body).is_err(), "{field}"); - } - let mut missing = lookup_body("succeeded"); - missing.as_object_mut().unwrap().remove("result_expires_at"); - assert!(original_lookup(&task, 200, &missing).is_err()); - let mut expired = lookup_body("succeeded"); - expired["result_expires_at"] = json!("2026-10-24T00:00:00Z"); - assert_eq!(original_lookup(&task, 200, &expired).unwrap()["status"], "succeeded"); - assert_eq!(task["phase"], "unknown"); - } - #[test] - fn original_chat_failure_accepts_the_gateway_error_metadata() { - let mut task = lookup_task(); - let mut response = lookup_body("failed"); - response["error"] = json!({"code":"rate_limit_exceeded","http_status":429}); - let proof = original_lookup(&task, 200, &response).unwrap(); - settle_lookup(&mut task, proof, |_| Ok(())).unwrap(); - assert_eq!(task["phase"], "failed"); - assert_eq!(checked_lookup(&task).unwrap()["status"], "failed"); - } - #[test] - fn unavailable_finish_refuses_missing_forged_or_failed_proofs_and_non_boolean_acknowledgement() { - let mut unavailable = lookup_task(); - let proof = original_lookup(&unavailable, 200, &lookup_body("succeeded")).unwrap(); - settle_lookup(&mut unavailable, proof, |_| Ok(())).unwrap(); - for (field, value) in [ - ("verified", json!(false)), - ("method", json!("POST")), - ("idempotencyKey", json!(Uuid::new_v4().to_string())), - ("requestId", json!(Uuid::new_v4().to_string())), - ("bodyHash", json!(hash("other-body"))), - ("bindingHash", json!(hash("other-binding"))), - ("lookupSha256", json!(hash("other-proof"))), - ("resultAvailable", json!(true)), - ("status", json!("failed")), - ("keyFingerprintMatches", json!(false)), - ] { - let mut task = unavailable.clone(); - task["originalLookup"][field] = value; - let before = task.clone(); - assert!(finish_task(&mut task, &json!({"bodyHash":unavailable["bodyHash"],"valid":false})).is_err(), "{field}"); - assert_eq!(task, before); - } - for valid in [Value::Null, json!("false"), json!(0), json!(true)] { - let mut task = unavailable.clone(); - assert!(finish_task(&mut task, &json!({"bodyHash":unavailable["bodyHash"],"valid":valid})).is_err()); - assert_eq!(task, unavailable); - } - let mut missing = unavailable.clone(); - missing.as_object_mut().unwrap().remove("originalLookup"); - assert!(finish_task(&mut missing, &json!({"bodyHash":unavailable["bodyHash"],"valid":false})).is_err()); - } - #[test] - fn settled_pi_outcomes_do_not_issue_late_queries_and_failed_proof_cannot_reopen_them() { - for phase in ["complete", "rejected", "failed"] { - let mut task = lookup_task(); - let proof = original_lookup(&task, 200, &lookup_body("failed")).unwrap(); - task["phase"] = json!(phase); - let original = task.clone(); - let mut calls = 0; - assert!( - lookup_unavailable(&task, |_, _| { - calls += 1; - Ok((200, lookup_body("failed"))) - }) - .is_err() - ); - assert_eq!(calls, 0); - assert!(settle_lookup(&mut task, proof, |_| panic!("settled outcomes cannot be persisted again")).is_err()); - assert_eq!(task, original); - } - } - #[test] - fn original_http_metadata_remains_distinct_from_result_get_and_lookup_receipts() { - let mut task = lookup_task(); - response_metadata(&mut task, "recover", 410, "application/json"); - assert_eq!(task["httpStatus"], 200); - assert_eq!(task["contentType"], "text/event-stream"); - assert_eq!(task["lastQueryHttpStatus"], 410); - assert_eq!(task["lastQueryContentType"], "application/json"); - let proof = original_lookup(&task, 200, &lookup_body("succeeded")).unwrap(); - assert_eq!(proof["httpStatus"], 200); - assert_eq!(task["lastQueryHttpStatus"], 410); - let mut legacy = lookup_task(); - legacy["httpStatus"] = json!(410); - legacy["contentType"] = json!("application/json"); - legacy["recovery"] = json!({"status":410}); - response_metadata(&mut legacy, "recover", 410, "application/json"); - assert_eq!(legacy["httpStatus"], 410, "do not invent the legacy original POST status"); - assert_eq!(legacy["legacyHttpMetadata"], true); - } - #[test] - fn failed_lookup_persistence_keeps_an_unknown_proof_if_the_settlement_write_fails() { - let mut task = lookup_task(); - let proof = original_lookup(&task, 200, &lookup_body("succeeded")).unwrap(); - let mut writes = 0; - let mut durable = Value::Null; - assert!( - settle_lookup(&mut task, proof, |value| { - writes += 1; - if writes == 2 { - return Err("fixture disk full".into()); - } - durable = value.clone(); - Ok(()) - }) - .is_err() - ); - assert_eq!(durable["phase"], "unknown"); - assert_eq!(task, durable); - assert_eq!(task["originalLookup"]["status"], "succeeded"); - assert_eq!(task["originalLookup"]["verified"], true); - } #[test] fn private_pi_journals_bound_three_full_streams_without_changing_global_json_limits() { let dir = std::env::temp_dir().join(format!("pi-three-stream-budget-{}", Uuid::new_v4())); @@ -1504,6 +624,7 @@ mod tests { assert!(dir.is_absolute() && dir.parent() == Some(std::env::temp_dir().as_path())); fs::remove_dir_all(dir).unwrap(); } + #[test] fn private_pi_task_reader_accepts_exact_file_bound_and_refuses_corruption_or_overflow() { let dir = std::env::temp_dir().join(format!("pi-task-read-bound-{}", Uuid::new_v4())); @@ -1526,6 +647,7 @@ mod tests { assert!(dir.is_absolute() && dir.parent() == Some(std::env::temp_dir().as_path())); fs::remove_dir_all(dir).unwrap(); } + #[test] fn private_pi_writer_rejects_bad_base64_large_decoded_streams_and_metadata_without_replacing_unknown() { let dir = std::env::temp_dir().join(format!("pi-task-write-bound-{}", Uuid::new_v4())); @@ -1555,99 +677,42 @@ mod tests { assert!(dir.is_absolute() && dir.parent() == Some(std::env::temp_dir().as_path())); fs::remove_dir_all(dir).unwrap(); } - #[test] - fn response_byte_cap_preserves_prefix_on_overflow() { - let mut raw = vec![b'x'; RESPONSE_LIMIT - 1]; - append_response(&mut raw, b"y").unwrap(); - assert_eq!(raw.len(), RESPONSE_LIMIT); - append_response(&mut raw, b"").unwrap(); - assert!(append_response(&mut raw, b"z").is_err()); - assert_eq!(raw.len(), RESPONSE_LIMIT); - assert_eq!(raw.last(), Some(&b'y')); - let mut empty = Vec::new(); - assert!(append_response(&mut empty, &vec![0; RESPONSE_LIMIT + 1]).is_err()); - assert!(empty.is_empty()); - } - #[test] - fn long_standard_sse_is_complete_but_corrupt_or_incomplete_streams_are_not() { - let chunk = "data: {\"model\":\"qa\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"product evidence\"}}]}\n\n"; - let blocks = (2 * 1024 * 1024) / chunk.len() + 1; - let body = format!("{}data: {{\"model\":\"qa\",\"choices\":[{{\"index\":0,\"finish_reason\":\"stop\"}}]}}\n\ndata: [DONE]\n\n", chunk.repeat(blocks)); - assert!(body.len() > 2 * 1024 * 1024 && body.len() < RESPONSE_LIMIT); - let mut raw = Vec::new(); - for part in body.as_bytes().chunks(8192) { - append_response(&mut raw, part).unwrap(); - } - assert!(stream_complete(std::str::from_utf8(&raw).unwrap(), false, Some("qa"))); - assert!(!stream_complete(&body.replace("data: [DONE]", ""), false, Some("qa"))); - assert!(!stream_complete(&format!("data: {{broken json\n\n{body}"), false, Some("qa"))); - assert!(!stream_complete(&format!("data: []\n\n{body}"), false, Some("qa"))); - let mut invalid_utf8 = raw; - invalid_utf8.push(255); - assert!(std::str::from_utf8(&invalid_utf8).is_err()); - } + #[test] fn broker_uses_the_selected_model_output_limit() { let mut payload = json!({"model":"qa","stream":true,"messages":[{"role":"user","content":"hello"}],"max_tokens":128000}); let mut model = json!({"id":"qa","protocol":"anthropic-messages","maxTokens":128000}); - assert!(validate_payload(&payload, &model).is_ok()); + assert!(validate_provider_payload(&payload, &model).is_ok()); payload["max_tokens"] = json!(128001); - assert!(validate_payload(&payload, &model).is_err()); + assert!(validate_provider_payload(&payload, &model).is_err()); model["maxTokens"] = Value::Null; payload.as_object_mut().unwrap().remove("max_tokens"); - assert!(validate_payload(&payload, &model).is_err()); + assert!(validate_provider_payload(&payload, &model).is_err()); model["protocol"] = json!("openai-chat"); - assert!(validate_payload(&payload, &model).is_ok()); - } - #[test] - fn recovery_keeps_the_original_partial_bytes_even_when_another_get_is_incomplete() { - let original_partial = STANDARD.encode(b"original interrupted SSE prefix"); - let original_raw = STANDARD.encode(b"previous retained raw response"); - let mut task = json!({"id":"same-original-task","requestId":"same-original-request","phase":"unknown", - "partialRaw":original_partial,"partialBytes":31,"raw":original_raw,"httpStatus":200}); - let recovery = vec![b'x'; RESPONSE_LIMIT]; - retain_incomplete(&mut task, &recovery, true).unwrap(); - assert_eq!(task["partialRaw"], original_partial); - assert_eq!(task["raw"], original_raw); - assert_eq!(task["requestId"], "same-original-request"); - assert_eq!(task["phase"], "unknown"); - assert_eq!(task["recovery"]["complete"], false); - assert_eq!(STANDARD.decode(task["recovery"]["raw"].as_str().unwrap()).unwrap(), recovery); - assert!(task_bytes(&task).is_ok()); + assert!(validate_provider_payload(&payload, &model).is_ok()); } + #[test] fn pi_tool_declarations_pass_through_the_transport() { let model = json!({"id":"chosen-model"}); let mut payload = json!({"model":"chosen-model","stream":true,"messages":[{"role":"user","content":"inspect"}]}); for names in [ &["bash", "plan_production", "adopt_production_image", "finish_production", "tool_search", "native_call"][..], - &["read_slot_images", "generate_slot_image", "read_production_knowledge", "read"][..], + &["read_slot_images", "generate_slot_image", "read"][..], &["review_candidate", "a_project_extension_tool"][..], ] { payload["tools"] = json!(names.iter().map(|name| json!({"name":name})).collect::>()); - assert!(validate_payload(&payload, &model).is_ok()); + assert!(validate_provider_payload(&payload, &model).is_ok()); payload["tools"] = json!(names.iter().map(|name| json!({"type":"function","function":{"name":name}})).collect::>()); - assert!(validate_payload(&payload, &model).is_ok()); + assert!(validate_provider_payload(&payload, &model).is_ok()); } payload["tools"] = json!([{"name":"read"},{"type":"function","function":{"name":"read"}}]); - assert!(validate_payload(&payload, &model).is_err()); + assert!(validate_provider_payload(&payload, &model).is_err()); payload["tools"] = json!([{"name":"read","function":{"name":"write"}}]); - assert!(validate_payload(&payload, &model).is_err()); + assert!(validate_provider_payload(&payload, &model).is_err()); payload["tools"] = json!([{"name":"read"}]); payload["model"] = json!("other"); - assert!(validate_payload(&payload, &model).is_err()); - } - - #[test] - #[ignore = "requires a request captured in an isolated native Pi run"] - fn captured_pi_request_passes_the_native_transport_contract() { - let path = std::env::var_os("XIAOYI_CAPTURED_PI_PAYLOAD").unwrap(); - let payload: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); - let model = json!({"id":payload["model"],"protocol":"openai-responses"}); - let tools = payload["tools"].as_array().unwrap(); - assert!(tools.iter().any(|tool| tool["name"] == "adopt_production_image")); - assert!(tools.iter().any(|tool| tool["name"] == "bash")); - validate_provider_payload(&payload, &model).unwrap(); + assert!(validate_provider_payload(&payload, &model).is_err()); } #[test] @@ -1659,81 +724,14 @@ mod tests { } assert!(invocation_headers(&json!({"invocationHeaders":{"X-Relay-Route-Option":"https://other.invalid"}})).is_err()); } + #[test] fn account_switch_cannot_read_or_dispatch_another_projects_requests() { assert!(scope_matches("info", &json!({}), "account-a")); - assert!(!scope_matches("info", &json!({"original":true}), "account-a")); assert!(scope_matches("info", &json!({"original":true,"accountScope":"account-a"}), "account-a")); assert!(!scope_matches("request", &json!({}), "account-a")); assert!(!scope_matches("read", &json!({"accountScope":"account-b"}), "account-a")); assert!(!scope_matches("info", &json!({"accountScope":"account-b"}), "account-a")); assert!(scope_matches("request", &json!({"accountScope":"account-a"}), "account-a")); } - #[test] - fn retained_sse_requires_terminal_and_original_model() { - let raw = "data: {\"model\":\"qa\",\"choices\":[{\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n"; - assert!(stream_complete(raw, false, Some("qa"))); - assert!(!stream_complete(raw, false, Some("other"))); - assert!(!stream_complete("data: {\"model\":\"qa\"}\n\n", false, Some("qa"))); - assert!(!stream_complete("data: [DONE]\n\n", false, Some("qa"))); - assert!(!stream_complete("data: {\"model\":\"qa\",\"choices\":[{\"delta\":{\"content\":\"prefix\"}}]}\n\ndata: [DONE]\n\n", false, Some("qa"))); - } - #[test] - fn bound_responses_stream_can_complete_without_repeating_the_model() { - let model = json!({"id":"gpt-6.1-sol","protocol":"openai-responses"}); - let terminal = "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[]}}\n\n"; - assert!(stream_terminal(terminal, &model, true)); - assert!(!stream_terminal(terminal, &model, false)); - let mismatched = format!("data: {{\"type\":\"response.created\",\"response\":{{\"model\":\"other\"}}}}\n\n{terminal}"); - assert!(!stream_terminal(&mismatched, &model, true)); - let interrupted = "data: {\"type\":\"response.created\",\"response\":{\"status\":\"in_progress\"}}\n\ndata: [DONE]\n\n"; - assert!(!stream_terminal(interrupted, &model, true)); - } - #[test] - fn a_terminal_truncated_detail_reply_does_not_leave_a_pending_model_request() { - let input = json!({"bodyHash":"same","valid":false,"reason":"length"}); - let mut slot = json!({"phase":"received","terminal":true,"bodyHash":"same","detailSlot":"hero"}); - finish_task(&mut slot, &input).unwrap(); - assert_eq!(slot["phase"], "rejected"); - for mut unproven in [json!({"phase":"received","bodyHash":"same","detailSlot":"hero"}), - json!({"phase":"received","terminal":true,"bodyHash":"same"})] { - finish_task(&mut unproven, &input).unwrap(); - assert_eq!(unproven["phase"], "unknown"); - } - } - #[test] - fn an_authenticated_terminal_refusal_rejects_the_original_production_reply() { - let refusal = "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"refusal\"}}\n\ndata: {\"type\":\"message_stop\"}\n\n"; - let chat_filter = "data: {\"choices\":[{\"index\":0,\"finish_reason\":\"content_filter\"}]}\n\ndata: [DONE]\n\n"; - for (protocol, body) in [("anthropic-messages", refusal), ("openai-chat", chat_filter)] { - let mut original = json!({"phase":"received","terminal":true,"bodyHash":"same","detailSlot":"product/goal/chair/detail", - "requestId":"original-id","model":{"protocol":protocol},"raw":STANDARD.encode(body)}); - let input = json!({"bodyHash":"same","valid":false,"reason":"refusal"}); - let mut unconfirmed = original.clone(); - unconfirmed["terminal"] = json!(false); - finish_task(&mut unconfirmed, &input).unwrap(); - assert_eq!(unconfirmed["phase"], "unknown"); - finish_task(&mut original, &input).unwrap(); - assert_eq!(original["phase"], "rejected"); - assert_eq!(original["requestId"], "original-id"); - } - } - - #[test] - fn result_query_header_cannot_replace_original_customer_request_number() { - let mut task = json!({"requestId":"original"}); - record_request_header(&mut task, "recover", "read-only-query"); - assert_eq!(task["requestId"], "original"); - assert_eq!(task["lastQueryRequestId"], "read-only-query"); - record_request_header(&mut task, "request", "generation"); - assert_eq!(task["requestId"], "generation"); - } - #[test] - fn unknown_is_not_safe_to_dispatch() { - let dir = std::env::temp_dir().join(format!("pi-barrier-{}", Uuid::new_v4())); - write_json(&dir.join("one.json"), &json!({"id":"one","phase":"received"})).unwrap(); - assert_eq!(unresolved(&dir).unwrap().len(), 1); - assert!(dir.is_absolute() && dir.parent() == Some(std::env::temp_dir().as_path())); - fs::remove_dir_all(dir).unwrap(); - } } 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 4137757a..52014032 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -68,10 +68,8 @@ fn original_rule(dir: &Path) -> R> { let old = read_json(&file)?; Ok(Some(rule_cache::package(old["id"].as_str().ok_or("项目规则编号无效")?, &old, None)?)) } -fn can_change_rule(b: &Backend, doc: u64, dir: &Path) -> R<()> { - let project = b.locations.get(&doc).ok_or("项目身份尚未绑定")?; - if !super::pi::unresolved(&b.dir().join("pi-validation").join(project).join("requests"))?.is_empty() - || super::creation::unresolved(dir)? +fn can_change_rule(dir: &Path) -> R<()> { + if super::creation::unresolved(dir)? || super::images::pending(dir)? || !super::projects::creation_barriers(dir)?.is_empty() { @@ -91,7 +89,7 @@ fn automatic_rule(b: &Backend, doc: u64, index: &Value) -> R<(Option, Val if let Some(saved) = original_rule(&dir)?.filter(|saved| rule_cache::matches_project(saved, brand, category)) { // A catalogue update never rewrites an existing project's fixed snapshot. if creation["designSnapshot"]["rules"] != saved { - can_change_rule(b, doc, &dir)?; + can_change_rule(&dir)?; super::creation::attach_agent_rules(&dir, &saved)?; } return Ok(( @@ -102,11 +100,11 @@ fn automatic_rule(b: &Backend, doc: u64, index: &Value) -> R<(Option, Val let Some(item) = item else { return Ok((None, json!({"state":"unavailable","reason":"此品牌与品类的模板待配置"}))); }; - can_change_rule(b, doc, &dir)?; + can_change_rule(&dir)?; let saved = cached_package(b, item)?; // Download outside the project write lock; re-read the actual project before // attaching so a late response cannot replace a newly selected product. - can_change_rule(b, doc, &dir)?; + can_change_rule(&dir)?; super::creation::attach_agent_rules(&dir, &saved)?; write_json(&dir.join("agent-binding.json"), &saved)?; Ok((Some(saved.clone()), json!({"state":"ready","updateAvailable":false,"templateId":saved["id"],"contentHash":saved["contentHash"]}))) @@ -143,16 +141,16 @@ fn knowledge_rule(b:&Backend,doc:u64) -> R,Value)>> { && saved["catalog"]["bindings"][0]["template"]["id"]==selected["id"] && saved["catalog"]["bindings"][0]["template"]["sourceVersion"]==selected["version"]) { if creation["designSnapshot"]["rules"]!=saved { - can_change_rule(b,doc,&dir)?; + can_change_rule(&dir)?; super::creation::attach_agent_rules(&dir,&saved)?; } return Ok(Some((Some(saved.clone()),json!({"state":"ready","updateAvailable":false,"templateId":selected["id"],"contentHash":saved["contentHash"]})))); } - can_change_rule(b,doc,&dir)?; + can_change_rule(&dir)?; let pack=b.selected_template_pack(selected,brand,category)?; let catalog=knowledge_catalog(&pack,&creation)?; let saved=rule_cache::package(pack["id"].as_str().ok_or("模板编号缺失")?,&json!({"catalog":catalog,"revision":pack["contentHash"]}),None)?; - can_change_rule(b,doc,&dir)?; + can_change_rule(&dir)?; super::creation::attach_agent_rules(&dir,&saved)?; write_json(&dir.join("agent-binding.json"),&saved)?; Ok(Some((Some(saved.clone()),json!({"state":"ready","updateAvailable":false,"templateId":pack["id"],"contentHash":saved["contentHash"]})))) @@ -257,7 +255,7 @@ pub(super) fn select(b: &mut Backend, input: &Value) -> R { .filter(|s| !s.is_empty() && s.len() <= 100 && s.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_'))) .ok_or("规则编号无效")?; let dir = b.project_dir(doc)?; - can_change_rule(b, doc, &dir)?; + can_change_rule(&dir)?; let file = dir.join("agent-binding.json"); let index = cached_index(b, Some(id.into()))?; let c = super::creation::load(&dir)?; @@ -270,7 +268,7 @@ pub(super) fn select(b: &mut Backend, input: &Value) -> R { return Ok(json!({"doc":doc,"rule":old,"updateAvailable":rule_cache::update_available(&old,Some(item))})); } let saved = cached_package(b, item)?; - can_change_rule(b, doc, &dir)?; + can_change_rule(&dir)?; super::creation::attach_agent_rules(&dir, &saved)?; write_json(&file, &saved)?; Ok(json!({"doc":doc,"rule":saved,"creation":super::creation::load(&dir)?})) @@ -385,25 +383,23 @@ fn project_evidence(c: &Value, scope: &str, project: &str, doc: u64, current_var .collect(); json!({"accountScope":scope,"project":project,"documentId":doc,"revision":c["revision"],"brief":brief,"currentVariantId":evidence_safe_text(current_variant,100),"facts":c["facts"],"sellingPoints":c["sellingPoints"],"plan":{"status":c["plan"]["status"],"screens":screens}}) } -pub(super) fn run(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender, ctx: &egui::Context) -> R { - let value = match run_inner(b, input, method, events, ctx) { +pub(super) fn run(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: &egui::Context) -> R { + let value = match run_inner(b, input, events, ctx) { Ok(value) => value, Err(error) => { let doc = input["context"]["id"].as_u64().or_else(|| input["doc"].as_u64()).ok_or(error.clone())?; if input["context"]["requestScope"]["productProduction"] == true { log::warn!("local product stage stopped for document {doc}: {error}"); } - let unknown = method != "agent" && b.locations.get(&doc) - .is_some_and(|project| combined_unknown(false, super::pi::unresolved(&b.dir().join("pi-validation").join(project).join("requests")))); let mut reply = json!({"engine":"pi","mode":"prompt","doc":doc,"accountId":b.auth["account"]["id"],"origin":b.origin, - "error":super::transfer::redact_text(&error.message),"failure":error.wire(),"unknown":unknown}); + "error":super::transfer::redact_text(&error.message),"failure":error.wire(),"unknown":false}); super::transfer::redact(&mut reply); if matches!(error.category, "auth_revoked" | "scope_changed") { reply["phase"] = json!("paused"); } reply } }; let epoch = &input["context"]["requestScope"]["writeEpoch"]; - let mut value = if epoch.is_u64() { + let value = if epoch.is_u64() { let mut observed = canonical_pi_result(b, value.clone()).unwrap_or_else(|error| { let mut value = value; value["error"] = json!(error); @@ -414,9 +410,6 @@ pub(super) fn run(b: &mut Backend, input: &Value, method: &str, events: &mpsc::S } else { canonical_pi_result(b, value)? }; - if method == "pi-recover" && input["automaticRecover"] == true { - value["automaticRecover"] = json!(true); - } Ok(value) } @@ -576,10 +569,6 @@ fn allowed_canvas_action(action: &str) -> bool { | "pi-workflow-navigate" | "pi-workflow-propose" | "pi-workflow-execute" | "pi-workflow-poll" | "pi-native-reconcile" | "pi-edit-reconcile" | "pi-workflow-reconcile") } -fn combined_unknown(reported: bool, pending: R>) -> bool { - reported || pending.map_or(true, |items| !items.is_empty()) -} - type CanvasReply = Result<(Value, Option), BridgeFailure>; fn queue_canvas_screen( @@ -616,24 +605,17 @@ fn take_late_workflow_delegations(replies: &mut Vec> ready } -fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender, ctx: &egui::Context) -> Result { +fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: &egui::Context) -> Result { b.check_dispatch().map_err(|message| BridgeFailure::new("auth_revoked", false, false, message))?; let doc = input["context"]["id"].as_u64().or_else(|| input["doc"].as_u64()).ok_or("请先打开项目")?; b.ensure_owner(doc)?; let project = b.locations.get(&doc).ok_or("项目身份尚未绑定")?.clone(); let dir = b.project_dir(doc)?; - if method == "pi-recover" - && let Some(id) = super::pi::settle_recorded_rate_limit(&b.dir().join("pi-validation").join(&project).join("requests"))? { - return Ok(json!({"engine":"pi","doc":doc,"accountId":b.auth["account"]["id"],"origin":b.origin, - "mode":"recover","unknown":false,"settledOriginalIds":[id],"text":super::pi::RATE_LIMIT_MESSAGE})); - } - let product_prompt = method == "agent" && input["context"]["requestScope"]["productProduction"] == true; + let product_prompt = input["context"]["requestScope"]["productProduction"] == true; let begin = std::time::Instant::now(); // Pi RPC validates the same account alongside model authorization before production starts. if !product_prompt { b.validate()?; } - let saved = if matches!(method, "pi-recover" | "pi-review") { - original_rule(&dir)? - } else if let Some((saved,_))=knowledge_rule(b,doc)? { + let saved = if let Some((saved,_))=knowledge_rule(b,doc)? { saved } else { let wanted = original_rule(&dir)?.and_then(|s| s["id"].as_str().map(str::to_owned)); @@ -645,25 +627,12 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender let (node, script) = runtime()?; let binary = std::env::current_exe().map_err(|_| "客户端位置不可用")?; let profile = b.root.parent().ok_or("配置位置无效")?; - let mode = if method == "pi-recover" { - "recover" - } else if method == "pi-review" { - "review" - } else { - "prompt" - }; - let production_originals = input["productionOriginals"].as_array().filter(|ids| !ids.is_empty()); - let model_role=if mode=="recover" && production_originals.is_some() { - "detail".to_owned() - }else if mode=="recover" { - super::pi::unresolved(&b.dir().join("pi-validation").join(&project).join("requests"))?.first().and_then(|pending|pending["modelRole"].as_str()).unwrap_or("chat").to_owned() - }else{"chat".to_owned()}; let scope = &input["context"]["requestScope"]; - let config = json!({"modelRole":model_role,"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"),"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"]), - "mode":mode,"text":input["text"],"productionOriginals":production_originals, + "mode":"prompt","text":input["text"], "writeEpoch":scope["writeEpoch"],"documentKey":scope["documentKey"],"revision":input["context"]["revision"], "outputId":if scope["productProduction"] == true { scope["outputId"].as_str() } else { Some(scope["outputId"].as_str().unwrap_or("detail")) }, @@ -674,7 +643,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender "requestedOutputs":scope["requestedOutputs"],"workspaceId":scope["project"]["workspaceId"], "productionTemplate":scope["productionTemplate"]}); let mut config = config; - if mode == "prompt" { + { use base64::{Engine as _, engine::general_purpose::STANDARD}; let mut content = Vec::new(); for (index, reference) in input["context"]["requestScope"]["references"].as_array().into_iter().flatten().enumerate() { @@ -726,6 +695,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender let mut workflow_children = WorkflowChildren::default(); let mut detail_image_reads = None; let mut canvas_screen_reads = None; + let screen_reader = Arc::new(super::canvas_workspace::ScreenReader::default()); let mut late_workflow_replies = Vec::new(); let start_workflow = |children: &mut WorkflowChildren, delegation: &Value, run: Option<&str>| { if b.exiting() { return Err("客户端正在退出,未派发工作流".into()); } @@ -853,8 +823,9 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender let transport = daemon.clone(); let run = daemon_run.clone(); let id = value["id"].clone(); + let reader = screen_reader.clone(); queue_canvas_screen(pool, cancellation, - move || super::canvas_workspace::read_production_screen(&document, &v), + move || reader.read(&document, &v), move |reply| { let _ = transport.reply(&run, &id, &reply); }) } else { Err("缺少实际工作画布") }; if let Err(error) = queued { @@ -929,12 +900,8 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender result["doc"] = json!(doc); result["accountId"] = b.auth["account"]["id"].clone(); result["origin"] = json!(b.origin); - result["mode"] = json!(mode); + result["mode"] = json!("prompt"); result["contextUsage"] = super::context_usage::read(b, &dir, &project); - if mode != "prompt" { - let pending = super::pi::unresolved(&b.dir().join("pi-validation").join(project).join("requests")); - result["unknown"] = json!(combined_unknown(result["unknown"].as_bool().unwrap_or(true), pending)); - } Ok(result) } fn merge_reference_identity(item: &mut Value, reference: &Value) { @@ -1056,14 +1023,6 @@ mod tests { } } #[test] - fn unknown_keeps_either_original_signal_and_fails_closed_on_journal_error() { - assert!(!combined_unknown(false, Ok(vec![]))); - assert!(combined_unknown(true, Ok(vec![])), "daemon uncertainty must not be cleared by an empty local listing"); - assert!(combined_unknown(false, Ok(vec![json!({"phase":"unknown"})]))); - assert!(combined_unknown(false, Err("journal unreadable".into())), "unreadable journals must stay unknown"); - assert!(combined_unknown(true, Err("journal unreadable".into()))); - } - #[test] fn workflow_delegation_requires_the_private_parents_exact_identity() { let original = json!({"method":"slot-append","run":"native-run","operationId":"07803e30-ab64-4e90-90c0-ec4a44518cdf", "accountId":"account","origin":"https://example.invalid","projectLocalId":"https://example.invalid|account|project", @@ -1167,7 +1126,7 @@ mod tests { json!({"engine":"pi","doc":doc,"accountId":backend.auth["account"]["id"],"origin":backend.origin,"unknown":false,"mode":"recover"}) } #[test] - fn canonical_pi_terminal_receipt_rechecks_private_journals_without_a_template_revision_change() { + fn canonical_pi_receipt_allows_material_work_with_an_archived_model_request() { let (backend, doc, local) = local_backend(); let dir = backend.project_dir(doc).unwrap(); write_json(&dir.join("context.json"), &json!({"localId":local})).unwrap(); @@ -1185,14 +1144,15 @@ mod tests { let journal = backend.dir().join("pi-validation").join(&local).join("requests/original.json"); let mut task = json!({"id":Uuid::new_v4().to_string(),"requestId":Uuid::new_v4().to_string(),"phase":"unknown"}); write_json(&journal, &task).unwrap(); - let pending = canonical_pi_result(&backend, pi_result(&backend, doc)).unwrap(); - assert_eq!(pending["pending"], true); - assert_eq!(pending["workflow"]["capabilities"]["imageDispatchAllowed"], false); + let before = canonical_pi_result(&backend, pi_result(&backend, doc)).unwrap(); + assert_eq!(before["pending"], false); + assert_eq!(before["workflow"]["capabilities"]["imageDispatchAllowed"], true); + assert_eq!(read_json(&journal).unwrap(), task); task["phase"] = json!("failed"); write_json(&journal, &task).unwrap(); let settled = canonical_pi_result(&backend, pi_result(&backend, doc)).unwrap(); assert_eq!(settled["projectLocalId"], local); - assert_eq!(settled["workflow"]["revision"], pending["workflow"]["revision"]); + assert_eq!(settled["workflow"]["revision"], before["workflow"]["revision"]); assert_eq!(settled["pending"], false); assert_eq!(settled["workflow"]["pending"], false); assert_eq!(settled["workflow"]["capabilities"]["imageDispatchAllowed"], true); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_product_layout.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_product_layout.rs deleted file mode 100644 index 79137163..00000000 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_product_layout.rs +++ /dev/null @@ -1,91 +0,0 @@ -//! Editable layout for products without a registered brand/category template. -use super::{R, Value, json, template_slots}; - -#[derive(Clone, Copy)] -struct Layout { - width: u64, -} - -impl Layout { - fn frame(self, x: u64, y: u64, width: u64, height: u64) -> Value { - json!({"x":x*self.width/750, "y":y*self.width/750, - "width":width*self.width/750, "height":height*self.width/750}) - } - - fn text(self, id: &str, label: &str, box_: [u64; 4], size: u64, max: u64) -> Value { - let [x, y, width, height] = box_; - json!({"fieldId":id,"kind":"text","name":label,"role":label, - "frame":self.frame(x,y,width,height), - "font":{"family":"Noto Sans SC","size":size*self.width/750,"weight":500,"color":"#322822"}, - "maxLines":1,"maxChars":max}) - } - - fn image(self, id: &str, label: &str, box_: [u64; 4], source: &str, guidance: &str) -> Value { - let [x, y, width, height] = box_; - json!({"fieldId":id,"kind":"image","name":label,"role":label,"imagePrompt":guidance, - "frame":self.frame(x,y,width,height),"sourcePolicy":source, - "crop":if source=="product" {"contain"} else {"cover"}}) - } - - fn page(self, id: &str, component: &str, name: &str, height: u64, background: &str, slots: Vec) -> Value { - json!({"id":id,"component":component,"name":name,"width":self.width, - "height":height*self.width/750,"background":background,"slots":slots}) - } -} - -pub(super) fn from_product(brief: &Value, width: u64) -> R { - if ![750, 1440].contains(&width) { - return Err("画布宽度请选择750或1440px".into()); - } - let l = Layout { width }; - let mut pack = json!({"schemaVersion":1,"id":"product-editorial","version":"1", - "name":"自主策划","productionRoute":"from_scratch", - "brandId":brief["brandId"].as_str().filter(|s| !s.is_empty()).unwrap_or("unassigned"), - "categoryId":brief["categoryId"].as_str().filter(|s| !s.is_empty()).unwrap_or("unassigned"), - "outputs":[ - l.page("S01", "detail", "首屏场景", 1190, "#f0eae1", vec![ - l.text("S01-T01", "首屏核心主张", [50,38,650,62], 39, 15), - l.text("S01-T02", "品名与可核验利益", [52,111,646,37], 20, 31), - l.image("S01-I01", "产品首屏场景", [0,190,750,1000], "generate", - "根据产品和购买任务设计一个连贯的实际使用场景,完整保留产品,避免同款结构或色彩变化。"),]), - l.page("S02", "detail", "设计证据", 780, "#faf7f1", vec![ - l.text("S02-T01", "一个可见的设计特点", [50,38,650,58], 36, 16), - l.text("S02-T02", "用原图能核验的细节", [52,107,646,39], 19, 33), - l.image("S02-I01", "设计证据原图", [50,168,650,562], "product", - "选择在实际像素中最能解释这一特点的同款视角。"),]), - l.page("S03", "detail", "整体外观", 730, "#ffffff", vec![ - l.text("S03-T01", "选款时看的整体关系", [50,35,650,57], 36, 16), - l.text("S03-T02", "外观或配色描述", [52,101,646,36], 19, 33), - l.image("S03-I01", "完整产品原图", [50,151,650,538], "product", - "选择最能完整呈现当前款轮廓与颜色的原图。"),]), - l.page("M01", "main_images", "独立主图", 750, "#ffffff", vec![ - l.text("M01-T01", "主图核心购买理由", [46,41,658,54], 35, 16), - l.text("M01-T02", "主图副文案", [48,102,654,33], 19, 33), - l.image("M01-I01", "主图全貌原图", [54,155,642,553], "product", - "独立主图的商品识别图。优先完整清晰的斜前视角,保持色彩和边缘。"),]), - l.page("K01", "sku_images", "SKU 规格图", 750, "#ffffff", vec![ - l.image("K01-I01", "本 SKU 规格原图", [65,26,620,588], "product", - "选择此 SKU 花色的完整正视或登记规格图,不拉伸、不裁缺主体。"), - l.text("K01-T01", "当前 SKU 货号或名称", [50,635,650,41], 25, 25), - l.text("K01-T02", "当前 SKU 可核对的色名或外观", [52,684,646,36], 17, 38),]) - ]}); - pack["contentHash"] = json!(template_slots::pack_hash(&pack)?); - template_slots::validate_pack(&pack)?; - Ok(pack) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn product_without_a_matched_template_has_three_editable_outputs() { - let pack = from_product(&json!({}), 750).unwrap(); - let variant = super::super::Uuid::new_v4().to_string(); - for component in ["detail", "main_images", "sku_images"] { - let doc = super::super::slot_canvas::skeleton(&pack, component, None, &variant).unwrap(); - assert_eq!(doc.size.width, 750); - assert!(doc.walk().iter().any(|(_, _, layer)| matches!(&layer.content, photocraft_doc::LayerContent::Text(_)))); - } - } -} diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs index 6872da60..69ccd187 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs @@ -1,6 +1,19 @@ //! A project file points to its sibling resource directory and its current checkpoint. use super::{Document, Path, PathBuf, R, Uuid, Value, fs, json, read_json, write_json}; -use super::transfer::{self, Policy, Selection}; +use super::transfer::{self, Policy}; +use std::collections::HashMap; + +#[derive(Default)] +struct Selection { + included: Vec, + excluded: Vec, + portable_digests: HashMap, +} + +pub(super) struct PortableDigests { + pub(super) checkpoint: String, + pub(super) archive: String, +} const CONTEXT: &str = "context.json"; const EXTENSION: &str = "xiaoyi"; @@ -96,8 +109,12 @@ fn copy_file(source: &Path, target: &Path, previous: Option<&Path>) -> R<()> { Ok(()) } -fn checkpoint_file(source: &Path, output: &Path, logical: &str, previous: Option<&Path>, - reopen: Option<(&Path, &Path)>, chat: bool) -> R<()> { +fn checkpoint_file(project: &Path, source: &Path, output: &Path, logical: &str, previous: Option<&Path>, + mode: CheckpointCopy<'_>, chat: bool) -> R> { + let reopen = match mode { + CheckpointCopy::Reopen(old, new) => Some((old, new)), + _ => None, + }; if matches!(logical, CONTEXT | "production-run.json") || reopen.is_some() && logical.ends_with(".json") { let mut value = read_json(source)?; if let Some((old, new)) = reopen { rebase_paths(&mut value, old, new); } @@ -128,10 +145,24 @@ fn checkpoint_file(source: &Path, output: &Path, logical: &str, previous: Option transfer::check_file(logical, &bytes)?; fs::write(output, bytes).map_err(disk)?; } else { - if logical.ends_with(".pcraft") { transfer::check_pcraft_file(source)?; } + if logical.ends_with(".pcraft") { + if reopen.is_none() && let Some(portable) = super::portable_draft(project, source, output)? { + return Ok(matches!(mode, CheckpointCopy::Deliver).then(|| { + use sha2::{Digest, Sha256}; + PortableDigests { + checkpoint: format!("{:x}", Sha256::digest(&portable.checkpoint)), + archive: format!("{:x}", Sha256::digest(&portable.archive)), + } + })); + } + if reopen.is_some() && photocraft_format::is_draft_file(source).map_err(disk)? { + return Err("工程画布缺少内嵌对象,无法独立打开".into()); + } + transfer::check_pcraft_file(source)?; + } copy_file(source, output, previous)?; } - Ok(()) + Ok(None) } #[derive(Clone, Copy)] @@ -159,6 +190,7 @@ fn copy_project( let path = entry.path(); let relative = path.strip_prefix(root).map_err(disk)?; let logical = relative.to_string_lossy().replace('\\', "/"); + if logical == "draft-objects" { continue; } if matches!(mode, CheckpointCopy::Deliver) && matches!(logical.as_str(), "product-exports" | "production-run.json") { selection.excluded.push(transfer::exclusion(&logical, "outside_delivery_checkpoint")); continue; @@ -182,11 +214,10 @@ fn copy_project( } let output = target.join(relative); fs::create_dir_all(output.parent().ok_or("工程资源路径无效")?).map_err(disk)?; - let reopen = match mode { - CheckpointCopy::Reopen(old, new) => Some((old, new)), - _ => None, - }; - checkpoint_file(&path, &output, &logical, previous.map(|p| p.join(relative)).as_deref(), reopen, policy.chat)?; + if let Some(digest) = checkpoint_file(root, &path, &output, &logical, + previous.map(|p| p.join(relative)).as_deref(), mode, policy.chat)? { + selection.portable_digests.insert(logical.clone(), digest); + } selection.included.push(logical); } else { selection.excluded.push(transfer::exclusion(&logical, "outside_project_checkpoint")); @@ -195,7 +226,7 @@ fn copy_project( Ok(()) } -pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, policy: &Policy<'_>, delivery: bool) -> R<()> { +pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, policy: &Policy<'_>, delivery: bool) -> R> { let checkpoint = resource_checkpoint(file, manifest)?; let resource_dir = checkpoint.parent().ok_or("工程资源目录无效")?; fs::create_dir_all(resource_dir).map_err(disk)?; @@ -221,7 +252,7 @@ pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, polic return Err(error); } if let Some(previous) = &previous { retire_checkpoint(resource_dir, previous, &manifest["localId"]); } - Ok(()) + Ok(selection.portable_digests) } fn retire_checkpoint(resource_dir: &Path, checkpoint: &Path, project: &Value) { @@ -363,7 +394,7 @@ pub(super) fn open(file: &Path, projects: &Path, scope: &str) -> R { #[cfg(test)] mod tests { use super::*; - use photocraft_doc::{ColorMode, SampleType, Size}; + use photocraft_doc::{Affine, ColorMode, Layer, LayerContent, SampleType, Size, SmartContentsId, SmartObject, SmartSource, Surface}; #[test] fn saved_project_restores_layers_metadata_and_candidate_files_without_the_working_directory() { @@ -372,8 +403,39 @@ mod tests { fs::create_dir(&root).unwrap(); let id = Uuid::new_v4().to_string(); let mut doc = Document::new("演示", Size::new(60, 40), ColorMode::Rgb, SampleType::U8); - doc.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", std::sync::Arc::new(vec![123; 1 << 20]))); - fs::write(root.join("canvas.pcraft"), photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap()).unwrap(); + let embedded = Document::new("嵌入对象", Size::new(6, 4), ColorMode::Rgb, SampleType::U8); + let linked = photocraft_io::linked::LinkedFile { + uuid: Uuid::new_v4().to_string(), + file_name: "source.psb".into(), + bytes: photocraft_io::export(&embedded, "psb", &Default::default()).unwrap().bytes, + }; + let block = photocraft_io::linked::encode_linked_file(&linked); + doc.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", std::sync::Arc::new(block))); + doc.layers.push(Layer::new("嵌入对象", LayerContent::Smart(SmartObject { + contents_id: SmartContentsId::fresh(), + source: SmartSource::Linked { path: linked.uuid.clone() }, + transform: Affine::IDENTITY, + smart_filters: Vec::new(), + cache: Some(Surface::new(doc.pixel_format())), + psd_raw: None, + filters_enabled: true, + filter_mask: None, + warp: None, + stack_mode: None, + perspective: None, + vector_preview: None, + }))); + let mut writer = photocraft_format::PcraftWriter::new(); + let standalone = writer.save_zip(&doc, &Default::default()).unwrap().0; + let legacy = root.join("legacy.pcraft"); + fs::write(&legacy, &standalone).unwrap(); + let objects = super::super::draft_objects(&root); + let legacy = photocraft_format::load_draft(&legacy, &objects).unwrap(); + assert_eq!(legacy.metadata.psd_global_blocks, doc.metadata.psd_global_blocks); + let draft = writer.save_draft_zip(&doc, &objects).unwrap(); + fs::write(root.join("canvas.pcraft"), &draft).unwrap(); + fs::create_dir(root.join("template-outputs")).unwrap(); + fs::write(root.join("template-outputs/detail-edited.pcraft"), &draft).unwrap(); let job = root.join("image-jobs").join(Uuid::new_v4().to_string()); fs::create_dir_all(&job).unwrap(); fs::write(job.join("generated.png"), b"candidate pixels").unwrap(); @@ -384,7 +446,7 @@ mod tests { let abandoned = delivery.join("generations").join("generation-unpublished"); fs::create_dir_all(&generation).unwrap(); fs::create_dir_all(&abandoned).unwrap(); - fs::copy(root.join("canvas.pcraft"), generation.join("detail.pcraft")).unwrap(); + fs::write(generation.join("detail.pcraft"), &standalone).unwrap(); fs::write(abandoned.join("detail.pcraft"), b"interrupted output").unwrap(); write_json(&delivery.join("detail.json"), &json!({"generationId":"generation-published", "sourceDocument":{"path":generation.join("detail.pcraft")}})).unwrap(); @@ -401,6 +463,9 @@ mod tests { assert_eq!(open(&file, &projects, "guest").unwrap(), id); let restored = projects.join(&id); let reopened = photocraft_format::load_path(&restored.join("canvas.pcraft")).unwrap(); + assert_eq!(fs::read(restored.join("canvas.pcraft")).unwrap(), standalone); + assert_eq!(fs::read(restored.join("template-outputs/detail-edited.pcraft")).unwrap(), standalone); + assert!(!restored.join("draft-objects").exists()); assert_eq!(reopened.name, doc.name); assert_eq!(reopened.size, doc.size); assert_eq!(reopened.metadata.psd_global_blocks, doc.metadata.psd_global_blocks); @@ -424,12 +489,28 @@ mod tests { fs::create_dir(&keep).unwrap(); let moved = keep.join(file.file_name().unwrap()); let resource_folder = manifest["resources"].as_str().unwrap(); - fs::rename(temp.path().join(resource_folder), keep.join(resource_folder)).unwrap(); - fs::rename(file, &moved).unwrap(); + let snapshot = resource_checkpoint(&file, &manifest).unwrap(); + let copied_snapshot = resource_checkpoint(&moved, &manifest).unwrap(); + for entry in manifest["projectManifest"]["included"].as_array().unwrap() { + let relative = entry.as_str().unwrap(); + let output = copied_snapshot.join(relative); + fs::create_dir_all(output.parent().unwrap()).unwrap(); + fs::copy(snapshot.join(relative), output).unwrap(); + } + assert!(keep.join(resource_folder).is_dir()); + fs::copy(&file, &moved).unwrap(); + fs::rename(root, temp.path().join("offline-original")).unwrap(); let moved_projects = temp.path().join("another-profile"); assert_eq!(open(&moved, &moved_projects, "guest").unwrap(), id); let moved_canvas = photocraft_format::load_path(&moved_projects.join(&id).join("canvas.pcraft")).unwrap(); assert_eq!(moved_canvas.metadata.psd_global_blocks, doc.metadata.psd_global_blocks); + for format in ["psd", "psb"] { + let original = photocraft_io::export(&doc, format, &Default::default()).unwrap(); + let copied = photocraft_io::export(&moved_canvas, format, &Default::default()).unwrap(); + let exported = photocraft_io::import(&format!("项目.{format}"), &copied.bytes).unwrap().document; + assert_eq!(photocraft_io::linked::find_linked_file(&exported.metadata, &linked.uuid), Some(linked.clone()), "{format}"); + assert_eq!(original.bytes, copied.bytes, "{format}"); + } } #[test] diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs index 2e05ed97..3171cfc2 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs @@ -95,11 +95,6 @@ pub(super) fn idle(dir: &Path) -> R<()> { if !creation_barriers(dir)?.is_empty() { return Err("项目有待处理的生成任务或待应用结果,请先处理原任务;不能完结或删除".into()); } - if let (Some(account), Some(id)) = (dir.parent().and_then(Path::parent), dir.file_name()) - && !super::pi::unresolved(&account.join("pi-validation").join(id).join("requests"))?.is_empty() - { - return Err("项目有小壹请求待核查,请先核查原请求再删除项目".into()); - } for name in ["task.json", "image-task.json", "creation-task.json"] { let path = dir.join(name); if path.exists() { @@ -311,10 +306,11 @@ impl Backend { if input["source"] == "native" { let dir = local_path(&self.dir().join("projects"), id)?; let file = dir.join("canvas.pcraft"); - if fs::metadata(&file).map_err(|_| "本机项目无法读取")?.len() > 256 * 1024 * 1024 { + if !photocraft_format::draft_fits(&file, &super::draft_objects(&dir), 256 * 1024 * 1024) + .map_err(|_| "本机项目无法读取")? { return Err("项目较大,请打开后查看".into()); } - let doc = photocraft_format::load_path(&file).map_err(|_| "本机封面读取失败,项目文件已保留")?; + let doc = super::load_draft(&dir, &file).map_err(|_| "本机封面读取失败,项目文件已保留")?; return first_screen(&doc); } self.validate()?; diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_recovery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_recovery.rs index 16786c0d..4cae8fa2 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_recovery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_recovery.rs @@ -42,12 +42,10 @@ fn read_canvas(path: &Path) -> R> { } Ok(out) } -fn same_canvas(a: &Path, b: &Path) -> R { - let mut original = photocraft_format::load_path(a).map_err(|_| "原画布基线无法读取")?; - let mut current = photocraft_format::load_path(b).map_err(|_| "本机草稿无法读取")?; +fn same_canvas(mut original: Document, mut current: Document) -> bool { original.id = photocraft_doc::DocId(0); current.id = photocraft_doc::DocId(0); - Ok(original == current) + original == current } fn comparable_group(layer: &photocraft_doc::Layer) -> photocraft_doc::Layer { let mut layer = layer.clone(); @@ -440,12 +438,12 @@ impl Backend { let bytes = if switched_before_restart { before.clone() } else { - let baseline_doc = photocraft_format::load_path(&baseline).map_err(|_| "原屏幕恢复基线无法读取")?; - let current = photocraft_format::load_path(&canonical).map_err(|_| "本机草稿无法读取")?; + let baseline_doc = super::load_draft(&dir, &baseline).map_err(|_| "原屏幕恢复基线无法读取")?; + let current = super::load_draft(&dir, &canonical).map_err(|_| "本机草稿无法读取")?; // Loading reserves persisted layer/document/smart-content identities. // Mint replacements afterwards, beyond every ID on the unchanged screens. let desired = creation::canvas(&c, &dir, 0)?; - let result = if staged["binding"]["baselineKind"] == "initial" && same_canvas(&baseline, &canonical)? { + let result = if staged["binding"]["baselineKind"] == "initial" && same_canvas(baseline_doc.clone(), current.clone()) { Ok(desired) } else { patch_screen(current, &baseline_doc, &desired, staged["binding"]["sequence"].as_u64().ok_or("原屏幕顺序缺失")? as usize) diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_preview.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_preview.rs new file mode 100644 index 00000000..b0fefa10 --- /dev/null +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_preview.rs @@ -0,0 +1,49 @@ +use photocraft_doc::Document; +use photocraft_geom::Rect; +use serde_json::Value; +use std::sync::{Arc, Mutex, Weak}; + +use super::{R, read_production_screen_with}; + +struct Preview { + document: Weak, + area: Rect, + text_gamma: u32, + jpeg: Arc>, +} + +/// Reuse the last screen image during a Pi run, keyed by the immutable canvas snapshot. +#[derive(Default)] +pub(in crate::jiansun_backend) struct ScreenReader(Mutex>); + +impl ScreenReader { + pub(in crate::jiansun_backend) fn read(&self, native: &Arc, input: &Value) -> R { + read_production_screen_with(native, input, |area| { + let document = Arc::downgrade(native); + let text_gamma = photocraft_compose::psblend::text_gamma().to_bits(); + { + let last = self.0.lock().map_err(|_| "整屏读取缓存状态失效")?; + if let Some(last) = last.as_ref().filter(|last| last.area == area && last.text_gamma == text_gamma && last.document.ptr_eq(&document)) { + return Ok(last.jpeg.clone()); + } + } + let jpeg = Arc::new(render(native, area)?); + *self.0.lock().map_err(|_| "整屏读取缓存状态失效")? = Some(Preview { document, area, text_gamma, jpeg: jpeg.clone() }); + Ok(jpeg) + }) + } +} + +pub(super) fn render(native: &Document, area: Rect) -> R> { + let scale = (1536.0 / f64::from(area.width().max(area.height()))).min(1.0); + let [w, h] = [area.width(), area.height()].map(|size| (f64::from(size) * scale).round().max(1.0) as u32); + let rendered = photocraft_compose::render_reduced_rect(native, area, w, h); + let rgb = rendered + .px + .into_iter() + .flat_map(|[r, g, b, alpha]| [r, g, b].map(|value| ((value * alpha + 1.0 - alpha).clamp(0.0, 1.0) * 255.0 + 0.5) as u8)) + .collect(); + let preview = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, rgb).map_err(|_| "实际画面无法读取")?; + let options = photocraft_codecs::EncodeOptions { jpeg_quality: 85, ..Default::default() }; + photocraft_codecs::encode(&preview, photocraft_codecs::Format::Jpeg, &options).map_err(|error| format!("实际画面无法编码:{error}")) +} diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_tests.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_tests.rs new file mode 100644 index 00000000..6fc16650 --- /dev/null +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_tests.rs @@ -0,0 +1,68 @@ +use super::*; +use std::sync::Arc; +use std::time::Instant; + +#[test] +fn jiansun_screen_read_reuses_exact_pixels_until_canvas_or_region_changes() { + let mut doc = Document::new("screen", photocraft_geom::Size::new(32, 48), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + doc.metadata.text.push(( + MAPPING.to_owned(), + json!({ + "canvasFirst": true, + "outputs": [ + {"mapping":{"fields":[]},"top":0,"width":32,"height":24}, + {"mapping":{"fields":[]},"top":24,"width":32,"height":24} + ] + }) + .to_string(), + )); + let mut bottom = photocraft_doc::Layer::raster("blue", photocraft_color::PixelFormat::RGBA8); + bottom.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::from_xywh(0, 24, 32, 24), &[0.0, 0.5, 1.0, 1.0]); + doc.layers.push(bottom); + let doc = Arc::new(doc); + let reader = ScreenReader::default(); + for (revision, page) in [0, 0, 1, 1, 0].into_iter().enumerate() { + let args = json!({"page":page,"revision":revision}); + assert_eq!(reader.read(&doc, &args).unwrap(), read_production_screen(&doc, &args).unwrap()); + } + let mut edited = (*doc).clone(); + let mut top = photocraft_doc::Layer::raster("red", photocraft_color::PixelFormat::RGBA8); + top.surface_mut().unwrap().fill_rect(edited.bounds(), &[0.5, 0.0, 0.0, 1.0]); + edited.layers.push(top); + let edited = Arc::new(edited); + let args = json!({"page":0,"revision":7}); + let next = reader.read(&edited, &args).unwrap(); + assert_eq!(next, read_production_screen(&edited, &args).unwrap()); + assert_ne!(next["images"], read_production_screen(&doc, &args).unwrap()["images"]); +} + +#[test] +#[ignore = "requires the local XIAOYI_CANVAS_BENCH draft"] +fn jiansun_detail_screen_read() { + let path = std::env::var_os("XIAOYI_CANVAS_BENCH").unwrap(); + let start = Instant::now(); + let doc = Arc::new(photocraft_format::load_path(Path::new(&path)).unwrap()); + println!("open={:?}", start.elapsed()); + let start = Instant::now(); + let meta = mapping(&doc).unwrap(); + println!("mapping={:?}", start.elapsed()); + let count = meta["outputs"].as_array().unwrap().len(); + let reader = ScreenReader::default(); + for _ in 0..3 { + for page in [0, 1, count / 2, count - 1] { + let input = json!({"page":page,"revision":1}); + let start = Instant::now(); + let previous = read_production_screen(&doc, &input).unwrap(); + let baseline = start.elapsed(); + let start = Instant::now(); + let first = reader.read(&doc, &input).unwrap(); + let miss = start.elapsed(); + let start = Instant::now(); + let second = reader.read(&doc, &input).unwrap(); + let hit = start.elapsed(); + assert_eq!(first, previous); + assert_eq!(second, previous); + println!("page={page} baseline={baseline:?} miss={miss:?} hit={hit:?}"); + } + } +} diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_canvas.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_canvas.rs index 9e21d920..59f7818e 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_canvas.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_canvas.rs @@ -153,7 +153,7 @@ fn materialize_at(application: &Value, dir: &Path, skeleton: bool, page: Option< if !matches!(application["component"].as_str(), Some("detail" | "main_images" | "sku_images")) { return Err("输出类型无效".into()); } - let width = application["width"].as_u64().filter(|w| [750, 1440].contains(w)).ok_or("输出宽度无效")?; + let width = application["width"].as_u64().filter(|width| (1..=8192).contains(width)).ok_or("输出宽度无效")?; let height = application["height"].as_u64().filter(|h| (1..=30000).contains(h)).ok_or("输出高度无效")?; let (top, canvas_height) = page.unwrap_or((0, height)); if canvas_height > 30000 || top.checked_add(height).is_none_or(|bottom| bottom > canvas_height) { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs index fce39a1c..85231d3a 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs @@ -159,7 +159,7 @@ fn collect_backup_sources(base: &Path, path: &Path, prefix: &str, files: &mut Ve if !path.exists() { return Ok(()); } let relative = path.strip_prefix(base).map_err(|_| "项目路径无效")?; if relative.components().count() > 12 { return Err("会话目录层级过多,尚未同步".into()); } - if prefix == "project/" && relative.starts_with("sync-staging") { return Ok(()); } + if prefix == "project/" && (relative.starts_with("sync-staging") || relative.starts_with("draft-objects")) { return Ok(()); } let meta = fs::symlink_metadata(path).map_err(|_| "项目文件不可读取")?; if meta.file_type().is_symlink() || !path.canonicalize().map_err(|_| "项目路径无效")?.starts_with(base.canonicalize().map_err(|_| "项目路径无效")?) { return Err("项目包含目录链接,尚未同步".into()); @@ -202,7 +202,15 @@ fn collect_backup_sources(base: &Path, path: &Path, prefix: &str, files: &mut Ve files.push(BackupSource { path: path.to_owned(), entry: json!({"path":logical,"sha256":digest(&bytes),"size":bytes.len(),"data":STANDARD.encode(bytes)}) }); return Ok(()); } + let staged = base.join("sync-staging").join(&logical); + let objects = super::draft_objects(base); + if !photocraft_format::draft_fits(path, &objects, SESSION_FILES_LIMIT.saturating_sub(*total)) + .map_err(|_| "工程画布对象无法读取")? { + return Err("项目附件超过1GiB,尚未同步".into()); + } + let path = if super::portable_draft(base, path, &staged)?.is_some() { staged.as_path() } else { path }; let (sha, size) = file_digest(path)?; + if total.saturating_add(size) > SESSION_FILES_LIMIT { return Err("项目附件超过1GiB,尚未同步".into()); } *total = total.saturating_add(size); files.push(BackupSource { path: path.to_owned(), entry: json!({"path":logical,"sha256":sha,"source":format!("native:{sha}"),"size":size}) }); } @@ -669,7 +677,10 @@ impl Backend { } let _stage_cleanup = SyncStage(stage.clone()); let canvas = stage.join("canvas.pcraft"); - fs::copy(dir.join("canvas.pcraft"), &canvas).map_err(|_| "本机工程快照无法准备")?; + let local_canvas = dir.join("canvas.pcraft"); + if super::portable_draft(&dir, &local_canvas, &canvas)?.is_none() { + fs::copy(local_canvas, &canvas).map_err(|_| "本机工程快照无法准备")?; + } let (canvas_sha, canvas_size) = file_digest(&canvas)?; transfer::check_pcraft_file(&canvas)?; let doc = photocraft_format::load_path(&canvas).map_err(|_| "本机工程读取失败,旧草稿保留")?; @@ -1599,7 +1610,9 @@ mod tests { let mut b = fixture(&origin); let mut engine = photocraft_engine::Session::new(); engine.execute("file.new", json!({"name":"云同步验收","width":1440,"height":400})).unwrap(); - let doc = engine.active().unwrap().doc.clone(); + let mut doc = engine.active().unwrap().doc.as_ref().clone(); + doc.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", Arc::new(vec![123; 1 << 16]))); + let doc = Arc::new(doc); let did = doc.id.0; b.save(doc.clone(), 7, json!({"composer":"保留输入","messages":[{"role":"user","text":"胡桃色"}]})).unwrap(); let dir = b.project_dir(did).unwrap(); @@ -1633,11 +1646,13 @@ mod tests { assert_eq!(context["syncedRevision"], 7); let restored_dir = other.project_dir(restored.id.0).unwrap(); assert_eq!(read_json(&restored_dir.join("creation.json")).unwrap()["revision"], 2); - assert_eq!(fs::read(restored_dir.join("template-outputs/edited.pcraft")).unwrap(), fs::read(dir.join("canvas.pcraft")).unwrap()); + assert_eq!(restored.metadata.psd_global_blocks, doc.metadata.psd_global_blocks); + let restored_edit = photocraft_format::load_path(&restored_dir.join("template-outputs/edited.pcraft")).unwrap(); + assert_eq!(restored_edit.metadata.psd_global_blocks, doc.metadata.psd_global_blocks); let restored_requests = other.dir().join("pi-validation").join(&other.locations[&restored.id.0]).join("requests"); assert_eq!(read_json(&restored_requests.join("original.json")).unwrap()["requestId"], "customer-original"); assert_eq!(super::super::pi::unresolved(&restored_requests).unwrap().len(), 1); - assert!(super::super::projects::idle(&restored_dir).is_err()); + super::super::projects::idle(&restored_dir).unwrap(); let restored_session = restored_dir.join(session.strip_prefix(&dir).unwrap()); assert!(fs::read_to_string(restored_session).unwrap().contains(&serde_json::to_string(&restored_dir.to_string_lossy()).unwrap())); assert!(!restored_dir.join(conversation.strip_prefix(&dir).unwrap()).join("pi-runtime-auth.json").exists()); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_template_slots.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_template_slots.rs index cfb45ca4..e6001160 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_template_slots.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_template_slots.rs @@ -47,7 +47,6 @@ pub(super) fn validate_pack(pack: &Value) -> R<()> { let outputs = pack["outputs"].as_array().filter(|a| !a.is_empty() && a.len() <= 40).ok_or("模板须含1至40项产出")?; let mut fields = std::collections::HashSet::new(); let mut ids = std::collections::HashSet::new(); - let mut details = 0; let mut detail_height = 0u64; for output in outputs { let id = short(&output["id"], 80, "产出编号")?; @@ -58,13 +57,12 @@ pub(super) fn validate_pack(pack: &Value) -> R<()> { if !matches!(output["component"].as_str(), Some("detail" | "main_images" | "sku_images")) { return Err("产出类型无效".into()); } - let width = output["width"].as_u64().filter(|n| matches!(*n, 750 | 1440) || pack["enterprise"]["adapterVersion"] == 4 && (1..=8192).contains(n)).ok_or("模板画布宽度不受支持")?; + let width = output["width"].as_u64().filter(|n| (1..=8192).contains(n)).ok_or("模板画布宽度不受支持")?; let height = output["height"].as_u64().filter(|n| (1..=30_000).contains(n)).ok_or("模板高度无效")?; if width * height > 43_200_000 { return Err("模板画布超出限制".into()); } if output["component"] == "detail" { - details += 1; detail_height += height; } if let Some(decorations) = output.get("decorations") { @@ -132,7 +130,7 @@ pub(super) fn validate_pack(pack: &Value) -> R<()> { } } } - if details > (if enterprise { 40 } else { 14 }) || detail_height > (if enterprise { 60_000 } else { 30_000 }) { + if detail_height > (if enterprise { 60_000 } else { 30_000 }) { return Err("详情页数量或总高超出模板导入限制".into()); } Ok(()) diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_template_workflow.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_template_workflow.rs index 929bd066..22ed1a6b 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_template_workflow.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_template_workflow.rs @@ -1,5 +1,5 @@ //! Account-scoped template candidates. Every image POST remains in the existing 98k adapter. -use super::{json, Value, Document, R, hash, Path, template_slots, read_json, slot_canvas, write_json, creation, Uuid, images, pi, project_not_trashed, Backend, mpsc, Event, original_project_present, sync, Arc}; +use super::{json, Value, Document, R, hash, Path, template_slots, read_json, slot_canvas, write_json, creation, Uuid, images, project_not_trashed, Backend, mpsc, Event, original_project_present, sync, Arc}; fn rev(value: &Value) -> u64 { value["revision"].as_u64().unwrap_or(0) @@ -67,7 +67,7 @@ fn materialize_output(dir: &Path, pack: &Value, component: &str, document: Optio } .into()); } - let native = photocraft_format::load_path(&edited).map_err(|_| "已编辑输出无法读取,未用默认版替换")?; + let native = super::load_draft(dir, &edited).map_err(|_| "已编辑输出无法读取,未用默认版替换")?; if mapping(&native).as_ref() != Some(&meta) { return Err("编辑稿与保存关联不一致,原稿已保留".into()); } @@ -176,23 +176,6 @@ fn reuse_action(dir: &Path, state: &Value, input: &Value) -> R { // no new task is reserved, dispatched, selected or applied here. template_slots::reuse_candidate(dir, target, target_letter, source, source_letter, rev(state)) } -pub(super) fn other_pending(dir: &Path, creation: &Value, state: &Value, except: Option<&Value>) -> R { - Ok(other_local_pending(dir, creation, state, except)? || pending_pi(dir)?.iter().any(|item| { - !except.is_some_and(|binding| binding["detailBatch"] == true - && item["detailSlot"].as_str().is_some_and(|scope| - scope.rsplit('/').next().is_some_and(|slot| binding["slotId"] != slot))) - })) -} - -pub(super) fn pending_pi(dir: &Path) -> R> { - if dir.parent().and_then(Path::file_name).is_some_and(|name| name == "projects") - && let (Some(account), Some(project)) = (dir.parent().and_then(Path::parent), dir.file_name()) - { - return pi::unresolved(&account.join("pi-validation").join(project).join("requests")); - } - Ok(Vec::new()) -} - pub(super) fn other_local_pending(dir: &Path, creation: &Value, state: &Value, except: Option<&Value>) -> R { if images::pending(dir)? { let task = read_json(&dir.join("image-task.json"))?; @@ -232,7 +215,7 @@ fn confirmed(dir: &Path, creation: &Value, state: &Value) -> bool { && creation["brief"]["categoryId"] == state["template"]["categoryId"] } fn capabilities(dir: &Path, creation: &Value, state: &Value) -> R { - let other = other_pending(dir, creation, state, None)?; + let other = other_local_pending(dir, creation, state, None)?; let pending = other || !creation::pending_text_tasks(dir)?.is_empty(); let ready = confirmed(dir, creation, state); let image = ready && !other && creation::slot_image_text_allowed(dir, creation, &state["template"])?; @@ -256,7 +239,7 @@ pub(super) fn validate_image_context(dir: &Path, except: Option<&Value>) -> R<() return Err("图位原任务关联已变化,未发送请求".into()); } } - if other_pending(dir, &creation, &state, except)? || !creation::slot_image_text_allowed(dir, &creation, &state["template"])? { + if other_local_pending(dir, &creation, &state, except)? || !creation::slot_image_text_allowed(dir, &creation, &state["template"])? { return Err("有依赖的原请求待核查,未发送新图位请求".into()); } Ok(()) diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_transfer.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_transfer.rs index dce63709..12b8d3db 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_transfer.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_transfer.rs @@ -135,12 +135,6 @@ pub(super) fn explicit_chat(value: &Value) -> R> { value.as_bool().map(Some).ok_or_else(|| "同步对话选项无效".into()) } -#[derive(Default)] -pub(super) struct Selection { - pub(super) included: Vec, - pub(super) excluded: Vec, -} - impl Policy<'_> { pub(super) fn agent_file(&self, path: &str) -> Result<(), &'static str> { let parts: Vec<_> = path.split('/').collect(); diff --git a/apps/detail-photocraft/crates/format/src/jiansun_load_tests.rs b/apps/detail-photocraft/crates/format/src/jiansun_load_tests.rs new file mode 100644 index 00000000..96617e4e --- /dev/null +++ b/apps/detail-photocraft/crates/format/src/jiansun_load_tests.rs @@ -0,0 +1,56 @@ +use super::*; +use std::time::Instant; + +struct CopyingZip<'a>(ZipSource<'a>); + +impl ByteSource for CopyingZip<'_> { + fn get(&self, path: &str, max: usize) -> Result> { + self.0.get(path, max) + } +} + +#[test] +#[ignore = "requires the local XIAOYI_CANVAS_BENCH draft"] +fn jiansun_detail_draft_loading() { + let path = std::env::var_os("XIAOYI_CANVAS_BENCH").unwrap(); + let t = Instant::now(); + let bytes = crate::read::read_file(Path::new(&path)).unwrap(); + println!("file bytes={} read={:?}", bytes.len(), t.elapsed()); + let t = Instant::now(); + let src = ZipSource::new(&bytes).unwrap(); + let index = t.elapsed(); + let opts = LoadOptions { preserve_ids: true, ..LoadOptions::default() }; + let t = Instant::now(); + let manifest = read_manifest(&src, &opts).unwrap(); + println!("zip_index={index:?} manifest={:?}", t.elapsed()); + println!("embedded_thumbnail={}", manifest.thumbnail.is_some()); + let mut hashes = HashSet::new(); + for (_, key, hash) in &manifest.document.metadata.psd_global_blocks { + if key != "6c6e6b32" || !hashes.insert(hash) { + continue; + } + let path = blob_path(hash); + let t = Instant::now(); + let copied = src.get(&path, usize::MAX).unwrap(); + let copy = t.elapsed(); + let t = Instant::now(); + let payload = src.get_payload(&path, usize::MAX).unwrap(); + let borrow = t.elapsed(); + assert_eq!(copied, payload.as_ref()); + drop(copied); + let t = Instant::now(); + let decoded = decompress_bounded(&payload, opts.max_blob_bytes, None, &path).unwrap(); + let zstd = t.elapsed(); + let t = Instant::now(); + assert_eq!(hash_bytes(&decoded), *hash); + println!("lnk2 bytes={} decoded={} zip_copy={copy:?} zip_borrow={borrow:?} zstd={zstd:?} hash={:?}", payload.len(), decoded.len(), t.elapsed()); + } + assert!(!hashes.is_empty(), "draft has no lnk2 blob"); + let src = CopyingZip(src); + for owned in [true, false, false, true, true, false] { + let source: &dyn ByteSource = if owned { &src } else { &src.0 }; + let t = Instant::now(); + let doc = load(source, &opts).unwrap(); + println!("decode owned={owned} time={:?} size={:?}", t.elapsed(), doc.size); + } +} diff --git a/apps/detail-photocraft/crates/format/src/lib.rs b/apps/detail-photocraft/crates/format/src/lib.rs index f20148d8..0b66d99d 100644 --- a/apps/detail-photocraft/crates/format/src/lib.rs +++ b/apps/detail-photocraft/crates/format/src/lib.rs @@ -168,6 +168,27 @@ pub fn load_path(path: &Path) -> Result { load_path_with(path, &LoadOptions::default()) } +/// Load a local draft against its project's object directory, or read an older standalone draft. +pub fn load_draft(path: &Path, objects: &Path) -> Result { + store::load_draft(&read_file(path)?, objects, &LoadOptions::default()) +} + +/// Detect a native project-local checkpoint by its first ZIP entry. +pub fn is_draft_file(path: &Path) -> Result { + store::is_draft_file(path) +} + +/// Check the compressed read budget for a draft, including its external objects. +pub fn draft_fits(path: &Path, objects: &Path, limit: u64) -> Result { + store::draft_fits(path, objects, limit) +} + +/// Embed the draft's exact compressed objects in a standalone archive. Older archives are +/// already standalone and can be copied unchanged. +pub fn portable_draft(bytes: &[u8], objects: &Path) -> Result> { + store::portable_draft(bytes, objects) +} + /// Load from any byte source — a directory behind a capability handle, an archive, a test /// fixture — the same migration and limits as the path loads. pub fn load_bytes_source(src: &dyn ByteSource, opts: &LoadOptions) -> Result { diff --git a/apps/detail-photocraft/crates/format/src/store.rs b/apps/detail-photocraft/crates/format/src/store.rs index af667808..ecf296ba 100644 --- a/apps/detail-photocraft/crates/format/src/store.rs +++ b/apps/detail-photocraft/crates/format/src/store.rs @@ -1,5 +1,6 @@ //! Object storage (ZIP or directory), incremental writer and loader. +use std::borrow::Cow; use std::collections::{BTreeMap, HashMap, HashSet}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; @@ -18,6 +19,19 @@ use crate::{FormatError, LoadOptions, Result, SaveOptions}; pub(crate) const MANIFEST: &str = "manifest.json"; pub(crate) const THUMB: &str = "thumb.png"; pub(crate) const COMPOSITE: &str = "composite/preview.png"; +const DRAFT_OBJECTS: &str = "draft-objects.json"; + +pub(crate) fn is_draft_file(path: &Path) -> Result { + const PREFIX_LEN: usize = 30 + DRAFT_OBJECTS.len(); + let mut prefix = [0; PREFIX_LEN]; + match std::fs::File::open(path)?.read_exact(&mut prefix) { + Ok(()) => Ok(prefix.starts_with(b"PK\x03\x04") + && prefix[26..28] == (DRAFT_OBJECTS.len() as u16).to_le_bytes() + && &prefix[30..] == DRAFT_OBJECTS.as_bytes()), + Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => Ok(false), + Err(error) => Err(error.into()), + } +} /// The file a directory save holds an exclusive lock on for its whole transaction (#4957). pub(crate) const SAVE_LOCK: &str = "save.lock"; /// How long a directory save waits for another save of the same bundle to finish. @@ -98,6 +112,11 @@ fn beside(parallel: bool, a: impl FnOnce() -> Result + Send, b: i pub trait ByteSource { fn get(&self, path: &str, max: usize) -> Result>; + + /// Read an entry, borrowing its bytes when the source already holds them. + fn get_payload(&self, path: &str, max: usize) -> Result> { + self.get(path, max).map(Cow::Owned) + } } pub(crate) struct ZipSource<'a> { @@ -112,7 +131,12 @@ impl<'a> ZipSource<'a> { impl ByteSource for ZipSource<'_> { fn get(&self, path: &str, max: usize) -> Result> { - self.zip.read_by_name(path, max) + self.get_payload(path, max).map(Cow::into_owned) + } + + fn get_payload(&self, path: &str, max: usize) -> Result> { + let entry = self.zip.find(path).ok_or_else(|| FormatError::corrupt(format!("missing `{path}`")))?; + self.zip.read_payload(entry, max) } } @@ -132,6 +156,78 @@ impl ByteSource for DirSource { } } +struct DraftSource<'a> { + archive: ZipSource<'a>, + objects: DirSource, + paths: Option>, +} + +impl<'a> DraftSource<'a> { + fn open(bytes: &'a [u8], objects: &Path) -> Result { + let archive = ZipSource::new(bytes)?; + let paths: Option> = archive.zip.find(DRAFT_OBJECTS) + .map(|entry| -> Result> { Ok(serde_json::from_slice(&archive.zip.read(entry, 16 << 20)?)?) }) + .transpose()?; + for path in paths.iter().flatten() { + let hash = path.strip_prefix("tiles/").or_else(|| path.strip_prefix("blobs/")) + .and_then(|name| name.strip_suffix(".zst")); + if !hash.is_some_and(is_valid_hash) { + return Err(FormatError::corrupt(format!("invalid draft object: {path}"))); + } + } + Ok(Self { archive, objects: DirSource { root: objects.to_owned() }, paths }) + } +} + +impl ByteSource for DraftSource<'_> { + fn get(&self, path: &str, max: usize) -> Result> { + if let Some(paths) = &self.paths && (path.starts_with("tiles/") || path.starts_with("blobs/")) { + if paths.binary_search_by(|name| name.as_str().cmp(path)).is_err() { + return Err(FormatError::corrupt(format!("missing draft object: {path}"))); + } + self.objects.get(path, max) + } else { + self.archive.get(path, max) + } + } +} + +pub(crate) fn load_draft(bytes: &[u8], objects: &Path, opts: &LoadOptions) -> Result { + load(&DraftSource::open(bytes, objects)?, opts) +} + +pub(crate) fn draft_fits(path: &Path, objects: &Path, limit: u64) -> Result { + let size = std::fs::metadata(path)?.len(); + let Some(mut remaining) = limit.checked_sub(size) else { return Ok(false); }; + if !is_draft_file(path)? { + return Ok(true); + } + let bytes = crate::read_file(path)?; + let source = DraftSource::open(&bytes, objects)?; + for path in source.paths.iter().flatten() { + let size = std::fs::metadata(objects.join(path))?.len(); + let Some(next) = remaining.checked_sub(size) else { return Ok(false); }; + remaining = next; + } + Ok(true) +} + +pub(crate) fn portable_draft(bytes: &[u8], objects: &Path) -> Result> { + let source = DraftSource::open(bytes, objects)?; + let paths = source.paths.as_ref().ok_or_else(|| FormatError::corrupt("missing draft object index"))?; + let dir = &source.objects.root; + let manifest = source.archive.get(MANIFEST, LoadOptions::default().max_manifest_bytes)?; + let entries = paths.iter().map(|path| Ok((path.as_str(), usize::try_from(std::fs::metadata(dir.join(path))?.len()) + .map_err(|_| FormatError::LimitExceeded(path.clone()))?))).collect::>>()?; + let mut zip = ZipWriter::with_entries(std::iter::once((MANIFEST, manifest.len())).chain(entries.iter().copied()))?; + zip.add(MANIFEST, &manifest)?; + for (path, size) in entries { + let data = source.objects.get(path, size)?; + zip.add(path, &data)?; + } + zip.finish() +} + /// Read one opened bundle entry under its `max` budget. The stat `len` is a buffer hint only /// (files can change while open, and a FIFO reports 0), so the bound is enforced on the read /// itself, never on the hint. @@ -197,7 +293,7 @@ fn check_manifest_depth(json: &[u8]) -> Result<()> { } pub(crate) fn read_manifest(src: &dyn ByteSource, opts: &LoadOptions) -> Result { - let raw = src.get(MANIFEST, opts.max_manifest_bytes)?; + let raw = src.get_payload(MANIFEST, opts.max_manifest_bytes)?; // serde_json stops at 128 levels (about 40 nested groups); the bounded check replaces that limit. check_manifest_depth(&raw)?; let mut de = serde_json::Deserializer::from_slice(&raw); @@ -268,7 +364,7 @@ impl Fetch for LoadFetch<'_> { } self.account(len)?; let path = tile_path(hash); - let z = self.src.get(&path, len + len / 8 + 4096)?; + let z = self.src.get_payload(&path, len + len / 8 + 4096)?; let data = decompress(&z, len, &path)?; if hash_bytes(&data) != hash { return Err(FormatError::corrupt(format!("{path}: content does not match its hash"))); @@ -294,7 +390,7 @@ impl Fetch for LoadFetch<'_> { let path = blob_path(hash); // The stored zstd frame of incompressible data is a little larger than the data, so a // blob right at `limit` must still be read; `decompress_bounded` enforces `limit`. - let z = self.src.get(&path, limit.saturating_add(limit / 8).saturating_add(4096))?; + let z = self.src.get_payload(&path, limit.saturating_add(limit / 8).saturating_add(4096))?; // Blob length is not in the manifest; the frame header bounds it and // we cap at max_blob_bytes. let data = decompress_bounded(&z, limit, None, &path)?; @@ -338,6 +434,10 @@ pub(crate) fn load(src: &dyn ByteSource, opts: &LoadOptions) -> Result loader.document(&m.document) } +#[cfg(test)] +#[path = "jiansun_load_tests.rs"] +mod jiansun_load_tests; + // --------------------------------------------------------------------------- // Saving // --------------------------------------------------------------------------- @@ -858,9 +958,16 @@ type Compressed<'a> = (&'a String, Arc>); /// Compresses `objects` on scoped worker threads (sequentially on wasm). fn par_compress<'a>(objects: &[(&'a String, &'a Object)]) -> Result>> { + par_objects(objects, |path, object| Ok((path, Arc::new(object.compressed())))) +} + +fn par_objects<'a, T: Send>( + objects: &[(&'a String, &'a Object)], + process: impl Fn(&'a String, &'a Object) -> Result + Sync, +) -> Result> { let threads = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 32) }; if threads < 2 || objects.len() < 2 { - return Ok(objects.iter().map(|(p, o)| (*p, Arc::new(o.compressed()))).collect()); + return objects.iter().map(|&(path, object)| process(path, object)).collect(); } let next = std::sync::atomic::AtomicUsize::new(0); std::thread::scope(|sc| { @@ -870,10 +977,10 @@ fn par_compress<'a>(objects: &[(&'a String, &'a Object)]) -> Result(objects: &[(&'a String, &'a Object)]) -> Result = hs.into_iter().map(|h| h.join()).collect(); let mut out = Vec::with_capacity(objects.len()); for r in joined { - out.extend(r.map_err(|_| FormatError::Io(std::io::Error::other("compression worker panicked")))?); + let objects: Result> = r.map_err(|_| FormatError::Io(std::io::Error::other("object worker panicked")))?; + out.extend(objects?); } Ok(out) }) @@ -945,6 +1053,26 @@ impl PcraftWriter { Ok(Prepared { manifest, objects, stats }) } + /// Save a small project-local checkpoint and publish new content-addressed objects first. + /// The project owns the shared objects for the lifetime of its checkpoints. + pub fn save_draft_zip(&mut self, doc: &Document, objects: &Path) -> Result> { + let prepared = self.prepare(doc, &SaveOptions::default())?; + std::fs::create_dir_all(objects.join("tiles"))?; + std::fs::create_dir_all(objects.join("blobs"))?; + let mut missing = Vec::new(); + for (path, object) in &prepared.objects { + if !objects.join(path).try_exists()? { + missing.push((path, object)); + } + } + par_objects(&missing, |path, object| write_atomic(&objects.join(path), &object.compressed()))?; + let paths = serde_json::to_vec(&prepared.objects.keys().collect::>())?; + let mut zip = ZipWriter::with_entries([(DRAFT_OBJECTS, paths.len()), (MANIFEST, prepared.manifest.len())])?; + zip.add(DRAFT_OBJECTS, &paths)?; + zip.add(MANIFEST, &prepared.manifest)?; + zip.finish() + } + /// Save as a ZIP bundle in memory. pub fn save_zip(&mut self, doc: &Document, opts: &SaveOptions) -> Result<(Vec, SaveStats)> { // Another thread encodes the previews while the document is collected and its new diff --git a/apps/detail-photocraft/crates/format/src/zip.rs b/apps/detail-photocraft/crates/format/src/zip.rs index 2452f879..9a1f7067 100644 --- a/apps/detail-photocraft/crates/format/src/zip.rs +++ b/apps/detail-photocraft/crates/format/src/zip.rs @@ -236,6 +236,11 @@ impl<'a> ZipReader<'a> { /// Entry payload (decompressed), at most `max` bytes, CRC-checked. pub fn read(&self, e: &Entry, max: usize) -> Result, FormatError> { + self.read_payload(e, max).map(Cow::into_owned) + } + + /// STORE entries already hold the payload in the archive. + pub(crate) fn read_payload(&self, e: &Entry, max: usize) -> Result, FormatError> { if e.uncompressed > max { return Err(FormatError::LimitExceeded(format!("zip entry `{}` is {} bytes (max {max})", e.name, e.uncompressed))); } @@ -246,7 +251,7 @@ impl<'a> ZipReader<'a> { .and_then(|end| self.bytes.get(e.data_offset..end)) .ok_or_else(|| FormatError::corrupt(format!("zip entry `{}` out of range", e.name)))?; let data = match e.method { - 0 => raw.to_vec(), + 0 => Cow::Borrowed(raw), 8 => { // The uncompressed length comes from an untrusted ZIP header: a // small forged archive must not reserve gigabytes up front, so the @@ -257,7 +262,7 @@ impl<'a> ZipReader<'a> { .take((e.uncompressed as u64).saturating_add(1)) .read_to_end(&mut out) .map_err(|err| FormatError::corrupt(format!("zip entry `{}`: {err}", e.name)))?; - out + Cow::Owned(out) } m => { return Err(FormatError::Unsupported(format!("zip compression method {m} for `{}`", e.name))); @@ -266,7 +271,7 @@ impl<'a> ZipReader<'a> { if data.len() != e.uncompressed || data.len() > max { return Err(FormatError::corrupt(format!("zip entry `{}` has wrong size", e.name))); } - if crc32(&data) != e.crc { + if crc32(data.as_ref()) != e.crc { return Err(FormatError::corrupt(format!("zip entry `{}` failed its CRC check", e.name))); } Ok(data) diff --git a/apps/detail-photocraft/crates/gpu/src/convert.rs b/apps/detail-photocraft/crates/gpu/src/convert.rs index 9dbfc818..e962c6eb 100644 --- a/apps/detail-photocraft/crates/gpu/src/convert.rs +++ b/apps/detail-photocraft/crates/gpu/src/convert.rs @@ -115,6 +115,14 @@ pub(crate) fn convert_tiles( } } } + // The raster tile is already laid out like the texture. Hand its bytes to the queue + // directly instead of allocating and copying every tile during a cold canvas refresh. + if matches!(kind, TexKind::Rgba8Direct | TexKind::R8Direct) { + for (tile, coordinates) in &groups { + put(tile, coordinates, tile.bytes()); + } + return groups.len(); + } // CMYK and Lab tiles convert pixel by pixel through a colour transform (a CMYK tile took // ~5 ms on one thread, the whole of a brush dab's refresh on an A4 CMYK page, #5108): those // go in bands of rows, so even the one tile a dab touches spreads over the threads. Workers diff --git a/apps/detail-photocraft/crates/ui-egui/src/canvas/gpu_canvas.rs b/apps/detail-photocraft/crates/ui-egui/src/canvas/gpu_canvas.rs index 965d0bc0..066ac197 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/canvas/gpu_canvas.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/canvas/gpu_canvas.rs @@ -1100,3 +1100,6 @@ mod fade_tests; #[cfg(test)] mod tests; + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod jiansun_open_tests; diff --git a/apps/detail-photocraft/crates/ui-egui/src/canvas/gpu_canvas/jiansun_open_tests.rs b/apps/detail-photocraft/crates/ui-egui/src/canvas/gpu_canvas/jiansun_open_tests.rs new file mode 100644 index 00000000..8f1417a7 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/canvas/gpu_canvas/jiansun_open_tests.rs @@ -0,0 +1,48 @@ +use super::*; +use std::time::Instant; + +#[test] +fn jiansun_first_gpu_refresh_preserves_pixels_across_tiles() { + use photocraft_color::{ColorMode, PixelFormat, SampleType}; + use photocraft_doc::{Document, Layer}; + use photocraft_geom::{Rect, Size}; + + let _guard = photocraft_testkit::gpu_lock(); + let rs = egui_kittest::wgpu::create_render_state(wgpu_setup(), Default::default()); + let mut doc = Document::new("detail", Size::new(300, 400), ColorMode::Rgb, SampleType::U8); + let mut layer = Layer::raster("detail", PixelFormat::RGBA8); + let surface = layer.surface_mut().unwrap(); + surface.fill_rect(Rect::new(50, 30, 295, 385), &[1.0, 0.0, 0.0, 1.0]); + surface.fill_rect(Rect::new(200, 190, 270, 380), &[0.0, 1.0, 1.0, 1.0]); + doc.layers.push(layer); + + let canvas = GpuCanvas::new(&rs); + let refresh = canvas.refresh(doc.id.0, &doc, None, None); + assert_eq!(refresh.kind, "gpu-full", "{:?}", refresh.fallback); + let (format, size, pixels) = canvas.read_texels(doc.id.0).unwrap(); + assert_eq!(size, [300, 400]); + let expected = photocraft_compose::render(&doc, doc.bounds()); + let expected = display_texels(format, None, &expected); + for (index, (actual, expected)) in pixels.iter().zip(expected.chunks_exact(texel_bytes(format) as usize)).enumerate() { + assert_eq!(*actual, texel_to_f32(format, expected), "pixel {index}"); + } +} + +#[test] +#[ignore = "requires the local XIAOYI_CANVAS_BENCH draft and a GPU adapter"] +fn jiansun_detail_first_gpu_refresh() { + let _guard = photocraft_testkit::gpu_lock(); + let path = std::env::var_os("XIAOYI_CANVAS_BENCH").unwrap(); + let doc = photocraft_format::load_path(std::path::Path::new(&path)).unwrap(); + let rs = egui_kittest::wgpu::create_render_state(wgpu_setup(), Default::default()); + println!("adapter={:?} bounds={:?}", rs.adapter.get_info(), doc.bounds()); + for _ in 0..3 { + let canvas = GpuCanvas::new(&rs); + let start = Instant::now(); + let refresh = canvas.refresh(doc.id.0, &doc, None, None); + assert_eq!(refresh.kind, "gpu-full", "{:?}", refresh.fallback); + let submit = start.elapsed(); + assert!(canvas.health.wait(&rs.device, None)); + println!("submit={submit:?} complete={:?} uploads={}", start.elapsed(), refresh.uploads); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index 055e02bb..d1b9b368 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -1112,7 +1112,6 @@ pub struct Workspace { retained_creation_ui: std::collections::HashMap, pending_project_open: Option, creation_width: u32, - creation_count: usize, creation_delivery_dir: Option, creation_catalog: std::collections::HashMap>, creation_reads: creation_reads::UiState, @@ -1614,8 +1613,7 @@ impl Workspace { retained_creation_ui: Default::default(), project_files: Default::default(), pending_project_open: None, - creation_width: 1440, - creation_count: 3, + creation_width: 0, creation_delivery_dir: None, creation_catalog: Default::default(), creation_reads: Default::default(), @@ -1825,7 +1823,7 @@ impl Workspace { state["nativeOperationReceipts"] = if state["nativeOperation"].is_object() { self.agent_native.recent_receipts() } else { Value::Null }; - state["creationView"] = json!({"open":self.creation_open,"step":self.creation_step,"dirty":self.creation_dirty,"progress":self.creation_progress,"pendingCanvas":self.creation_pending.is_some(),"brief":self.creation_brief,"screenCount":self.creation_count,"selected":self.creation_selected}); + state["creationView"] = json!({"open":self.creation_open,"step":self.creation_step,"dirty":self.creation_dirty,"progress":self.creation_progress,"pendingCanvas":self.creation_pending.is_some(),"brief":self.creation_brief,"screenCount":self.creation_template_screen_count(),"selected":self.creation_selected}); state["templateProgress"] = self.template_progress.clone(); state["creationView"]["geometry"] = self.creation_view_geometry.clone(); let mut catalogs = json!(self.creation_catalog); @@ -1963,6 +1961,25 @@ impl Workspace { self.creation_step = 3; } } + fn creation_draft_width(&self) -> Option { + if self.creation_width == 0 { + self.creation["width"].as_u64() + } else { + Some(u64::from(self.creation_width)) + } + } + + fn creation_template_screen_count(&self) -> Option { + let catalog = &self.creation["designSnapshot"]["rules"]["catalog"]; + if catalog["shops"][0]["id"] != self.creation_brief["brandId"] { + return None; + } + let binding = catalog["bindings"].as_array()?.iter() + .find(|binding| binding["categoryId"] == self.creation_brief["categoryId"] && binding["state"] == "ready")?; + let count = binding["template"]["screens"].as_array()?.iter().filter(|screen| screen["role"] == "content").count(); + (count > 0).then_some(count) + } + fn show_creation_step(&mut self, step: usize, document_open: bool) { self.cancel_project_open(); if !document_open { @@ -2019,8 +2036,7 @@ impl Workspace { self.creation_selected = retained.draft["selected"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); self.creation_direction = retained.draft["direction"].as_str().unwrap_or("").into(); self.creation_plan = retained.draft["screens"].clone(); - self.creation_width = retained.draft["width"].as_u64().unwrap_or(1440) as u32; - self.creation_count = retained.draft["screenCount"].as_u64().unwrap_or(3) as usize; + self.creation_width = retained.draft["width"].as_u64().unwrap_or_default() as u32; self.creation_delivery_dir = product_production::delivery_dir(&retained.draft); self.creation_dirty = true; self.draft_changed = true; @@ -5626,7 +5642,7 @@ mod tests { }))).unwrap(); workspace_frame(&mut w, &mut app); let canonical = json!({"revision":7,"brief":{"name":"已保存资料"},"width":1440,"screenCount":3,"plan":{"screens":[]}}); - let draft = json!({"revision":7,"brief":{"name":"未提交的资料草稿"},"width":1440,"screenCount":3,"screens":[],"direction":"","selected":[]}); + let mut draft = json!({"revision":7,"brief":{"name":"未提交的资料草稿"},"width":1440,"screenCount":3,"screens":[],"direction":"","selected":[]}); events.send(Event::Json("draft".into(), Ok(json!({"doc":id,"revision":9,"syncDirty":true,"creationDraft":draft})))).unwrap(); w.touched = Instant::now() - Duration::from_secs(3); workspace_frame(&mut w, &mut app); @@ -5640,6 +5656,7 @@ mod tests { w.creation_touched = Instant::now() - Duration::from_secs(2); workspace_frame(&mut w, &mut app); assert!(w.creation_dirty); + draft.as_object_mut().unwrap().remove("screenCount"); assert_eq!(w.creation_draft(), draft); assert!(!requests.try_iter().any(|request| matches!(&request, Request::Save(..)) || matches!(&request, Request::Action(method, _) if method == "creation-save"))); @@ -5715,7 +5732,6 @@ mod tests { w.creation_direction = "保留桌面细节".into(); w.creation_plan = json!([{"id":"first","title":"刚修改的方案"}]); w.creation_width = 750; - w.creation_count = 5; w.creation_dirty = true; w.touched = Instant::now(); let unsent = w.creation_draft(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs index e5af4985..585b7728 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs @@ -485,28 +485,25 @@ fn production_turn(command: Option<&str>) -> bool { }) } -fn production_reference(token: &str) -> Option { - fn read(token: &str, prefix: char) -> Option { - let digits = token.strip_prefix(prefix)?; - (digits.len() == 2).then(|| digits.parse().ok()).flatten() - } - let position = |token| { - read(token, 'T').map(|n| format!("第{n}处文案")) - .or_else(|| read(token, 'I').map(|n| format!("第{n}个图位"))) +pub(super) fn production_reply_text(text: &str, streaming: bool, workflow: &Value) -> String { + let mut labels = std::collections::HashMap::new(); + let mut insert = |id, label| { + labels.entry(id).and_modify(|current| { + if *current != Some(label) { + *current = None; + } + }).or_insert(Some(label)); }; - if let Some((screen, field)) = token.split_once('-') { - return Some(format!("第{}屏{}", read(screen, 'S')?, position(field)?)); + for output in workflow["outputs"].as_array().into_iter().flatten() { + if let (Some(id), Some(name)) = (output["documentId"].as_str(), output["name"].as_str()) { + insert(id, name); + } + for field in output["fields"].as_array().into_iter().flatten() { + if let (Some(id), Some(label)) = (field["fieldId"].as_str(), field["label"].as_str()) { + insert(id, label); + } + } } - position(token).or_else(|| read(token, 'S').map(|n| format!("第{n}屏"))) - .or_else(|| read(token, 'P').map(|n| format!("原图{n}"))) - .or_else(|| match token { - "sources" => Some("资料来源".into()), - "links" => Some("图文对应关系".into()), - _ => None, - }) -} - -pub(super) fn production_reply_text(text: &str, streaming: bool) -> String { let tool_tags = [("", ""), ("", "")]; let mut visible = String::new(); let mut remaining = text; @@ -536,14 +533,11 @@ pub(super) fn production_reply_text(text: &str, streaming: bool) -> String { while chars.next_if(|&(_, c)| is_word(c)).is_some() {} let end = chars.peek().map_or(text.len(), |&(end, _)| end); let token = &text[start..end]; - if let Some(reference) = production_reference(token) { - value.push_str(&reference); - } else if !(streaming && end == text.len() - && matches!(token.as_bytes(), [b'S' | b'P' | b'T' | b'I'] | [b'S' | b'P' | b'T' | b'I', b'0'..=b'9'] - | [b'S', b'0'..=b'9', b'0'..=b'9', b'-', ..])) - { - value.push_str(token); - } + value.push_str(labels.get(token).copied().flatten().unwrap_or(match token { + "sources" => "资料来源", + "links" => "图文对应关系", + _ => token, + })); } value.replace("分句编号", "句子对应关系").replace("分句索引", "句子对应关系") } @@ -1332,7 +1326,7 @@ impl Workspace { remember_visible_stream(ui, reply_id, &self.stream_reply); let running = self.pending() && !self.agent_effects_paused; let product = self.pi_request_scope["productProduction"] == true; - let display = product.then(|| production_reply_text(&self.stream_reply, running)); + let display = product.then(|| production_reply_text(&self.stream_reply, running, &self.template_workflow)); let response = agent_motion::message_visual(ui, stream_enter, |ui| { ui.set_width(column_width); timeline::reply(ui, reply_id, timeline::Reply { text: display.as_deref().unwrap_or(&self.stream_reply), streaming: running, animate_final: false }, self.reduce_motion); @@ -1815,7 +1809,7 @@ impl Workspace { let paint_stream = |ui: &mut Ui, text: &str| { remember_visible_stream(ui, reply_id, text); ui.push_id(reply_id, |ui| { - let display = product.then(|| production_reply_text(text, turn_running)); + let display = product.then(|| production_reply_text(text, turn_running, &self.template_workflow)); timeline::reply(ui, reply_id, timeline::Reply { text: display.as_deref().unwrap_or(text), streaming: turn_running, animate_final: false }, self.reduce_motion); }); ui.add_space(8.0); @@ -1828,7 +1822,7 @@ impl Workspace { } TurnItem::Notice(text) => { let text = activity_history_label(text); - let display = product.then(|| production_reply_text(text, false)); + let display = product.then(|| production_reply_text(text, false, &self.template_workflow)); let row = timeline::notice_row(ui, ui.next_auto_id().with("notice"), timeline::Notice { kind: notice_kind(text), text: display.as_deref().unwrap_or(text), hint: None, }, self.reduce_motion); @@ -1870,7 +1864,7 @@ impl Workspace { .then(|| final_handoff(ui, reply_id, text)).flatten(); let arrival = agent_motion::message_enter(ui, conversation_id, index, count, self.reduce_motion); let anchor = reply_id.with(index); - let display = product.then(|| production_reply_text(text, false)); + let display = product.then(|| production_reply_text(text, false, &self.template_workflow)); let text = display.as_deref().unwrap_or(text); let copy_id = anchor.with("copy"); // The copy action keeps its row but shows only while the @@ -1957,7 +1951,12 @@ impl Workspace { let target = image_location(value, id); let original = value["kind"] == "template-image" || value["original"] == true; let (page_label, short_label, label) = if original { - let field = value["fieldId"].as_str().unwrap_or(""); + let field = self.template_workflow["outputs"].as_array().into_iter().flatten() + .filter(|output| value["outputId"].is_null() || output["outputId"] == value["outputId"]) + .flat_map(|output| output["fields"].as_array().into_iter().flatten()) + .find(|field| field["kind"] == "image" && field["fieldId"] == value["fieldId"]) + .and_then(|field| field["label"].as_str()) + .or_else(|| value["fieldId"].as_str()).unwrap_or(""); let label = if field.is_empty() { "模板原图".into() } else { format!("{field} · 模板原图") }; (String::new(), "模板原图".into(), label) } else if value["slotId"].is_null() && value["candidateId"].is_null() @@ -1967,11 +1966,6 @@ impl Workspace { } else { image_result_labels(&target, &self.template_workflow, &self.creation_brief) }; - let (page_label, label) = if original || value["workerNumber"].is_number() { - (production_reply_text(&page_label, false), production_reply_text(&label, false)) - } else { - (page_label, label) - }; let ratio_id = ui.scope_id().with(("result-image-ratio", id)); let ratio = ui.data_mut(|data| { if let Some(texture) = self.agent_images.peek(id) { @@ -1984,7 +1978,7 @@ impl Workspace { if value["kind"] == "image-job" { let active = !self.agent_effects_paused && value["finished"].is_null() && (value["projected"] == true || self.pi_run.as_deref().is_some_and(|run| value["run"] == run)); - let text = production_reply_text(value["slotLabel"].as_str().unwrap_or(""), false); + let text = value["slotLabel"].as_str().unwrap_or("").to_owned(); if !active { // A queued slot keeps its cell and its place in order; it grows // into the image card only once its own generation starts. @@ -2374,7 +2368,7 @@ impl Workspace { let stage = WorkerStage::infer(step, review, image_step.is_some()); ProductionWorker { row, number, active, stage, step: step.to_owned(), review, - slot: production_reply_text(row["label"].as_str().unwrap_or(""), false), + slot: row["label"].as_str().unwrap_or("").to_owned(), frame: job.map(|job| job["imageFrame"].clone()).unwrap_or_default(), } }).collect() @@ -4777,19 +4771,21 @@ mod tests { #[test] fn production_reply_uses_readable_references_in_live_and_saved_text() { - assert_eq!( - production_reply_text("S09-T02 对应 S09-I01、S09-I02,原始依据 P03。SKU", false), - "第9屏第2处文案 对应 第9屏第1个图位、第9屏第2个图位,原始依据 原图3。SKU", - ); - assert_eq!(production_reply_text("正在修订 S09-T0", true), "正在修订 "); - assert_eq!(production_reply_text("正在修订 S0", true), "正在修订 "); - assert_eq!(production_reply_text("已制作用于 SKU", true), "已制作用于 SKU"); - assert_eq!(production_reply_text("核对 sources、links 和分句索引", false), + let workflow = json!({"outputs":[{"documentId":"front","name":"展示页","fields":[ + {"fieldId":"front-copy","kind":"text","label":"标题"}, + {"fieldId":"S09-T02","kind":"image","label":"产品全貌"} + ]}]}); + let display = |text, streaming| production_reply_text(text, streaming, &workflow); + assert_eq!(display("front 的 front-copy 对应 S09-T02,原图 P03。", false), + "展示页 的 标题 对应 产品全貌,原图 P03。"); + assert_eq!(display("正在修订 S09-T0", true), "正在修订 S09-T0"); + assert_eq!(display("已制作用于 SKU", true), "已制作用于 SKU"); + assert_eq!(display("核对 sources、links 和分句索引", false), "核对 资料来源、图文对应关系 和句子对应关系"); - assert_eq!(production_reply_text("正在补图。[{\"name\":\"delegate_image_slots\"}]继续验图。", false), + assert_eq!(display("正在补图。[{\"name\":\"delegate_image_slots\"}]继续验图。", false), "正在补图。继续验图。"); - assert_eq!(production_reply_text("正在补图。[{\"name\":", true), "正在补图。"); - assert_eq!(production_reply_text("正在补图。[{\"name\":", true), "正在补图。"); + assert_eq!(display("正在补图。 { - let format = stitch_ui::halo_select(ui, "creation-width", field_width, &(format!("{} px", self.creation_width)).to_owned(), self.reduce_motion, |ui| { - for width in [1440, 750] { - if stitch_ui::select_option(ui, &format!("{width} px"), self.creation_width == width, true).clicked() && self.creation_width != width { - self.creation_width = width; - self.creation_dirty = true; - } - } - }); + let width = if self.creation_width == 0 || self.creation_brief["templateSelection"].is_null() { + "由模板决定".to_owned() + } else { + format!("{} px", self.creation_width) + }; + let size = vec2(field_width, crate::theme::agent_scale::control::DEFAULT); + let format = ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_size(size); + ui.label(width); + }); self.control_geometry("output-width", format.response.rect); } _ => {} @@ -1292,7 +1286,7 @@ impl Workspace { }); ui.add_space(8.0); field_group(ui, width, "补充资料 / 设计说明", |ui| { - self.creation_dirty |= edit_hint(ui, (field_scope, "note"), &mut self.creation_brief["note"], width, true, "已核实的资料可按行填写,例如「材质:橡胶木」「结构:双梁加固」…"); + self.creation_dirty |= edit_hint(ui, (field_scope, "note"), &mut self.creation_brief["note"], width, true, "按行填写已核实的产品资料与设计说明"); }); brief_section_break(ui); if width >= 600.0 { @@ -1339,11 +1333,7 @@ impl Workspace { let missing = canvas_entry_missing(&self.creation_brief, &template); let new_project = self.template_workflow["canvasFirst"] != true; let chosen_pending = template.is_null() && self.creation_reads.resource_set["id"].is_string(); - let mut missing_for_production = missing.clone(); - if template.is_null() && !chosen_pending { - missing_for_production.retain(|label| matches!(*label, "产品名称" | "产品图")); - } - let prerequisites = if new_project { &missing_for_production } else { &missing }; + let prerequisites = &missing; let scoped_pending = self.scoped_production_pending(); let blocked = if self.unknown { Some(if scoped_pending { "可继续制作其余图位。" } @@ -1631,7 +1621,7 @@ impl Workspace { let variants = brief_variants(&brief); set_brief_variants(&mut brief, variants); brief["templateSelection"] = template.clone(); - if let Err(error) = self.slot_action(app, "slot-skeleton", json!({"brief":brief,"width":self.creation_width,"template":template,"outputId":"detail","generateProduct":generate,"deliveryDir":self.creation_delivery_dir})) { + if let Err(error) = self.slot_action(app, "slot-skeleton", json!({"brief":brief,"template":template,"outputId":"detail","generateProduct":generate,"deliveryDir":self.creation_delivery_dir})) { self.error = error; } } @@ -1964,7 +1954,7 @@ impl Workspace { && choice["categoryId"] == self.creation_brief["categoryId"] { let mut choice = choice.clone(); - if let Some(width) = choice["width"].as_u64().filter(|width| matches!(width, 750 | 1440)) { + if let Some(width) = choice["width"].as_u64() { self.creation_width = width as u32; } if let Some(fields) = choice.as_object_mut() { @@ -2471,14 +2461,9 @@ impl Workspace { ui.label(egui::RichText::new("调整页面文案与画面要求,修改后保存并重新确认").size(12.0).color(t.text_dim)); ui.add_space(16.0); ui.horizontal_wrapped(|ui| { - stitch_ui::halo_select(ui, "creation-count", 100.0, &(format!("{} 屏", self.creation_count)).to_owned(), self.reduce_motion, |ui| { - for count in [3, 5, 6, 8, 12] { - if stitch_ui::select_option(ui, &format!("{count} 屏"), self.creation_count == count, true).clicked() && self.creation_count != count { - self.creation_count = count; - self.creation_dirty = true; - } - } - }); + if let Some(count) = self.creation_template_screen_count() { + ui.label(format!("{count} 屏")); + } let generate = stitch_ui::button(ui, if screens.is_empty() { "生成页面方案" } else { "重新生成方案" }, false); self.control_geometry("plan-generate", generate.rect); if generate.clicked() { @@ -4378,7 +4363,6 @@ mod tests { w.creation_direction = "刚输入的表达方向".into(); w.creation_plan = json!([{"id":"one","title":"尚未保存的标题"}]); w.creation_width = 750; - w.creation_count = 6; w.creation_dirty = true; let draft = w.creation_draft(); let mut value = reference(&w); 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 710ba335..5a488387 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 @@ -419,12 +419,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})); @@ -444,11 +446,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("缺少填写文字")?; @@ -548,8 +563,17 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co "templateHash":w.template_workflow["templateHash"],"canvasLayerId":canvas_layer})) } "pi-image-request" => { - let action = input["action"].as_str().filter(|action| matches!(*action,"prepare"|"dispatch"|"transform")) + let action = input["action"].as_str().filter(|action| matches!(*action,"prepare"|"dispatch"|"transform"|"read"|"pending")) .ok_or("生图请求动作无效")?; + if matches!(action, "read" | "pending") { + if w.pi_request_scope["productProduction"] != true { + return Err("本轮没有制作请求的读取授权".into()); + } + return Ok(json!({"action":action,"request":input["request"], + "scope":{"id":w.template_workflow["workspaceId"],"templateHash":w.template_workflow["templateHash"], + "outputId":w.pi_request_scope["outputId"], + "variantId":w.pi_request_scope["variantId"]}})); + } if w.pi_request_scope["productProduction"] != true || !w.canvas_scope_valid(app) || w.pi_request_scope["outputId"] != w.template_workflow["outputId"] || w.pi_request_scope["variantId"] != w.template_workflow["variantId"] { @@ -1468,7 +1492,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| @@ -1505,6 +1529,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"]}, @@ -1518,10 +1550,21 @@ mod tests { .collect::>(), 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()); 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 8af7cfea..ee6aa81b 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 @@ -490,8 +490,7 @@ fn selected_slot(w: &Workspace, input: &Value, output: &str) -> Result bool { w.creation_brief != w.creation["brief"] - || w.creation["width"].as_u64().is_some_and(|width| width != u64::from(w.creation_width)) - || w.creation["screenCount"].as_u64().is_some_and(|count| count != w.creation_count as u64) + || w.creation["width"].as_u64() != w.creation_draft_width() } fn plan_dirty(w: &Workspace) -> bool { @@ -623,7 +622,7 @@ fn read(w: &Workspace, version: u64, section: &str, output: &str, offset: usize, let batches = projected_batches(w); let mut result = json!({"available":true,"version":version,"section":section,"stage":stage(w),"outputId":output, "revisions":{"canvas":canvas["revision"],"creation":w.creation["revision"],"slots":w.template_workflow["revision"]}, - "dirty":w.creation_dirty,"draftDirty":brief_dirty(w) || plan_dirty(w),"width":w.creation_width,"screenCount":w.creation_count, + "dirty":w.creation_dirty,"draftDirty":brief_dirty(w) || plan_dirty(w),"width":w.creation_draft_width(),"screenCount":w.creation_template_screen_count(), "pending":w.unknown || w.template_workflow["pending"]==true,"writeBlocked":w.pi_write_blocked, "factsStatus":facts["status"],"missing":facts["missing"],"selected":w.creation_selected, "batchCount":batches.len(),"planConfirmed":plan["confirmed"],"capabilities":w.template_workflow["capabilities"],"productEvidence":product_evidence(w)}); @@ -669,6 +668,9 @@ fn read(w: &Workspace, version: u64, section: &str, output: &str, offset: usize, result["slots"] = json!(slots.into_iter().skip(offset).take(12).map(|slot| { let candidates=slot["candidates"].as_array().into_iter().flatten().rev().map(|candidate| json!({"id":clip(&candidate["id"],100),"variant":clip(&candidate["variant"],100),"status":clip(&candidate["status"],24),"sourceType":candidate["sourceType"], "materialTaskId":candidate["materialTaskId"],"sourceRequestId":candidate["sourceRequestId"], + "sequence":candidate["sequence"],"requestId":candidate["requestId"],"error":candidate["error"],"resultExpiry":candidate["resultExpiry"], + "reworkOf":candidate["reworkOf"],"retryableFailure":candidate["retryableFailure"], + "retryAfterSeconds":candidate["retryAfterSeconds"], "reused":candidate["reusedFrom"].is_object()})).collect::>(); let rejection = if w.pi_request_scope["productProduction"] == true && w.pi_canvas_basis.is_some() { slot["nativeLayerId"].as_u64().zip(active_doc) @@ -678,6 +680,7 @@ fn read(w: &Workspace, version: u64, section: &str, output: &str, offset: usize, "label":clip(&slot["label"],160),"selectedCandidateId":if w.template_workflow["canvasFirst"]==true{adopted(&slot["id"])}else{slot["selectedCandidateId"].clone()}, "sourcePolicy":slot["sourcePolicy"],"manuallyEdited":rejection == Some(super::product_production::LayerRejection::UserEdit), "writeBlockReason":rejection.map(|reason| reason.code()),"candidates":candidates, + "generationRequestIds":slot["generationRequestIds"],"retiredCandidateIds":slot["retiredCandidateIds"], "role":slot["role"],"requirements":slot["requirements"], "templatePrompt":slot["templatePrompt"],"relatedFields":slot["relatedFields"], "layoutReference":slot["layoutReference"],"textRegions":slot["textRegions"],"productionRule":slot["productionRule"]}) @@ -2653,7 +2656,7 @@ mod tests { let before = w.creation_direction.clone(); let read = call(&mut w, &mut app, "pi-workflow-read", json!({})).unwrap(); assert_eq!(read["width"], 1440); - assert_eq!(read["screenCount"], 3); + assert!(read["screenCount"].is_null()); assert!(call(&mut w, &mut app, "pi-workflow-propose", json!({"version":read["version"],"intent":intent,"instruction":"改为12屏"})).is_err()); assert!(w.workflow.proposal().is_none()); assert_eq!(w.creation_direction, before);