From 65e7c47bbd8c551611768b16e62d435c08c951b4 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Thu, 26 Nov 2026 18:25:50 +0800 Subject: [PATCH 1/4] feat(xiaoyi): fence account workloads and declare project backup contents --- apps/detail-agent-pi/src/agent.mjs | 10 +- apps/detail-agent-pi/src/bridge-error.mjs | 13 +- apps/detail-agent-pi/src/credentials.mjs | 23 ++ apps/detail-agent-pi/src/desktop-daemon.mjs | 37 ++- apps/detail-agent-pi/src/desktop-host.mjs | 52 +++- apps/detail-agent-pi/src/native-bridge.mjs | 37 ++- apps/detail-agent-pi/src/store.mjs | 28 +- .../test/account-authorization.test.mjs | 104 +++++++ .../test/desktop-daemon.test.mjs | 30 ++ .../photocraft/src/jiansun_agent_daemon.rs | 9 +- .../apps/photocraft/src/jiansun_backend.rs | 263 +++++++++++++++++- .../src/jiansun_canvas_workspace.rs | 30 +- .../apps/photocraft/src/jiansun_creation.rs | 10 +- .../apps/photocraft/src/jiansun_images.rs | 35 ++- .../apps/photocraft/src/jiansun_pi.rs | 52 +++- .../apps/photocraft/src/jiansun_pi_runtime.rs | 35 ++- .../photocraft/src/jiansun_project_file.rs | 210 +++++++++++--- .../apps/photocraft/src/jiansun_projects.rs | 8 +- .../photocraft/src/jiansun_prompt_library.rs | 3 + .../apps/photocraft/src/jiansun_sync.rs | 191 +++++++++---- .../src/jiansun_template_workflow.rs | 3 + .../apps/photocraft/src/jiansun_transfer.rs | 217 +++++++++++++++ .../apps/photocraft/src/logging.rs | 5 +- .../crates/ui-egui/src/jiansun.rs | 61 +++- .../crates/ui-egui/src/jiansun/creation.rs | 18 +- .../crates/ui-egui/src/jiansun/pi_bridge.rs | 25 ++ .../ui-egui/src/jiansun/product_production.rs | 13 + .../ui-egui/src/jiansun/project_browser.rs | 9 +- .../ui-egui/src/jiansun/project_file.rs | 22 +- 29 files changed, 1363 insertions(+), 190 deletions(-) create mode 100644 apps/detail-agent-pi/src/credentials.mjs create mode 100644 apps/detail-agent-pi/test/account-authorization.test.mjs create mode 100644 apps/detail-photocraft/apps/photocraft/src/jiansun_transfer.rs diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index a215c05d..abf61452 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -9,6 +9,7 @@ import lockfile from 'proper-lockfile'; import { Type } from '@sinclair/typebox'; import { CanvasOperations } from './canvas-operations.mjs'; import { BridgeError, stoppedCanvas } from './bridge-error.mjs'; +import { protectSession, redactText } from './credentials.mjs'; import { productionTools, callProductionTool, closeProductionTurn, runPiProductionGoal, mayContinueProductionGoal, piGoalState } from './production-goal.mjs'; import { Agent, runToolCall } from '@earendil-works/pi-agent-core'; @@ -484,6 +485,7 @@ export class DetailPiAgent { ...(firstToolAt === undefined ? {} : {firstToolMs:firstToolAt-sentAt}), }) }); host.inflight = ['complete', 'failed'].includes(settled.phase) ? null : round.id; + 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)) { @@ -512,7 +514,8 @@ export class DetailPiAgent { output.push({ type: 'done', reason: message.stopReason, message }); output.end(message); } else { output.push(finalEvent); output.end(result); } } catch (error) { - 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)+' '+error.message : String(error.message), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } }, timestamp: Date.now() }; + 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() }; await store.appendEvent({ type: 'provider_error', id: round?.id, reason: message.errorMessage }); output.push({ type: 'error', reason: 'error', error: message }); output.end(message); } @@ -521,7 +524,8 @@ export class DetailPiAgent { }, }); const saved = await store.get('session.json', null); - host.manager = saved ? SessionManager.open(path.join(store.dir,'sessions',path.basename(saved.file)), store.dir, store.dir) : SessionManager.create(store.dir, path.join(store.dir, 'sessions')); + host.manager = protectSession(saved ? SessionManager.open(path.join(store.dir,'sessions',path.basename(saved.file)), store.dir, store.dir) + : 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]; @@ -643,6 +647,7 @@ export class DetailPiAgent { const message=await stream.result(); const valid=finalEvent?.type==='done' && ['stop','toolUse'].includes(message.stopReason); const receipt=await round.finish(valid,message.stopReason); + if (broker?.authority?.error) throw broker.authority.error; const raw=valid&&receipt.phase==='complete'?await wire:null; const usage=raw?responseUsage(raw):null; await store.appendEvent({type:'provider_finished',id:round.id,slotId,...receipt,requestBytes,firstOutputMs,promptCacheKeyPresent, @@ -899,6 +904,7 @@ export class DetailPiAgent { if (this.needsReopen) throw Error('原响应已恢复,请重新打开此会话;未发起新请求'); if ((await this.store.get('recovered-tools.json', [])).some(t => t.phase === 'review')) 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); this.firstTurnBrokerInfo = null; if (latest.accountScope !== this.store.identity.scope) throw Error('账户与项目不一致;原草稿已保留'); diff --git a/apps/detail-agent-pi/src/bridge-error.mjs b/apps/detail-agent-pi/src/bridge-error.mjs index 2bca8b0f..c12127b3 100644 --- a/apps/detail-agent-pi/src/bridge-error.mjs +++ b/apps/detail-agent-pi/src/bridge-error.mjs @@ -1,6 +1,8 @@ +import { redactText } from './credentials.mjs'; + export class BridgeError extends Error { constructor(message, category = 'failed', {retryable = false, dispatched = false} = {}) { - super(message); + super(redactText(String(message ?? '本机操作未完成'))); this.category=category; this.retryable=retryable; this.dispatched=dispatched; @@ -19,4 +21,11 @@ export class BridgeError extends Error { } export const stoppedCanvas = error => - ['scope_changed','write_revoked','revision_conflict','result_unknown','cancelled','transport_interrupted'].includes(error?.category); + ['scope_changed','auth_revoked','write_revoked','revision_conflict','result_unknown','cancelled','transport_interrupted'].includes(error?.category); + +export const authorityLost = error => ['scope_changed', 'auth_revoked'].includes(error?.category); + +export function authorityFailure(category, options) { + return new BridgeError(category === 'scope_changed' ? '账户已改变,原项目和原请求已保留;请切回原账户' + : '授权已失效,制作已暂停;请重新登录', category, options); +} diff --git a/apps/detail-agent-pi/src/credentials.mjs b/apps/detail-agent-pi/src/credentials.mjs new file mode 100644 index 00000000..81055733 --- /dev/null +++ b/apps/detail-agent-pi/src/credentials.mjs @@ -0,0 +1,23 @@ +const credentialText = /\b(?:authorization|(?:set[-_ ]?)?cookie|x[-_ ]?api[-_ ]?key|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|password|secret[-_ ]?key)["']?\s*[:=]\s*[^\r\n]+|\bbearer[ \t]+[a-z0-9._~+/=-]{4,}|\b(?:sk-(?:proj-)?|dcs_|dca_)[a-z0-9_-]{16,}/gi; +const credentialKeys = new Set(['authorization', 'cookie', 'setcookie', 'apikey', 'xapikey', + 'accesstoken', 'refreshtoken', 'password', 'secretkey', 'credentials', 'privatekey', 'token', 'composerdrafttoken']); + +export const redactText = text => text.replace(credentialText, '[已脱敏]'); + +export function redact(value) { + if (typeof value === 'string') return redactText(value); + if (Array.isArray(value)) return value.map(redact); + if (!value || typeof value !== 'object') return value; + return Object.fromEntries(Object.entries(value) + .filter(([key, item]) => !credentialKeys.has(key.toLowerCase().replace(/[-_ ]/g, '')) && redactText(key) === key + && !(key.toLowerCase() === 'key' && typeof item === 'string' && item.startsWith('sk-'))) + .map(([key, item]) => [key, redact(item)])); +} + +export function protectSession(manager) { + for (const name of ['appendMessage', 'appendCompaction', 'branchWithSummary', 'appendCustomEntry', 'appendCustomMessageEntry']) { + const append = manager[name].bind(manager); + manager[name] = (...args) => append(...args.map(redact)); + } + return manager; +} diff --git a/apps/detail-agent-pi/src/desktop-daemon.mjs b/apps/detail-agent-pi/src/desktop-daemon.mjs index e0279634..a75feeba 100644 --- a/apps/detail-agent-pi/src/desktop-daemon.mjs +++ b/apps/detail-agent-pi/src/desktop-daemon.mjs @@ -1,4 +1,5 @@ -import { BridgeError } from './bridge-error.mjs'; +import { BridgeError, authorityFailure, authorityLost } from './bridge-error.mjs'; +import { redact } from './credentials.mjs'; import { createInterface } from 'node:readline'; import { Native98kBroker } from './native-bridge.mjs'; @@ -12,7 +13,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out // Retain unresolved operations across the distinct SDK Host instances owned // by this daemon. Never evict an unresolved identity to make room. const recovery = new Map(); - const send=value=>{if(!closed)output.write(JSON.stringify(value)+'\n');}; + const send=value=>{if(!closed)output.write(JSON.stringify(redact(value))+'\n');}; const stop=async()=>{ if(closed)return; closed=true;clearInterval(watch);lines.close(); for(const controller of knowledge.values())controller.abort();knowledge.clear(); @@ -31,6 +32,14 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out if(closed)return; let value;try{if(line.length>2*1024*1024)throw Error();value=JSON.parse(line);}catch{send({type:'fatal',error:'本地消息无效;不会重发'});void stop();return;} if(value?.type==='heartbeat') {send({type:'heartbeat_ack',id:value.id,brokerPid:broker?.child?.pid??null});return;} + if (value?.type === 'auth_revoke') { + if (active && active.config.scope === value.scope) { + const error = authorityFailure(value.category); + broker?.revoke?.(error, false); + active.abort(error); + } + return; + } if(value?.type==='production_pause') { const config=active?.config; if(config?.productProduction===true && value.documentId===config.documentId @@ -57,7 +66,16 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out if(value?.type==='canvas_result') { const task=waiting.get(value.id); if(!task||value.runId!==task.runId||active?.runId!==task.runId)return; - waiting.delete(value.id);clearTimeout(task.timer);value.error?task.reject(BridgeError.from(value.error)):task.resolve(value.value);return; + waiting.delete(value.id);clearTimeout(task.timer); + if (value.error) { + const error = BridgeError.from(value.error); + if (authorityLost(error)) { + broker?.revoke?.(error, false); + active.abort(error); + } + task.reject(error); + } else task.resolve(value.value); + return; } if(value?.type!=='run'||!uuid.test(value.runId||'')||!value.config||typeof value.config!=='object'||Array.isArray(value.config)) {send({type:'fatal',error:'本地消息无效;不会重发'});return;} if(active){if(active.runId!==value.runId)failure(value.runId,'已有运行中的任务,未派发');return;} @@ -66,14 +84,14 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out seen.add(runId); const deadline = config.productProduction === true && Number.isSafeInteger(config.productionDeadline) ? config.productionDeadline * 1000 : null; - const controller = config.productProduction === true ? new AbortController() : null; + const controller = new AbortController(); const abort = error => { controller.abort(error); for (const [id, task] of waiting) { if (task.runId !== runId) continue; waiting.delete(id); clearTimeout(task.timer); - task.reject(new BridgeError(error.message,'cancelled',{dispatched:true})); + task.reject(new BridgeError(error.message,error.category ?? 'cancelled',{dispatched:true})); } }; active={runId,config,abort}; @@ -81,7 +99,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out const timer = deadline === null ? null : setTimeout(expire, Math.max(0, deadline - Date.now())); const call=(action,input)=>new Promise((resolve,reject)=>{ if(closed||active?.runId!==runId){reject(new BridgeError('客户端连接已关闭,原操作需核查','transport_interrupted',{retryable:true}));return;} - if(controller?.signal.aborted){reject(new BridgeError(controller.signal.reason.message,'cancelled'));return;} + if(controller.signal.aborted){reject(new BridgeError(controller.signal.reason.message,controller.signal.reason.category ?? 'cancelled'));return;} if (action === 'pi-delta' || action === 'pi-activity') { send({type:'presentation',runId,action,input}); resolve(); @@ -99,7 +117,12 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out if(!broker){broker=brokerFactory({binary:config.binary,profile:config.profile,project:config.project});identity=next;} } if (deadline !== null && deadline <= Date.now()) expire(); - const result=await runSession(config,call,broker,recovery,controller?.signal); + const result=await runSession(config,call,broker,recovery,controller.signal,error=>{ + if (active?.runId===runId && !controller.signal.aborted) { + send({type:'auth_failure',runId,category:error.category}); + abort(error); + } + }); if(!closed&&active?.runId===runId){for(const [id,task] of waiting)if(task.runId===runId){waiting.delete(id);clearTimeout(task.timer);task.reject(new BridgeError('原会话已结束,操作结果需核查','transport_interrupted',{retryable:true,dispatched:true}));}active=null;send({type:'complete',runId,value:result});} } catch {if(!closed&&active?.runId===runId){for(const [id,task] of waiting)if(task.runId===runId){waiting.delete(id);clearTimeout(task.timer);task.reject(new BridgeError('原会话已结束,操作结果需核查','transport_interrupted',{retryable:true,dispatched:true}));}active=null;failure(runId,controller?.signal.reason?.message??'本地模型桥失败;请核查原请求,不会重发',true);}} finally { if (timer !== null) clearTimeout(timer); } diff --git a/apps/detail-agent-pi/src/desktop-host.mjs b/apps/detail-agent-pi/src/desktop-host.mjs index 5a2db4b3..fcd35092 100644 --- a/apps/detail-agent-pi/src/desktop-host.mjs +++ b/apps/detail-agent-pi/src/desktop-host.mjs @@ -1,5 +1,6 @@ import { CanvasOperations } from './canvas-operations.mjs'; -import { BridgeError } from './bridge-error.mjs'; +import { BridgeError, authorityFailure, authorityLost } from './bridge-error.mjs'; +import { redact } from './credentials.mjs'; import { createInterface } from 'node:readline'; import path from 'node:path'; import { assertPiNodeVersion } from './runtime-policy.mjs'; @@ -28,7 +29,7 @@ async function cli() { const lines = createInterface({ input: process.stdin, crlfDelay: Infinity }); let initial, serial = 0, closed = false; const waiting = new Map(); - const send = value => { if (!closed) process.stdout.write(JSON.stringify(value) + '\n'); }; + const send = value => { if (!closed) process.stdout.write(JSON.stringify(redact(value)) + '\n'); }; const call = (action, input) => new Promise((resolve, reject) => { const id = ++serial; waiting.set(id, { resolve, reject }); send({ type: 'canvas', id, action, input }); @@ -82,14 +83,14 @@ export function bindRecovery(host, recovery, identity) { } }; } -export async function runSession(config, call, sharedBroker, recovery, signal) { +export async function runSession(config, call, sharedBroker, recovery, signal, onAuthorizationLost) { if (config.mode === 'record-production-export') { try { const {recordProductionExport} = await import('./production-goal.mjs'); return await recordProductionExport(config.sessionDir, config.goalId); - } catch(error) { return {error:error.message}; } + } catch(error) { return {error:BridgeError.from(error).message}; } } - let host, broker, store, output; + let host, broker, store, output, atomic; let releaseRecovery; const productionGoal=config.mode==='prompt'&&config.wholeDetail===true&&config.productProduction===true ? {outputId:config.outputId,variantId:config.variantId,requestedOutputs:config.requestedOutputs, @@ -98,18 +99,15 @@ export async function runSession(config, call, sharedBroker, recovery, signal) { const startedAt = performance.now(); const abort = () => { if (host) void host.session.abort().catch(()=>{}); }; try { - signal?.throwIfAborted(); + if (!authorityLost(signal?.reason)) signal?.throwIfAborted(); signal?.addEventListener('abort',abort,{once:true}); - const [{DetailPiAgent},{Native98kBroker},{ProjectStore,atomic},{StdioCanvas},{resolveRules}] = await Promise.all([import('./agent.mjs'),import('./native-bridge.mjs'),import('./store.mjs'),import('./stdio-canvas.mjs'),import('./rules.mjs')]); + const [{DetailPiAgent},{Native98kBroker},storage,{StdioCanvas},{resolveRules}] = await Promise.all([import('./agent.mjs'),import('./native-bridge.mjs'),import('./store.mjs'),import('./stdio-canvas.mjs'),import('./rules.mjs')]); + atomic = storage.atomic; const modelRole=config.mode==='recover'?config.modelRole||'chat':config.wholeDetail?'detail':'chat'; - const bindingConfig={binary:config.binary,profile:config.profile,project:config.project,scope:config.scope,modelRole}; + const bindingConfig={binary:config.binary,profile:config.profile,project:config.project,scope:config.scope,modelRole, + dispatchLease:config.dispatchLease,onAuthorizationLost}; broker=sharedBroker??new Native98kBroker(bindingConfig); - broker.bind(bindingConfig); const brokerStartedAt = performance.now(); - const info = await broker.info(config.mode==='recover'?{original:true,id:config.productionOriginals?.[0]} - :productionGoal&&!config.goalUserEntry?{reuseDetailSelection:true}:undefined); - const brokerReadyAt = performance.now(); - if (info.accountScope !== config.scope) throw Error('账户已切换,未发送请求'); let binding; if(config.ruleCatalog==null&&config.ruleId==null){ binding={brandId:'unconfigured',shopId:'unconfigured',categoryId:'unconfigured',brandName:'未配置',shopName:'未配置',categoryName:'未配置',platform:'native-project',version:'unconfigured-v1',source:'explicit-unconfigured-project-discussion',rules:['当前项目未配置品牌/店铺/品类规则。可以讨论通用思路;不得编造或借用其他品牌规则,产品事实以本项目只读资料为准。']}; @@ -119,7 +117,13 @@ export async function runSession(config, call, sharedBroker, recovery, signal) { const shop = config.ruleCatalog.shops.find(s => s.id === combo.shopId); binding = resolveRules({ brandId: shop.brandId, shopId: shop.id, categoryId: combo.categoryId }, config.ruleCatalog); } - store = await ProjectStore.open(config.root, { scope: info.accountScope, project: config.project }, binding, { continuous:true }); + 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 brokerReadyAt = performance.now(); + if (info.accountScope !== config.scope) throw authorityFailure('scope_changed'); const canvas = new StdioCanvas(call, config.documentId); const usage = []; host = await DetailPiAgent.open({ store, broker, productionGoal, productionSignal:signal, brokerInfo:info, canvas, projectEvidence:config.projectEvidence, documentId:config.documentId, onEvent: event => { @@ -164,15 +168,33 @@ export async function runSession(config, call, sharedBroker, recovery, signal) { outputId:config.outputId, production:config.productProduction===true, }); else result = await host.prompt(config.text, { referenceContent: config.referenceContent, goalContinuation: !!productionGoal&&!config.goalUserEntry }); + signal?.throwIfAborted(); + if (broker.authority?.error) throw broker.authority.error; const pending = (await broker.status()).pending; const reviews = (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() }; } catch (error) { + const authority = [signal?.reason, broker?.authority?.error, error].find(authorityLost); + if (authority) { + onAuthorizationLost?.(authority); + let draftSaved = false; + if (store) { + const draft = {state:'paused', reason:authority.category, documentId:config.documentId, + scope:config.scope, project:config.project, text:config.text, sessionFile:host?.manager.getSessionFile()}; + try { + await atomic(path.join(store.dir, 'authorization-pause.json'), draft); + draftSaved = true; + } 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 (broker) { try { pending = (await broker.status()).pending; unknown = pending.length > 0; } catch { unknown = broker.hasUnconfirmedRequest; } } else if (sharedBroker && sharedBroker.binary===config.binary && sharedBroker.profile===config.profile && sharedBroker.project===config.project && sharedBroker.scope===config.scope) unknown=sharedBroker.hasUnconfirmedRequest; - output = { error:error.message, failure:BridgeError.from(error).wire(), unknown, pending, reposted:false, contextUsage:host?.contextUsage }; + const failure = BridgeError.from(error).wire(); + output = { error:failure.message, failure, unknown, pending, reposted:false, contextUsage:host?.contextUsage }; if (host && productionGoal) { const scope=host.goalRequestScope; const models=pending.filter(request=>request.modelRole==='detail'&&request.detailSlot===scope) diff --git a/apps/detail-agent-pi/src/native-bridge.mjs b/apps/detail-agent-pi/src/native-bridge.mjs index 300c09f5..d7d34d77 100644 --- a/apps/detail-agent-pi/src/native-bridge.mjs +++ b/apps/detail-agent-pi/src/native-bridge.mjs @@ -5,6 +5,7 @@ import { createInterface } from 'node:readline'; import { randomUUID } from 'node:crypto'; import { setTimeout as delay } from 'node:timers/promises'; import path from 'node:path'; +import { BridgeError, authorityFailure, authorityLost } from './bridge-error.mjs'; /** Keep an explicit local upstream exception consistent across Windows casing. */ export function nativeBrokerEnvironment(profile, source = process.env) { @@ -37,24 +38,35 @@ export class Native98kBroker { Object.assign(this, { binary, profile, project, modelRole, invocationHeaders, spawnProcess }); this.potentiallyDispatched = new Set(); this.dispatchScopes = new Map(); + this.authority = {}; } forDetailSlot(slotId) { const worker = new Native98kBroker({binary:this.binary, profile:this.profile, project:this.project, modelRole:this.modelRole, invocationHeaders:this.invocationHeaders, spawnProcess:this.spawnProcess}); worker.scope = this.scope; + worker.authority = this.authority; + worker.dispatchLease = this.dispatchLease; worker.detailSlot = slotId; worker.selectionId = this.selectionId; return worker; } - bind({ binary, profile, project, scope, modelRole = 'chat' }) { + bind({ binary, profile, project, scope, modelRole = 'chat', dispatchLease, onAuthorizationLost }) { if (this.active || this.closed || this.failed) 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) { + this.authority.error = error; + if (notify) this.authority.onAuthorizationLost?.(error); + } + } async open() { if (this.failed) throw this.failed; if (this.closed) throw Error('模型桥已关闭'); @@ -81,11 +93,16 @@ export class Native98kBroker { 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 (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; } if (value.type === 'result' || value.type === 'error') { this.active = null; if (value.type === 'error') { - const error = Error(value.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; @@ -104,14 +121,20 @@ export class Native98kBroker { } async start(method, args = {}, onEvent = () => {}) { if (method !== 'info' && !this.scope) await this.info(); + const authority = this.authority; const run = async () => { + const needsAuthority = !['status','read','finish'].includes(method); + if (authority !== this.authority) throw authorityFailure('scope_changed'); + if (needsAuthority && authority.error) throw authority.error; await this.open(); + if (authority !== this.authority) throw authorityFailure('scope_changed'); + if (needsAuthority && 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({ method, project: this.project, accountScope: this.scope, ...(this.modelRole==='chat'?{}:{modelRole:this.modelRole}), ...(this.detailSlot?{detailSlot:this.detailSlot}:{}), ...args }) + '\n', error => { + 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(); } }); @@ -141,7 +164,11 @@ export class Native98kBroker { status() { return this.start('status'); } async info(args) { const info = await this.start('info', args); - if (this.scope && info.accountScope !== this.scope) throw Error('账户已改变,请切回原账户'); + if (this.scope && info.accountScope !== this.scope) { + const error = authorityFailure('scope_changed'); + this.revoke(error); + throw error; + } this.scope = info.accountScope; if (info.invocationHeaders) this.invocationHeaders = info.invocationHeaders; this.selectionId = info.selectionId ?? undefined; @@ -174,7 +201,7 @@ export class Native98kBroker { this.failed = null; } const abort = () => { - if (this.active?.requestId === id) this.child?.kill(); + if (!this.authority.error && this.active?.requestId === id) this.child?.kill(); }; init.signal?.addEventListener('abort', abort, {once:true}); completed = request().catch(error=>{ diff --git a/apps/detail-agent-pi/src/store.mjs b/apps/detail-agent-pi/src/store.mjs index e0e5d7d0..bd73f11e 100644 --- a/apps/detail-agent-pi/src/store.mjs +++ b/apps/detail-agent-pi/src/store.mjs @@ -3,6 +3,7 @@ import path from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import { createHash, randomUUID } from 'node:crypto'; import { ruleContext, templateConstraints } from './rule-context.mjs'; +import { redact, redactText } from './credentials.mjs'; export const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex'); export async function atomic(file, value) { @@ -10,7 +11,7 @@ export async function atomic(file, value) { const temp = `${file}.${randomUUID()}.tmp`; const handle = await fs.open(temp, 'wx', 0o600); try { - try { await handle.writeFile(JSON.stringify(value, null, 2)); await handle.sync(); } finally { await handle.close(); } + try { await handle.writeFile(JSON.stringify(redact(value), null, 2)); await handle.sync(); } finally { await handle.close(); } const retryDelays = [25, 75, 225]; for (let attempt = 0; ; attempt++) { try { @@ -42,11 +43,20 @@ async function copyIdentical(file, bytes) { if (!stat.isFile() || stat.isSymbolicLink() || !(await fs.readFile(file)).equals(bytes)) throw Error('旧会话迁移目标与原件不一致,请保留文件核查'); } } +function cleanLegacyJsonLines(bytes) { + return Buffer.from(bytes.toString('utf8').split(/(?<=\n)/).map(line => { + if (!line.trim()) return line; + const value = JSON.parse(line); + const safe = JSON.stringify(redact(value)); + return safe === JSON.stringify(value) ? line : safe + (line.endsWith('\n') ? '\n' : ''); + }).join('')); +} export class ProjectStore { static async open(root, identity, binding, { continuous = false } = {}) { if (!/^[a-f0-9]{64}$/.test(identity.scope) || !/^[a-f0-9-]{36}$/i.test(identity.project)) throw Error('项目身份无效'); for (const key of ['brandId', 'shopId', 'categoryId', 'platform', 'version', 'source']) if (typeof binding[key] !== 'string' || !binding[key]) throw Error(`规则缺少 ${key}`); if (!Array.isArray(binding.rules) || binding.rules.length > 100 || binding.rules.some(s => typeof s !== 'string' || s.length > 2000)) throw Error('规则内容无效'); + binding = redact(binding); const dir = path.join(root, identity.scope, identity.project), hash = digest(binding); // Different shop/category/version gets an independent conversation and memory. const ruleDir = path.join(dir, hash); @@ -71,8 +81,17 @@ export class ProjectStore { if(!resolved.startsWith(realLegacy+path.sep)||!resolved.endsWith('.jsonl'))throw Error('旧会话文件不属于当前项目,未迁移'); const bytes=await fs.readFile(resolved),target=path.join(scopeDir,'sessions','legacy-'+previous.bindingHash+'.jsonl'); await fs.mkdir(path.dirname(target),{recursive:true}); - await copyIdentical(target,bytes); - for(const name of ['events.jsonl','recovered-tools.json'])if(await exists(path.join(legacy,name)))await copyIdentical(path.join(scopeDir,name),await fs.readFile(path.join(legacy,name))); + await copyIdentical(target,cleanLegacyJsonLines(bytes)); + for (const name of ['events.jsonl','recovered-tools.json']) { + if (!await exists(path.join(legacy,name))) continue; + const original = await fs.readFile(path.join(legacy,name)); + const safe = name.endsWith('.jsonl') ? cleanLegacyJsonLines(original) : (() => { + const value = JSON.parse(original); + const sanitized = JSON.stringify(redact(value)); + return sanitized === JSON.stringify(value) ? original : Buffer.from(sanitized); + })(); + await copyIdentical(path.join(scopeDir,name),safe); + } await copyIdentical(path.join(scopeDir,'migration.json'),Buffer.from(JSON.stringify({sourceBindingHash:previous.bindingHash,sourceSha256:createHash('sha256').update(bytes).digest('hex'),originalRetained:true},null,2))); // Publish the pointer last, after every required file is durably present. await copyIdentical(path.join(scopeDir,'session.json'),Buffer.from(JSON.stringify({file:target},null,2))); @@ -105,6 +124,7 @@ export class ProjectStore { } async recordUserEvidence(text) { if(typeof text!=='string'||!text.trim()||text.length>6000)throw Error('当前用户证据无效'); + text = redactText(text); await fs.appendFile(path.join(this.memoryDir,'user-evidence.jsonl'),JSON.stringify({...this.identity,bindingHash:this.hash,text,textHash:digest(text),at:Date.now()})+'\n',{mode:0o600}); } async context() { @@ -117,7 +137,7 @@ export class ProjectStore { constraints: templateConstraints(this.binding, options) }; } async appendEvent(event) { - await fs.appendFile(path.join(this.dir, 'events.jsonl'), JSON.stringify({ at: Date.now(), ...event }) + '\n', { mode: 0o600 }); + await fs.appendFile(path.join(this.dir, 'events.jsonl'), JSON.stringify(redact({ at: Date.now(), ...event })) + '\n', { mode: 0o600 }); } async ownsRequest(id) { let text; try { text = await fs.readFile(path.join(this.dir, 'events.jsonl'), 'utf8'); } catch { return false; } diff --git a/apps/detail-agent-pi/test/account-authorization.test.mjs b/apps/detail-agent-pi/test/account-authorization.test.mjs new file mode 100644 index 00000000..0396d12b --- /dev/null +++ b/apps/detail-agent-pi/test/account-authorization.test.mjs @@ -0,0 +1,104 @@ +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { EventEmitter } from 'node:events'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { PassThrough } from 'node:stream'; +import { test } from 'node:test'; +import { SessionManager } from '@earendil-works/pi-coding-agent'; +import { BridgeError } from '../src/bridge-error.mjs'; +import { protectSession } from '../src/credentials.mjs'; +import { runSession } from '../src/desktop-host.mjs'; +import { Native98kBroker } from '../src/native-bridge.mjs'; +import { ProjectStore } from '../src/store.mjs'; +import { cleanup } from './cleanup.mjs'; + +const scope = 'a'.repeat(64); +const nextScope = 'b'.repeat(64); +const binding = {brandId:'brand',shopId:'shop',categoryId:'category',platform:'local',version:'1',source:'fixture',rules:[]}; + +async function fixture(t) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-auth-')); + t.after(() => cleanup(root)); + return {root, profile:root, binary:'fixture', scope, project:randomUUID(), documentId:7}; +} + +test('native HTTP 401 revokes the bound broker and all workers without another dispatch', async t => { + const config = await fixture(t); + const child = new EventEmitter(); + for (const name of ['stdin', 'stdout', 'stderr']) child[name] = new PassThrough(); + child.stdin.once('finish', () => { + child.stdout.end(); + child.stderr.end(); + child.emit('close', 0); + }); + const requests = []; + child.stdin.on('data', bytes => { + requests.push(JSON.parse(bytes)); + child.stdout.write(JSON.stringify({type:'headers',status:401,headers:{}}) + '\n'); + child.stdout.write(JSON.stringify({type:'error',category:'auth_revoked', + error:'Cookie: session=never-log-auth-fixture',dispatched:true}) + '\n'); + }); + const paused = []; + const broker = new Native98kBroker({...config, spawnProcess:()=>child}); + broker.bind({...config,onAuthorizationLost:error=>paused.push(error.wire())}); + const formerWorker = broker.forDetailSlot('detail'); + const round = broker.round(); + const address = 'https://api.vip98k.com/v1/chat/completions'; + const options = {method:'POST',body:'{}'}; + 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(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 { + await formerWorker.close(); + await broker.close(); + } +}); + +test('a rejected authorization refresh saves a paused draft under the original account', async t => { + const config = await fixture(t); + const text = '保留此草稿\nAuthorization: Bearer never-log-draft-fixture'; + let checks = 0; + const broker = {bind() {}, async info() { + checks++; + throw new BridgeError('连接已撤销\nAPI Key: never-log-reply-fixture','auth_revoked'); + }}; + const receipt = await runSession({...config,mode:'prompt',text}, () => assert.fail('canvas dispatch'), broker); + assert.equal(checks, 1); + assert.equal(receipt.phase, 'paused'); + assert.equal(receipt.draftSaved, true); + assert.equal(receipt.failure.category, 'auth_revoked'); + assert.equal(receipt.reposted, false); + assert.doesNotMatch(JSON.stringify(receipt), /never-log-/); + const file = path.join(config.root, scope, config.project, 'conversation-v1', 'authorization-pause.json'); + const draft = JSON.parse(await fs.readFile(file, 'utf8')); + assert.equal(draft.scope, scope); + assert.match(draft.text, /保留此草稿/); + assert.doesNotMatch(JSON.stringify(draft), /never-log-/); + await assert.rejects(fs.stat(path.join(config.root, nextScope)), {code:'ENOENT'}); +}); + +test('late journal data stays in the original account and credentials stay out of Pi files', async t => { + const {root,project} = await fixture(t); + const original = await ProjectStore.open(root, {scope,project}, binding, {continuous:true}); + const current = await ProjectStore.open(root, {scope:nextScope,project}, binding, {continuous:true}); + await original.appendEvent({type:'late_image',candidate:'original-candidate', + diagnostic:'Set-Cookie: id=never-log-cookie-fixture', authorization:'never-log-header-fixture'}); + const session = protectSession(SessionManager.create(original.dir, path.join(original.dir, 'sessions'))); + session.appendMessage({role:'user',timestamp:1,content:'保留说明\nBearer never-log-token-fixture'}); + session.appendMessage({role:'assistant',timestamp:2,content:[{type:'text',text:'API_KEY=never-log-key-fixture'}]}); + const log = await fs.readFile(path.join(original.dir, 'events.jsonl'), 'utf8'); + const transcript = await fs.readFile(session.getSessionFile(), 'utf8'); + assert.match(log, /original-candidate/); + assert.match(transcript, /保留说明/); + assert.doesNotMatch(log + transcript, /never-log-/); + await assert.rejects(fs.stat(path.join(current.dir, 'events.jsonl')), {code:'ENOENT'}); +}); diff --git a/apps/detail-agent-pi/test/desktop-daemon.test.mjs b/apps/detail-agent-pi/test/desktop-daemon.test.mjs index 372c2129..29852853 100644 --- a/apps/detail-agent-pi/test/desktop-daemon.test.mjs +++ b/apps/detail-agent-pi/test/desktop-daemon.test.mjs @@ -146,3 +146,33 @@ test('presentation notifications do not wait for replies and the terminal comman await tick(); assert.equal(frames.at(-1).type,'complete'); }); + +test('account revocation rejects a pending write and ignores its late result after a new scope opens', async t => { + const oldScope = 'account-a', newScope = 'account-b'; + const nextRun = '170ff5d1-43ad-4f24-b9cb-b0c540e01bc3'; + const {frames,send} = daemonFixture(t,{ + runSession:async (config,call) => { + if (config.scope === newScope) return {activeScope:config.scope}; + await assert.rejects(call('pi-edit', {text:'original edit'}), {category:'scope_changed',dispatched:true}); + await assert.rejects(call('pi-image-request', {}), {category:'scope_changed',dispatched:false}); + return {phase:'paused'}; + }, + }); + send({type:'run',runId,config:{scope:oldScope}}); + await tick(); + const edit = frames.find(frame=>frame.action==='pi-edit'); + assert.ok(edit); + send({type:'auth_revoke',scope:newScope,category:'scope_changed'}); + await tick(); + assert.equal(frames.some(frame=>frame.type==='complete'),false); + send({type:'auth_revoke',scope:oldScope,category:'scope_changed'}); + await tick(); + send({type:'run',runId:nextRun,config:{scope:newScope}}); + send({type:'canvas_result',runId,id:edit.id,value:{completed:true}}); + await tick(); + assert.deepEqual(frames.filter(frame=>frame.type==='complete').map(frame=>frame.value), [ + {phase:'paused'}, {activeScope:newScope}, + ]); + assert.equal(frames.filter(frame=>frame.type==='canvas').length,1); + assert.equal(frames.some(frame=>frame.type==='fatal'),false); +}); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs index 7baa9018..3f699bcf 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs @@ -80,7 +80,7 @@ impl Daemon { number => Some(u32::try_from(number.as_u64().ok_or("模型桥身份无效")?).map_err(|_| "模型桥身份无效")?), }; } - Some("canvas" | "presentation" | "complete") if state.ready => { + Some("canvas" | "presentation" | "complete" | "auth_failure") if state.ready => { let (run, sender) = state.active.as_ref().ok_or("本机Agent收到无主回合消息")?; if value["runId"].as_str() != Some(run.as_str()) { return Err("本机Agent回合身份不一致".into()); } sender.send(Ok(value)).map_err(|_| "原回合已关闭")?; @@ -282,6 +282,13 @@ pub(super) fn pause_production(doc: u64, project_identity: &str) { } } +pub(super) fn revoke_scope(scope: &str, category: &str) { + let service = registry().lock().ok().and_then(|registry| registry.service.clone()); + if let Some(service) = service { + let _ = service.send(&json!({"type":"auth_revoke","scope":scope,"category":category})); + } +} + pub(super) fn shutdown() { if let Ok(mut registry) = registry().lock() { registry.mark_shutdown(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 1c795aee..6139ff65 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -88,6 +88,8 @@ mod context_usage; mod prompt_library; #[path = "jiansun_project_file.rs"] mod project_file; +#[path = "jiansun_transfer.rs"] +pub(crate) mod transfer; #[path = "jiansun_projects.rs"] mod projects; #[path = "jiansun_reads.rs"] @@ -391,6 +393,7 @@ struct Backend { http: NetworkClient, origin: String, auth: Value, + access: AccountAccess, models: Vec, model: String, copy_models: Vec, @@ -406,6 +409,52 @@ struct Backend { recovery_serial: Arc>, composer_store: Arc, } + +const AUTH_REVOKED: &str = "授权已失效,制作已暂停;请重新登录"; +const ACCOUNT_CHANGED: &str = "账户已改变,原项目和原请求已保留;请切回原账户"; + +#[derive(Clone, Default)] +struct AccountAccess { + epoch: u64, + current: Arc, + notifications: Option<(mpsc::Sender, egui::Context)>, + dispatch_dir: Option>, +} + +impl AccountAccess { + fn check(&self) -> R<()> { + use std::sync::atomic::Ordering::Acquire; + if self.current.load(Acquire) == self.epoch && self.dispatch_path().is_none_or(|path| path.is_file()) { + Ok(()) + } else { Err(AUTH_REVOKED.into()) } + } + + fn invalidate(&self) -> bool { + use std::sync::atomic::Ordering::{AcqRel, Acquire}; + let changed = self.current.compare_exchange(self.epoch, self.epoch + 1, AcqRel, Acquire).is_ok(); + if changed && let Some(path) = self.dispatch_path() && fs::remove_file(path).is_err() { + log::error!("无法清理已撤销的模型派发许可"); + } + changed + } + + fn renew(&mut self) -> R<()> { + use std::sync::atomic::Ordering::AcqRel; + self.epoch = self.current.fetch_add(1, AcqRel) + 1; + self.publish_dispatch() + } + + fn dispatch_path(&self) -> Option { + self.dispatch_dir.as_ref().map(|dir| dir.path().join(self.epoch.to_string())) + } + + fn publish_dispatch(&self) -> R<()> { + if let Some(path) = self.dispatch_path() { + fs::File::create_new(path).map_err(|_| "无法建立模型派发许可")?; + } + Ok(()) + } +} #[derive(Debug)] struct PortalFailure { state: &'static str, @@ -444,6 +493,7 @@ impl Backend { http, origin, auth, + access: Default::default(), models: vec![], model: String::new(), copy_models: vec![], @@ -465,6 +515,42 @@ impl Backend { fn scope(&self) -> String { self.auth["account"]["id"].as_str().map(|id| hash(&format!("{}|{}", self.origin, id))).unwrap_or("guest".into()) } + fn revoke_access(&self, category: &str) { + if self.access.invalidate() { + let scope = self.scope(); + agent_daemon::revoke_scope(&scope, category); + if let Some((events, ctx)) = &self.access.notifications { + let _ = events.send(Event::Json("auth-fence".into(), Ok(json!({ + "accountId":self.auth["account"]["id"],"origin":self.origin,"category":category + })))); + ctx.request_repaint(); + } + } + } + fn check_dispatch(&self) -> R<()> { self.access.check() } + + fn renew_portal_session(&mut self) -> Result<(), PortalFailure> { + // Desktop grants are reissued through browser OAuth. Revalidate any + // grant already renewed in the system vault under the same account. + let account = self.auth["account"]["id"].clone(); + let renewed = vault(&format!("account:{}", hash(&self.origin))).ok() + .and_then(|entry| entry.get_password().ok()).and_then(|text| serde_json::from_str::(&text).ok()); + let Some(renewed) = renewed.filter(|grant| !account.is_null() && grant["account"]["id"] == account + && grant["access_token"].is_string() && grant["access_token"] != self.auth["access_token"]) else { + return Err(PortalFailure::http(401, None)); + }; + let previous = std::mem::replace(&mut self.auth, renewed); + match self.portal_json("session") { + Ok(value) if value["account"]["id"] == account => { + self.auth["account"] = value["account"].clone(); + Ok(()) + } + _ => { + self.auth = previous; + Err(PortalFailure::http(401, None)) + } + } + } fn bind_composer_draft(&self, doc: u64, dir: &Path, meta: &mut Value) -> R<()> { let project = self.locations.get(&doc).ok_or("项目身份尚未绑定")?; let account = dir.parent().and_then(Path::parent).ok_or("项目路径无效")?; @@ -500,6 +586,7 @@ impl Backend { .send() .map_err(|_| PortalFailure::local("unavailable", "素材库暂时无法连接,本机草稿已保留"))?; let status = r.status().as_u16(); + if status == 401 { self.revoke_access("auth_revoked"); } let (code, v) = body(r, MAX_JSON).map_err(|error| { if status != 200 { PortalFailure::http(status, None) @@ -516,15 +603,29 @@ impl Backend { self.portal_json(path).map_err(|failure| failure.message) } fn validate_connection(&mut self) -> Result<(), PortalFailure> { - let v = self.portal_json("session")?; + let v = match self.portal_json("session") { + Ok(value) => value, + Err(failure) if failure.http_status == Some(401) => { + self.revoke_access("auth_revoked"); + return self.renew_portal_session(); + } + Err(failure) => return Err(failure), + }; if v["account"]["id"] != self.auth["account"]["id"] { + self.revoke_access("scope_changed"); return Err(PortalFailure::local("sign_in_required", "账户状态不一致,请重新授权")); } self.auth["account"] = v["account"].clone(); Ok(()) } fn validate(&mut self) -> R<()> { - self.validate_connection().map_err(|failure| failure.message) + self.check_dispatch()?; + self.validate_connection().map_err(|failure| match failure.state { + "sign_in_required" if failure.http_status == Some(401) => AUTH_REVOKED.into(), + "sign_in_required" if failure.message == "账户状态不一致,请重新授权" => ACCOUNT_CHANGED.into(), + _ => failure.message, + })?; + self.check_dispatch() } fn project_operation(&mut self, input: Value, busy: Arc, events: &mpsc::Sender, ctx: &egui::Context) { use std::sync::atomic::Ordering; @@ -750,12 +851,24 @@ impl Backend { } fn key_catalog(&self, key: &str) -> R> { let response = self.http.get(format!("{UPSTREAM}/v1/models")).bearer_auth(key).send().map_err(|error| catalog_transport_error(&error))?; + if response.status().as_u16() == 401 { return Err("个人Key校验失败(HTTP 401)".into()); } let (status, value) = body(response, MAX_JSON).map_err(|error| format!("98k模型目录读取失败:{error}"))?; if status != 200 { return Err(format!("个人Key校验失败(HTTP {status})")); } crate::jiansun_models::key_models(&value) } + fn check_model_authority(&self, response: &Response, key: &str) -> R<()> { + if response.status().as_u16() != 401 { return Ok(()); } + self.revoke_access("auth_revoked"); + self.refresh_model_authority(key); + Err(AUTH_REVOKED.into()) + } + fn refresh_model_authority(&self, previous: &str) { + let settings = self.settings().ok(); + let key = settings.as_ref().and_then(|value| value["key"].as_str()).unwrap_or(previous); + let _ = self.key_catalog(key); + } fn connection_data(&self, saved: &Value, available: Option<&[String]>) -> Value { let key_saved = saved["key"].as_str().is_some_and(|k| (12..=500).contains(&k.len())); let ready = |chosen: &Value, items: &[Value]| { @@ -780,6 +893,7 @@ impl Backend { if !self.auth.is_null() { match self.validate_connection() { Ok(()) => { + if self.check_dispatch().is_err() { self.access.renew()?; } library_status = "connected"; library_http_status = Some(200); } @@ -851,6 +965,7 @@ impl Backend { }; let mut result = self.connection_data(&saved, available.as_deref()); result["account"] = self.auth["account"].clone(); + result["accountEpoch"] = json!(self.access.epoch); result["origin"] = json!(self.origin); result["libraryStatus"] = json!(library_status); result["libraryHttpStatus"] = json!(library_http_status); @@ -920,6 +1035,12 @@ impl Backend { return Err("素材库授权未完成".into()); } vault(&format!("account:{}", hash(&origin)))?.set_password(&auth.to_string()).map_err(|_| "授权无法写入系统凭据库")?; + if self.auth["access_token"] != auth["access_token"] || self.origin != origin { + self.revoke_access(if self.origin != origin || self.auth["account"]["id"] != auth["account"]["id"] { + "scope_changed" + } else { "auth_revoked" }); + self.access.renew()?; + } write_json(&self.root.join("settings.json"), &json!({"origin":origin}))?; self.origin = origin; self.auth = auth; @@ -937,6 +1058,11 @@ impl Backend { fn bytes(&self, path: &str) -> R> { let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?; let r = self.http.get(format!("{}/api/desktop/{path}", self.origin)).bearer_auth(token).send().map_err(|_| "素材下载连接中断")?; + if r.status().as_u16() == 401 { + self.revoke_access("auth_revoked"); + let _ = self.clone().renew_portal_session(); + return Err(AUTH_REVOKED.into()); + } if !r.status().is_success() { return Err(format!("素材不可读取(HTTP {})", r.status().as_u16())); } @@ -1075,12 +1201,18 @@ impl Backend { if !value["status"].is_string() || changed_revision || meta["syncDirty"] == true { value["status"] = json!("draft"); } + transfer::redact(&mut value); write_json(&dir.join("context.json"), &value)?; - self.remember_project(project)?; + let current_account = self.owners.get(&doc.id.0) == Some(&self.scope()); + if current_account { self.remember_project(project)?; } if let Some(reason) = canvas_problem { return Err(reason); } - let mut receipt = json!({"time":value["time"],"localId":project,"status":value["status"],"project":value["project"],"cloudLink":value["project"],"syncedRevision":value["syncedRevision"],"syncDirty":value["syncDirty"],"projects":self.native_projects()?,"savedPath":dir.join("canvas.pcraft")}); + let mut receipt = json!({"time":value["time"],"localId":project,"status":value["status"],"project":value["project"],"cloudLink":value["project"],"syncedRevision":value["syncedRevision"],"syncDirty":value["syncDirty"],"savedPath":dir.join("canvas.pcraft"), + "localSave":{"state":"saved","revision":revision,"path":dir.join("canvas.pcraft")}}); if activate_view { receipt["activeProductViewRevision"] = active_revision; } - self.bind_composer_draft(doc.id.0, &dir, &mut receipt)?; + if current_account { + receipt["projects"] = json!(self.native_projects()?); + self.bind_composer_draft(doc.id.0, &dir, &mut receipt)?; + } Ok(receipt) } fn deliver_project(&self, doc: &Document, revision: u64, options: &Value, receipt: &mut Value) -> R<()> { @@ -1095,6 +1227,7 @@ impl Backend { let delivery = project_file::save(&dir, doc, options, scope, local, &mut state)?; write_json(&path, &state)?; receipt["projectFile"] = state["projectFile"].clone(); + if !delivery["localSave"].is_null() { receipt["localSave"] = delivery["localSave"].clone(); } receipt["deliveryError"] = delivery["outputError"].clone(); receipt["delivered"] = delivery; Ok(()) @@ -1195,6 +1328,7 @@ impl Backend { if recover && task["keyFingerprint"].as_str().is_some_and(|fingerprint| fingerprint != hash(key)) { return Err("原请求属于另一把Key;请切回原Key只读核查,不会重发".into()); } + if !recover { transfer::redact(&mut task); } let response = if recover { let id = task["requestId"].as_str().filter(|s| Uuid::parse_str(s).is_ok()).ok_or("原请求没有可公开查询的编号;保持待核查,不会重发")?; self.http.get(format!("{UPSTREAM}/api/external/requests/{id}/result")).bearer_auth(key).send() @@ -1210,6 +1344,7 @@ impl Backend { json!({"model":task["model"]["id"],"messages":[{"role":"system","content":system},{"role":"user","content":task["text"]}],"max_tokens":4096,"stream":true}) }; let invocation = pi_runtime::invocation(self, &task["model"])?; + self.check_dispatch()?; task["phase"] = json!("dispatched"); write_json(&file, &task)?; let mut r = self @@ -1234,6 +1369,7 @@ impl Backend { write_json(&file, &task)?; } let status = response.status().as_u16(); + self.check_model_authority(&response, key)?; if status != 200 { return Err(format!("98k未返回可恢复的结果(HTTP {status}),不会重发")); } @@ -1250,7 +1386,7 @@ impl Backend { let anthropic = task["model"]["protocol"] == "anthropic-messages"; let mut v = if is_stream { let result = stream::read(response, anthropic, |content| { - let text = stream::partial_reply(content); + let text = transfer::redact_text(&stream::partial_reply(content)); if !text.is_empty() && text != last_text { task["partialReply"] = json!(text); if last_emit.elapsed() >= Duration::from_millis(45) { @@ -1274,6 +1410,7 @@ impl Backend { } else { body(response, MAX_JSON)?.1 }; + transfer::redact(&mut v); // Persist the actual completed response for this request before interpreting edits. task["response"] = v.clone(); if recover { @@ -1330,13 +1467,15 @@ impl Backend { .bearer_auth(token) .send() .map_err(|_| "素材库暂时无法连接;尚未退出,原草稿已保留")?; - if !r.status().is_success() { + if !r.status().is_success() && r.status().as_u16() != 401 { return Err("授权撤销未完成,请稍后再试".into()); } } + self.revoke_access("scope_changed"); vault(&format!("account:{}", hash(&self.origin)))?.delete_credential().map_err(|_| "本机授权清理未完成")?; self.composer_store.activate(None)?; self.auth = Value::Null; + self.access.renew()?; self.models.clear(); self.state() } @@ -1404,12 +1543,17 @@ impl Backend { "draft" => self.draft(input["doc"].as_u64().ok_or("项目编号无效")?), "product-run-checkpoint" | "product-exit-checkpoint" => { let doc = input["doc"].as_u64().ok_or("项目编号无效")?; - self.ensure_owner(doc)?; let checkpoint = &input["checkpoint"]; + if checkpoint["active"] == true { + self.ensure_owner(doc)?; + self.check_dispatch()?; + } if self.locations.get(&doc).is_none_or(|project| checkpoint["project"] != *project) { return Err("制作任务属于其他项目".into()); } - write_json(&self.project_dir(doc)?.join("production-run.json"), checkpoint)?; + let mut checkpoint = checkpoint.clone(); + transfer::redact(&mut checkpoint); + write_json(&self.project_dir(doc)?.join("production-run.json"), &checkpoint)?; Ok(Value::Null) } "pi-rules" => pi_runtime::rules(self, input), @@ -1599,6 +1743,8 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let internal_requests = tx.clone(); let composer_store = Arc::new(draft_store::Store::default()); let backend_store = composer_store.clone(); + let account_epoch = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let backend_epoch = account_epoch.clone(); std::thread::spawn(move || { let mut backend = match Backend::new(root.join("jiansun")) { Ok(b) => b, @@ -1608,6 +1754,15 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { return; } }; + let lease = tempfile::Builder::new().prefix("xiaoyi-account-").tempdir().map_err(|_| "无法建立模型派发目录".to_owned()) + .and_then(|dir| { backend.access.dispatch_dir = Some(Arc::new(dir)); backend.access.publish_dispatch() }); + if let Err(error) = lease { + let _ = events.send(Event::Json("restore".into(), Err(error))); + ctx.request_repaint(); + return; + } + backend.access.notifications = Some((events.clone(), ctx.clone())); + backend.access.current = backend_epoch; backend.composer_store = backend_store; if let Err(error) = backend.composer_store.activate(Some(backend.scope())) { let _ = events.send(Event::Json("restore".into(), Err(error))); @@ -2012,6 +2167,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { } }); let mut workspace = Workspace::new(tx, results); + workspace.account_epoch = Some(account_epoch); workspace.draft_flush = Some(Arc::new(move |token, text, primary, secondary, generation| composer_store.flush(token, text, primary, secondary, generation))); workspace.pause_production_agent = Some(agent_daemon::pause_production); workspace @@ -2020,6 +2176,92 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { #[cfg(test)] mod tests { use super::*; + + #[test] + fn portal_401_revokes_running_workers_and_retains_the_paused_original_draft() { + let site = TcpListener::bind("127.0.0.1:0").unwrap(); + let origin = format!("http://{}", site.local_addr().unwrap()); + let server = std::thread::spawn(move || { + let (mut socket, _) = site.accept().unwrap(); + let mut request = [0u8; 4096]; + let count = socket.read(&mut request).unwrap(); + assert!(String::from_utf8_lossy(&request[..count]).starts_with("GET /api/desktop/session ")); + let body = r#"{"message":"Authorization: Bearer reflected-test-secret"}"#; + write!(socket, "HTTP/1.1 401 Unauthorized\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap(); + }); + let temp = tempfile::tempdir().unwrap(); + let mut backend = Backend::new(temp.path().to_owned()).unwrap(); + backend.origin = origin; + backend.auth = json!({"account":{"id":"old-account"},"access_token":"original-test-credential"}); + backend.composer_store.activate(Some(backend.scope())).unwrap(); + let (events, observed) = mpsc::channel(); + let ctx = egui::Context::default(); + backend.access.notifications = Some((events.clone(), ctx.clone())); + let mut engine = photocraft_engine::Session::new(); + engine.execute("file.new", json!({"name":"draft","width":40,"height":30})).unwrap(); + let doc = engine.active().unwrap().doc.clone(); + backend.save(doc.clone(), 1, json!({"composer":"未提交编辑"})).unwrap(); + let dir = backend.project_dir(doc.id.0).unwrap(); + let before = backend.clone(); + assert_eq!(backend.validate().unwrap_err(), AUTH_REVOKED); + assert_eq!(before.check_dispatch().unwrap_err(), AUTH_REVOKED); + assert_eq!(backend.validate().unwrap_err(), AUTH_REVOKED, "revoked lease blocks a second request"); + let Event::Json(name, Ok(value)) = observed.recv_timeout(Duration::from_secs(2)).unwrap() else { panic!("missing auth event"); }; + assert_eq!(name, "auth-fence"); + assert_eq!(value["category"], "auth_revoked"); + assert!(!value.to_string().contains("test-secret")); + backend.action("product-run-checkpoint", &json!({"doc":doc.id.0,"checkpoint":{ + "project":backend.locations[&doc.id.0],"active":false,"phase":"paused","reason":"auth_revoked", + "note":"Cookie: client=reflected-test-secret" + }}), &events, &ctx).unwrap(); + assert_eq!(read_json(&dir.join("context.json")).unwrap()["composer"], "未提交编辑"); + let paused = read_json(&dir.join("production-run.json")).unwrap(); + assert_eq!(paused["phase"], "paused"); + assert!(!paused.to_string().contains("reflected-test-secret")); + server.join().unwrap(); + } + + #[test] + fn account_switch_fences_old_dispatch_and_late_image_receipts_settle_in_the_original_project() { + let temp = tempfile::tempdir().unwrap(); + let mut backend = Backend::new(temp.path().to_owned()).unwrap(); + backend.auth = json!({"account":{"id":"old"}}); + backend.access.dispatch_dir = Some(Arc::new(tempfile::tempdir_in(temp.path()).unwrap())); + backend.access.publish_dispatch().unwrap(); + backend.composer_store.activate(Some(backend.scope())).unwrap(); + let mut engine = photocraft_engine::Session::new(); + engine.execute("file.new", json!({"width":40,"height":30})).unwrap(); + let first = engine.active().unwrap().doc.clone(); + backend.save(first.clone(), 1, json!({"composer":"原账户"})).unwrap(); + let original = backend.clone(); + let old_lease = original.access.dispatch_path().unwrap(); + assert!(old_lease.is_file()); + let original_dir = original.project_dir(first.id.0).unwrap(); + let task = Uuid::new_v4().to_string(); + let artifact = original_dir.join("image-jobs").join(&task).join("generated.png"); + backend.revoke_access("scope_changed"); + backend.access.renew().unwrap(); + backend.auth = json!({"account":{"id":"new"}}); + backend.composer_store.activate(Some(backend.scope())).unwrap(); + engine.execute("file.new", json!({"width":40,"height":30})).unwrap(); + let second = engine.active().unwrap().doc.clone(); + backend.save(second.clone(), 1, json!({"composer":"新账户"})).unwrap(); + assert!(original.check_dispatch().is_err()); + assert!(!old_lease.exists()); + assert!(backend.access.dispatch_path().unwrap().is_file()); + assert!(backend.check_dispatch().is_ok()); + fs::create_dir_all(artifact.parent().unwrap()).unwrap(); + fs::write(&artifact, b"original candidate").unwrap(); + images::job_save(&original_dir, &json!({"id":task,"phase":"complete","artifact":artifact, + "accountScope":original.scope(),"localProjectId":original.locations[&first.id.0]})).unwrap(); + backend.save(first, 2, json!({"composer":"迟到的原账户草稿"})).unwrap(); + let new_dir = backend.project_dir(second.id.0).unwrap(); + assert!(!new_dir.join("image-jobs").exists()); + assert_eq!(read_json(&original_dir.join("image-task.json")).unwrap()["accountScope"], original.scope()); + assert_eq!(read_json(&new_dir.join("context.json")).unwrap()["composer"], "新账户"); + assert_eq!(read_json(&backend.dir().join("last-project.json")).unwrap()["id"], backend.locations[&second.id.0]); + assert_eq!(read_json(&original_dir.join("context.json")).unwrap()["composer"], "迟到的原账户草稿"); + } #[test] fn context_presence_survives_atomic_saves_and_rejects_removed_projects() { use std::sync::atomic::{AtomicBool, Ordering}; @@ -2319,6 +2561,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + access: Default::default(), }; let first = b.scope(); b.auth = json!({"account":{"id":"account-b"}}); @@ -2505,6 +2748,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + access: Default::default(), }; b.composer_store.activate(Some(b.scope())).unwrap(); b.bind_new(7); @@ -2535,6 +2779,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + access: Default::default(), }; first.composer_store.activate(Some(first.scope())).unwrap(); let mut s = photocraft_engine::Session::new(); 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 1b57b71c..2187e020 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -2,6 +2,7 @@ //! manufacture an AI plan. Original A/B files and image journals stay intact. use super::{json, Path, Value, R, Uuid, PathBuf, hash, original_project_present, read_json, template_slots, Digest, sync, write_json, fs, Sha256, creation, mpsc, Event, template_workflow, now, Document, Backend, production_profile, slot_canvas, Arc}; use photocraft_ui_egui::jiansun::BridgeFailure; +use super::transfer; const FILE: &str = "canvas-workspace.json"; const CANDIDATE: &str = "canvas-candidate.json"; @@ -2777,6 +2778,7 @@ pub(super) fn read_production_screen(native: &Document, input: &Value) -> R R { + self.check_dispatch()?; self.ensure_owner(native.id.0)?; let dir = self.project_dir(native.id.0)?; let state = load(&dir)?; @@ -2853,6 +2855,7 @@ fn publish_product_generation( }; let size = fs::metadata(&editable).map_err(|error| format!("无法读取成品工程信息:{error}"))?.len(); let sha = file_digest(&editable).map_err(|error| format!("无法核对成品工程内容:{error}"))?; + let delivery = json!({"state":"output_exported","outputState":"exported","outputId":component,"generationId":id}); result["generationId"] = json!(id); result["sourceDocument"] = json!({"path":editable,"format":"pcraft","role":"editable","generationId":id, "revision":document_revision,"reopened":true,"width":reopened.size.width,"height":reopened.size.height, @@ -2860,6 +2863,7 @@ fn publish_product_generation( result["files"] = json!(files); if !split.is_empty() { result["screenFiles"] = json!(split); } result["editable"] = json!(editable); + result["productionDelivery"] = delivery; let _guard = sync::context_guard(); write_json(receipt, result)?; let _ = generation.keep(); @@ -2876,6 +2880,7 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va } let mut result = json!({"doc":doc,"workspaceId":state["id"],"outputId":component,"variantId":variant_id,"files":[]}); if input["complete"] != true { + result["productionDelivery"] = json!({"state":"pending","outputId":component}); result["originals"] = input["originals"].clone(); result["canContinue"] = input["canContinue"].clone(); result["issues"] = input["issues"].clone(); @@ -2884,6 +2889,10 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va return Ok(result); } result["exportAttempted"] = json!(true); + let blocked = |mut result: Value| { + result["productionDelivery"] = json!({"state":"blocked","outputId":component}); + Ok(result) + }; let key = mapping_key(&variant_id, component, None); let editable = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft")); let loaded; @@ -2904,18 +2913,18 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va result["productionProfile"] = production_profile::source(&state["template"], component); if let Some(layer) = production_profile::visible_sample_layer(native, profile) { result["visibleSampleLayer"] = json!(layer.name); - return Ok(result); + return blocked(result); } let missing_text = production_profile::missing_visible_text(native, &meta, profile); if !missing_text.is_empty() { result["missingVisibleText"] = json!(missing_text); - return Ok(result); + return blocked(result); } } if production_profile::fixed_text_policy(profile) { if let Some(layer) = production_profile::unapproved_fixed_text(native, &meta) { result["visibleSampleLayer"] = json!(format!("{}(模板未声明可保留此固定文字)", layer.name)); - return Ok(result); + return blocked(result); } } else { result["warnings"] = json!([production_profile::UNPUBLISHED_FIXED_TEXT]); @@ -2923,13 +2932,13 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va let (missing, image_sources) = export_image_sources(dir, native, state, &meta, component, &variant_id); if !missing.is_empty() { result["missingImages"] = json!(missing); - return Ok(result); + return blocked(result); } let journal = production_audit(dir, state, component, &variant_id, scope)?; let unverified_copy = unverified_export_copy(native, &meta, &journal); if !unverified_copy.is_empty() { result["unverifiedCopy"] = json!(unverified_copy); - return Ok(result); + return blocked(result); } let path = receipt_path(dir, &variant_id, component); let pages = meta["outputs"].as_array().ok_or("没有可导出的画布页面")?; @@ -2977,6 +2986,8 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va { result["goalSyncError"] = json!(error); } + result["productionDelivery"] = json!({"state":if remaining.is_empty() {"completed"} else {"in_progress"}, + "outputState":"exported","outputId":component,"generationId":result["generationId"]}); result["productionStages"] = json!(runnable_stages(state, remaining)); Ok(result) } @@ -3214,11 +3225,13 @@ impl Backend { ) } pub(super) fn production_image_request(&mut self, doc: u64, binding: &Value, events: &mpsc::Sender, ctx: &egui::Context) -> Result { + self.check_dispatch().map_err(|message| BridgeFailure::new("auth_revoked", false, false, message))?; self.ensure_owner(doc)?; let dir = self.project_dir(doc)?; original_project_present(&dir)?; let phase = binding["action"].as_str().ok_or("生图请求动作缺失")?; let request = &binding["request"]; + transfer::no_credentials(request)?; if phase == "prepare" { let mut input = request.clone(); input["doc"] = json!(doc); @@ -3278,6 +3291,7 @@ impl Backend { let snapshot = operation_receipt(self.canvas_workspace_result(doc, &dir).map_err(|error| dispatch_error(error, self))?, Some(receipt.clone()), None); let _ = events.send(Event::Json("slot-append".into(), Ok(snapshot))); ctx.request_repaint(); + self.check_dispatch().map_err(|message| BridgeFailure::new("auth_revoked", false, true, message))?; Ok(receipt) } @@ -3300,6 +3314,9 @@ impl Backend { } pub(super) fn canvas_workspace_action(&mut self, method: &str, input: &Value, events: &mpsc::Sender, ctx: &egui::Context) -> R { + if !matches!(method, "slot-read" | "slot-recover" | "slot-templates" | "slot-adopted") { + self.check_dispatch()?; + } let doc = input["doc"].as_u64().ok_or("请先打开项目")?; self.ensure_owner(doc)?; let dir = self.project_dir(doc)?; @@ -4776,6 +4793,7 @@ mod tests { save(&doc); let result = export_product_stage(&fixture.dir, 1, &state, &input, "test-account").unwrap(); assert_eq!(result["missingImages"], json!(["S01-I01"])); + assert_eq!(result["productionDelivery"]["state"], "blocked"); assert_eq!(result["files"], json!([])); assert!(!receipt_path(&fixture.dir,variant,"detail").exists()); @@ -4824,6 +4842,8 @@ mod tests { save(&doc); let ready = export_product_stage(&fixture.dir, 1, &state, &input, "test-account").unwrap(); assert_eq!(ready["warnings"], json!(["该模板未发布固定文字许可"])); + assert_eq!(ready["productionDelivery"]["outputState"], "exported"); + assert!(ready["localSave"].is_null() && ready["cloudSync"].is_null()); let written = read_json(&receipt_path(&fixture.dir,variant,"detail")).unwrap(); assert_eq!(written["warnings"], ready["warnings"]); assert_eq!(written["blankCopyReasons"][blank_id.to_string()], json!({"field":"S01-T02","reason":"缺少规格时留空"})); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs index 896c4bab..7cba7edb 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs @@ -146,8 +146,10 @@ fn persisted_inputs(c: &Value, input: &Value) -> R<()> { } fn task_save(dir: &Path, t: &Value) -> R<()> { let id = t["id"].as_str().filter(|s| Uuid::parse_str(s).is_ok()).ok_or("创作请求身份无效")?; - write_json(&dir.join("creation-tasks").join(format!("{id}.json")), t)?; - write_json(&dir.join("creation-task.json"), t) + let mut safe = t.clone(); + transfer::redact(&mut safe); + write_json(&dir.join("creation-tasks").join(format!("{id}.json")), &safe)?; + write_json(&dir.join("creation-task.json"), &safe) } pub(super) fn unresolved(dir: &Path) -> R { let f = dir.join("creation-task.json"); @@ -898,6 +900,7 @@ impl Backend { if anthropic { req = req.header("Anthropic-Version", "2023-06-01"); } + self.check_dispatch()?; req.send() }; let response = response.map_err(|error| stream::transport_error(&error))?; @@ -906,6 +909,7 @@ impl Backend { task_save(&dir, &task)?; } let status = response.status().as_u16(); + self.check_model_authority(&response, key)?; let sse = response.headers().get("content-type").and_then(|s| s.to_str().ok()).is_some_and(|s| s.starts_with("text/event-stream")); if status != 200 { task["httpStatus"] = json!(status); @@ -913,6 +917,7 @@ impl Backend { } let mut raw = if sse { stream::read(response, anthropic, |text| { + let text = transfer::redact_text(text); task["partialText"] = json!(text); task_save(&dir, &task)?; let mut event = identity.clone(); @@ -1573,6 +1578,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + access: Default::default(), }; backend.bind_new(1); let dir = backend.project_dir(1).unwrap(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs index 5664b493..4437d38a 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs @@ -229,6 +229,7 @@ fn job_save_locked(dir: &Path, t: &Value, current_only: bool) -> R<()> { let id = t["id"].as_str().filter(|s| Uuid::parse_str(s).is_ok()).ok_or("任务身份无效")?; let archive = dir.join("image-jobs").join(id).join("task.json"); let mut settled = t.clone(); + transfer::redact(&mut settled); if archive.exists() { let existing = read_json(&archive)?; if existing["id"] != t["id"] @@ -617,6 +618,7 @@ impl Backend { if deadline.is_none() { return self.validate(); } + self.check_dispatch()?; let token = self.auth["access_token"].as_str().ok_or("请先在素材库登录")?; let response = self .http @@ -626,11 +628,20 @@ impl Backend { .send() .map_err(|_| "素材库授权校验连接中断")?; let (code, value) = body(response, MAX_JSON)?; - if code != 200 || value["account"]["id"] != self.auth["account"]["id"] { + if code == 401 { + self.revoke_access("auth_revoked"); + let _ = self.renew_portal_session(); + return Err(AUTH_REVOKED.into()); + } + if code == 200 && value["account"]["id"] != self.auth["account"]["id"] { + self.revoke_access("scope_changed"); + return Err(ACCOUNT_CHANGED.into()); + } + if code != 200 { return Err("授权已失效或账户已变化,原请求保留待核查".into()); } self.auth["account"] = value["account"].clone(); - Ok(()) + self.check_dispatch() } pub(super) fn reference_image_preview(&self, input: &Value) -> R> { let doc = input["doc"].as_u64().ok_or("项目身份无效")?; @@ -841,6 +852,7 @@ impl Backend { input["screen"].as_str().unwrap_or("当前图片") ) }; + let prompt = transfer::redact_text(&prompt); protocol::validate_prompt_length(&contract, &prompt)?; let prior = if dir.join("image-task.json").exists() { read_json(&dir.join("image-task.json"))?["id"].clone() } else { Value::Null }; json!({"version":1,"id":job,"doc":id,"revision":input["revision"],"mode":input["mode"],"target":target,"modelId":model_id,"modelKey":choice,"protocol":contract,"prompt":prompt,"references":references,"omittedOptionalLayout":omit_layout,"keyFingerprint":hash(key),"phase":"prepared","requestId":null,"upstreamTaskId":null,"center":input["center"],"accountScope":self.scope(),"localProjectId":self.locations.get(&id),"origin":self.origin,"createdAt":now(),"replacesTaskId":prior,"creationBinding":input["creationBinding"],"slotBinding":input["slotBinding"],"sceneComposite":scene.as_ref().map(|(recipe,_)|recipe)}) @@ -925,6 +937,7 @@ impl Backend { last["status"] = json!(response.status().as_u16()); } job_json(&dir, &diagnostic_file, &diagnostic)?; + self.check_model_authority(&response, key)?; let decoded = body(response, if matches!(kind, "lookup" | "task-status") { 64 * 1024 } else { RESPONSE_BYTES })?; if let Some(last) = diagnostic["attempts"].as_array_mut().and_then(|a| a.last_mut()) { match kind { @@ -992,6 +1005,7 @@ impl Backend { job_save(&dir, &t)?; } let response = slot_post(&dir, &t, || { + self.check_dispatch()?; progress("98k 正在生成图片…", true); client.execute(request).map_err(|_| "生成连接中断,结果待核查;不会重发".into()) })?; @@ -1003,6 +1017,10 @@ impl Backend { t["requestId"] = json!(rid); job_save(&dir, &t)?; } + if let Err(error) = self.check_model_authority(&response, key) { + t["phase"] = json!("failed"); + return Err(error); + } let (code, v) = body(response, RESPONSE_BYTES)?; if !(200..300).contains(&code) { return Err(format!("图片服务暂时未能完成请求(HTTP {code}),原请求待核查;不会重发")); @@ -1018,15 +1036,14 @@ impl Backend { } let uid = t["upstreamTaskId"].as_str().filter(|s| protocol::token(s)).ok_or("任务号无效")?; progress(if recover { "正在等待原任务结果…" } else { "正在生成图片…" }, false); - let (code, v) = body( - self.http + let response = self.http .get(format!("{UPSTREAM}/extensions/v1/tasks/{uid}/result")) .bearer_auth(key) .timeout(recovery_timeout(deadline, Duration::from_secs(30))?) .send() - .map_err(|_| "任务查询连接中断")?, - RESPONSE_BYTES, - )?; + .map_err(|_| "任务查询连接中断")?; + self.check_model_authority(&response, key)?; + let (code, v) = body(response, RESPONSE_BYTES)?; if code == 202 && v["ready"] == false { return Err("原任务仍在生成,可继续查询进度".into()); } @@ -1048,7 +1065,9 @@ impl Backend { if raw["model"].is_string() && raw["model"] != t["modelId"] { return Err("原结果与任务模型不一致,未应用".into()); } - job_bytes(&dir, &raw_file, &serde_json::to_vec(&raw).map_err(|_| "原响应保存失败")?).map_err(|_| "原结果保存失败,请保留原请求号")?; + let mut safe_response = raw.clone(); + transfer::redact(&mut safe_response); + job_bytes(&dir, &raw_file, &serde_json::to_vec(&safe_response).map_err(|_| "原响应保存失败")?).map_err(|_| "原结果保存失败,请保留原请求号")?; let outputs = raw["data"].as_array().filter(|a| a.len() == 1).ok_or("98k图片结果结构无法确认;不会重发")?; let out = &outputs[0]; progress("正在下载并检查图片…", false); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs index be79c074..111a5174 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs @@ -650,7 +650,8 @@ fn rpc_error_frame(error: &str, new_request_preflight: bool) -> Value { "98k连接中断,结果未知;不会重发" => "98k连接中断,结果未知;不会重发", "98k响应中断,结果未知;不会重发" => "98k响应中断,结果未知;不会重发", "原SDK请求只读定位连接中断,保留未知状态;不会重发" => "原SDK请求只读定位连接中断,保留未知状态;不会重发", - "账户已改变,原项目和原请求已保留;请切回原账户" => "账户已改变,原项目和原请求已保留;请切回原账户", + ACCOUNT_CHANGED | AUTH_REVOKED => error, + "个人Key校验失败(HTTP 401)" => AUTH_REVOKED, "原请求待核查或已提交,禁止重发" => "原请求待核查或已提交,禁止重发", "原创作或生图请求待核查,禁止从Agent重新派发" => "原创作或生图请求待核查,禁止从Agent重新派发", "SDK输入过大" => "SDK输入过大", @@ -658,6 +659,13 @@ fn rpc_error_frame(error: &str, new_request_preflight: bool) -> Value { _ => "本地SDK操作失败;请检查原请求状态,勿重发", }; let mut frame = json!({"type":"error","error":safe}); + if safe == ACCOUNT_CHANGED { + frame["category"] = json!("scope_changed"); + frame["dispatched"] = json!(false); + } else if safe == AUTH_REVOKED { + frame["category"] = json!("auth_revoked"); + frame["dispatched"] = json!(!new_request_preflight); + } if new_request_preflight { if safe == "本地SDK操作失败;请检查原请求状态,勿重发" { frame["error"] = json!("客户端准备模型请求失败,本次未发送"); @@ -687,6 +695,12 @@ pub(super) fn run_rpc() -> R<()> { type Selection = (String, String, Value, Value, Value); +fn check_dispatch_lease(value: &Value) -> R<()> { + if value.is_null() || value.as_str().map(Path::new).is_some_and(|path| path.is_absolute() && path.is_file()) { + Ok(()) + } else { Err(AUTH_REVOKED.into()) } +} + fn verified_detail_model(record: &Value, input: &Value, settings: &Value, scope: &str) -> Option { let id = input["selectionId"].as_str()?; Uuid::parse_str(id).ok()?; @@ -718,7 +732,13 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m } let method = input["method"].as_str().ok_or("SDK操作缺失")?; if !scope_matches(method, &input, &backend.scope()) { - return Err("账户已改变,原项目和原请求已保留;请切回原账户".into()); + *selection = None; + return Err(ACCOUNT_CHANGED.into()); + } + if !matches!(method, "status" | "read" | "finish") + && 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"); @@ -824,6 +844,7 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m .map(|(_, _, _, model, _)| model.clone()) }; if let Some(model) = scoped_model { + backend.validate()?; (settings, model, "run") } else { let (settings, mut model, invocation, _) = selected(&mut backend, role)?; @@ -909,6 +930,12 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m } else { request = request.bearer_auth(key); } + if let Err(error) = check_dispatch_lease(&input["dispatchLease"]) { + task["phase"] = json!("not_dispatched"); + write_task(&file, &task)?; + *new_request_preflight = true; + return Err(error); + } request.send() }; let mut raw = Vec::new(); @@ -929,6 +956,18 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m 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); write_task(&file, &task)?; + if status == 401 { + if method == "request" { + task["phase"] = json!("failed"); + task["failureCode"] = json!("auth_revoked"); + write_task(&file, &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 { @@ -940,6 +979,7 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m append_response(&mut raw, part)?; emit(json!({"type":"chunk","data":STANDARD.encode(part)}))?; } + 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)}); @@ -994,14 +1034,16 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m })(); if let Err(e) = result { if matches!(task["phase"].as_str(), Some("failed" | "unavailable")) - && (checked_lookup(&task).is_ok() || task["failureCode"] == "rate_limit_exceeded") { + && (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"); - retain_incomplete(&mut task, &raw, method == "recover")?; - task["lastError"] = json!(&e); + 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); } 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 09e770a1..4777900f 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -394,7 +394,11 @@ pub(super) fn run(b: &mut Backend, input: &Value, method: &str, events: &mpsc::S } let pending = b.locations.get(&doc).map(|project| super::pi::unresolved(&b.dir().join("pi-validation").join(project).join("requests"))).transpose(); let unknown = pending.as_ref().map_or(true, |p| p.as_ref().is_some_and(|p| !p.is_empty())); - json!({"engine":"pi","mode":"prompt","doc":doc,"accountId":b.auth["account"]["id"],"origin":b.origin,"error":error.message,"failure":error.wire(),"unknown":unknown}) + 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}); + super::transfer::redact(&mut reply); + if matches!(error.category, "auth_revoked" | "scope_changed") { reply["phase"] = json!("paused"); } + reply } }; let mut value = canonical_pi_result(b, value)?; @@ -542,6 +546,7 @@ fn take_late_workflow_delegations(replies: &mut Vec> } fn run_inner(b: &mut Backend, input: &Value, method: &str, 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(); @@ -584,6 +589,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender }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, + "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, @@ -643,7 +649,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender let mut detail_image_reads = None; let mut late_workflow_replies = Vec::new(); let start_workflow = |children: &mut WorkflowChildren, delegation: &Value, run: Option<&str>| { - let start = run.ok_or_else(|| "原Agent回合尚未绑定".to_owned()) + let start = b.check_dispatch().and_then(|()| run.ok_or_else(|| "原Agent回合尚未绑定".to_owned())) .and_then(|run| children.start(b, delegation, (run, &project, doc), events, ctx)); if let Err(error) = &start && let Some(method) = delegation["method"].as_str().filter(|method| matches!(*method, "slot-append" | "slot-adopt-prep")) @@ -667,21 +673,33 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender } }; if value["runId"] != daemon_run { return Err("本机Agent回合身份不一致".into()); } - if value["type"] == "presentation" { + if value["type"] == "auth_failure" { + let category = value["category"].as_str().filter(|category| matches!(*category, "auth_revoked" | "scope_changed")) + .ok_or("Agent授权状态无效")?; + b.revoke_access(category); + } else if value["type"] == "presentation" && b.check_dispatch().is_ok() { let action = value["action"].as_str().filter(|action| matches!(*action, "pi-delta" | "pi-activity")) .ok_or("Agent展示动作未授权")?; let (reply, _) = mpsc::channel(); - let _ = events.send(Event::PiAction(action.into(), value["input"].clone(), reply)); + let mut presentation = value["input"].clone(); + presentation.as_object_mut().ok_or("Agent展示参数无效")?.insert("accountEpoch".into(), json!(b.access.epoch)); + let _ = events.send(Event::PiAction(action.into(), presentation, reply)); ctx.request_repaint(); } else if value["type"] == "canvas" { let request_id = value["id"].as_u64().filter(|id| *id > 0).ok_or("Agent请求身份无效")?; if !request_ids.insert(request_id) { return Err("Agent请求身份重复".into()); } let action = value["action"].as_str().filter(|action| allowed_canvas_action(action)).ok_or("Agent本机动作未授权")?; + if let Err(message) = b.check_dispatch() { + let error = BridgeFailure::new("auth_revoked", false, false, message); + daemon.reply(&daemon_run, &value["id"], &json!({"error":error.wire()}))?; + continue; + } let (tx, rx) = mpsc::channel(); let mut native_input = value["input"].clone(); + let fields = native_input.as_object_mut().ok_or("Agent动作参数无效")?; + fields.insert("accountEpoch".into(), json!(b.access.epoch)); if action == "pi-begin" { // Only the trusted native owner establishes product evidence scope. - let fields = native_input.as_object_mut().ok_or("Agent启动参数无效")?; fields.insert("accountScope".into(), json!(b.scope())); fields.insert("project".into(), json!(project)); // The owner forwards the target captured before starting the @@ -810,6 +828,12 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender drop(workflow_children); daemon.end(&daemon_run); turn_guard.complete = true; + if b.check_dispatch().is_err() && result["phase"] != "paused" { + result.as_object_mut().ok_or("Agent结果格式无效")?.retain(|key, _| matches!(key.as_str(), "unknown" | "reposted")); + result["phase"] = json!("paused"); + result["error"] = json!(super::AUTH_REVOKED); + result["failure"] = BridgeFailure::new("auth_revoked", false, false, super::AUTH_REVOKED).wire(); + } result["engine"] = json!("pi"); result["doc"] = json!(doc); result["accountId"] = b.auth["account"]["id"].clone(); @@ -942,6 +966,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + access: Default::default(), }; let doc = 7; let local = Uuid::new_v4().to_string(); 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 ccef36da..cc5c1b32 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs @@ -1,5 +1,6 @@ //! 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}; const CONTEXT: &str = "context.json"; const EXTENSION: &str = "xiaoyi"; @@ -22,15 +23,15 @@ fn project_entry(relative: &Path) -> bool { let Some(root) = parts.next().and_then(|part| part.to_str()) else { return false }; if parts.next().is_none() { return matches!(root, "canvas.pcraft" | "context.json" | "canvas-workspace.json" - | "creation.json" | "composer-draft.json" | ".composer-identity" | "agent-binding.json" - | "template-workflow.json" | "template-slots.json" | "task.json" | "image-task.json" | "production-run.json") - || root.starts_with("material-"); + | "creation.json" | "creation-task.json" | "creation-canvas.pcraft" | "composer-draft.json" | "agent-binding.json" + | "template-workflow.json" | "template-slots.json" | "template-input.json" + | "task.json" | "image-task.json" | "production-run.json") + || root.starts_with("material-") && root.ends_with(".png"); } match root { - "agent" => relative.parent().and_then(Path::file_name).and_then(|n| n.to_str()) == Some("conversation-v1") - && relative.file_name().and_then(|n| n.to_str()).is_some_and(|name| - name == "product-production-strategy.json" || name.starts_with("production-") && name.ends_with(".json")), - "creation-assets" | "template-outputs" | "product-exports" | "composer-attachments" => true, + "creation-assets" | "creation-generated" | "creation-tasks" | "template-outputs" + | "product-exports" | "composer-attachments" | "reference-previews" => + matches!(relative.extension().and_then(|ext| ext.to_str()), Some("json" | "png" | "jpg" | "jpeg" | "webp" | "pcraft")), "image-jobs" => relative.file_name().and_then(|name| name.to_str()).is_some_and(|name| matches!(name, "canvas-candidate.json" | "task.json" | "generated.png" | "failure.json" | "scene-product.png") || name.starts_with("reference-") && name.ends_with(".png")), @@ -64,13 +65,52 @@ 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<()> { + 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); } + if logical == CONTEXT { + let fields = value.as_object_mut().ok_or("工程上下文格式无效")?; + fields.remove("projectFile"); + if !chat { fields.remove("messages"); } + } + if logical == "production-run.json" && value["active"] == true { + value["active"] = json!(false); + value["phase"] = json!("paused"); + } + transfer::no_credentials(&value)?; + write_json(output, &value)?; + } else if let Some((old, new)) = reopen && logical.ends_with(".jsonl") { + let bytes = fs::read(source).map_err(disk)?; + transfer::check_file(logical, &bytes)?; + let mut rebased = Vec::new(); + for line in std::str::from_utf8(&bytes).map_err(disk)?.lines().filter(|line| !line.trim().is_empty()) { + let mut value: Value = serde_json::from_str(line).map_err(disk)?; + rebase_paths(&mut value, old, new); + serde_json::to_writer(&mut rebased, &value).map_err(disk)?; + rebased.push(b'\n'); + } + fs::write(output, rebased).map_err(disk)?; + } else if logical.ends_with(".json") || logical.ends_with(".jsonl") { + let bytes = fs::read(source).map_err(disk)?; + transfer::check_file(logical, &bytes)?; + fs::write(output, bytes).map_err(disk)?; + } else { + if logical.ends_with(".pcraft") { transfer::check_pcraft_file(source)?; } + copy_file(source, output, previous)?; + } + Ok(()) +} + fn copy_project( root: &Path, dir: &Path, target: &Path, previous: Option<&Path>, reopen: Option<(&Path, &Path)>, + policy: &Policy<'_>, selection: &mut Selection, ) -> R<()> { let relative_dir = dir.strip_prefix(root).map_err(disk)?; let published = (relative_dir.starts_with("product-exports") && relative_dir.components().count() == 3 && relative_dir.file_name().is_some_and(|name| name == "generations")).then(|| { - let variant = dir.parent().unwrap(); + let Some(variant) = dir.parent() else { return Vec::new(); }; ["detail.json", "main_images.json", "sku_images.json"].into_iter() .filter_map(|name| read_json(&variant.join(name)).ok()) .filter_map(|receipt| receipt["generationId"].as_str().map(str::to_owned)) @@ -78,45 +118,56 @@ fn copy_project( }); for entry in fs::read_dir(dir).map_err(disk)? { let entry = entry.map_err(disk)?; - if let Some(ids) = &published - && entry.file_name().to_str().is_none_or(|name| !ids.iter().any(|id| id == name)) { continue; } let path = entry.path(); let relative = path.strip_prefix(root).map_err(disk)?; + let logical = relative.to_string_lossy().replace('\\', "/"); + if let Some(ids) = &published + && entry.file_name().to_str().is_none_or(|name| !ids.iter().any(|id| id == name)) { + selection.excluded.push(transfer::exclusion(&logical, "unpublished_output")); + continue; + } let kind = entry.file_type().map_err(disk)?; - if kind.is_dir() && (dir != root || ["creation-assets", "template-outputs", "product-exports", - "composer-attachments", "image-jobs", "agent"].iter().any(|name| relative == Path::new(name))) { - copy_project(root, &path, target, previous, reopen)?; - } else if kind.is_file() && project_entry(relative) { + if kind.is_dir() && (dir != root || ["creation-assets", "creation-generated", "creation-tasks", "template-outputs", + "product-exports", "composer-attachments", "image-jobs", "reference-previews", "agent"].iter().any(|name| relative == Path::new(name))) { + copy_project(root, &path, target, previous, reopen, policy, selection)?; + } else if kind.is_file() { + let allowed = if relative.starts_with("agent") { + policy.agent_file(&logical) + } else if project_entry(relative) { Ok(()) } else { Err("outside_project_checkpoint") }; + if let Err(reason) = allowed { + selection.excluded.push(transfer::exclusion(&logical, reason)); + continue; + } let output = target.join(relative); fs::create_dir_all(output.parent().ok_or("工程资源路径无效")?).map_err(disk)?; - if let Some((old, new)) = reopen - && relative.extension().and_then(|text| text.to_str()) == Some("json") - { - let mut value = read_json(&path)?; - rebase_paths(&mut value, old, new); - write_json(&output, &value)?; - } else if relative == Path::new(CONTEXT) { - let mut context = read_json(&path)?; - if let Some(fields) = context.as_object_mut() { fields.remove("projectFile"); } - write_json(&output, &context)?; - } else { - copy_file(&path, &output, previous.map(|p| p.join(relative)).as_deref())?; - } + checkpoint_file(&path, &output, &logical, previous.map(|p| p.join(relative)).as_deref(), reopen, policy.chat)?; + selection.included.push(logical); + } else { + selection.excluded.push(transfer::exclusion(&logical, "outside_project_checkpoint")); } } Ok(()) } -fn write_project(dir: &Path, file: &Path, manifest: &Value) -> R<()> { +fn write_project(dir: &Path, file: &Path, manifest: &mut Value, policy: &Policy<'_>) -> R<()> { let checkpoint = resource_checkpoint(file, manifest)?; let resource_dir = checkpoint.parent().ok_or("工程资源目录无效")?; fs::create_dir_all(resource_dir).map_err(disk)?; - let previous = read_json(file).ok().filter(|old| old["version"] == 1 && old["localId"] == manifest["localId"] + let previous = read_json(file).ok().filter(|old| matches!(old["version"].as_u64(), Some(1 | 2)) && old["localId"] == manifest["localId"] && old["scope"] == manifest["scope"] && old["resources"] == manifest["resources"]) .and_then(|old| resource_checkpoint(file, &old).ok()) .filter(|previous| previous.is_dir()); let stage = tempfile::tempdir_in(resource_dir).map_err(disk)?; - copy_project(dir, dir, stage.path(), previous.as_deref(), None)?; + let mut selection = Selection::default(); + copy_project(dir, dir, stage.path(), previous.as_deref(), None, policy, &mut selection)?; + if !["canvas.pcraft", CONTEXT].into_iter().all(|required| selection.included.iter().any(|path| path == required)) { + return Err("工程缺少必要的编辑数据,未写入工程包".into()); + } + if !policy.chat { selection.excluded.push(transfer::exclusion("context.json#messages", "chat_history_disabled")); } + selection.excluded.push(transfer::exclusion("pi-validation/requests", "account_local")); + selection.excluded.push(transfer::exclusion("enterprise-templates", "account_local")); + manifest["projectManifest"] = policy.manifest(stage.path(), selection.included, selection.excluded)?; + transfer::no_credentials(manifest)?; fs::rename(stage.path(), &checkpoint).map_err(disk)?; if let Err(error) = write_json(file, manifest) { retire_checkpoint(resource_dir, &checkpoint, &manifest["localId"]); @@ -154,11 +205,15 @@ pub(super) fn save( if options["project"] == true { let snapshot = Uuid::new_v4().to_string(); let name = file.file_stem().and_then(|s| s.to_str()).ok_or("工程名称无效")?; - let manifest = json!({"version":1,"localId":local,"scope":scope,"snapshot":snapshot, + let chat = transfer::explicit_chat(&options["syncChatHistory"])?.unwrap_or_else(|| + context["projectFile"]["path"] == json!(file) && context["projectFile"]["syncChatHistory"] == true); + let policy = Policy { chat, scope, project: local }; + let mut manifest = json!({"version":2,"localId":local,"scope":scope,"snapshot":snapshot, "sourceRoot":dir,"resources":format!("{name} 资源")}); - write_project(dir, &file, &manifest)?; - context["projectFile"] = json!({"path":file,"snapshot":snapshot}); + write_project(dir, &file, &mut manifest, &policy)?; + context["projectFile"] = json!({"path":file,"snapshot":snapshot,"syncChatHistory":chat}); result["path"] = json!(file); + result["localSave"] = json!({"state":"saved","path":file,"manifest":manifest["projectManifest"]}); } if let Some((stage, count)) = staged { let name = file.file_stem().and_then(|s| s.to_str()).ok_or("工程名称无效")?; @@ -172,9 +227,11 @@ pub(super) fn save( Ok(()) => { result["outputs"] = json!(destination); result["count"] = json!(count); + result["artifactExport"] = json!({"state":"exported","path":destination,"count":count}); } Err(error) if result["path"].is_string() => { result["outputError"] = json!(format!("工程已保存,成品文件夹写入失败:{error}")); + result["artifactExport"] = json!({"state":"failed"}); } Err(error) => return Err(disk(error)), }; @@ -188,6 +245,14 @@ fn rebase_paths(value: &mut Value, old: &Path, new: &Path) { Value::String(text) => { if let Ok(relative) = Path::new(text).strip_prefix(old) { *text = new.join(relative).to_string_lossy().into_owned(); + return; + } + let normalized = text.replace('\\', "/"); + let original = old.to_string_lossy().replace('\\', "/"); + if normalized == original { + *text = new.to_string_lossy().into_owned(); + } else if let Some(relative) = normalized.strip_prefix(&original).and_then(|tail| tail.strip_prefix('/')) { + *text = new.join(relative.split('/').collect::()).to_string_lossy().into_owned(); } } Value::Array(items) => items.iter_mut().for_each(|value| rebase_paths(value, old, new)), @@ -201,12 +266,19 @@ pub(super) fn open(file: &Path, projects: &Path, scope: &str) -> R { let manifest = read_json(&file)?; let resources = resource_checkpoint(&file, &manifest)?; if !resources.is_dir() { return Err("找不到工程资源,请把工程文件和资源文件夹放在同一位置".into()); } - if manifest["version"] != 1 { return Err("此小壹工程需要兼容的客户端版本".into()); } + if !matches!(manifest["version"].as_u64(), Some(1 | 2)) { return Err("此小壹工程需要兼容的客户端版本".into()); } + transfer::no_credentials(&manifest)?; if manifest["scope"] != scope { return Err("请切回保存工程时使用的小壹账户".into()); } let id = manifest["localId"].as_str().filter(|id| Uuid::parse_str(id).is_ok()).ok_or("工程编号无效")?; - let old = manifest["sourceRoot"].as_str().map(Path::new).filter(|path| path.is_absolute()).ok_or("工程数据目录无效")?; + let old = manifest["sourceRoot"].as_str().filter(|path| !path.is_empty()).map(Path::new).ok_or("工程数据目录无效")?; let snapshot = manifest["snapshot"].as_str().filter(|id| Uuid::parse_str(id).is_ok()).ok_or("工程版本无效")?; - let checkpoint = json!({"path":file,"snapshot":snapshot}); + let chat = if manifest["version"] == 1 { + true + } else { + transfer::explicit_chat(&manifest["projectManifest"]["policy"]["syncChatHistory"])?.ok_or("工程缺少会话政策")? + }; + let policy = Policy { chat, scope, project: id }; + let checkpoint = json!({"path":file,"snapshot":snapshot,"syncChatHistory":policy.chat}); let destination = projects.join(id); if destination.exists() { let mut context = read_json(&destination.join(CONTEXT))?; @@ -221,7 +293,15 @@ pub(super) fn open(file: &Path, projects: &Path, scope: &str) -> R { } fs::create_dir_all(projects).map_err(disk)?; let stage = tempfile::tempdir_in(projects).map_err(disk)?; - copy_project(&resources, &resources, stage.path(), None, Some((old, &destination)))?; + let mut selection = Selection::default(); + copy_project(&resources, &resources, stage.path(), None, Some((old, &destination)), &policy, &mut selection)?; + if manifest["version"] == 2 { + let restored = policy.manifest(stage.path(), selection.included, selection.excluded)?; + if manifest["projectManifest"]["version"] != 1 || restored["included"] != manifest["projectManifest"]["included"] + || restored["containsPiSession"] != manifest["projectManifest"]["containsPiSession"] { + return Err("工程资源与恢复清单不一致,未导入本机".into()); + } + } let mut context = read_json(&stage.path().join(CONTEXT))?; context["projectFile"] = checkpoint; write_json(&stage.path().join(CONTEXT), &context)?; @@ -266,7 +346,7 @@ mod tests { let file = temp.path().join("选定的位置.xiaoyi"); save(&root, &doc, &json!({"file":file,"project":true}), "guest", &id, &mut context).unwrap(); let manifest = read_json(&file).unwrap(); - assert!(file.metadata().unwrap().len() < 1024); + assert_eq!(manifest["version"], 2); assert!(resource_checkpoint(&file, &manifest).unwrap().join("canvas.pcraft").is_file()); let projects = temp.path().join("new-profile"); assert_eq!(open(&file, &projects, "guest").unwrap(), id); @@ -276,7 +356,7 @@ mod tests { assert_eq!(reopened.size, doc.size); let metadata = read_json(&restored.join(CONTEXT)).unwrap(); assert_eq!(metadata["composer"], context["composer"]); - assert_eq!(metadata["messages"], context["messages"]); + assert!(metadata.get("messages").is_none()); assert_eq!(metadata["projectFile"], context["projectFile"]); let job = restored.join(job.strip_prefix(&root).unwrap()); assert_eq!(fs::read(job.join("generated.png")).unwrap(), b"candidate pixels"); @@ -298,6 +378,58 @@ mod tests { assert_eq!(open(&moved, &temp.path().join("another-profile"), "guest").unwrap(), id); } + #[test] + fn portable_manifest_round_trips_with_and_without_pi_and_rejects_credential_text() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("working"); + let scope = "scope"; + let id = Uuid::new_v4().to_string(); + let conversation = root.join("agent").join(scope).join(&id).join("conversation-v1"); + let session = conversation.join("sessions/turn.jsonl"); + fs::create_dir_all(session.parent().unwrap()).unwrap(); + let doc = Document::new("portable", Size::new(40, 30), ColorMode::Rgb, SampleType::U8); + fs::write(root.join("canvas.pcraft"), photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap()).unwrap(); + let mut context = json!({"localId":id,"messages":[{"text":"可选的对话"}],"composer":"待发送的草稿"}); + write_json(&root.join(CONTEXT), &context).unwrap(); + write_json(&conversation.join("session.json"), &json!({"file":session})).unwrap(); + write_json(&conversation.join("pi-runtime-auth.json"), &json!({"Cookie":"fixture-vault"})).unwrap(); + fs::write(&session, format!("{}\n", json!({"type":"session","cwd":root}))).unwrap(); + for chat in [false, true] { + let file = temp.path().join(format!("portable-{chat}.xiaoyi")); + let options = json!({"file":file,"project":true,"syncChatHistory":chat}); + let saved = save(&root, &doc, &options, scope, &id, &mut context).unwrap(); + assert_eq!(saved["localSave"]["state"], "saved"); + assert!(saved["cloudSync"].is_null() && saved["productionDelivery"].is_null()); + let manifest = read_json(&file).unwrap(); + assert_eq!(saved["localSave"]["manifest"], manifest["projectManifest"]); + assert_eq!(manifest["projectManifest"]["containsPiSession"], chat); + let profile = temp.path().join(format!("clean-{chat}")); + open(&file, &profile, scope).unwrap(); + let destination = profile.join(&id); + assert_eq!(destination.join(session.strip_prefix(&root).unwrap()).exists(), chat); + assert_eq!(read_json(&destination.join(CONTEXT)).unwrap().get("messages").is_some(), chat); + assert!(!destination.join(conversation.strip_prefix(&root).unwrap()).join("pi-runtime-auth.json").exists()); + assert!(!manifest.to_string().contains("fixture-vault")); + if chat { + let pointer = destination.join(conversation.strip_prefix(&root).unwrap()).join("session.json"); + assert_eq!(read_json(&pointer).unwrap()["file"], json!(destination.join(session.strip_prefix(&root).unwrap()))); + fs::remove_file(resource_checkpoint(&file, &manifest).unwrap().join(session.strip_prefix(&root).unwrap())).unwrap(); + assert!(open(&file, &temp.path().join("missing-file-profile"), scope).is_err()); + } + } + fs::write(&session, b"{\"type\":\"message\",\"text\":\"API Key: fixture-leak-123\"}\n").unwrap(); + let blocked = temp.path().join("blocked.xiaoyi"); + let error = save(&root, &doc, &json!({"file":blocked,"project":true,"syncChatHistory":true}), scope, &id, &mut context).unwrap_err(); + assert!(!blocked.exists() && !error.contains("fixture-leak-123")); + + let mut contaminated = doc.clone(); + contaminated.metadata.text.push(("note".into(), "Cookie: session=fixture-canvas-secret".into())); + fs::write(root.join("canvas.pcraft"), photocraft_format::save_to_bytes(&contaminated, &Default::default()).unwrap()).unwrap(); + let blocked_canvas = temp.path().join("blocked-canvas.xiaoyi"); + let error = save(&root, &contaminated, &json!({"file":blocked_canvas,"project":true}), scope, &id, &mut context).unwrap_err(); + assert!(!blocked_canvas.exists() && !error.contains("fixture-canvas-secret")); + } + #[test] fn psd_and_jpg_can_be_saved_without_an_editable_checkpoint() { let temp = tempfile::tempdir().unwrap(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs index 032212dd..94eb1742 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs @@ -658,9 +658,13 @@ mod tests { let remote = json!({"id":Uuid::new_v4().to_string(),"source":"web","revision":3,"deleteBlocked":true,"deleteBlockedReason":"pending_request"}); let dir = b.project_dir(doc.id.0).unwrap(); let mut context = read_json(&dir.join("context.json")).unwrap(); + assert_eq!(context["syncDirty"], true); + // The fixture models a confirmed link to a clean copy of the web project. context["project"] = remote.clone(); + context["syncDirty"] = json!(false); write_json(&dir.join("context.json"), &context).unwrap(); local["cloudLink"] = remote.clone(); + local["syncDirty"] = json!(false); let merged = b.reconcile_projects(vec![local.clone()], vec![remote.clone()], &[]).unwrap(); assert_eq!(merged.len(), 1); assert_eq!(merged[0]["cloudPresent"], true); @@ -669,15 +673,13 @@ mod tests { assert_eq!(b.reconcile_projects(vec![local.clone()], vec![], &[]).unwrap()[0]["cloudPresent"], false); assert!(b.delete_project(&local).unwrap_err().contains("尚未核对")); // A clean linked copy is still protected by an original unknown request. - assert_eq!(context["syncDirty"], false); write_json(&dir.join("task.json"), &json!({"phase":"unknown","requestId":"original"})).unwrap(); let kept = b.reconcile_projects(vec![local.clone()], vec![], std::slice::from_ref(&remote)).unwrap(); assert_eq!(kept.len(), 1); assert_eq!(kept[0]["cloudDeleted"], true); assert_eq!(read_json(&dir.join("task.json")).unwrap()["requestId"], "original"); write_json(&dir.join("task.json"), &json!({"phase":"failed","requestId":"original"})).unwrap(); - // The fixture's first save was clean. Mark a real unsynced edit explicitly - // before testing the separate dirty-draft retention rule. + // Mark an unsynced edit before testing dirty-draft retention. context["syncDirty"] = json!(true); local["syncDirty"] = json!(true); write_json(&dir.join("context.json"), &context).unwrap(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs index 8c2cb68f..c5a6e75d 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs @@ -545,6 +545,7 @@ mod tests { locations: HashMap::new(), last_saved: HashMap::new(), superseded_docs: Default::default(), draft_zip_writer: Default::default(), recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + access: Default::default(), }; let mut cache = Cache { version: 1, prompts: vec![prompt()], operations: vec![] }; let id = cache.prompts[0].id.clone(); @@ -650,6 +651,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + access: Default::default(), }; let input = json!({"accountId":"owner-b","origin":b.origin,"action":"create","title":"标题","body":"正文"}); assert!(action(&mut b, "prompt-library-edit", &input).is_err()); @@ -722,6 +724,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + access: Default::default(), }; let mut cache = Cache { version: 1, ..Default::default() }; edit(&mut cache, &json!({"action":"create","title":"标题","body":"正文"})).unwrap(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs index b4d9e18d..a47d1119 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs @@ -1,6 +1,7 @@ //! Explicit, revision-checked native backup. The portal stores opaque files; all //! preview rendering and session restoration take place on this computer. use super::*; +use super::transfer::{self, Policy, no_credentials}; use base64::engine::general_purpose::STANDARD; use photocraft_doc::LayerContent; use photocraft_geom::Rect; @@ -97,7 +98,7 @@ fn safe_path(s: &str) -> R<&str> { Ok(s) } fn allowed_file(path: &str) -> bool { - let roots = ["agent/", "image-jobs/", "creation-tasks/", "creation-assets/", "creation-generated/", "template-outputs/", "reference-previews/"]; + let roots = ["image-jobs/", "creation-tasks/", "creation-assets/", "creation-generated/", "template-outputs/", "reference-previews/"]; let exact = [ "agent-binding.json", "task.json", @@ -112,40 +113,6 @@ fn allowed_file(path: &str) -> bool { (exact.contains(&path) || roots.iter().any(|p| path.starts_with(p))) && matches!(Path::new(path).extension().and_then(|e| e.to_str()), Some("json" | "jsonl" | "wasm" | "png" | "jpg" | "jpeg" | "webp" | "pcraft")) } -fn no_credentials(value: &Value) -> R<()> { - match value { - Value::Object(map) => { - for (key, value) in map { - let key = key.to_ascii_lowercase(); - if ["authorization", "api_key", "apikey", "access_token", "refresh_token", "password", "secretkey"].contains(&key.as_str()) - || (key == "key" && value.as_str().is_some_and(|s| s.starts_with("sk-"))) - { - return Err("项目文件含连接凭据,未上传;请移除该文件中的凭据后再同步".into()); - } - no_credentials(value)?; - } - } - Value::Array(items) => { - for item in items { - no_credentials(item)?; - } - } - _ => {} - } - Ok(()) -} -fn check_text(path: &str, bytes: &[u8]) -> R<()> { - if path.ends_with(".json") { - let value: Value = serde_json::from_slice(bytes).map_err(|_| "项目JSON损坏,尚未同步")?; - no_credentials(&value)?; - } else if path.ends_with(".jsonl") { - let text = std::str::from_utf8(bytes).map_err(|_| "Agent会话编码无效,尚未同步")?; - for line in text.lines().filter(|line| !line.trim().is_empty()) { - no_credentials(&serde_json::from_str::(line).map_err(|_| "Agent会话记录不完整,请保留原文件")?)?; - } - } - Ok(()) -} fn collect_files(base: &Path, path: &Path, prefix: &str, depth: usize, files: &mut Vec, total: &mut u64) -> R<()> { if !path.exists() { return Ok(()); @@ -178,7 +145,7 @@ fn collect_files(base: &Path, path: &Path, prefix: &str, depth: usize, files: &m return Err("会话附件超过256MiB或2048项,尚未同步".into()); } let bytes = fs::read(path).map_err(|_| "会话文件无法读取")?; - check_text(&relative, &bytes)?; + transfer::check_file(&logical, &bytes)?; *total = total.saturating_add(bytes.len() as u64); files.push(json!({"path":logical,"sha256":digest(&bytes),"data":STANDARD.encode(bytes)})); } @@ -187,9 +154,12 @@ fn collect_files(base: &Path, path: &Path, prefix: &str, depth: usize, files: &m struct BackupSource { path: PathBuf, entry: Value } -fn collect_backup_sources(base: &Path, path: &Path, prefix: &str, depth: usize, files: &mut Vec, total: &mut u64) -> R<()> { +fn collect_backup_sources(base: &Path, path: &Path, prefix: &str, files: &mut Vec, total: &mut u64, + policy: &Policy<'_>, excluded: &mut Vec) -> R<()> { if !path.exists() { return Ok(()); } - if depth > 12 { return Err("会话目录层级过多,尚未同步".into()); } + 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(()); } 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()); @@ -197,16 +167,29 @@ fn collect_backup_sources(base: &Path, path: &Path, prefix: &str, depth: usize, if meta.is_dir() { let mut entries = fs::read_dir(path).map_err(|_| "会话目录无法读取")?.collect::, _>>().map_err(|_| "会话目录无法读取")?; entries.sort_by_key(|entry| entry.file_name()); - for entry in entries { collect_backup_sources(base, &entry.path(), prefix, depth + 1, files, total)?; } + for entry in entries { collect_backup_sources(base, &entry.path(), prefix, files, total, policy, excluded)?; } } else if meta.is_file() { - let relative = path.strip_prefix(base).map_err(|_| "项目路径无效")?.to_string_lossy().replace('\\', "/"); + let relative = relative.to_string_lossy().replace('\\', "/"); let logical = format!("{prefix}{relative}"); + if prefix == "project/" { + let allowed = if relative.starts_with("agent/") { policy.agent_file(&relative) } + else if allowed_file(&relative) { Ok(()) } else { Err("outside_sync_scope") }; + if let Err(reason) = allowed { + if !matches!(relative.as_str(), "context.json" | "canvas.pcraft" | "cloud-sync.json") { + excluded.push(transfer::exclusion(&logical, reason)); + } + return Ok(()); + } + } + if prefix == "requests/" && (!relative.ends_with(".json") || relative.contains('/')) { + excluded.push(transfer::exclusion(&logical, "outside_sync_scope")); + return Ok(()); + } safe_path(&logical)?; - if prefix == "project/" && !allowed_file(&relative) { return Ok(()); } - if prefix == "requests/" && (!relative.ends_with(".json") || relative.contains('/')) { return Ok(()); } if files.len() >= FILES_LIMIT || total.saturating_add(meta.len()) > SESSION_FILES_LIMIT { return Err("项目附件超过1GiB或2048项,尚未同步".into()); } if meta.len() == 0 { - check_text(&relative, &[])?; + if relative.ends_with(".pcraft") { return Err("项目画布为空,尚未备份".into()); } + transfer::check_file(&logical, &[])?; files.push(BackupSource { path: path.to_owned(), entry: json!({"path":logical,"sha256":digest(&[]),"size":0,"data":""}) }); return Ok(()); } @@ -214,7 +197,7 @@ fn collect_backup_sources(base: &Path, path: &Path, prefix: &str, depth: usize, let inline_size = files.iter().filter(|file| file.entry["source"].is_null()).filter_map(|file| file.entry["size"].as_u64()).sum::(); if inline_size.saturating_add(meta.len()) > BACKUP_LIMIT { return Err("会话附件超过256MiB,尚未同步".into()); } let bytes = fs::read(path).map_err(|_| "会话文件无法读取")?; - check_text(&relative, &bytes)?; + transfer::check_file(&logical, &bytes)?; *total = total.saturating_add(bytes.len() as u64); files.push(BackupSource { path: path.to_owned(), entry: json!({"path":logical,"sha256":digest(&bytes),"size":bytes.len(),"data":STANDARD.encode(bytes)}) }); return Ok(()); @@ -578,9 +561,11 @@ impl Backend { value["status"] = json!(state); value["syncDirty"] = json!(true); write_json(&dir.join("context.json"), &value)?; - Ok(json!({"doc":id,"status":state,"revision":value["revision"],"projects":self.native_projects()?})) + Ok(json!({"doc":id,"status":state,"revision":value["revision"],"accountId":self.auth["account"]["id"], + "origin":self.origin,"projectState":{"state":state},"projects":self.native_projects()?})) } fn put_sync_json(&self, id: &str, value: &Value) -> R { + self.check_dispatch()?; let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?; let response = self .http @@ -589,6 +574,7 @@ impl Backend { .json(value) .send() .map_err(|_| "云同步结果未确认,本机文件和同步身份已保留;请刷新核对")?; + self.check_cloud_authority(response.status().as_u16())?; let (code, value) = body(response, MAX_JSON)?; if code != 200 { return Err(request_error(code)); @@ -603,6 +589,7 @@ impl Backend { .bearer_auth(token) .send() .map_err(|_| "云端状态暂时无法核对,本机草稿保留")?; + self.check_cloud_authority(response.status().as_u16())?; let (code, value) = body(response, MAX_JSON)?; if code == 404 { Ok(None) @@ -613,6 +600,7 @@ impl Backend { } } fn upload_native(&self, id: &str, path: &Path, sha: &str, size: u64) -> R<()> { + self.check_dispatch()?; let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?; let file = fs::File::open(path).map_err(|_| "本机同步文件无法读取")?; let response = self @@ -626,12 +614,20 @@ impl Backend { .body(reqwest::blocking::Body::new(file)) .send() .map_err(|_| "文件上传中断,本机项目保留;可重新同步,已存相同内容不会重复占空间")?; + self.check_cloud_authority(response.status().as_u16())?; let (code, value) = body(response, MAX_JSON)?; if code != 200 || value["sha256"] != sha { return Err(request_error(code)); } Ok(()) } + fn check_cloud_authority(&self, status: u16) -> R<()> { + if status != 401 { return Ok(()); } + self.revoke_access("auth_revoked"); + let _ = self.clone().renew_portal_session(); + Err(request_error(status)) + } + pub(super) fn sync_project(&mut self, input: &Value) -> R { let id = input["doc"].as_u64(); let local_id = if let Some(local) = input["localId"].as_str() { @@ -675,24 +671,40 @@ impl Backend { let canvas = stage.join("canvas.pcraft"); fs::copy(dir.join("canvas.pcraft"), &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(|_| "本机工程读取失败,旧草稿保留")?; if state == "completed" && doc.layers.is_empty() { return Err("空白画布不能标记完结,请先完成详情页内容".into()); } let rectangles = screen_rects(&doc)?; let mut files = Vec::new(); + let mut excluded = Vec::new(); let mut total = 0; - collect_backup_sources(&dir, &dir, "project/", 0, &mut files, &mut total)?; + let scope = self.scope(); + let policy = Policy { chat: transfer::explicit_chat(&input["syncChatHistory"])?.unwrap_or(false), scope: &scope, project: &local_id }; + collect_backup_sources(&dir, &dir, "project/", &mut files, &mut total, &policy, &mut excluded)?; let requests = self.dir().join("pi-validation").join(&local_id).join("requests"); - collect_backup_sources(&requests, &requests, "requests/", 0, &mut files, &mut total)?; + collect_backup_sources(&requests, &requests, "requests/", &mut files, &mut total, &policy, &mut excluded)?; + for file in files.iter().filter(|file| file.entry["source"].is_string()) { + transfer::check_pcraft_file(&file.path)?; + } + if !policy.chat { excluded.push(transfer::exclusion("project/context.json#messages", "chat_history_disabled")); } + let included = files.iter().filter_map(|file| file.entry["path"].as_str().map(str::to_owned)) + .chain(["project/canvas.pcraft".into(), "project/context.json".into()]).collect(); + let sync_manifest = policy.manifest(&dir, included, excluded)?; let conversation = recovery_summary(&dir, &requests)?; + no_credentials(&json!(conversation))?; let backup_version = if files.iter().any(|file| file.entry["source"].is_string()) { 2 } else { 1 }; - let backup = json!({"version":backup_version,"localId":local_id,"accountScope":self.scope(),"oldProjectRoot":dir.to_string_lossy(),"files":files.iter().map(|file|file.entry.clone()).collect::>()}); + let backup = json!({"version":backup_version,"localId":local_id,"accountScope":scope,"oldProjectRoot":dir.to_string_lossy(),"syncManifest":sync_manifest,"files":files.iter().map(|file|file.entry.clone()).collect::>()}); + no_credentials(&backup)?; write_json(&stage.join("session-backup.json"), &backup)?; let mut snapshot = context.clone(); - for key in ["doc", "path", "time", "cloudSyncedAt", "syncedRevision", "syncDirty", "cloudLink"] { + for key in ["doc", "path", "time", "projectFile", "cloudSyncedAt", "syncedRevision", "syncDirty", "cloudLink"] { snapshot.as_object_mut().ok_or("项目上下文无效")?.remove(key); } + if !policy.chat { + snapshot.as_object_mut().ok_or("项目上下文无效")?.remove("messages"); + } let previous_project = context["project"].clone(); snapshot["project"] = json!({}); for key in ["document", "materialReferences"] { @@ -736,6 +748,7 @@ impl Backend { let bytes = fs::read(&creation.path).map_err(|_| "创作资料备份无效")?; document["creation"] = super::creation::cloud_creation(&serde_json::from_slice::(&bytes).map_err(|_| "创作资料备份格式无效")?)?; } + no_credentials(&document)?; let source_web = if linked["source"] == "web" { linked["id"].clone() } else { linked["sourceWebId"].clone() }; if cloud_revision > 0 || pending["id"] == cloud_id { if let Some(remote) = self.cloud_snapshot(&cloud_id)? { @@ -744,7 +757,7 @@ impl Backend { let rev = remote["revision"].as_u64().ok_or("云端版本无效")?; let context = finish_sync(&dir, &cloud_id, rev, revision, state, &source_web, &identity)?; return Ok( - json!({"doc":id,"revision":revision,"localId":local_id,"cloudLink":context["project"],"cloudRevision":rev,"syncedRevision":revision,"syncDirty":context["syncDirty"],"status":context["status"],"accountId":self.auth["account"]["id"],"origin":self.origin,"projects":self.projects()?,"reconciled":true}), + json!({"doc":id,"revision":revision,"localId":local_id,"cloudLink":context["project"],"cloudRevision":rev,"syncedRevision":revision,"syncDirty":context["syncDirty"],"status":context["status"],"accountId":self.auth["account"]["id"],"origin":self.origin,"reconciled":true,"cloudSync":{"state":"synced","revision":rev,"manifest":sync_manifest}}), ); } if cloud_revision == 0 && remote["document"]["native"]["documentSource"].is_null() { @@ -792,6 +805,7 @@ impl Backend { } let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?; for (source, bytes) in previews { + self.check_dispatch()?; let response = self .http .put(format!("{}/api/desktop/projects/desktop/{cloud_id}/assets/{source}", self.origin)) @@ -800,6 +814,7 @@ impl Backend { .body(bytes) .send() .map_err(|_| "预览上传中断,本机项目保留")?; + self.check_cloud_authority(response.status().as_u16())?; let (code, _) = body(response, MAX_JSON)?; if code != 200 { return Err(request_error(code)); @@ -815,7 +830,7 @@ impl Backend { let context = finish_sync(&dir, &cloud_id, remote_revision, revision, state, &source_web, &identity)?; write_json(&pending_file, &json!({"id":cloud_id,"revision":remote_revision,"localRevision":revision,"phase":"complete"}))?; Ok( - json!({"doc":id,"revision":revision,"localId":local_id,"cloudLink":context["project"],"cloudRevision":remote_revision,"syncedRevision":revision,"syncDirty":context["syncDirty"],"status":context["status"],"accountId":self.auth["account"]["id"],"origin":self.origin,"projects":self.projects()?}), + json!({"doc":id,"revision":revision,"localId":local_id,"cloudLink":context["project"],"cloudRevision":remote_revision,"syncedRevision":revision,"syncDirty":context["syncDirty"],"status":context["status"],"accountId":self.auth["account"]["id"],"origin":self.origin,"cloudSync":{"state":"synced","revision":remote_revision,"manifest":sync_manifest}}), ) } fn native_bytes(&self, id: &str, source: &str, size: u64, sha: &str) -> R> { @@ -830,6 +845,7 @@ impl Backend { .timeout(Duration::from_secs(300)) .send() .map_err(|_| "工程下载中断,本机项目保留")?; + self.check_cloud_authority(response.status().as_u16())?; if response.status().as_u16() != 200 { return Err(request_error(response.status().as_u16())); } @@ -931,6 +947,13 @@ impl Backend { return Err("会话备份账户或项目不一致".into()); } let files = backup["files"].as_array().filter(|v| v.len() <= FILES_LIMIT).ok_or("会话备份清单无效")?; + let scope = self.scope(); + let sync_manifest = &backup["syncManifest"]; + let chat = if sync_manifest.is_null() { true } else { + transfer::explicit_chat(&sync_manifest["policy"]["syncChatHistory"])?.ok_or("云工程缺少会话政策")? + }; + let policy = Policy { chat, scope: &scope, project: &source_local_id }; + no_credentials(&backup)?; let request_target = account.join("pi-validation").join(&local_id).join("requests"); if request_target.exists() && existing.is_none() { return Err("本机已有此项目原请求日志,未覆盖;请先保留并核对原项目".into()); @@ -954,7 +977,11 @@ impl Backend { return Err("备份文件重复".into()); } let relative = if let Some(p) = name.strip_prefix("project/") { - if !allowed_file(p) { + let agent = p.starts_with("agent/") && if sync_manifest.is_null() { + // V1/V2 backups that predate the explicit policy used the old path contract. + matches!(Path::new(p).extension().and_then(|ext| ext.to_str()), Some("json" | "jsonl" | "wasm" | "png" | "jpg" | "jpeg" | "webp" | "pcraft")) + } else { policy.agent_file(p).is_ok() }; + if !allowed_file(p) && !agent { return Err("备份文件不在白名单".into()); } p @@ -976,7 +1003,8 @@ impl Backend { if total > limit || digest(&bytes) != file["sha256"] { return Err("会话备份校验失败".into()); } - check_text(relative, &bytes)?; + transfer::check_file(name, &bytes)?; + if relative.ends_with(".pcraft") { transfer::check_pcraft(&bytes)?; } let bytes = restored_bytes(relative, &bytes, old_root, &new_root)?; let target = staging.join(relative); if let Some(parent) = target.parent() { @@ -984,6 +1012,15 @@ impl Backend { } photocraft_format::atomic_write(&target, &bytes).map_err(|_| "会话恢复未完成,本机旧文件保留")?; } + if !sync_manifest.is_null() { + let included = seen.into_iter().chain(["project/canvas.pcraft".into(), "project/context.json".into()]).collect(); + let restored = policy.manifest(&staging, included, Vec::new())?; + if sync_manifest["version"] != 1 || restored["included"] != sync_manifest["included"] + || restored["containsPiSession"] != sync_manifest["containsPiSession"] + || !policy.chat && context.get("messages").is_some() { + return Err("同步清单与实际恢复文件不一致".into()); + } + } if let Some(existing) = &existing { // Keep terminal original request journals active as well as in // the rollback copy. Differing records require explicit review. @@ -1005,6 +1042,7 @@ impl Backend { } } photocraft_format::atomic_write(&staging.join("canvas.pcraft"), data.get("canvas.pcraft").ok_or("工程文件缺失")?).map_err(|_| "工程写入失败")?; + transfer::check_pcraft(data.get("canvas.pcraft").ok_or("工程文件缺失")?)?; let mut doc = photocraft_format::load_path(&staging.join("canvas.pcraft")).map_err(|_| "云工程格式不可读取,未替换旧项目")?; doc.id = photocraft_doc::DocId::fresh(); context["doc"] = json!(doc.id.0); @@ -1445,7 +1483,9 @@ mod tests { assert!(no_credentials(&json!({"nested":{"apiKey":"hidden"}})).is_err()); assert!(no_credentials(&json!({"keyFingerprint":"hash","requestId":"original","phase":"unknown"})).is_ok()); assert!(!allowed_file("settings.json")); - assert!(allowed_file("agent/a/b/sessions/session.jsonl")); + assert!(!allowed_file("agent/a/b/sessions/session.jsonl")); + assert!(no_credentials(&json!({"text":"服务返回 Authorization: Bearer test-secret"})).is_err()); + assert!(no_credentials(&json!({"text":"连接 Cookie=session=secret"})).is_err()); assert!(allowed_file("creation-tasks/task.json")); assert!(allowed_file("canvas-workspace.json")); assert!(allowed_file("image-jobs/00000000-0000-4000-8000-000000000001/canvas-candidate.json")); @@ -1472,7 +1512,8 @@ mod tests { fs::File::create(&file).unwrap().set_len(BACKUP_LIMIT + 1).unwrap(); let mut sources = Vec::new(); let mut total = 0; - collect_backup_sources(&dir, &dir, "project/", 0, &mut sources, &mut total).unwrap(); + let policy = Policy { chat: false, scope: "scope", project: "project" }; + collect_backup_sources(&dir, &dir, "project/", &mut sources, &mut total, &policy, &mut Vec::new()).unwrap(); assert_eq!(total, BACKUP_LIMIT + 1); assert_eq!(sources.len(), 1); assert_eq!(sources[0].path, file); @@ -1483,6 +1524,31 @@ mod tests { fs::remove_dir_all(&dir).unwrap(); } #[test] + fn sync_defaults_to_production_journals_and_validates_explicit_pi_opt_in() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path(); + let conversation = dir.join("agent/scope/project/conversation-v1"); + let session = conversation.join("sessions/turn.jsonl"); + write_json(&conversation.join("session.json"), &json!({"file":session})).unwrap(); + write_json(&conversation.join("production-detail-blue.json"), &json!({"state":"pending"})).unwrap(); + write_json(&conversation.join("events.jsonl"), &json!({"event":"private local diagnostics"})).unwrap(); + fs::create_dir_all(session.parent().unwrap()).unwrap(); + fs::write(&session, b"{\"text\":\"Bearer fixture-auth-secret\"}\n").unwrap(); + let mut policy = Policy { chat: false, scope: "scope", project: "project" }; + let (mut files, mut excluded, mut total) = (Vec::new(), Vec::new(), 0); + collect_backup_sources(dir, dir, "project/", &mut files, &mut total, &policy, &mut excluded).unwrap(); + assert_eq!(files.len(), 1); + let included = vec![files[0].entry["path"].as_str().unwrap().to_owned()]; + let manifest = policy.manifest(dir, included, excluded).unwrap(); + assert_eq!(manifest["containsPiSession"], false); + assert_eq!(manifest["policy"]["syncChatHistory"], false); + assert!(manifest["excluded"].as_array().unwrap().iter().any(|item| item["reason"] == "chat_history_disabled")); + assert!(manifest["excluded"].as_array().unwrap().iter().any(|item| item["reason"] == "agent_private")); + policy.chat = true; + let error = collect_backup_sources(dir, dir, "project/", &mut Vec::new(), &mut 0, &policy, &mut Vec::new()).err().unwrap(); + assert!(!error.contains("fixture-auth-secret")); + } + #[test] fn real_native_file_and_unknown_session_round_trip_without_a_model_post() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let origin = format!("http://{}", listener.local_addr().unwrap()); @@ -1491,7 +1557,7 @@ mod tests { let server = std::thread::spawn(move || { let mut uploaded = HashMap::new(); let mut revision = 0; - for _ in 0..14 { + for _ in 0..12 { let (mut socket, _) = listener.accept().unwrap(); let (head, payload) = read_request(&mut socket); assert!(head.to_ascii_lowercase().contains("authorization: bearer fixture-token")); @@ -1540,14 +1606,22 @@ mod tests { fs::create_dir_all(dir.join("template-outputs")).unwrap(); fs::copy(dir.join("canvas.pcraft"), dir.join("template-outputs/edited.pcraft")).unwrap(); write_json(&dir.join("creation.json"), &json!({"version":1,"revision":2,"width":1440,"brief":{"source":"upload","name":"真实资料备份","brandId":"","brandName":"","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})).unwrap(); - let session = dir.join("agent").join(b.scope()).join(&b.locations[&did]).join("binding").join("session.jsonl"); + let conversation = dir.join("agent").join(b.scope()).join(&b.locations[&did]).join("conversation-v1"); + let session = conversation.join("sessions/session.jsonl"); fs::create_dir_all(session.parent().unwrap()).unwrap(); fs::write(&session, format!("{{\"type\":\"session\",\"cwd\":{}}}\n", serde_json::to_string(&dir.to_string_lossy()).unwrap())).unwrap(); + write_json(&conversation.join("session.json"), &json!({"file":session})).unwrap(); + write_json(&conversation.join("pi-runtime-auth.json"), &json!({"Cookie":"secret"})).unwrap(); let requests = b.dir().join("pi-validation").join(&b.locations[&did]).join("requests"); write_json(&requests.join("original.json"), &json!({"id":"original","requestId":"customer-original","phase":"unknown","keyFingerprint":"hash-only"})) .unwrap(); - let response = b.sync_project(&json!({"doc":did,"revision":7,"status":"draft"})).unwrap(); + let response = b.sync_project(&json!({"doc":did,"revision":7,"status":"draft","syncChatHistory":true})).unwrap(); assert_eq!(response["syncedRevision"], 7); + assert_eq!(response["cloudSync"]["state"], "synced"); + assert_eq!(response["cloudSync"]["manifest"]["containsPiSession"], true); + assert!(response["cloudSync"]["manifest"]["excluded"].as_array().unwrap().iter() + .any(|entry| entry["path"].as_str().unwrap().ends_with("pi-runtime-auth.json"))); + assert!(response["localSave"].is_null() && response["productionDelivery"].is_null()); let cloud = remote.lock().unwrap().clone(); assert_eq!(cloud["document"]["version"], 3); let mut other = fixture(&origin); @@ -1566,6 +1640,7 @@ mod tests { assert!(super::super::projects::idle(&restored_dir).is_err()); 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()); assert!(other.restore_native_project(&cloud).unwrap_err().contains("未覆盖")); server.join().unwrap(); fs::remove_dir_all(&b.root).unwrap(); 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 4b5b1971..5885e4a5 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_template_workflow.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_template_workflow.rs @@ -356,6 +356,9 @@ impl Backend { Ok(json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"workflow":workflow,"creation":c,"pending":workflow["pending"]})) } pub(super) fn slot_action(&mut self, method: &str, input: &Value, events: &mpsc::Sender, ctx: &egui::Context) -> R { + if !matches!(method, "slot-read" | "slot-recover" | "slot-templates" | "slot-adopted") { + self.check_dispatch()?; + } if matches!(method, "slot-skeleton" | "slot-append" | "slot-adopt-prep" | "slot-edit-prep" | "slot-adopted" | "slot-templates" | "slot-product-export" | "slot-product-view") || matches!(method, "slot-read" | "slot-recover" | "slot-reuse") && self.project_dir(input["doc"].as_u64().ok_or("请先打开项目")?)?.join("canvas-workspace.json").is_file() diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_transfer.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_transfer.rs new file mode 100644 index 00000000..dce63709 --- /dev/null +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_transfer.rs @@ -0,0 +1,217 @@ +//! Data that can leave the account's working directory. +use super::{Path, R, Value, json}; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use regex::Regex; +use std::collections::HashMap; +use std::sync::LazyLock; + +const CREDENTIAL_ERROR: &str = "项目资料含连接凭据,未写入备份"; + +static CREDENTIAL_TEXT: LazyLock = LazyLock::new(|| { + #[allow(clippy::expect_used)] + Regex::new(concat!( + r#"(?i)\b(?:authorization|(?:set[-_ ]?)?cookie|x[-_ ]?api[-_ ]?key|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|password|secret[-_ ]?key)["']?\s*[:=]\s*[^\r\n]+"#, + r#"|\bbearer[ \t]+[a-z0-9._~+/=-]{4,}"#, + r#"|\b(?:sk-(?:proj-)?|dcs_|dca_)[a-z0-9_-]{16,}"#, + )).expect("constant credential pattern") +}); + +fn credential_key(key: &str) -> bool { + let key: String = key.chars().filter(|c| !matches!(c, '-' | '_' | ' ')).flat_map(char::to_lowercase).collect(); + matches!(key.as_str(), "authorization" | "cookie" | "setcookie" | "apikey" | "xapikey" + | "accesstoken" | "refreshtoken" | "password" | "secretkey" | "credentials" | "privatekey" | "token" | "composerdrafttoken") +} + +fn credential_field(key: &str, value: &Value) -> bool { + credential_key(key) || CREDENTIAL_TEXT.is_match(key) + || key.eq_ignore_ascii_case("key") && value.as_str().is_some_and(|text| text.starts_with("sk-")) +} + +pub(crate) fn redact_text(text: &str) -> String { + CREDENTIAL_TEXT.replace_all(text, "[已脱敏]").into_owned() +} + +pub(super) fn redact(value: &mut Value) { + match value { + Value::String(text) => { + if let std::borrow::Cow::Owned(safe) = CREDENTIAL_TEXT.replace_all(text.as_str(), "[已脱敏]") { + *text = safe; + } + } + Value::Array(values) => values.iter_mut().for_each(redact), + Value::Object(fields) => { + fields.retain(|key, value| !credential_field(key, value)); + fields.values_mut().for_each(redact); + } + _ => {} + } +} + +pub(super) fn no_credentials(value: &Value) -> R<()> { + match value { + Value::String(text) if CREDENTIAL_TEXT.is_match(text) => return Err(CREDENTIAL_ERROR.into()), + Value::Array(items) => for item in items { no_credentials(item)?; }, + Value::Object(fields) => for (key, item) in fields { + if credential_field(key, item) { + return Err(CREDENTIAL_ERROR.into()); + } + no_credentials(item)?; + }, + _ => {} + } + Ok(()) +} + +pub(super) fn check_wire(bytes: &[u8]) -> R<()> { + let text = std::str::from_utf8(bytes).map_err(|_| "模型响应编码无效")?; + if CREDENTIAL_TEXT.is_match(text) { return Err(CREDENTIAL_ERROR.into()); } + if let Ok(value) = serde_json::from_str(text) { no_credentials(&value)?; } + let mut deltas = HashMap::<(&str, u64), String>::new(); + for line in text.lines().filter_map(|line| line.strip_prefix("data:")) { + let Ok(value) = serde_json::from_str::(line.trim_start()) else { continue }; + no_credentials(&value)?; + let delta = &value["delta"]; + let index = value["index"].as_u64().or(value["output_index"].as_u64()).unwrap_or(0); + for (kind, part) in [("text", delta["text"].as_str()), ("thinking", delta["thinking"].as_str()), + ("tool", delta["partial_json"].as_str()), ("responses", delta.as_str())] { + if let Some(part) = part { deltas.entry((kind, index)).or_default().push_str(part); } + } + for choice in value["choices"].as_array().into_iter().flatten() { + for kind in ["content", "reasoning_content"] { + if let Some(part) = choice["delta"][kind].as_str() { + deltas.entry((kind, choice["index"].as_u64().unwrap_or(0))).or_default().push_str(part); + } + } + for tool in choice["delta"]["tool_calls"].as_array().into_iter().flatten() { + if let Some(part) = tool["function"]["arguments"].as_str() { + deltas.entry(("arguments", tool["index"].as_u64().unwrap_or(0))).or_default().push_str(part); + } + } + } + } + for content in deltas.into_values() { + if CREDENTIAL_TEXT.is_match(&content) { return Err(CREDENTIAL_ERROR.into()); } + if let Ok(value) = serde_json::from_str(&content) { no_credentials(&value)?; } + } + Ok(()) +} + +pub(super) fn check_pcraft(bytes: &[u8]) -> R<()> { + let manifest = photocraft_format::read_manifest(bytes).map_err(|_| "工程画布清单不可读取")?; + if manifest.document.metadata.text.iter().any(|(name, _)| credential_key(name)) { + return Err(CREDENTIAL_ERROR.into()); + } + no_credentials(&serde_json::to_value(manifest).map_err(|_| "工程画布清单无效")?) +} + +pub(super) fn check_file(path: &str, bytes: &[u8]) -> R<()> { + if path.ends_with(".json") { + let value: Value = serde_json::from_slice(bytes).map_err(|_| "项目JSON损坏,尚未备份")?; + no_credentials(&value)?; + if path.starts_with("requests/") { + for item in [&value["raw"], &value["partialRaw"], &value["recovery"]["raw"]] { + if let Some(encoded) = item.as_str() { + check_wire(&STANDARD.decode(encoded).map_err(|_| "原请求响应编码无效")?)?; + } + } + } + } else if path.ends_with(".jsonl") { + let text = std::str::from_utf8(bytes).map_err(|_| "Agent会话编码无效,尚未备份")?; + for line in text.lines().filter(|line| !line.trim().is_empty()) { + no_credentials(&serde_json::from_str::(line).map_err(|_| "Agent会话记录不完整,请保留原文件")?)?; + } + } + Ok(()) +} + +pub(super) struct Policy<'a> { + pub(super) chat: bool, + pub(super) scope: &'a str, + pub(super) project: &'a str, +} + +pub(super) fn explicit_chat(value: &Value) -> R> { + if value.is_null() { return Ok(None); } + 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(); + match parts.as_slice() { + ["agent", scope, project, "conversation-v1", name] if *scope == self.scope && *project == self.project => { + if *name == "product-production-strategy.json" || production_journal(name) { + Ok(()) + } else if *name == "session.json" { + if self.chat { Ok(()) } else { Err("chat_history_disabled") } + } else { + Err("agent_private") + } + } + ["agent", scope, project, "conversation-v1", "sessions", name] + if *scope == self.scope && *project == self.project && name.ends_with(".jsonl") => + { + if self.chat { Ok(()) } else { Err("chat_history_disabled") } + } + _ => Err("agent_private"), + } + } + + pub(super) fn manifest(&self, stage: &Path, mut included: Vec, mut excluded: Vec) -> R { + let prefix = format!("agent/{}/{}/conversation-v1/", self.scope, self.project); + let pointer = format!("{prefix}session.json"); + let paths = || included.iter().map(|path| path.strip_prefix("project/").unwrap_or(path)); + let has_session = paths().any(|path| path == pointer); + if has_session { + let value = super::read_json(&stage.join(&pointer))?; + let name = value["file"].as_str().and_then(|file| file.rsplit(['/', '\\']).next()).ok_or("工程会话指针无效")?; + let session = format!("{prefix}sessions/{name}"); + if !paths().any(|path| path == session) { + return Err("工程会话缺少当前记录".into()); + } + } else if paths().any(|path| path.starts_with(&format!("{prefix}sessions/"))) { + return Err("工程会话缺少当前记录指针".into()); + } + included.sort(); + excluded.sort_by(|a, b| a["path"].as_str().cmp(&b["path"].as_str())); + let value = json!({"version":1,"policy":{"syncChatHistory":self.chat}, + "containsPiSession":has_session,"included":included,"excluded":excluded}); + no_credentials(&value)?; + Ok(value) + } +} + +fn production_journal(name: &str) -> bool { + let Some(name) = name.strip_prefix("production-").and_then(|name| name.strip_suffix(".json")) else { return false }; + ["detail-", "main_images-", "sku_images-"].iter().any(|prefix| name.strip_prefix(prefix) + .is_some_and(|variant| !variant.is_empty() && variant.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_')))) +} + +pub(super) fn exclusion(path: &str, reason: &str) -> Value { + json!({"path":redact_text(path),"reason":reason}) +} + +pub(super) fn check_pcraft_file(path: &Path) -> R<()> { + let bytes = photocraft_format::read_file(path).map_err(|_| "工程画布文件无法读取")?; + check_pcraft(&bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn detects_a_credential_split_across_saved_provider_delta_frames() { + let wire = concat!( + "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Bearer \"}}]}\n\n", + "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"fixture-cross-frame-secret\"}}]}\n\n", + ); + assert!(check_wire(wire.as_bytes()).is_err()); + } +} diff --git a/apps/detail-photocraft/apps/photocraft/src/logging.rs b/apps/detail-photocraft/apps/photocraft/src/logging.rs index f5f014a3..a307affd 100644 --- a/apps/detail-photocraft/apps/photocraft/src/logging.rs +++ b/apps/detail-photocraft/apps/photocraft/src/logging.rs @@ -352,7 +352,8 @@ impl log::Log for AppLogger { return; } let thread = std::thread::current(); - let line = format_line(×tamp(SystemTime::now()), record.level(), thread.name().unwrap_or("?"), record.target(), &record.args().to_string()); + let message = crate::jiansun_backend::transfer::redact_text(&record.args().to_string()); + let line = format_line(×tamp(SystemTime::now()), record.level(), thread.name().unwrap_or("?"), record.target(), &message); if self.stderr { let _ = std::io::stderr().write_all(line.as_bytes()); } @@ -621,11 +622,13 @@ mod tests { let path = logger.attach_dir(&dir).expect("attach"); assert_eq!(path, dir.join(LOG_FILE)); record(log::Level::Warn, "wgpu_hal::vulkan", "a real warning"); + record(log::Level::Warn, "photocraft::jiansun", "gateway returned Cookie: session=fixture-log-secret"); record(log::Level::Debug, "photocraft", "below info"); let text = read(&path); assert!(text.contains(" INFO [") && text.contains("photocraft::app_dirs: settings directory\n"), "{text}"); assert!(text.contains("wgpu_hal::vulkan: a real warning\n"), "{text}"); assert!(!text.contains("too chatty") && !text.contains("below info"), "{text}"); + assert!(text.contains("gateway returned [已脱敏]") && !text.contains("fixture-log-secret"), "{text}"); assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("photocraft_gpu").build())); assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build())); let _ = std::fs::remove_dir_all(&dir); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index d9be1f94..5258af07 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -1010,6 +1010,8 @@ pub struct Workspace { pub pause_production_agent: Option, loaded_draft: Option, pub draft_flush: Option, + pub account_epoch: Option>, + accepted_account_epoch: u64, composer_drafts: composer_drafts::State, allow_apply: bool, preview: Option<(Value, egui::TextureHandle)>, @@ -1495,6 +1497,8 @@ impl Workspace { product_checkpoint: Value::Null, production_exit: None, pause_production_agent: None, + account_epoch: None, + accepted_account_epoch: 0, loaded_draft: None, draft_flush: None, composer_drafts: composer_drafts::State::default(), @@ -2512,6 +2516,8 @@ impl Workspace { self.requested_previews.clear(); self.stream_reply.clear(); self.handover(); + self.pi_run = None; + self.pi_binding = Value::Null; self.ready_image = None; self.project_covers.clear(); self.cover_loading.clear(); @@ -2520,6 +2526,7 @@ impl Workspace { self.delete_error.clear(); } self.account = v["account"].clone(); + if let Some(epoch) = v["accountEpoch"].as_u64() { self.accepted_account_epoch = epoch; } if let Some(origin) = v["origin"].as_str() { self.origin = origin.into(); } @@ -2895,6 +2902,22 @@ impl Workspace { fn receive_json_success(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, v: Value, live_image_request: bool) { match method { + "auth-fence" if v["accountId"] == self.account["id"] && v["origin"] == self.origin => { + self.with_product_target(app, |w, app| { + w.pause_for_authorization(&v["category"]); + if let Some(state) = app.session.active().filter(|state| w.loaded_draft == Some(state.doc.id.0)) { + w.save_project_draft(state, ctx); + } + }); + if v["category"] == "auth_revoked" { + self.receive_library_status(&json!({"libraryStatus":"sign_in_required","libraryHttpStatus":401, + "libraryMessage":"授权已失效,制作已暂停;请重新登录"})); + self.model_ready = false; + self.image_ready = false; + self.copy_ready = false; + self.note("授权已失效,制作已暂停"); + } + } "slot-product-export" => self.production_export_received(app, &v), "slot-skeleton" if v["productionPreparation"] == true => { let current = app.session.active().filter(|state| v["doc"] == state.doc.id.0); @@ -2916,7 +2939,13 @@ impl Workspace { } name if name.starts_with("slot-") => self.receive_json_slot(app, name, v), name if name.starts_with("creation-") => self.receive_creation_ui(app, name, &v), - "project-sync" | "project-state" => creation::sync_received(self, app, &v), + "project-sync" => creation::sync_received(self, app, &v), + "project-state" if v["accountId"] == self.account["id"] && v["origin"] == self.origin + && v["doc"].as_u64() == app.session.active().map(|state| state.doc.id.0) => { + self.project_context["status"] = v["projectState"]["state"].clone(); + self.sync_dirty = true; + if let Some(items) = v["projects"].as_array() { self.merge_project_receipt(app, items); } + } "login-url" => { if let Some(url) = v.as_str() && let Some(open) = &app.services.open_url @@ -3386,13 +3415,17 @@ impl Workspace { canvas_workspace::observe_canvas_input(ctx); self.observe_startup_interaction(ctx); } - self.with_product_target(app, |w, app| { - if let Some((meta, adopted)) = w.poll_canvas_adoption(app, ctx, painting) { - w.finish_adoption_receipt(app, &meta, adopted); - } - }); - // Settle owned native apply receipts before manual-edit detection. - agent_native::settle_jobs(self, app); + if self.authority_active() { + self.with_product_target(app, |w, app| { + if let Some((meta, adopted)) = w.poll_canvas_adoption(app, ctx, painting) { + w.finish_adoption_receipt(app, &meta, adopted); + } + }); + // Settle owned native apply receipts before manual-edit detection. + agent_native::settle_jobs(self, app); + } else { + self.agent_native.cancel(); + } self.professional_sync(app); self.enforce_canvas_scope(app); self.project_open_locals = self.live_project_locals(app); @@ -3447,7 +3480,7 @@ impl Workspace { } if !self.tick_context(app, ctx) { return; } let current = app.session.active().map(|s| (s.doc.id.0, s.revision)); - self.tick_pending_edits(app, ctx, current); + if self.authority_active() { self.tick_pending_edits(app, ctx, current); } self.creation_autosave(app, ctx); if painting && (self.busy.is_some() || self.saving.is_some()) { ctx.request_repaint_after(Duration::from_millis(100)); @@ -3518,6 +3551,10 @@ impl Workspace { fn receive_event(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, event: Event) { match event { Event::PiAction(method, input, reply) => { + if !self.authority_active() || input["accountEpoch"].as_u64().is_some_and(|epoch| epoch != self.accepted_account_epoch) { + let _ = reply.send(Err(BridgeFailure::new("auth_revoked", false, false, "授权已失效,原操作未应用"))); + return; + } if self.production_exit.is_some() { let _ = reply.send(Err(BridgeFailure::new("cancelled", false, false, "客户端正在退出,原操作可在重新打开后核查"))); return; @@ -3550,6 +3587,7 @@ impl Workspace { } } Event::SlotAdopt { bytes, meta } => { + if !self.authority_active() { return; } if meta["purpose"] == "professional-edit" { self.professional_image_received(app, bytes, meta); } else if let Some((meta, adopted)) = self.canvas_adopt(app, bytes, meta) { self.finish_adoption_receipt(app, &meta, adopted); @@ -3804,6 +3842,10 @@ impl Workspace { } else if status != "connected" { self.library_authorization_enabled = None; } } } + fn authority_active(&self) -> bool { + self.account_epoch.as_ref().is_none_or(|epoch| + epoch.load(std::sync::atomic::Ordering::Acquire) == self.accepted_account_epoch) + } fn needs_library_login(&self) -> bool { self.library_status == "sign_in_required" || self.account.is_null() && !self.library_blocked() } @@ -3818,6 +3860,7 @@ impl Workspace { fn set_library_issue(&mut self, error: &str) -> bool { let state = match error { "请先在素材库登录" | "账户状态不一致,请重新授权" | + "授权已失效,制作已暂停;请重新登录" | "素材库授权已过期或被撤销,请重新连接;本机作品已保留" => "sign_in_required", "当前账户没有素材库访问权限,请核对账户或联系管理员;本机作品已保留" => "forbidden", "素材库尚未开放客户端连接,请由管理员恢复服务开关;本机作品已保留" => "disabled", diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs index 02a8cea7..6e08f7d3 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs @@ -663,6 +663,7 @@ pub(super) fn sync_received(w: &mut Workspace, app: &PhotocraftApp, value: &Valu if let Some(items) = value["projects"].as_array() { w.merge_project_receipt(app, items); } + w.project_refresh_requested = true; w.creation_progress = if w.sync_dirty { "云端已保存该版本,当前仍有新修改" } else { "已同步" }.into(); } // The import worker reports a final receipt rather than intermediate bytes; @@ -783,7 +784,10 @@ impl Workspace { } pub(super) fn sync_action(&mut self, app: &PhotocraftApp, method: &str, mut input: Value) { if method == "project-sync" && input["status"] != "completed" { - if let Err(error) = self.request_current_sync(app) { self.error = error.clone(); self.project_list_error = error; } + if let Err(error) = self.request_current_sync(app, input["syncChatHistory"] == true) { + self.error = error.clone(); + self.project_list_error = error; + } return; } if self.busy.is_some() || self.saving.is_some() || self.project_operation_pending() { @@ -820,9 +824,15 @@ impl Workspace { && self.project_operation["accountId"] == self.account["id"] && self.project_operation["origin"] == self.origin && self.current_sync_item(app).is_some_and(|item| item["id"] == self.project_operation["projectId"]); let label = if self.project_operation_pending() {"正在处理…"} else if sync_failed {"同步失败"} else if changed {"云同步"} else {"已同步"}; - let hint = if sync_failed { self.project_operation["message"].as_str().unwrap_or("同步未完成,请查看我的项目") } else { "备份工程、资料和对话到当前素材库账户" }; + let chat_option = ui.scope_id().with(("cloud-chat-history", self.origin.as_str(), + self.account["id"].as_str(), app.session.active().map(|state| state.doc.id.0))); + let mut chat = ui.ctx().data(|data| data.get_temp::(chat_option)).unwrap_or(false); + if ui.add_enabled(idle && changed, egui::Checkbox::new(&mut chat, "同步对话")).changed() { + ui.ctx().data_mut(|data| data.insert_temp(chat_option, chat)); + } + let hint = if sync_failed { self.project_operation["message"].as_str().unwrap_or("同步未完成,请查看我的项目") } else { "备份工程和资料到当前素材库账户" }; if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Secondary, idle && changed && !self.creation_dirty).on_hover_text(hint).clicked() { - self.sync_action(app, "project-sync", json!({"status":"draft"})); + self.sync_action(app, "project-sync", json!({"status":"draft","syncChatHistory":chat})); } if stitch_ui::action_button(ui, "完结", stitch_ui::ButtonRole::Primary, idle && !self.unknown && !self.creation_dirty).clicked() { self.sync_confirm = true; @@ -835,7 +845,7 @@ impl Workspace { } if stitch_ui::action_button(ui, "完结并同步", stitch_ui::ButtonRole::Primary, idle).clicked() { self.sync_confirm = false; - self.sync_action(app, "project-sync", json!({"status":"completed"})); + self.sync_action(app, "project-sync", json!({"status":"completed","syncChatHistory":chat})); } }); }); 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 42f24815..af243fb5 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 @@ -216,8 +216,14 @@ fn image_linked_copy(doc: &photocraft_doc::Document, slot_id: &Value) -> Vec, method: &str, input: &Value, private: bool) -> Result { + if !w.authority_active() { + return Err(BridgeFailure::new("auth_revoked", false, false, "授权已失效,原操作未应用")); + } if matches!(method, "pi-production-open" | "pi-image-request" | "pi-workflow-execute" | "pi-detail-copy-fields" | "pi-detail-copy-apply" | "pi-product-screen") && !private { return Err("工作流执行仅允许当前本机Agent会话".into()); } if method == "pi-begin" { + if w.library_http_status == Some(401) { + return Err(BridgeFailure::new("auth_revoked", false, false, "授权已失效,制作已暂停;请重新登录")); + } if (input["accountId"].is_string() && input["accountId"] != w.account["id"]) || (input["origin"].is_string() && input["origin"] != w.origin) { return Err("画布与模型账户不一致".into()); } @@ -783,6 +789,25 @@ mod tests { (w, app, input) } + #[test] + fn an_auth_epoch_change_rejects_a_queued_write_before_the_account_event() { + use std::sync::{Arc, atomic::{AtomicU64, Ordering}}; + let (mut w, mut app, mut input) = activity_fixture(); + let epoch = Arc::new(AtomicU64::new(0)); + w.account_epoch = Some(epoch.clone()); + w.allow_apply = true; + input["accountEpoch"] = json!(0); + epoch.store(1, Ordering::Release); + let (reply, result) = mpsc::channel(); + let ctx = egui::Context::default(); + w.receive_event(&mut app, &ctx, super::super::Event::PiAction("pi-edit".into(), input, reply)); + assert_eq!(result.recv().unwrap().unwrap_err().category, "auth_revoked"); + let change = json!({"category":"auth_revoked","accountId":w.account["id"],"origin":w.origin}); + w.receive_event(&mut app, &ctx, super::super::Event::Json("auth-fence".into(), Ok(change))); + assert!(!w.allow_apply && w.pi_write_blocked && w.agent_effects_paused); + assert_eq!(w.library_http_status, Some(401)); + } + #[test] fn public_pi_action_cannot_expose_private_workflow_delegation() { let (mut w, mut app, mut input) = activity_fixture(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs index 0d53267b..f478a7c6 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs @@ -882,6 +882,19 @@ impl Workspace { self.handover(); } + pub(super) fn pause_for_authorization(&mut self, category: &Value) { + if let Some(run) = self.product_production.as_ref() { + let mut input = Self::production_checkpoint_request(run, false); + input["checkpoint"]["phase"] = json!("paused"); + input["checkpoint"]["reason"] = category.clone(); + let _ = self.tx.send(Request::Action("product-run-checkpoint".into(), input)); + } + self.product_checkpoint = Value::Null; + self.handover(); + self.pi_write_blocked = true; + self.agent_effects_paused = true; + } + fn restore_production_checkpoint(&mut self, app: &PhotocraftApp) { if self.product_checkpoint["active"] != true || self.busy.is_some() || self.saving.is_some() || !self.model_ready || !self.image_ready diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs index 22510806..b6c16a95 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs @@ -118,9 +118,9 @@ impl Workspace { Some(self.project_sync_item(app, &item)) } - pub(super) fn request_current_sync(&mut self, app: &PhotocraftApp) -> Result { + pub(super) fn request_current_sync(&mut self, app: &PhotocraftApp, chat: bool) -> Result { let item = self.current_sync_item(app).ok_or("请先保存并打开项目")?; - self.request_project_sync(app, &item) + self.request_project_sync_with_policy(app, &item, chat) } fn project_action_block(&self, app: &PhotocraftApp, item: &Value) -> Option<&'static str> { @@ -149,6 +149,10 @@ impl Workspace { } pub(super) fn request_project_sync(&mut self, app: &PhotocraftApp, item: &Value) -> Result { + self.request_project_sync_with_policy(app, item, false) + } + + fn request_project_sync_with_policy(&mut self, app: &PhotocraftApp, item: &Value, chat: bool) -> Result { if let Some(reason) = self.project_action_block(app, item) { return Err(reason.into()); } let item = self.project_sync_item(app, item); let (_, action) = sync_choice(&item); @@ -162,6 +166,7 @@ impl Workspace { input = item["cloudUpdateRef"].clone(); } else if kind == "sync" { input["localId"] = item["id"].clone(); + input["syncChatHistory"] = json!(chat); input["status"] = json!("draft"); let identity = self.local_identity(item["id"].as_str().ok_or("项目编号无效")?); if let Some(state) = app.session.documents().iter().find(|state| self.open_projects.get(&state.doc.id.0) == Some(&identity)) { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_file.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_file.rs index f926f291..7f60b50b 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_file.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_file.rs @@ -11,11 +11,12 @@ struct SaveDialog { psd: bool, jpg: bool, candidates: bool, + chat_history: Option, } impl SaveDialog { fn options(&self, file: String) -> Value { - json!({"file":file,"project":self.project,"psd":self.psd,"jpg":self.jpg,"candidates":self.candidates}) + json!({"file":file,"project":self.project,"psd":self.psd,"jpg":self.jpg,"candidates":self.candidates,"syncChatHistory":self.chat_history}) } } @@ -59,7 +60,7 @@ impl PhotocraftApp { let name: String = name.chars().map(|ch| if ch.is_control() || "\"<>:/\\|?*".contains(ch) { '_' } else { ch }).collect(); let suggested = previous.clone().unwrap_or_else(|| format!("{name}.xiaoyi")); let dialog = SaveDialog { doc, account:w.account["id"].clone(), origin:w.origin.clone(), - project:true, psd:false, jpg:false, candidates:false, suggested }; + project:true, psd:false, jpg:false, candidates:false, chat_history:(choose || previous.is_none()).then_some(false), suggested }; if let Some(file) = previous.filter(|_| !choose) { Some(w.submit_project_save(self, ctx, &dialog, file)) } else { @@ -90,6 +91,9 @@ pub(super) fn show_project_save(w: &mut Workspace, app: &mut PhotocraftApp, ctx: ui.add_space(12.0); ui.checkbox(&mut dialog.project, "小壹工程 (.xiaoyi)"); ui.label(RichText::new("打开工程可继续编辑画布和候选").size(12.0).color(tokens.text_dim)); + let mut include_chat = dialog.chat_history == Some(true); + ui.add_enabled(dialog.project, egui::Checkbox::new(&mut include_chat, "随工程保存项目对话")); + dialog.chat_history = Some(include_chat && dialog.project); ui.add_space(8.0); ui.checkbox(&mut dialog.psd, "PSD 分层文件"); ui.checkbox(&mut dialog.jpg, "JPG 图片"); @@ -143,6 +147,12 @@ mod tests { #[test] fn save_dialog_initializes_project_and_keeps_export_choices_independent() { + for width in [800.0, 420.0] { + exercise_save_dialog(width); + } + } + + fn exercise_save_dialog(width: f32) { let (tx, _) = std::sync::mpsc::channel(); let (_, rx) = std::sync::mpsc::channel(); let mut workspace = Workspace::new(tx, rx); @@ -155,7 +165,7 @@ mod tests { let mut started = false; let builder = Harness::builder() .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) - .with_size(egui::vec2(800.0, 570.0)); + .with_size(egui::vec2(width, 570.0)); let mut harness = builder.wgpu().build_ui_state(move |ui, app| { if !started { PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); @@ -171,8 +181,9 @@ mod tests { let read = |ctx: &egui::Context| ctx.data(|data| data.get_temp::(id)).unwrap(); let initial = read(&harness.ctx); assert!(initial.project); + assert_eq!(initial.chat_history, Some(false)); assert!(!initial.psd && !initial.jpg && !initial.candidates); - for label in ["PSD 分层文件", "JPG 图片", "候选区图片"] { + for label in ["随工程保存项目对话", "PSD 分层文件", "JPG 图片", "候选区图片"] { let pos = harness.get_by_label(label).rect().center(); harness.hover_at(pos); harness.run_steps(2); @@ -183,7 +194,10 @@ mod tests { } let selected = read(&harness.ctx); assert!(selected.project && selected.psd && selected.jpg && selected.candidates); + assert_eq!(selected.options("test.xiaoyi".into())["syncChatHistory"], true); if let Some(path) = std::env::var_os("PHOTOCRAFT_PROJECT_SAVE_SCREENSHOT") { + let path = std::path::PathBuf::from(path); + let path = if width < 700.0 { path.with_file_name("project-save-narrow.png") } else { path }; harness.render().unwrap().save(path).unwrap(); } } From 82d3e4ef23820e096127d9d7e612b778b4fc71ad Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Thu, 26 Nov 2026 18:38:36 +0800 Subject: [PATCH 2/4] feat(xiaoyi): keep active work in the tray and flush on exit --- apps/detail-agent-pi/src/desktop-daemon.mjs | 29 +- apps/detail-agent-pi/src/native-bridge.mjs | 22 +- .../src/production-operations.mjs | 7 +- .../test/desktop-daemon.test.mjs | 109 ++++++++ .../detail-agent-pi/test/native-wire.test.mjs | 50 ++++ apps/detail-photocraft/Cargo.lock | 45 ++- .../apps/photocraft/Cargo.toml | 1 + .../photocraft/examples/xiaoyi_tray_exit.rs | 40 +++ .../apps/photocraft/src/app_tray.rs | 73 +++++ .../photocraft/src/jiansun_agent_daemon.rs | 91 ++++-- .../apps/photocraft/src/jiansun_backend.rs | 109 +++++--- .../src/jiansun_canvas_workspace.rs | 16 +- .../apps/photocraft/src/jiansun_creation.rs | 15 +- .../apps/photocraft/src/jiansun_images.rs | 4 +- .../apps/photocraft/src/jiansun_pi_runtime.rs | 14 +- .../photocraft/src/jiansun_prompt_library.rs | 3 + .../apps/photocraft/src/jiansun_recovery.rs | 2 +- .../src/jiansun_template_workflow.rs | 4 +- .../apps/photocraft/src/main.rs | 4 + .../examples/xiaoyi_production_exit.rs | 42 ++- .../crates/ui-egui/src/app.rs | 1 + .../crates/ui-egui/src/app/files.rs | 4 + .../crates/ui-egui/src/app/frame.rs | 4 + .../crates/ui-egui/src/dialogs/discard_ui.rs | 67 ++++- .../crates/ui-egui/src/jiansun.rs | 72 ++++- .../ui-egui/src/jiansun/canvas_workspace.rs | 2 +- .../ui-egui/src/jiansun/composer_drafts.rs | 34 +++ .../ui-egui/src/jiansun/product_production.rs | 259 +++++++++++++++--- .../crates/ui-egui/src/lib.rs | 2 + .../crates/ui-egui/src/menus/invoke.rs | 13 +- .../crates/ui-egui/src/services.rs | 14 + 31 files changed, 1005 insertions(+), 147 deletions(-) create mode 100644 apps/detail-photocraft/apps/photocraft/examples/xiaoyi_tray_exit.rs create mode 100644 apps/detail-photocraft/apps/photocraft/src/app_tray.rs diff --git a/apps/detail-agent-pi/src/desktop-daemon.mjs b/apps/detail-agent-pi/src/desktop-daemon.mjs index e0279634..018e7f49 100644 --- a/apps/detail-agent-pi/src/desktop-daemon.mjs +++ b/apps/detail-agent-pi/src/desktop-daemon.mjs @@ -7,7 +7,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out parentAlive=pid=>{try{process.kill(pid,0);return true;}catch(error){return error.code==='EPERM';}}, intervalMs=100, brokerFactory=config=>new Native98kBroker(config), exit=code=>process.exit(code)}={}) { const lines=createInterface({input,crlfDelay:Infinity}); - let active=null, broker=null, identity=null, closed=false, serial=0; + let active=null, broker=null, identity=null, closed=false, exiting=false, serial=0; const waiting=new Map(), seen=new Set(), knowledge=new Map(); // Retain unresolved operations across the distinct SDK Host instances owned // by this daemon. Never evict an unresolved identity to make room. @@ -15,6 +15,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out const send=value=>{if(!closed)output.write(JSON.stringify(value)+'\n');}; const stop=async()=>{ if(closed)return; closed=true;clearInterval(watch);lines.close(); + active?.abort(Error('客户端连接中断,原操作需核查')); for(const controller of knowledge.values())controller.abort();knowledge.clear(); for(const item of waiting.values()){clearTimeout(item.timer);item.reject(new BridgeError('客户端连接中断,原操作需核查;不会重发','transport_interrupted',{retryable:true,dispatched:true}));}waiting.clear(); // Kill only our child. Never wait for a synchronous HTTP call to return. @@ -27,10 +28,20 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out if(!parentAlive(parentPid))void stop(); },intervalMs); const failure=(runId,error,unknown=false)=>send({type:'complete',runId,value:{error,unknown,reposted:false}}); + const exitReady=()=>{if(exiting&&!active&&!knowledge.size)send({type:'exit_ready'});}; lines.on('line',line=>{ if(closed)return; let value;try{if(line.length>2*1024*1024)throw Error();value=JSON.parse(line);}catch{send({type:'fatal',error:'本地消息无效;不会重发'});void stop();return;} if(value?.type==='heartbeat') {send({type:'heartbeat_ack',id:value.id,brokerPid:broker?.child?.pid??null});return;} + if(value?.type==='prepare_exit') { + if(exiting)return; + exiting=true; + const reason=Error('客户端正在退出,已保留原请求'); + active?.abort(reason); + for(const controller of knowledge.values())controller.abort(reason); + exitReady(); + return; + } if(value?.type==='production_pause') { const config=active?.config; if(config?.productProduction===true && value.documentId===config.documentId @@ -44,6 +55,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out return; } if(value?.type==='knowledge' && uuid.test(value.id||'') && readKnowledge) { + if(exiting){send({type:'knowledge_result',id:value.id,error:'客户端正在退出,未派发新任务'});return;} if(knowledge.has(value.id))return; const controller=new AbortController();knowledge.set(value.id,controller); void Promise.resolve().then(()=>readKnowledge(value.input,{signal:controller.signal,onProgress:progress=>{ @@ -51,7 +63,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out }})).then( result=>send({type:'knowledge_result',id:value.id,value:result}), error=>send({type:'knowledge_result',id:value.id,error:error.message || '企业知识库读取失败'})) - .finally(()=>knowledge.delete(value.id)); + .finally(()=>{knowledge.delete(value.id);exitReady();}); return; } if(value?.type==='canvas_result') { @@ -60,13 +72,14 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out waiting.delete(value.id);clearTimeout(task.timer);value.error?task.reject(BridgeError.from(value.error)):task.resolve(value.value);return; } if(value?.type!=='run'||!uuid.test(value.runId||'')||!value.config||typeof value.config!=='object'||Array.isArray(value.config)) {send({type:'fatal',error:'本地消息无效;不会重发'});return;} + if(exiting){failure(value.runId,'客户端正在退出,未派发新任务');return;} if(active){if(active.runId!==value.runId)failure(value.runId,'已有运行中的任务,未派发');return;} if(seen.has(value.runId)||seen.size>=10000){failure(value.runId,'会话编号已使用或达到上限,未派发');return;} const runId=value.runId, config=structuredClone(value.config); seen.add(runId); const deadline = config.productProduction === true && Number.isSafeInteger(config.productionDeadline) ? config.productionDeadline * 1000 : null; - const controller = config.productProduction === true ? new AbortController() : null; + const controller = new AbortController(); const abort = error => { controller.abort(error); for (const [id, task] of waiting) { @@ -81,7 +94,7 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out const timer = deadline === null ? null : setTimeout(expire, Math.max(0, deadline - Date.now())); const call=(action,input)=>new Promise((resolve,reject)=>{ if(closed||active?.runId!==runId){reject(new BridgeError('客户端连接已关闭,原操作需核查','transport_interrupted',{retryable:true}));return;} - if(controller?.signal.aborted){reject(new BridgeError(controller.signal.reason.message,'cancelled'));return;} + if(controller.signal.aborted){reject(new BridgeError(controller.signal.reason.message,'cancelled'));return;} if (action === 'pi-delta' || action === 'pi-activity') { send({type:'presentation',runId,action,input}); resolve(); @@ -99,10 +112,14 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out if(!broker){broker=brokerFactory({binary:config.binary,profile:config.profile,project:config.project});identity=next;} } if (deadline !== null && deadline <= Date.now()) expire(); - const result=await runSession(config,call,broker,recovery,controller?.signal); + controller.signal.throwIfAborted(); + const result=await runSession(config,call,broker,recovery,controller.signal); if(!closed&&active?.runId===runId){for(const [id,task] of waiting)if(task.runId===runId){waiting.delete(id);clearTimeout(task.timer);task.reject(new BridgeError('原会话已结束,操作结果需核查','transport_interrupted',{retryable:true,dispatched:true}));}active=null;send({type:'complete',runId,value:result});} } catch {if(!closed&&active?.runId===runId){for(const [id,task] of waiting)if(task.runId===runId){waiting.delete(id);clearTimeout(task.timer);task.reject(new BridgeError('原会话已结束,操作结果需核查','transport_interrupted',{retryable:true,dispatched:true}));}active=null;failure(runId,controller?.signal.reason?.message??'本地模型桥失败;请核查原请求,不会重发',true);}} - finally { if (timer !== null) clearTimeout(timer); } + finally { + if (timer !== null) clearTimeout(timer); + exitReady(); + } })(); }); lines.on('close',()=>void stop()); diff --git a/apps/detail-agent-pi/src/native-bridge.mjs b/apps/detail-agent-pi/src/native-bridge.mjs index b77fa9d7..ff5ddad8 100644 --- a/apps/detail-agent-pi/src/native-bridge.mjs +++ b/apps/detail-agent-pi/src/native-bridge.mjs @@ -35,9 +35,11 @@ export class Native98kBroker { Object.assign(this, { binary, profile, project, modelRole, invocationHeaders, spawnProcess }); this.potentiallyDispatched = new Set(); this.dispatchScopes = new Map(); + this.children = new Set(); } forDetailSlot(slotId) { const worker = new Native98kBroker({binary:this.binary, profile:this.profile, project:this.project, modelRole:this.modelRole, invocationHeaders:this.invocationHeaders, spawnProcess:this.spawnProcess}); + worker.parent = this; worker.scope = this.scope; worker.detailSlot = slotId; worker.selectionId = this.selectionId; @@ -53,9 +55,9 @@ export class Native98kBroker { if (!this.dispatchScopes.has(identity)) this.dispatchScopes.set(identity, new Set()); this.potentiallyDispatched = this.dispatchScopes.get(identity); } - async open() { + async open(signal) { if (this.failed) throw this.failed; - if (this.closed) throw Error('模型桥已关闭'); + if (this.closed || this.parent?.closed) throw Error('模型桥已关闭'); if (this.child) return; let local; try { local = JSON.parse((await fs.readFile(path.join(this.profile, 'jiansun', 'runtime-network.json'), 'utf8')).replace(/^\uFEFF/, '')); } @@ -63,9 +65,11 @@ export class Native98kBroker { const owned = ownedBrokerNetwork(local, process.ppid, this.binary); const env = nativeBrokerEnvironment(this.profile, owned ? { ...process.env, PHOTOCRAFT_BYPASS_UPSTREAM_PROXY: '1' } : process.env); if (owned) await fs.appendFile(path.join(this.profile, 'jiansun', 'runtime-network-audit.jsonl'), JSON.stringify({at:Date.now(),method:'rpc',ownerPid:process.ppid,upstreamExceptionApplied:true,noProxyAliasesMatch:env.NO_PROXY===env.no_proxy})+'\n'); - if (this.closed) throw Error('模型桥已关闭'); + signal?.throwIfAborted(); + if (this.closed || this.parent?.closed) throw Error('模型桥已关闭'); const child = this.spawnProcess(this.binary, ['--jiansun-pi-rpc'], { env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] }); this.child = child; + this.parent?.children.add(this); this.exited = new Promise(resolve => child.once('close', resolve)); const fail = () => { if (this.closed) return; @@ -100,10 +104,13 @@ export class Native98kBroker { child.once('error', fail); child.once('close', fail); } - async start(method, args = {}, onEvent = () => {}) { + async start(method, args = {}, onEvent = () => {}, signal) { + signal?.throwIfAborted(); if (method !== 'info' && !this.scope) await this.info(); const run = async () => { - await this.open(); + signal?.throwIfAborted(); + await this.open(signal); + signal?.throwIfAborted(); if (this.failed) throw this.failed; if (this.closed) throw Error('模型桥已关闭'); return new Promise((resolve, reject) => { @@ -127,6 +134,7 @@ export class Native98kBroker { 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 (this.child) { @@ -135,6 +143,8 @@ export class Native98kBroker { const timer = setTimeout(() => this.child.kill(), 2000); try { await this.exited; } finally { clearTimeout(timer); } } + await Promise.all(children); + this.parent?.children.delete(this); } status() { return this.start('status'); } async info(args) { @@ -165,7 +175,7 @@ export class Native98kBroker { 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; diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 73c1ca24..3a8adf9e 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -553,7 +553,12 @@ export async function openProductionOperations(host) { } return { get active(){return jobs.size;}, - async close(){await drain();displayEpoch++;}, + async close(){ + await drain(); + await canvasWrite; + await journalWrite; + displayEpoch++; + }, async plan_production({slotIds}={}){ await current({refresh:true}); recordProductionInputs(repository,plan,slots); diff --git a/apps/detail-agent-pi/test/desktop-daemon.test.mjs b/apps/detail-agent-pi/test/desktop-daemon.test.mjs index 3bc97d71..44ba48e4 100644 --- a/apps/detail-agent-pi/test/desktop-daemon.test.mjs +++ b/apps/detail-agent-pi/test/desktop-daemon.test.mjs @@ -1,7 +1,15 @@ import assert from 'node:assert/strict'; import { PassThrough } from 'node:stream'; +import { spawn } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { once } from 'node:events'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createInterface } from 'node:readline'; import { test } from 'node:test'; import { startDaemon } from '../src/desktop-daemon.mjs'; +import { ProjectRepository } from '../src/project-repository.mjs'; import { StdioCanvas } from '../src/stdio-canvas.mjs'; const runId = '9a1ba294-f2c4-4e5f-91e0-ef6002f50e22'; @@ -128,6 +136,107 @@ test('a pause on the bound production stops further tools and leaves the origina }); }); +test('explicit exit closes admission immediately and acknowledges only after the run drains', async t => { + const dir = await mkdtemp(path.join(tmpdir(), 'xiaoyi-graceful-exit-')); + t.after(() => rm(dir, {recursive:true,force:true})); + const repository = () => new ProjectRepository(path.join(dir, 'project-repository.sqlite'), + {accountId:'account',projectId:'project',outputId:'detail',variantId:'oak'}); + let release; + const durable = new Promise(resolve => { release = resolve; }); + let runs = 0; + const {frames,send,input,exits} = daemonFixture(t, { + runSession: async (_, call, _broker, _recovery, signal) => { + runs++; + await assert.rejects(call('pi-detail-images', {original: 'original-image'}), {category:'cancelled',dispatched:true}); + assert.equal(signal.aborted, true); + await assert.rejects(call('pi-edit', {}), {category:'cancelled',dispatched:false}); + await durable; + repository().replaceLedger({binding:'template',items:{front:{state:'unknown', + pendingOperation:{operationId:'original-operation',requestId:'original-image'}}}}); + return {pending:['original-image'], unknown:true, reposted:false}; + }, + }); + send({type:'run',runId,config:{}}); + await tick(); + send({type:'prepare_exit'}); + const later = '775ac3bd-50da-476c-9051-627e7f26e53b'; + send({type:'run',runId:later,config:{}}); + await tick(); + assert.equal(runs, 1); + assert.equal(frames.filter(frame => frame.type === 'canvas').length, 1); + assert.equal(frames.some(frame => frame.type === 'exit_ready'), false); + assert.equal(repository().readLedger(), null); + assert.match(frames.find(frame => frame.runId === later).value.error, /未派发/); + release(); + await tick(); + assert.deepEqual(frames.at(-2).value.pending, ['original-image']); + assert.deepEqual(frames.at(-1), {type:'exit_ready'}); + input.end(); + await tick(); + assert.deepEqual(exits, [0]); + assert.deepEqual(repository().readLedger().items.front.pendingOperation, + {operationId:'original-operation',requestId:'original-image'}); +}); + +test('a killed daemon reopens the original ledger without accepting a missing save receipt', {timeout: 15_000}, async t => { + const dir = await mkdtemp(path.join(tmpdir(), 'xiaoyi-exit-')); + t.after(() => rm(dir, {recursive:true,force:true})); + const canvas = path.join(dir, 'canvas.txt'); + const script = ` + import {startDaemon} from ${JSON.stringify(new URL('../src/desktop-daemon.mjs', import.meta.url).href)}; + import {ProjectRepository} from ${JSON.stringify(new URL('../src/project-repository.mjs', import.meta.url).href)}; + import {writeFileSync} from 'node:fs'; + import {createHash} from 'node:crypto'; + const dir = process.argv[1]; + const id = 'same-operation'; + const requestId = 'same-request'; + const file = dir + '/canvas.txt'; + const repository = new ProjectRepository(dir + '/project-repository.sqlite', + {accountId:'account',projectId:'project',outputId:'detail',variantId:'oak'}); + startDaemon({brokerFactory:()=>({close:async()=>{}}),runSession:async(config,call)=>{ + if(config.mode==='first'){ + writeFileSync(file,'saved baseline'); + const hash=createHash('sha256').update('edited canvas').digest('hex'); + repository.replaceLedger({binding:'template',items:{front:{state:'unknown', + pendingAdoption:{operationId:id,requestId,hash}}}}); + await call('save-canvas',{operationId:id,requestId}); + return {saved:true}; + } + const original=repository.readLedger().items.front.pendingAdoption; + return await call('reconcile-original',original); + }}); + `; + async function start(mode) { + const child = spawn(process.execPath, ['--input-type=module','-e',script,dir], {windowsHide:true}); + const ended = once(child, 'exit'); + const lines = createInterface({input:child.stdout}); + const frames = lines[Symbol.asyncIterator](); + const next = async () => JSON.parse((await frames.next()).value); + const send = value => child.stdin.write(JSON.stringify(value)+'\n'); + t.after(async () => { child.kill(); await ended; }); + assert.equal((await next()).type, 'ready'); + send({type:'run', runId, config:{mode}}); + return {child,ended,send,next}; + } + const first = await start('first'); + const write = await first.next(); + assert.equal(write.action, 'save-canvas'); + first.child.kill('SIGKILL'); + await first.ended; + assert.equal(await readFile(canvas,'utf8'), 'saved baseline'); + const reopened = await start('reopen'); + const original = await reopened.next(); + assert.equal(original.action, 'reconcile-original'); + assert.equal(original.input.operationId, write.input.operationId); + assert.equal(original.input.requestId, write.input.requestId); + const diskHash = createHash('sha256').update(await readFile(canvas)).digest('hex'); + assert.notEqual(diskHash, original.input.hash); + reopened.send({type:'canvas_result',runId,id:original.id,value:{saved:false,phase:'unknown'}}); + assert.deepEqual((await reopened.next()).value, {saved:false,phase:'unknown'}); + reopened.child.stdin.end(); + await reopened.ended; +}); + test('presentation notifications do not wait for replies and the terminal command still does', async t => { const {frames,send}=daemonFixture(t,{ runSession:async(_config,call)=>{ diff --git a/apps/detail-agent-pi/test/native-wire.test.mjs b/apps/detail-agent-pi/test/native-wire.test.mjs index 16da08f0..1ccd4b2a 100644 --- a/apps/detail-agent-pi/test/native-wire.test.mjs +++ b/apps/detail-agent-pi/test/native-wire.test.mjs @@ -130,6 +130,56 @@ test('parallel production brokers inherit the native turn selection without reva assert.equal(parent.forDetailSlot('new-turn').selectionId,undefined); }); +test('an exit signal during native broker startup prevents the original request from being sent', async () => { + let admit, enter; + const startup = new Promise(resolve => { admit = resolve; }); + const entered = new Promise(resolve => { enter = resolve; }); + const broker = new Native98kBroker({project:randomUUID()}); + const abort = new AbortController(); + const requests = []; + broker.scope = 'fixture'; + broker.open = async () => { + enter(); + await startup; + broker.child = {stdin:{write:bytes => requests.push(bytes)},kill(){}}; + }; + const pending = broker.round().fetch('https://api.vip98k.com/v1/chat/completions', + {method:'POST',body:'{}',signal:abort.signal}); + await entered; + abort.abort(Error('退出已停止接单')); + 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 => { + const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-wire-')); + t.after(() => cleanup(profile)); + const killed = []; + let serial = 0; + const parent = new Native98kBroker({project:randomUUID(),profile,spawnProcess:() => { + const pid = ++serial; + const child = new EventEmitter(); + child.stdin = new PassThrough(); + child.stdout = new PassThrough(); + child.stderr = new PassThrough(); + child.kill = () => { + killed.push(pid); + child.stdout.end(); + child.stderr.end(); + child.emit('close',0); + }; + return child; + }}); + await parent.open(); + await parent.forDetailSlot('goal').open(); + await parent.forDetailSlot('cover').open(); + await parent.close({force:true}); + assert.deepEqual(killed.sort(), [1,2,3]); + await assert.rejects(parent.forDetailSlot('late').open(), /模型桥已关闭/); +}); + test('Pi sends an inline image and decodes a streamed function on both OpenAI APIs', async () => { const pixel = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jNHsAAAAASUVORK5CYII='; const tool = {name:'record_color',description:'Record the observed color',parameters:{type:'object',properties:{color:{type:'string'}},required:['color']}}; diff --git a/apps/detail-photocraft/Cargo.lock b/apps/detail-photocraft/Cargo.lock index 887d6621..138368ff 100644 --- a/apps/detail-photocraft/Cargo.lock +++ b/apps/detail-photocraft/Cargo.lock @@ -3304,7 +3304,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" dependencies = [ "io-lifetimes 3.0.1", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -4009,6 +4009,25 @@ dependencies = [ "pxfm", ] +[[package]] +name = "muda" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996" +dependencies = [ + "crossbeam-channel", + "dpi", + "keyboard-types", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "png 0.18.1", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + [[package]] name = "muda" version = "0.21.2" @@ -4993,13 +5012,13 @@ dependencies = [ "dispatch2", "eframe", "egui", + "flate2", "fmv-macos-events", "futures-lite", "image", "keyring", - "flate2", "log", - "muda", + "muda 0.21.2", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", @@ -5031,6 +5050,7 @@ dependencies = [ "sha2", "tempfile", "thiserror 2.0.21", + "tray-icon", "url", "uuid", "winit", @@ -7797,6 +7817,25 @@ dependencies = [ "strength_reduce", ] +[[package]] +name = "tray-icon" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" +dependencies = [ + "crossbeam-channel", + "muda 0.20.0", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "once_cell", + "png 0.18.1", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + [[package]] name = "tree_magic_mini" version = "3.2.2" diff --git a/apps/detail-photocraft/apps/photocraft/Cargo.toml b/apps/detail-photocraft/apps/photocraft/Cargo.toml index b00f0cc0..f33451b4 100644 --- a/apps/detail-photocraft/apps/photocraft/Cargo.toml +++ b/apps/detail-photocraft/apps/photocraft/Cargo.toml @@ -117,6 +117,7 @@ winit = { version = "=0.30.13", default-features = false, features = ["x11"] } # Safe Windows screen-capture bindings; Linux uses the pure-Rust X11 client/portal. xcap = "=0.9.8" winsafe = { version = "=0.0.29", default-features = false, features = ["user"] } +tray-icon = { version = "=0.25.1", default-features = false } # tests/mac_menu_appkit.rs: reads AppKit's menu bar back and sends it real key events. [target.'cfg(target_os = "macos")'.dev-dependencies] diff --git a/apps/detail-photocraft/apps/photocraft/examples/xiaoyi_tray_exit.rs b/apps/detail-photocraft/apps/photocraft/examples/xiaoyi_tray_exit.rs new file mode 100644 index 00000000..6b65db8b --- /dev/null +++ b/apps/detail-photocraft/apps/photocraft/examples/xiaoyi_tray_exit.rs @@ -0,0 +1,40 @@ +//! Opens an isolated Windows window and saves a real canvas while it is parked. +#[cfg(target_os = "windows")] +#[path = "../src/app_icon.rs"] +#[allow(dead_code)] +mod app_icon; +#[cfg(target_os = "windows")] +#[path = "../src/app_tray.rs"] +mod app_tray; +#[cfg(target_os = "windows")] +#[path = "../../../crates/ui-egui/examples/xiaoyi_production_exit.rs"] +#[allow(dead_code)] +mod production_exit; + +fn main() { + #[cfg(target_os = "windows")] + production_exit::windows::run( + std::env::args_os().nth(1).expect("an isolated project directory").into(), + "tray".into(), + Some(production_exit::windows::TrayProbe { + create: |ctx| Box::new(app_tray::WindowsTray::new(ctx)), + hidden: root_hidden, + }), + ); +} + +#[cfg(target_os = "windows")] +fn root_hidden(frame: &eframe::Frame) -> bool { + use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle}; + let Ok(handle) = frame.window_handle() else { return false }; + let RawWindowHandle::Win32(handle) = handle.as_raw() else { return false }; + let mut hidden = false; + let _ = winsafe::EnumWindows(|window| { + if window.ptr() as isize == handle.hwnd.get() { + hidden = !window.IsWindowVisible(); + return false; + } + true + }); + hidden +} diff --git a/apps/detail-photocraft/apps/photocraft/src/app_tray.rs b/apps/detail-photocraft/apps/photocraft/src/app_tray.rs new file mode 100644 index 00000000..dd14316c --- /dev/null +++ b/apps/detail-photocraft/apps/photocraft/src/app_tray.rs @@ -0,0 +1,73 @@ +use std::sync::mpsc; + +use photocraft_ui_egui::{AppTray, TrayAction}; +use tray_icon::menu::{Menu, MenuEvent, MenuItem, PredefinedMenuItem}; +use tray_icon::{Icon, TrayIcon, TrayIconBuilder}; + +pub struct WindowsTray { + actions: mpsc::Receiver, + icon: Option<(TrayIcon, MenuItem, String)>, +} + +impl WindowsTray { + pub fn new(ctx: &egui::Context) -> Self { + let (send, actions) = mpsc::channel(); + let ctx = ctx.clone(); + MenuEvent::set_event_handler(Some(move |event: MenuEvent| { + let action = match event.id().as_ref() { + "xiaoyi-tray-restore" => TrayAction::Restore, + "xiaoyi-tray-exit" => TrayAction::Exit, + _ => return, + }; + if send.send(action).is_ok() { + ctx.request_repaint_of(egui::ViewportId::ROOT); + } + })); + Self { actions, icon: None } + } +} + +impl AppTray for WindowsTray { + fn visible(&self) -> bool { + self.icon.is_some() + } + + fn show(&mut self, status: &str) -> Result<(), String> { + if self.icon.is_some() { + return Ok(()); + } + let menu = Menu::new(); + let restore = MenuItem::with_id("xiaoyi-tray-restore", "显示主窗口", true, None); + let summary = MenuItem::new(status, false, None); + let exit = MenuItem::with_id("xiaoyi-tray-exit", "保存并退出小壹", true, None); + menu.append_items(&[&restore, &summary, &PredefinedMenuItem::separator(), &exit]) + .map_err(|error| error.to_string())?; + let brand = super::app_icon::window_icon(); + let icon = Icon::from_rgba(brand.rgba, brand.width, brand.height) + .map_err(|error| error.to_string())?; + let tray = TrayIconBuilder::new().with_menu(Box::new(menu)) + .with_icon(icon).build().map_err(|error| error.to_string())?; + // A tray window can exist while Explorer has yet to register the icon. + tray.set_tooltip(Some(format!("小壹 · {status}"))).map_err(|error| error.to_string())?; + self.icon = Some((tray, summary, status.to_owned())); + Ok(()) + } + + fn take_action(&mut self) -> Option { + let action = self.actions.try_iter().last()?; + self.icon = None; + Some(action) + } + + fn set_status(&mut self, status: &str) { + if let Some((tray, item, previous)) = &mut self.icon + && previous != status + { + item.set_text(status); + if let Err(error) = tray.set_tooltip(Some(format!("小壹 · {status}"))) { + log::warn!("小壹托盘状态更新失败:{error}"); + } + *previous = status.to_owned(); + } + } +} diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs index 7baa9018..ad989cde 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs @@ -7,6 +7,8 @@ use std::sync::{Mutex, OnceLock, mpsc}; use std::time::{Duration, Instant}; enum KnowledgeEvent { Progress(Value), Result(R) } +type ExitReceipt = Box) + Send>; + struct State { alive: bool, ready: bool, @@ -16,6 +18,8 @@ struct State { last_ack: Option, last_sent: u64, last_acked: u64, + exiting: bool, + exit_receipt: Option, } pub(super) struct Daemon { identity: (PathBuf, PathBuf, PathBuf, PathBuf, u32), @@ -46,10 +50,14 @@ impl Daemon { if let Ok(mut state) = self.state.lock() { if !state.alive { return; } state.alive = false; + if let Some(receipt) = state.exit_receipt.take() { receipt(Err("本机Agent退出回执未确认".into())); } for (_, sender) in state.knowledge.drain() { let _ = sender.send(KnowledgeEvent::Result(Err("企业知识库连接中断".into()))); } if let Some((_, sender)) = state.active.take() { let _ = sender.send(Err(BridgeFailure::interrupted("本机Agent连接中断,原请求需核查", true))); } } if let Ok(mut output) = self.outbound.lock() { output.take(); } + self.wait_for_exit(); + } + fn wait_for_exit(&self) { if let Ok(mut child) = self.child.lock() { // Give the owned daemon its EOF cleanup path before killing it; // its cleanup also closes its own RPC child. @@ -80,10 +88,14 @@ impl Daemon { number => Some(u32::try_from(number.as_u64().ok_or("模型桥身份无效")?).map_err(|_| "模型桥身份无效")?), }; } + Some("exit_ready") if state.exiting => { + if let Some(receipt) = state.exit_receipt.take() { receipt(Ok(())); } + } Some("canvas" | "presentation" | "complete") if state.ready => { + if state.exiting && state.active.is_none() { return Ok(()); } let (run, sender) = state.active.as_ref().ok_or("本机Agent收到无主回合消息")?; if value["runId"].as_str() != Some(run.as_str()) { return Err("本机Agent回合身份不一致".into()); } - sender.send(Ok(value)).map_err(|_| "原回合已关闭")?; + if sender.send(Ok(value)).is_err() && !state.exiting { return Err("原回合已关闭".into()); } } Some("knowledge_progress") if state.ready => { if let Some(sender) = value["id"].as_str().and_then(|id| state.knowledge.get(id)) { @@ -113,13 +125,15 @@ impl Daemon { } pub(super) fn begin(&self, run: &str, config: &Value) -> Result>, BridgeFailure> { let (sender, receiver) = mpsc::channel(); - { + let sent = { let mut state = self.state.lock().map_err(|_| "本机Agent状态不可用")?; + if state.exiting { return Err(BridgeFailure::new("cancelled", false, false, "客户端正在退出,未派发新任务")); } if !state.alive || !state.ready { return Err(BridgeFailure::interrupted("本机Agent不可用,未重发", false)); } if state.active.is_some() { return Err("原Agent回合仍在处理".into()); } state.active = Some((run.to_owned(), sender)); - } - if let Err(error) = self.send(&json!({"type":"run","runId":run,"config":config})) { self.fail(); return Err(BridgeFailure::interrupted(error, false)); } + self.send(&json!({"type":"run","runId":run,"config":config})) + }; + if let Err(error) = sent { self.fail(); return Err(BridgeFailure::interrupted(error, false)); } Ok(receiver) } #[cfg(test)] @@ -131,10 +145,14 @@ impl Daemon { let (sender, receiver) = mpsc::channel(); { let mut state = self.state.lock().map_err(|_| "企业知识库连接不可用")?; - if !state.alive || !state.ready { return Err("企业知识库连接已关闭".into()); } + if !state.alive || !state.ready || state.exiting { return Err("企业知识库连接已关闭".into()); } state.knowledge.insert(id.clone(), sender); + if let Err(error) = self.send(&json!({"type":"knowledge","id":id,"input":input})) { + state.knowledge.remove(&id); + return Err(error); + } } - let result = self.send(&json!({"type":"knowledge","id":id,"input":input})).and_then(|_| { + let result = { progress(json!({"jobId":id,"phase":"metadata"})); let mut deadline = Instant::now() + Duration::from_secs(300); loop { @@ -149,7 +167,7 @@ impl Daemon { Err(_) => { let _ = self.cancel_knowledge(&id); break Err("模板读取超时,请重试;已下载内容保留".into()); } } } - }); + }; if let Ok(mut state) = self.state.lock() { state.knowledge.remove(&id); } result } @@ -173,6 +191,21 @@ impl Daemon { pub(super) fn end(&self, run: &str) { if let Ok(mut state) = self.state.lock() && state.active.as_ref().is_some_and(|(current, _)| current == run) { state.active = None; } } + + fn prepare_exit(&self, receipt: ExitReceipt) { + match self.state.lock() { + Ok(mut state) if state.alive => { + state.exiting = true; + match self.send(&json!({"type":"prepare_exit"})) { + Ok(()) => state.exit_receipt = Some(receipt), + Err(error) => receipt(Err(error)), + } + } + // A dead daemon cannot admit work. Recovery reads its persistent journals. + Ok(_) => receipt(Ok(())), + Err(_) => receipt(Err("本机Agent状态不可用".into())), + } + } } pub(super) fn cancel_knowledge(id: &str) -> R<()> { @@ -231,7 +264,8 @@ pub(super) fn service(node: &Path, script: &Path, binary: &Path, profile: &Path) }; let (output, messages) = mpsc::channel(); let daemon = Arc::new(Daemon { identity, child: Mutex::new(child), outbound: Mutex::new(Some(output)), pid, - state: Mutex::new(State { alive:true, ready:false, active:None, knowledge:Default::default(), broker_pid:None, last_ack:None, last_sent:0, last_acked:0 }) }); + state: Mutex::new(State { alive:true, ready:false, active:None, knowledge:Default::default(), broker_pid:None, last_ack:None, last_sent:0, last_acked:0, + exiting:false, exit_receipt:None }) }); spawn_writer(&daemon, stdin, messages); let reader_daemon = daemon.clone(); std::thread::spawn(move || { @@ -282,17 +316,31 @@ pub(super) fn pause_production(doc: u64, project_identity: &str) { } } +pub(super) fn prepare_exit(receipt: ExitReceipt) { + let Ok(mut registry) = registry().lock() else { receipt(Err("本机Agent状态不可用".into())); return }; + registry.mark_shutdown(); + if let Some(service) = ®istry.service { service.prepare_exit(receipt); } + else { receipt(Ok(())); } +} + +pub(super) fn cancel_exit() { + let service = registry().lock().ok().and_then(|mut registry| { + registry.shutting_down = false; + registry.service.take() + }); + if let Some(service) = service { + std::thread::spawn(move || service.fail()); + } +} + pub(super) fn shutdown() { - if let Ok(mut registry) = registry().lock() { + let service = registry().lock().ok().and_then(|mut registry| { registry.mark_shutdown(); - if let Some(service) = ®istry.service { - if let Ok(mut state) = service.state.lock() { - state.alive = false; - for (_, sender) in state.knowledge.drain() { let _ = sender.send(KnowledgeEvent::Result(Err("客户端已关闭".into()))); } - if let Some((_, sender)) = state.active.take() { let _ = sender.send(Err("本机Agent已关闭,原请求需核查".into())); } - } - if let Ok(mut output) = service.outbound.lock() { output.take(); } - } + registry.service.take() + }); + if let Some(service) = service { + service.fail(); + service.wait_for_exit(); } } @@ -316,6 +364,7 @@ mod tests { fn synthetic_daemon_reuses_one_child_and_rejects_foreign_frames() { let script = r#"const rl=require('node:readline').createInterface({input:process.stdin}); console.log(JSON.stringify({type:'ready'})); +rl.on('line',line=>{if(JSON.parse(line).type==='prepare_exit')console.log(JSON.stringify({type:'exit_ready'}));}); rl.on('line',line=>{const x=JSON.parse(line);if(x.type==='run'){console.log(JSON.stringify({type:'presentation',runId:x.runId,action:'pi-delta'}));console.log(JSON.stringify({type:'complete',runId:x.runId,value:{ok:true}}));}if(x.type==='knowledge'){console.log(JSON.stringify({type:'knowledge_progress',id:x.id,value:{phase:'download',completed:1,fileCount:2}}));if(!x.input.slow)console.log(JSON.stringify({type:'knowledge_result',id:x.id,value:{ok:true}}));}});"#; let mut command = Command::new("node"); command.args(["-e", script]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()); @@ -328,7 +377,8 @@ rl.on('line',line=>{const x=JSON.parse(line);if(x.type==='run'){console.log(JSON let (output, messages) = mpsc::channel(); let daemon = Arc::new(Daemon { identity:(PathBuf::new(),PathBuf::new(),PathBuf::new(),PathBuf::new(),0), child:Mutex::new(child),outbound:Mutex::new(Some(output)),pid, - state:Mutex::new(State { alive:true,ready:false,active:None,knowledge:Default::default(),broker_pid:None,last_ack:None,last_sent:0,last_acked:0 }) }); + state:Mutex::new(State { alive:true,ready:false,active:None,knowledge:Default::default(),broker_pid:None,last_ack:None,last_sent:0,last_acked:0, + exiting:false,exit_receipt:None }) }); spawn_writer(&daemon, stdin, messages); let handle = daemon.clone(); let reader = std::thread::spawn(move || { @@ -367,6 +417,11 @@ rl.on('line',line=>{const x=JSON.parse(line);if(x.type==='run'){console.log(JSON assert!(result.unwrap_err().contains("已取消")); assert!(daemon.state.lock().unwrap().knowledge.is_empty()); assert!(daemon.knowledge(json!({})).unwrap()["ok"] == true); + let (send, receipt) = mpsc::channel(); + daemon.prepare_exit(Box::new(move |result| { send.send(result).unwrap(); })); + assert!(!daemon.begin("after-exit", &json!({})).unwrap_err().dispatched); + assert!(daemon.knowledge(json!({})).is_err()); + receipt.recv_timeout(Duration::from_secs(5)).unwrap().unwrap(); daemon.fail(); reader.join().unwrap(); } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 1c795aee..b6082bba 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -405,6 +405,7 @@ struct Backend { recovery_attempts: Arc>>, recovery_serial: Arc>, composer_store: Arc, + exit_admission_closed: Arc, } #[derive(Debug)] struct PortalFailure { @@ -458,10 +459,14 @@ impl Backend { recovery_attempts: Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())), recovery_serial: Arc::new(std::sync::Mutex::new(())), composer_store: Default::default(), + exit_admission_closed: Default::default(), }; backend.composer_store.activate(Some(backend.scope()))?; Ok(backend) } + fn exiting(&self) -> bool { + self.exit_admission_closed.load(std::sync::atomic::Ordering::Acquire) + } fn scope(&self) -> String { self.auth["account"]["id"].as_str().map(|id| hash(&format!("{}|{}", self.origin, id))).unwrap_or("guest".into()) } @@ -531,7 +536,7 @@ impl Backend { let operation = input["operation"].clone(); if busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { let _ = events.send(Event::Json("project-operation".into(), Ok(json!({"operation":operation,"error":"项目操作仍在处理,请稍后再试"})))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); return; } if let Some(id) = input["doc"].as_u64() { self.bind_new(id); } @@ -555,7 +560,7 @@ impl Backend { }; let _ = events.send(Event::Json("project-operation".into(), Ok(reply))); busy.store(false, Ordering::Release); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); }); } fn settings(&self) -> R { @@ -889,7 +894,7 @@ impl Backend { ("code_challenge_method", "S256"), ]); let _ = tx.send(Event::Json("login-url".into(), Ok(json!(url.as_str())))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); let deadline = Instant::now() + Duration::from_secs(300); while Instant::now() < deadline { match listener.accept() { @@ -1210,6 +1215,7 @@ impl Backend { json!({"model":task["model"]["id"],"messages":[{"role":"system","content":system},{"role":"user","content":task["text"]}],"max_tokens":4096,"stream":true}) }; let invocation = pi_runtime::invocation(self, &task["model"])?; + if self.exiting() { return Err("客户端正在退出,未派发新请求".into()); } task["phase"] = json!("dispatched"); write_json(&file, &task)?; let mut r = self @@ -1225,6 +1231,7 @@ impl Backend { if task["model"]["protocol"] == "anthropic-messages" { r = r.header("Anthropic-Version", "2023-06-01"); } + if self.exiting() { return Err("客户端正在退出,保留原任务编号".into()); } r.send() }; let result = (|| -> R { @@ -1256,7 +1263,7 @@ impl Backend { if last_emit.elapsed() >= Duration::from_millis(45) { let value = json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"taskId":task["id"],"text":text}); let _ = tx.send(Event::Json("agent-stream".into(), Ok(value))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); updates = updates.saturating_add(1); last_text = text; last_emit = Instant::now(); @@ -1409,7 +1416,16 @@ impl Backend { if self.locations.get(&doc).is_none_or(|project| checkpoint["project"] != *project) { return Err("制作任务属于其他项目".into()); } - write_json(&self.project_dir(doc)?.join("production-run.json"), checkpoint)?; + let path = self.project_dir(doc)?.join("production-run.json"); + if method == "product-exit-checkpoint" && checkpoint["active"].is_null() { + let mut saved = if path.is_file() { read_json(&path)? } + else { json!({"active":false,"project":checkpoint["project"]}) }; + if saved["project"] != checkpoint["project"] { return Err("制作记录属于其他项目".into()); } + saved["status"] = checkpoint["status"].clone(); + write_json(&path, &saved)?; + } else { + write_json(&path, checkpoint)?; + } Ok(Value::Null) } "pi-rules" => pi_runtime::rules(self, input), @@ -1514,7 +1530,7 @@ impl Backend { progress["accountId"] = self.auth["account"]["id"].clone(); progress["origin"] = json!(self.origin); let _ = tx.send(Event::Json("template-progress".into(), Ok(progress))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); }); let _guard = sync::context_guard(); if sync::opened_copy_identity(&dir)? != open_identity { @@ -1599,19 +1615,33 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let internal_requests = tx.clone(); let composer_store = Arc::new(draft_store::Store::default()); let backend_store = composer_store.clone(); + let mut workspace = Workspace::new(tx, results); + let exit_admission = workspace.exit_admission_closed.clone(); + let exit_ctx = ctx.clone(); + workspace.prepare_daemon_exit = Some(Box::new(move || { + let (send, receive) = mpsc::channel(); + let exit_ctx = exit_ctx.clone(); + agent_daemon::prepare_exit(Box::new(move |result| { + let _ = send.send(result); + exit_ctx.request_repaint_of(egui::ViewportId::ROOT); + })); + receive + })); + workspace.cancel_daemon_exit = Some(agent_daemon::cancel_exit); std::thread::spawn(move || { let mut backend = match Backend::new(root.join("jiansun")) { Ok(b) => b, Err(e) => { let _ = events.send(Event::Json("restore".into(), Err(e))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); return; } }; backend.composer_store = backend_store; + backend.exit_admission_closed = exit_admission; if let Err(error) = backend.composer_store.activate(Some(backend.scope())) { let _ = events.send(Event::Json("restore".into(), Err(error))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); return; } let model_busy = Arc::new(std::sync::atomic::AtomicBool::new(false)); @@ -1629,6 +1659,12 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { std::thread::spawn(move || b.scan_recovery(&tx, &ctx)); } for request in rx { + if backend.exiting() && !matches!(&request, Request::Save(..)) + && !matches!(&request, Request::Action(method, _) if matches!(method.as_str(), + "product-run-checkpoint" | "product-exit-checkpoint" | "slot-adopted")) + { + continue; + } match request { Request::OpenedResult { binding, result } => { let label = if binding["autoResume"] == true { "startup-open" } else { "open" }; @@ -1654,7 +1690,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { std::thread::spawn(move || { let preview = worker.provisional_slot(doc, &input).ok().map(Box::new); let _ = events.send(Event::SlotPreview(input, preview)); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); }); } Request::Generate(doc, input) => { @@ -1671,7 +1707,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let result = b.image_job(Some(doc), &input, false, &events, &ctx); let _ = events.send(Event::Json("image".into(), result)); busy.store(false, Ordering::Release); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); }); } } @@ -1686,7 +1722,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { Err(error) => Event::Json("slot-product-view-save".into(), Ok(json!({"doc":id,"revision":revision,"error":error}))), }; let _ = task_events.send(event); - task_ctx.request_repaint(); + task_ctx.request_repaint_of(egui::ViewportId::ROOT); }); } Request::Save(doc, revision, meta) => { @@ -1695,6 +1731,15 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let deliver = meta["deliverProject"].clone(); let export = meta["exportProduct"].clone(); let event = match backend.save(doc.clone(), revision, meta) { + Ok(mut value) if (export.is_object() || deliver.is_object()) && backend.exiting() => { + let error = "客户端正在退出,未开始导出"; + if export.is_object() { + let _ = events.send(Event::Json("slot-product-export".into(), Err(error.into()))); + } else { + value["deliveryError"] = json!(error); + } + Event::Saved(id, revision, value) + } Ok(value) if export.is_object() => { let _ = events.send(Event::Saved(id, revision, value)); let worker = backend.clone(); @@ -1703,7 +1748,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { std::thread::spawn(move || { let result = worker.export_product_snapshot(&doc, &export); let _ = events.send(Event::Json("slot-product-export".into(), result)); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); }); continue; } @@ -1720,7 +1765,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { value["deliveryError"] = json!(error); } let _ = events.send(Event::Saved(id, revision, value)); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); }); continue; } @@ -1740,7 +1785,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let result = input["jobId"].as_str().ok_or_else(|| "模板读取编号缺失".to_owned()) .and_then(agent_daemon::cancel_knowledge).map(|_| json!({"cancelled":true})); let _ = events.send(Event::Json(method, result)); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); return true; } let handled_read = if matches!(method.as_str(), "prompt-library-list" | "prompt-library-edit" | "prompt-library-sync" | "project-list") { @@ -1759,11 +1804,11 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { Ok(json!({"accountId":task_input["accountId"],"origin":task_input["origin"],"readId":task_input["readId"],"error":error})) }); let _ = task_events.send(Event::Json(task_method, result)); - task_ctx.request_repaint(); + task_ctx.request_repaint_of(egui::ViewportId::ROOT); }).is_err() { let value = json!({"accountId":input["accountId"],"origin":input["origin"],"readId":input["readId"],"error":"提示库操作繁忙,请稍后再试;本机内容未更改"}); let _ = events.send(Event::Json(method, Ok(value))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } return true; } @@ -1776,10 +1821,10 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { if let Err(error) = project_reads.submit(move || { let result = bound_material_read(reader.project_list(&input), &task_reference); let _ = task_events.send(Event::Json("project-list".into(), Ok(result))); - task_ctx.request_repaint(); + task_ctx.request_repaint_of(egui::ViewportId::ROOT); }) { let _ = events.send(Event::Json("project-list".into(), Ok(bound_material_read(Err(error.into()), &reference)))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } return true; } @@ -1803,12 +1848,12 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { result = result.or_else(|error| Ok(json!({"productViewId":input["productViewId"],"error":error}))); } let _ = task_events.send(Event::Json(method, result)); - task_ctx.request_repaint(); + task_ctx.request_repaint_of(egui::ViewportId::ROOT); }); } else { let result = backend.slot_action(&method, &input, &events, &ctx); let _ = events.send(Event::Json(method, result)); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } return true; } @@ -1841,7 +1886,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { }; let _ = task_events.send(Event::Json(task_method, result)); } - task_ctx.request_repaint(); + task_ctx.request_repaint_of(egui::ViewportId::ROOT); }) { let result = if matches!(method.as_str(), "materials" | "preview") { Ok(bound_material_read(Err(error.into()), &reference)) @@ -1851,13 +1896,13 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { Ok(value) }; let _ = events.send(Event::Json(method, result)); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } return true; } if matches!(method.as_str(), "project-sync" | "project-state" | "project-delete") && model_busy.load(std::sync::atomic::Ordering::Acquire) { let _ = events.send(Event::Json(method, Err("任务仍在运行,请等待完成或接手后再保存云端状态".into()))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); return true; } if method == "slot-adopted" { @@ -1868,7 +1913,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { // remain available while the owning Pi model lease is held. let result = backend.slot_action(&method, &input, &events, &ctx); let _ = events.send(Event::Json(method, result)); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } else if method == "project-sync" { use std::sync::atomic::Ordering; if model_busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { @@ -1882,7 +1927,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let result = b.sync_project(&input); let _ = events.send(Event::Json(method, result)); busy.store(false, Ordering::Release); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); }); } } else if method.starts_with("slot-") @@ -1923,7 +1968,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { }; let _ = task_events.send(Event::Json(method, result)); busy.store(false, Ordering::Release); - task_ctx.request_repaint(); + task_ctx.request_repaint_of(egui::ViewportId::ROOT); }); } } else if method.starts_with("creation-") { @@ -1948,7 +1993,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { } }; let _ = events.send(event); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); }); } else if method == "agent-image-preview" { let reference_thumbnail = input["taskId"].as_str().is_some_and(images::reference_preview_id); @@ -1973,7 +2018,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let updating = input["updateExisting"] == true; if updating && model_busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { let _ = events.send(Event::Json(method, Err("任务仍在处理,请先保留原请求后读取新版".into()))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); return true; } let mut b = backend.clone(); @@ -1986,7 +2031,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { binding["openCopyIdentity"] = meta["openCopyIdentity"].clone(); (Box::new(doc), meta) }); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); Request::OpenedResult { binding, result } }); } else if method == "place" { @@ -2008,10 +2053,9 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let ctx = ctx.clone(); std::thread::spawn(move || b.scan_recovery(&tx, &ctx)); } - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } }); - let mut workspace = Workspace::new(tx, results); workspace.draft_flush = Some(Arc::new(move |token, text, primary, secondary, generation| composer_store.flush(token, text, primary, secondary, generation))); workspace.pause_production_agent = Some(agent_daemon::pause_production); workspace @@ -2319,6 +2363,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + exit_admission_closed: Default::default(), }; let first = b.scope(); b.auth = json!({"account":{"id":"account-b"}}); @@ -2505,6 +2550,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + exit_admission_closed: Default::default(), }; b.composer_store.activate(Some(b.scope())).unwrap(); b.bind_new(7); @@ -2535,6 +2581,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + exit_admission_closed: Default::default(), }; first.composer_store.activate(Some(first.scope())).unwrap(); let mut s = photocraft_engine::Session::new(); 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 eaf7fa7e..ed7c7332 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -1757,7 +1757,7 @@ impl Backend { let record = result?; if doc == source_doc { publish_prepared(events, self.canvas_workspace_result(doc, &dir)?)?; - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } return Ok(candidate_receipt(&record)); } @@ -1765,7 +1765,7 @@ impl Backend { let receipt = retire_candidate(&dir, target, reason)?; if receipt["status"] == "retired" { publish_prepared(events, self.canvas_workspace_result(doc, &dir)?)?; - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } return Ok(receipt); } @@ -1781,7 +1781,7 @@ impl Backend { reference["purpose"] = json!("template-candidate"); let _ = events.send(Event::Preview(reference, preview)); } - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); Ok(candidate_receipt(&record)) } @@ -3116,7 +3116,7 @@ impl Backend { let snapshot = operation_receipt(self.canvas_workspace_result(doc, &dir) .map_err(|error| BridgeFailure::new("image_request_failed", false, true, error))?, Some(receipt.clone()), None); let _ = events.send(Event::Json("slot-append".into(), Ok(snapshot))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } Ok(receipt) } @@ -3164,7 +3164,7 @@ impl Backend { "outputId":task["outputScope"],"candidate":candidate_receipt(record)}); } publish_prepared(events, snapshot)?; - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); validate_image_context(dir, Some(slot))?; let call = self.image_job(None, &json!({"doc":doc,"frozenRequestId":id}), false, events, ctx); let dispatch_error = |error, backend: &Self| BridgeFailure::new("image_request_failed", false, backend.image_dispatch_may_have_started(doc, &id), error); @@ -3363,7 +3363,7 @@ impl Backend { "template-progress" }; let _ = events.send(Event::Json(event.into(), Ok(value))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); }; let has_edit = edited.is_file(); if browsing { @@ -3537,7 +3537,7 @@ impl Backend { if let Ok((mut reference, preview)) = self.agent_image_preview(&json!({"doc":doc,"taskId":candidate})) { reference["purpose"] = json!("template-candidate"); let _ = events.send(Event::Preview(reference, preview)); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None)); } @@ -3638,7 +3638,7 @@ impl Backend { if let Ok((mut reference, preview)) = self.agent_image_preview(&json!({"doc":doc,"taskId":record["id"]})) { reference["purpose"] = json!("template-candidate"); let _ = events.send(Event::Preview(reference, preview)); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None)); } else if method == "slot-recover" { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs index 896c4bab..9db79ce2 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs @@ -506,7 +506,7 @@ impl Backend { value["accountId"]=self.auth["account"]["id"].clone(); value["origin"]=json!(self.origin); let _=tx.send(Event::Json("resource-progress".into(), Ok(value))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); })?; let catalog = if matches!(kind, "brands" | "categories") { result["catalog"].take() } else { if kind == "resource-component" && let Some(row) = result["items"].get_mut(0) { @@ -611,7 +611,7 @@ impl Backend { }; let v = reference.clone(); tx.send(Event::Preview(v.clone(), image)).map_err(|_| "工作台已关闭")?; - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); Ok(v) })(); match outcome { @@ -760,7 +760,7 @@ impl Backend { result["path"] = json!(path.to_string_lossy()); result["creation"] = c; tx.send(Event::CreationCanvas(Box::new(document), result.clone())).map_err(|_| "工作台已关闭,结果仍保存在本机")?; - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); Ok(result) } _ => Err("创作操作未开放".into()), @@ -882,6 +882,7 @@ impl Backend { pi_runtime::apply_invocation_capacity(&mut request_model, &invocation)?; let payload = request_body(&request_model, task["prompt"].as_str().ok_or("任务提示词缺失")?, &pictures)?; self.validate()?; + if self.exiting() { return Err("客户端正在退出,未派发新请求".into()); } task["phase"] = json!("dispatched"); task["message"] = json!("模型处理中;不会自动重发"); task_save(&dir, &task)?; @@ -898,6 +899,7 @@ impl Backend { if anthropic { req = req.header("Anthropic-Version", "2023-06-01"); } + if self.exiting() { return Err("客户端正在退出,保留原任务编号".into()); } req.send() }; let response = response.map_err(|error| stream::transport_error(&error))?; @@ -919,7 +921,7 @@ impl Backend { event["text"] = json!(text); event["stage"] = json!(stage); let _ = tx.send(Event::Json("creation-progress".into(), Ok(event))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); Ok(()) })? } else { @@ -1240,7 +1242,7 @@ impl Backend { let (reply, rx) = mpsc::channel(); let payload = json!({"doc":input["doc"],"accountId":self.auth["account"]["id"],"origin":self.origin,"baseRevision":input["baseRevision"],"run":run,"sequence":sequence}); tx.send(Event::PiAction("creation-allowed".into(), payload, reply)).map_err(|_| "工作台已关闭,后续屏幕未发送")?; - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); let (value, _) = rx.recv_timeout(Duration::from_secs(12)).map_err(|_| "画布未确认状态,后续屏幕未发送")??; if value["allowed"] != true { return Err("用户已接手或画布有新编辑,后续屏幕未发送;已生成结果保留".into()); @@ -1261,7 +1263,7 @@ impl Backend { result["sequence"] = json!(sequence); result["taskId"] = c["generation"]["lastTaskId"].clone(); tx.send(Event::CreationCanvas(Box::new(native), result.clone())).map_err(|_| "工作台已关闭;生成画布仍保留在本机")?; - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); Ok(result) } pub(super) fn creation_record_image(&self, dir: &Path, c: &mut Value, screen: &str, result: &Value) -> R<()> { @@ -1573,6 +1575,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + exit_admission_closed: Default::default(), }; backend.bind_new(1); let dir = backend.project_dir(1).unwrap(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs index 0e098735..c400395a 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs @@ -908,7 +908,7 @@ impl Backend { v["imageFrame"] = json!({"width":width,"height":height}); } let _ = tx.send(Event::Json("image-progress".into(), Ok(v))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); }; let result = (|| -> R<()> { let raw_file = taskdir.join("response.json"); @@ -1018,6 +1018,7 @@ impl Backend { let (client, request) = req.build_split(); let request = request.map_err(|_| "生图请求准备失败,未提交")?; self.image_validate(deadline)?; // Live permission immediately before a paid dispatch. + if self.exiting() { return Err("客户端正在退出,未提交生图请求".into()); } t["phase"] = json!("dispatched"); job_save(&dir, &t)?; if t["creationBinding"].is_object() { @@ -1026,6 +1027,7 @@ impl Backend { job_save(&dir, &t)?; } let response = slot_post(&dir, &t, || { + if self.exiting() { return Err("客户端正在退出,未提交生图请求".into()); } progress("98k 正在生成图片…", true); client.execute(request).map_err(|_| "生成连接中断,结果待核查;不会重发".into()) })?; 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 a64b114c..99fa5ceb 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -493,7 +493,7 @@ impl WorkflowChildren { // model_busy throughout; no global model lock is bypassed. let result = child_backend.slot_action(&method, &input, &child_events, &child_ctx); let _ = child_events.send(Event::Json(method, workflow_receipt(&receipt_identity, result))); - child_ctx.request_repaint(); + child_ctx.request_repaint_of(egui::ViewportId::ROOT); }).map_err(|_| "本机工作流线程无法启动,未派发模型")?); Ok(()) } @@ -636,7 +636,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender } if let Ok(Some((meta, image))) = b.reference_image_preview(&json!({"doc":doc,"taskId":id})) { let _ = events.send(Event::Preview(meta, image)); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } } if item.is_object() { @@ -664,13 +664,14 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender let mut canvas_screen_reads = None; let mut late_workflow_replies = Vec::new(); let start_workflow = |children: &mut WorkflowChildren, delegation: &Value, run: Option<&str>| { + if b.exiting() { return Err("客户端正在退出,未派发工作流".into()); } let start = run.ok_or_else(|| "原Agent回合尚未绑定".to_owned()) .and_then(|run| children.start(b, delegation, (run, &project, doc), events, ctx)); if let Err(error) = &start && let Some(method) = delegation["method"].as_str().filter(|method| matches!(*method, "slot-append" | "slot-adopt-prep")) { let _ = events.send(Event::Json(method.into(), workflow_receipt(delegation, Err(error.clone())))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } start }; @@ -693,7 +694,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender .ok_or("Agent展示动作未授权")?; let (reply, _) = mpsc::channel(); let _ = events.send(Event::PiAction(action.into(), value["input"].clone(), reply)); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } else if value["type"] == "canvas" { let request_id = value["id"].as_u64().filter(|id| *id > 0).ok_or("Agent请求身份无效")?; if !request_ids.insert(request_id) { return Err("Agent请求身份重复".into()); } @@ -717,7 +718,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender } log::debug!("小壹原生活动:{action}"); events.send(Event::PiAction(action.into(), native_input, tx)).map_err(|_| "工作台已关闭,原请求需核查")?; - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); let reply = match rx.recv_timeout(Duration::from_secs(12)) { Ok(Ok((mut v, snapshot))) => { if action == "pi-image-request" { @@ -799,7 +800,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender meta["templateOriginal"] = json!({"fieldId":image["fieldId"],"templateVersion":image["templateVersion"], "run":requested_run}); let _ = events.send(Event::Preview(meta, bitmap)); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } json!({"id":value["id"],"value":image}) }, @@ -1002,6 +1003,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + exit_admission_closed: Default::default(), }; let doc = 7; let local = Uuid::new_v4().to_string(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs index 8c2cb68f..7c16ea00 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs @@ -545,6 +545,7 @@ mod tests { locations: HashMap::new(), last_saved: HashMap::new(), superseded_docs: Default::default(), draft_zip_writer: Default::default(), recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + exit_admission_closed: Default::default(), }; let mut cache = Cache { version: 1, prompts: vec![prompt()], operations: vec![] }; let id = cache.prompts[0].id.clone(); @@ -650,6 +651,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + exit_admission_closed: Default::default(), }; let input = json!({"accountId":"owner-b","origin":b.origin,"action":"create","title":"标题","body":"正文"}); assert!(action(&mut b, "prompt-library-edit", &input).is_err()); @@ -722,6 +724,7 @@ mod tests { recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(), + exit_admission_closed: Default::default(), }; let mut cache = Cache { version: 1, ..Default::default() }; edit(&mut cache, &json!({"action":"create","title":"标题","body":"正文"})).unwrap(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_recovery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_recovery.rs index dad1f918..16786c0d 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_recovery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_recovery.rs @@ -271,7 +271,7 @@ impl Backend { match self.auto_recover_project_window(&local, false, budget, tx, ctx) { Ok(value) if !value.is_null() => { let _ = tx.send(Event::Json("recovery-status".into(), Ok(value))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); } Err(_) | 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 4b5b1971..086012e1 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_template_workflow.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_template_workflow.rs @@ -463,7 +463,7 @@ impl Backend { template_slots::reserve_candidate(&dir, id, letter, settings["imageModel"].as_str().ok_or("请选择生图模型")?, &prompt, &refs, rev(&state))?; let binding = template_slots::binding(&state, id, letter)?; let _ = events.send(Event::Json("slot-progress".into(), self.slot_result(doc, &dir))); - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); let profile = &c["designSnapshot"]["brand"]["profile"]; let visual = profile["visualRules"].as_object().map(|m| m.values().filter_map(Value::as_str).collect::>().join("\n")).unwrap_or_default(); @@ -531,7 +531,7 @@ impl Backend { } else { return Err("图位操作不存在".into()); } - ctx.request_repaint(); + ctx.request_repaint_of(egui::ViewportId::ROOT); self.slot_result(doc, &dir) } } diff --git a/apps/detail-photocraft/apps/photocraft/src/main.rs b/apps/detail-photocraft/apps/photocraft/src/main.rs index 8c3e9c64..ab977d9c 100644 --- a/apps/detail-photocraft/apps/photocraft/src/main.rs +++ b/apps/detail-photocraft/apps/photocraft/src/main.rs @@ -40,6 +40,8 @@ mod jiansun_models; #[cfg(all(test, not(target_arch = "wasm32")))] mod jiansun_acceptance; mod app_icon; +#[cfg(target_os = "windows")] +mod app_tray; mod appearance; #[cfg(target_os = "macos")] mod apple_events; @@ -717,6 +719,8 @@ fn main() -> eframe::Result { app.open_paths(&files); if let Some(root) = services::config_dir() { app.jiansun = Some(jiansun_backend::start(root, cc.egui_ctx.clone())); + #[cfg(target_os = "windows")] + { app.services.app_tray = Some(Box::new(app_tray::WindowsTray::new(&cc.egui_ctx))); } std::thread::spawn(|| { if let Err(error) = jiansun_backend::start_agent_daemon() { log::warn!("小壹常驻服务启动未完成:{error}"); diff --git a/apps/detail-photocraft/crates/ui-egui/examples/xiaoyi_production_exit.rs b/apps/detail-photocraft/crates/ui-egui/examples/xiaoyi_production_exit.rs index d521f452..fb200d18 100644 --- a/apps/detail-photocraft/crates/ui-egui/examples/xiaoyi_production_exit.rs +++ b/apps/detail-photocraft/crates/ui-egui/examples/xiaoyi_production_exit.rs @@ -1,7 +1,7 @@ //! Local Windows acceptance of PhotoCraft's exit and restart with a paid-request //! boundary replaced by a channel. Each process reopens the native file from disk. #[cfg(target_os = "windows")] -mod windows { +pub mod windows { use std::path::{Path, PathBuf}; use std::sync::{Arc, atomic::{AtomicBool, Ordering::Relaxed}, mpsc}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -14,12 +14,21 @@ mod windows { const ACCOUNT: &str = "local-qa"; const EDIT: &str = "Edit made during the production turn"; + pub struct TrayProbe { + pub create: fn(&egui::Context) -> Box, + pub hidden: fn(&eframe::Frame) -> bool, + } + struct Host { app: PhotocraftApp, dispatched: Arc, mode: String, dir: PathBuf, handled: bool, + hidden: Arc, + saved: Arc, + exited_from_tray: bool, + native_window_hidden: Option bool>, } impl eframe::App for Host { @@ -37,9 +46,23 @@ mod windows { std::fs::write(self.dir.join("edited"), b"canvas edit applied").unwrap(); if self.mode.starts_with("exit") { photocraft_ui_egui::menus::invoke(&mut self.app, ctx, "file.exit", Value::Null).unwrap(); + } else if self.mode == "tray" { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); } } } + if self.app.services.app_tray.as_ref().is_some_and(|tray| tray.visible()) + && self.native_window_hidden.is_some_and(|is_hidden| is_hidden(frame)) + { + if !self.hidden.swap(true, Relaxed) { + println!("root viewport hidden with real notification-area icon"); + } + if self.saved.load(Relaxed) && !self.exited_from_tray { + self.exited_from_tray = true; + println!("background save completed while root viewport was hidden"); + photocraft_ui_egui::menus::invoke(&mut self.app, ctx, "file.exit", Value::Null).unwrap(); + } + } eframe::App::logic(&mut self.app, ctx, frame); if self.mode == "exit-fail" && self.app.jiansun.is_some() && self.app.ui.status_error && self.app.ui.status.contains("保存未确认") { @@ -64,7 +87,7 @@ mod windows { photocraft_format::atomic_write(path, &serde_json::to_vec(value).unwrap()).unwrap(); } - pub fn run(dir: PathBuf, mode: String) { + pub fn run(dir: PathBuf, mode: String, tray: Option) { let canvas = dir.join("canvas.pcraft"); let journal = dir.join("production-run.json"); let draft = dir.join("draft.json"); @@ -95,11 +118,17 @@ mod windows { let (tx, requests) = mpsc::channel(); let (events, rx) = mpsc::channel(); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.services.app_tray = tray.as_ref().map(|probe| (probe.create)(&cc.egui_ctx)); + let native_window_hidden = tray.map(|probe| probe.hidden); let mut workspace = Workspace::new(tx, rx); workspace.draft_flush = Some(Arc::new(|_, _, _, _, _| Ok(()))); app.jiansun = Some(workspace); let dispatched = Arc::new(AtomicBool::new(false)); let signal = Arc::clone(&dispatched); + let hidden = Arc::new(AtomicBool::new(false)); + let worker_hidden = hidden.clone(); + let saved = Arc::new(AtomicBool::new(false)); + let worker_saved = saved.clone(); let ctx = cc.egui_ctx.clone(); let current_mode = mode.clone(); let evidence = dir.clone(); @@ -126,18 +155,21 @@ mod windows { continue; } Request::Action(method, input) if method == "product-exit-checkpoint" => { + assert_eq!(input["checkpoint"]["status"], "paused_on_exit"); write(&journal, &input["checkpoint"]); Event::Json(method, Ok(Value::Null)) } Request::Save(..) if current_mode == "exit-fail" => Event::Json("save".into(), Err("QA: 本机草稿写入失败".into())), - Request::Save(doc, revision, _) if current_mode == "exit" => { + Request::Save(doc, revision, _) if matches!(current_mode.as_str(), "exit" | "tray") => { assert!(doc.layers.iter().any(|layer| layer.name == EDIT)); assert!(evidence.join("edited").is_file()); + if current_mode == "tray" { assert!(worker_hidden.load(Relaxed)); } // Make the receipt arrive in a later native frame. std::thread::sleep(Duration::from_millis(300)); writer.save_path(&doc, &canvas, &Default::default()).unwrap(); write(&draft, &json!({"revision":revision})); + worker_saved.store(true, Relaxed); println!("saved real native canvas at revision {revision}"); Event::Saved(doc.id.0, revision, json!({"localId":PROJECT,"savedPath":canvas})) } @@ -148,7 +180,7 @@ mod windows { ctx.request_repaint(); } }); - Ok(Box::new(Host { app, dispatched, mode, dir, handled:false })) + Ok(Box::new(Host { app, dispatched, mode, dir, handled:false, hidden, saved, exited_from_tray:false, native_window_hidden })) })).unwrap(); println!("native window exited"); } @@ -159,6 +191,6 @@ fn main() { let mut args = std::env::args_os().skip(1); let mode = args.next().unwrap().into_string().unwrap(); let dir = args.next().unwrap().into(); - windows::run(dir, mode); + windows::run(dir, mode, None); } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/app.rs b/apps/detail-photocraft/crates/ui-egui/src/app.rs index 5f0af2c0..f64be2d8 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/app.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/app.rs @@ -209,6 +209,7 @@ impl PhotocraftApp { held_opens: Default::default(), held_preset_import: None, allow_close: false, + explicit_exit: false, stylus: Default::default(), control_click: Default::default(), background_jobs: false, diff --git a/apps/detail-photocraft/crates/ui-egui/src/app/files.rs b/apps/detail-photocraft/crates/ui-egui/src/app/files.rs index 2fee62f4..c3ea1c2e 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/app/files.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/app/files.rs @@ -583,6 +583,10 @@ impl PhotocraftApp { !self.jobs.saves.is_empty() } + pub(crate) fn exporting(&self) -> bool { + self.session.jobs().iter().any(|job| job.command.starts_with("file.export")) + } + /// Save through the control session's capability-scoped writer. No file /// picker or ambient writer is reachable from this path. Returns the path /// written and the export warnings (also shown to the user). diff --git a/apps/detail-photocraft/crates/ui-egui/src/app/frame.rs b/apps/detail-photocraft/crates/ui-egui/src/app/frame.rs index 41704bb9..88f62cbe 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/app/frame.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/app/frame.rs @@ -100,6 +100,7 @@ impl PhotocraftApp { // A window bigger than its display (1440 × 900 on 1366 × 768) runs under the taskbar: // maximize it into the work area once (#315). work_area::fit_window(ctx); + discard_ui::poll_tray(self, ctx); discard_ui::guard_window_close(self, ctx); // A zoom field being typed in: plays its alert, and notes a click on the pasteboard. crate::zoom_field::tick(self, ctx); @@ -174,6 +175,7 @@ impl PhotocraftApp { self.poll_file_dialog(ctx, Some(frame)); #[cfg(not(target_arch = "wasm32"))] crate::jiansun::advance(self, ctx); + discard_ui::refresh_tray_status(self); } /// Shared UI body. A wrapping host must call `finish_type_reset_pass` after return, @@ -181,6 +183,8 @@ impl PhotocraftApp { pub fn ui_frame(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let ctx = ui.ctx().clone(); #[cfg(not(target_arch = "wasm32"))] + if crate::jiansun::flushing_exit(self) { ui.disable(); } + #[cfg(not(target_arch = "wasm32"))] canvas::retain_agent_adoption(self, &ctx); // One control owner even when this callback cannot draw the custom editor. if !self.fonts_ready diff --git a/apps/detail-photocraft/crates/ui-egui/src/dialogs/discard_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/dialogs/discard_ui.rs index 020856ba..dea4bbc3 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/dialogs/discard_ui.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/dialogs/discard_ui.rs @@ -118,13 +118,58 @@ impl PhotocraftApp { } } -/// Called once per frame: holds back a window close request while there is unsaved work. Every -/// way of leaving (File › Exit / Quit, the close button, the OS's quit event, `app.quit`) ends up -/// here as a close request. +pub(crate) fn poll_tray(app: &mut PhotocraftApp, ctx: &egui::Context) { + if ctx.viewport_id() != egui::ViewportId::ROOT { return; } + let Some(action) = app.services.app_tray.as_mut().and_then(|tray| tray.take_action()) else { return }; + ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true)); + ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + if matches!(action, crate::TrayAction::Exit) + && let Err(error) = crate::menus::invoke(app, ctx, EXIT, Value::Null) + { + app.ui.status = error; + app.ui.status_error = true; + } +} + +pub(crate) fn refresh_tray_status(app: &mut PhotocraftApp) { + if app.services.app_tray.as_ref().is_some_and(|tray| tray.visible()) { + let status = background_status(app).unwrap_or_else(|| "当前没有运行中的任务".into()); + if let Some(tray) = app.services.app_tray.as_mut() { tray.set_status(&status); } + } +} + +fn background_status(app: &PhotocraftApp) -> Option { + #[cfg(not(target_arch = "wasm32"))] + if let Some(status) = crate::jiansun::background_status(app) { return Some(status); } + if app.saving() { return Some("正在保存文档".into()); } + app.exporting().then(|| "正在导出文件".into()) +} + +/// Native close parks an active workspace. File › Exit and the tray's Exit drain it. pub fn guard_window_close(app: &mut PhotocraftApp, ctx: &egui::Context) { - if !ctx.input(|i| i.viewport().close_requested()) { + if ctx.viewport_id() != egui::ViewportId::ROOT || !ctx.input(|i| i.viewport().close_requested()) { return; } + if !app.explicit_exit && !app.allow_close && app.services.app_tray.is_some() + && let Some(status) = background_status(app) + && let Some(tray) = app.services.app_tray.as_mut() + { + match tray.show(&status) { + Ok(()) => { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false)); + return; + } + Err(error) => { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + app.ui.status = format!("无法移至小壹托盘:{error}。可通过文件菜单退出。"); + app.ui.status_error = true; + return; + } + } + } + #[cfg(not(target_arch = "wasm32"))] if crate::jiansun::guard_production_exit(app, ctx) { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); return; @@ -136,7 +181,11 @@ pub fn guard_window_close(app: &mut PhotocraftApp, ctx: &egui::Context) { } // A save or print worker must finish its external side effect before the process exits; // `jobs_ui` repeats the close after completion and keeps errors visible. - if app.saving() || app.printing() { + #[cfg(not(target_arch = "wasm32"))] + let flush_finished = crate::jiansun::exit_flush_finished(app); + #[cfg(target_arch = "wasm32")] + let flush_finished = false; + if (app.saving() && !flush_finished) || app.printing() { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); app.jobs.close_after_saves = true; return; @@ -346,7 +395,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { /// Acts on the answer about `doc`, the document the prompt is asking about. fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId, answer: Answer) { match answer { - Answer::Cancel => app.discard = None, + Answer::Cancel => { + if app.discard.take().is_some_and(|prompt| prompt.id == EXIT) { + app.explicit_exit = false; + #[cfg(not(target_arch = "wasm32"))] + crate::jiansun::cancel_exit(app); + } + } Answer::Discard => advance(app, ctx), Answer::Save if save(app, ctx, doc) => advance(app, ctx), Answer::Save => {} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index a08d4b61..b5f33625 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -103,6 +103,8 @@ pub struct PiCanvasSnapshot { pub cancellation: Arc, } +type ExitReceipt = mpsc::Receiver>; + pub enum Event { Json(String, Result), Opened(Box, Value), @@ -1013,6 +1015,9 @@ pub struct Workspace { draft_changed: bool, product_checkpoint: Value, production_exit: Option, + pub exit_admission_closed: Arc, + pub prepare_daemon_exit: Option ExitReceipt>>, + pub cancel_daemon_exit: Option, pub pause_production_agent: Option, loaded_draft: Option, pub draft_flush: Option, @@ -1500,6 +1505,9 @@ impl Workspace { draft_changed: false, product_checkpoint: Value::Null, production_exit: None, + exit_admission_closed: Arc::new(AtomicBool::new(false)), + prepare_daemon_exit: None, + cancel_daemon_exit: None, pause_production_agent: None, loaded_draft: None, draft_flush: None, @@ -3414,6 +3422,13 @@ impl Workspace { self.sync_dirty = true; } while let Ok(mut event) = self.rx.try_recv() { + if self.production_exit.is_some() + && !matches!(&event, Event::Saved(..) | Event::PiAction(..)) + && !matches!(&event, Event::Json(method, _) if matches!(method.as_str(), + "save" | "product-exit-checkpoint" | "slot-product-view-save" | "slot-product-export")) + { + continue; + } if let Event::SlotCanvas(doc, meta) = &mut event && let Some(preview) = meta.as_object_mut().and_then(|fields| fields.remove("originalPreview")) && meta["accountId"] == self.account["id"] && meta["origin"] == self.origin @@ -3459,13 +3474,11 @@ impl Workspace { self.advance_production_exit(app, ctx); return; } + if self.exit_admission_closed.load(std::sync::atomic::Ordering::Acquire) { return; } if !self.tick_context(app, ctx) { return; } let current = app.session.active().map(|s| (s.doc.id.0, s.revision)); self.tick_pending_edits(app, ctx, current); self.creation_autosave(app, ctx); - if painting && (self.busy.is_some() || self.saving.is_some()) { - ctx.request_repaint_after(Duration::from_millis(100)); - } let visible = self.library && !self.material && !self.creation_open; let focused = ctx.input(|i| i.raw.focused); let refresh_due = project_refresh_due( @@ -3516,8 +3529,12 @@ impl Workspace { } } fn save_project_draft(&mut self, state: &photocraft_engine::DocState, ctx: &egui::Context) -> bool { + let composer_saved = self.flush_document_draft(ctx, Some(state.doc.id.0), false); + self.enqueue_project_draft(state, composer_saved) + } + + fn enqueue_project_draft(&mut self, state: &photocraft_engine::DocState, composer_saved: bool) -> bool { let key = (state.doc.id.0, state.revision); - let composer_saved = self.flush_document_draft(ctx, Some(key.0), false); if !composer_saved { self.draft_changed = true; } let meta = json!({"composer":self.composer,"messages":self.messages,"project":self.project_context,"syncDirty":self.sync_dirty,"creationDraft":self.creation_draft()}); let submitted = self.tx.send(Request::Save(state.doc.clone(), state.revision, meta)).is_ok(); @@ -4134,9 +4151,51 @@ pub(crate) fn guard_production_exit(app: &mut PhotocraftApp, ctx: &egui::Context let Some(mut workspace) = app.jiansun.take() else { return false; }; let waiting = workspace.begin_production_exit(app, ctx); app.jiansun = Some(workspace); + if waiting { app.explicit_exit = true; } waiting } +pub(crate) fn flushing_exit(app: &PhotocraftApp) -> bool { + app.jiansun.as_ref().is_some_and(|w| w.production_exit.is_some()) +} + +pub(crate) fn exit_flush_finished(app: &PhotocraftApp) -> bool { + app.jiansun.as_ref().is_some_and(|w| w.production_exit.is_none() + && w.exit_admission_closed.load(std::sync::atomic::Ordering::Acquire)) +} + +pub(crate) fn cancel_exit(app: &mut PhotocraftApp) { + use std::sync::atomic::Ordering; + let Some(workspace) = app.jiansun.as_mut() else { return }; + if workspace.exit_admission_closed.swap(false, Ordering::AcqRel) { + if let Some(cancel) = workspace.cancel_daemon_exit { cancel(); } + workspace.busy = None; + workspace.pi_run = None; + workspace.pi_native = false; + workspace.pi_request_scope = Value::Null; + } +} + +pub(crate) fn background_status(app: &PhotocraftApp) -> Option { + app.jiansun.as_ref().and_then(|workspace| workspace.background_status(app)) +} + +impl Workspace { + fn background_status(&self, app: &PhotocraftApp) -> Option { + self.product_production.as_ref().and_then(product_production::Run::progress_label) + .or_else(|| (self.product_start_queued || self.product_export.is_some() + || self.busy.as_deref() == Some("slot-product-export")).then(|| "正在制作或导出".into())) + .or_else(|| (self.saving.is_some() || self.product_view_save_pending()).then(|| "正在保存小壹工程".into())) + .or_else(|| (self.pending() || self.pending_slot_apply.is_some() + || matches!(self.busy.as_deref(), Some("creation-facts" | "creation-points" | "creation-plan" | "creation-generate" | "creation-recover"))) + .then(|| "小壹正在处理任务".into())) + .or_else(|| (self.unknown && self.automatic_recovery_doc(app).is_some() + && self.original_image_recoveries().any(|(_, id)| { + self.image_recovery_schedules.get(id).is_none_or(|schedule| !schedule.exhausted()) + })).then(|| "正在核查原生图请求".into())) + } +} + pub(crate) fn bind_workspace_rendering(app: &PhotocraftApp, ui: &Ui) { if app.jiansun.is_some() { glow_pill::bind(ui, app.gpu_render_state.as_ref()); @@ -4620,6 +4679,11 @@ mod agent_daemon_control_tests { } fn action_impl(app: &mut PhotocraftApp, ctx: Option<&egui::Context>, method: &str, input: Value) -> Result { + if app.jiansun.as_ref().is_some_and(|w| w.exit_admission_closed.load(std::sync::atomic::Ordering::Acquire)) + && !matches!(method, "state" | "agent-daemon-state") + { + return Err("小壹正在退出,未派发新任务".into()); + } if matches!(method, "agent-daemon-state" | "agent-daemon-start") { if !input.as_object().is_some_and(|fields| fields.is_empty()) { return Err("后台 Agent 控制不接受参数".into()); } return app.services.agent_daemon.as_ref().ok_or("当前客户端不支持后台 Agent 服务")?(method == "agent-daemon-start"); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs index 2cfc2c2e..e98ace6c 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs @@ -1635,7 +1635,7 @@ impl Workspace { .unwrap_or_else(|_| Err("原图源校验失败".into())); ADOPTION_WORKER_BUSY.store(false, Ordering::Release); let _ = tx.send(result); - wake.request_repaint(); + wake.request_repaint_of(egui::ViewportId::ROOT); }); if spawned.is_err() { ADOPTION_WORKER_BUSY.store(false, Ordering::Release); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/composer_drafts.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/composer_drafts.rs index f0be69f8..ec2754a7 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/composer_drafts.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/composer_drafts.rs @@ -17,6 +17,40 @@ pub(super) struct State { drafts: HashMap<(u64, String), Draft>, } impl Workspace { + pub(super) fn save_exit_composers(&self, ctx: &egui::Context) -> Option>> { + let scope = self.local_identity(""); + let cursor = egui::text_edit::TextEditState::load(ctx, super::composer_input_id()).and_then(|state| state.cursor.char_range()); + let drafts: Vec<_> = self.composer_drafts.drafts.iter() + .filter(|((_, identity), _)| identity.starts_with(&scope)) + .filter_map(|(key, draft)| { + let (text, selection) = if self.composer_drafts.active.as_ref() == Some(key) { + (self.composer.as_str(), cursor) + } else { (draft.text.as_str(), draft.cursor) }; + if !draft.dirty && text == draft.text && selection == draft.cursor { return None; } + let length = text.chars().count(); + let primary = selection.map_or(length, |c| usize::from(c.primary.index)).min(length) as u64; + let secondary = selection.map_or(primary, |c| usize::from(c.secondary.index).min(length) as u64); + Some((draft.token.clone(), text.to_owned(), primary, secondary, draft.generation)) + }).collect(); + if drafts.is_empty() { return None; } + let flush = self.draft_flush.clone(); + let ctx = ctx.clone(); + let (send, receive) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let result = (|| { + let flush = flush.ok_or("草稿存储暂不可用")?; + for (token, text, primary, secondary, generation) in drafts { + let next = generation.checked_add(1).ok_or("草稿版本溢出")?; + flush(&token, &text, primary, secondary, next)?; + } + Ok(()) + })(); + let _ = send.send(result); + ctx.request_repaint_of(egui::ViewportId::ROOT); + }); + Some(receive) + } + pub(super) fn flush_account_drafts(&mut self, ctx: &egui::Context) -> bool { if self.observed_doc.is_some() && !self.flush_document_draft(ctx, self.observed_doc, false) { self.account_error = "草稿保存失败,内容已保留在内存;请恢复本机写入后重试".into(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs index 50ac5095..ebd71741 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs @@ -2,7 +2,7 @@ use super::{Document, PhotocraftApp, Request, Value, Workspace, canvas_workspace use photocraft_doc::LayerId; use photocraft_engine::DocState; use std::collections::{HashMap, HashSet, VecDeque}; -use std::sync::Arc; +use std::sync::{Arc, mpsc, atomic::Ordering}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; #[derive(Clone, Eq, Hash, PartialEq)] @@ -520,10 +520,7 @@ impl Workspace { "messages":self.messages,"project":self.project_context,"syncDirty":!reuse_saved&&self.sync_dirty, "creationDraft":self.creation_draft()}) } else { json!({"productViewOnly":true}) }; - if self.tx.send(Request::Save(active.doc.clone(), active.revision, meta)).is_ok() { - self.product_views.saving = Some(active.revision); - ctx.request_repaint_after(std::time::Duration::from_millis(50)); - } + self.queue_product_view_save(active, meta); return; } if !ready { return; } @@ -587,6 +584,14 @@ impl Workspace { app.sync_views(); ctx.request_repaint(); } + + fn queue_product_view_save(&mut self, state: &DocState, meta: Value) -> bool { + if self.tx.send(Request::Save(state.doc.clone(), state.revision, meta)).is_err() { + return false; + } + self.product_views.saving = Some(state.revision); + true + } } impl Canvas { @@ -648,14 +653,32 @@ pub(super) struct Run { } pub(super) struct PendingExit { - doc: u64, - project: String, + draft: Option, deadline: Instant, + daemon: Option>>, + composers: Option>>, pub(super) checkpoint: Option>, pub(super) save_error: Option, save_requested: bool, } +impl PendingExit { + fn poll_receipts(&mut self) -> Option> { + let checkpoint = self.checkpoint.clone()?; + for pending in [&mut self.daemon, &mut self.composers] { + let Some(receipt) = pending else { continue }; + let result = match receipt.try_recv() { + Ok(result) => result, + Err(mpsc::TryRecvError::Empty) => return None, + Err(mpsc::TryRecvError::Disconnected) => Err("退出保存回执未确认".into()), + }; + if let Err(error) = result { self.save_error.get_or_insert(error); } + *pending = None; + } + Some(self.save_error.clone().map_or(checkpoint, Err)) + } +} + pub(super) const DEFAULT_BUDGET_MINUTES: u64 = 45; pub(super) fn budget_minutes(value: &Value) -> u64 { @@ -817,13 +840,23 @@ impl Workspace { pub(super) fn begin_production_exit(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { if self.production_exit.is_some() { return true; } - let Some(run) = self.product_production.take() else { return false; }; - if let Some(pause) = self.pause_production_agent { - pause(run.doc, &run.project); + let draft = self.with_product_target(app, |w, app| app.session.active() + .filter(|state| w.loaded_draft == Some(state.doc.id.0)) + .map(|state| (state.doc.id.0, w.draft_changed || w.creation_dirty + || w.persisted_revisions.get(&state.doc.id.0) != Some(&state.revision)))); + if self.exit_admission_closed.load(Ordering::Acquire) + || !app.explicit_exit && !(draft.is_some_and(|(_, dirty)| dirty) || self.product_production.is_some() + || self.background_status(app).is_some() || app.services.app_tray.is_some() && (app.saving() || app.exporting())) + { + return false; } + self.exit_admission_closed.store(true, Ordering::Release); + let deadline = Instant::now() + Duration::from_secs(90); + let daemon = self.prepare_daemon_exit.as_ref().map(|prepare| prepare()); + let composers = self.save_exit_composers(ctx); + let run = self.product_production.take(); self.with_product_target(app, |w, _| { w.pi_ui_cancel("客户端正在退出"); - w.allow_apply = false; w.handover(); }); self.pending_slot_apply = None; @@ -831,13 +864,23 @@ impl Workspace { self.agent_effects_paused = true; self.product_checkpoint = Value::Null; - let checkpoint = self.tx.send(Request::Action("product-exit-checkpoint".into(), - Self::production_checkpoint_request(&run, true))); + let input = run.map(|run| Self::production_checkpoint_request(&run, true)).or_else(|| { + let (doc, _) = draft?; + let identity = self.open_projects.get(&doc)?; + let project = identity.strip_prefix(&self.local_identity(""))?; + Some(json!({"doc":doc,"checkpoint":{"project":project}})) + }); + let checkpoint = if let Some(mut input) = input { + input["checkpoint"]["status"] = json!("paused_on_exit"); + self.tx.send(Request::Action("product-exit-checkpoint".into(), input)).err() + .map(|_| Err("本机制作记录保存服务已断开".into())) + } else { Some(Ok(())) }; self.production_exit = Some(PendingExit { - doc: run.doc, - project: run.project, - deadline: Instant::now() + Duration::from_secs(90), - checkpoint: checkpoint.err().map(|_| Err("本机制作记录保存服务已断开".into())), + draft: draft.map(|(id, _)| id), + deadline, + daemon, + composers, + checkpoint, save_error: None, save_requested: false, }); @@ -848,28 +891,16 @@ impl Workspace { } pub(super) fn advance_production_exit(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) { - let result = self.with_product_target(app, |w, app| { - let exit = w.production_exit.as_ref()?; - let remaining = exit.deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { return Some(Err("退出等待超时,保存结果未确认".to_owned())); } + let Some(exit) = &self.production_exit else { return }; + let remaining = exit.deadline.saturating_duration_since(Instant::now()); + let result = if remaining.is_zero() { + Some(Err("退出等待超时,保存结果未确认".to_owned())) + } else { ctx.request_repaint_after(remaining); - if w.saving.is_some() || w.product_view_save_pending() { return None; } - if let Some(error) = &exit.save_error { return Some(Err(error.clone())); } - let Some(state) = app.session.active().filter(|state| state.doc.id.0 == exit.doc - && w.open_projects.get(&exit.doc) == Some(&exit.project) && exit.project.starts_with(&w.local_identity(""))) else { - return Some(Err("制作工程已切换,请核对原工程的草稿".into())); - }; - if w.persisted_revisions.get(&exit.doc) != Some(&state.revision) || w.draft_changed { - if exit.save_requested { return Some(Err("仍有编辑未落盘,请检查保存状态".into())); } - if !w.save_project_draft(state, ctx) { return Some(Err("本机草稿保存服务已断开".into())); } - if let Some(exit) = &mut w.production_exit { - exit.save_requested = true; - } - return None; - } - exit.checkpoint.clone() - }); - let Some(result) = result else { return; }; + let view = self.flush_exit_view(app); + self.with_product_target(app, Workspace::flush_exit_draft).map(|draft| draft.and(view)) + }; + let Some(result) = result else { return }; self.production_exit = None; if let Err(error) = result { log::warn!("小壹退出前保存未确认:{error}"); @@ -879,6 +910,50 @@ impl Workspace { ctx.send_viewport_cmd(egui::ViewportCommand::Close); } + fn flush_exit_view(&mut self, app: &PhotocraftApp) -> Result<(), String> { + // The editable view may be on another output of the same project. + // Preserve its own draft before briefly swapping in the working canvas. + if !self.product_view_save_pending() && !app.saving() + && let Some(view) = app.session.active().filter(|state| state.is_dirty()) + && self.product_views.worker.as_ref().is_some_and(|worker| worker.document.doc.id == view.doc.id) + { + if self.product_views.failed_revision == Some(view.revision) { + return Err(self.error.clone()); + } + if !self.queue_product_view_save(view, json!({"productViewOnly":true})) { + return Err("当前产品画布保存服务已断开".into()); + } + } + Ok(()) + } + + fn flush_exit_draft(&mut self, app: &mut PhotocraftApp) -> Option> { + if self.saving.is_some() || self.product_view_save_pending() || app.saving() { return None; } + let exit = self.production_exit.as_mut()?; + if let Some(id) = exit.draft + && exit.save_error.is_none() + { + let Some(state) = app.session.active().filter(|state| state.doc.id.0 == id) else { + return Some(Err("制作工程已切换,请核对原工程的草稿".into())); + }; + if self.persisted_revisions.get(&id) != Some(&state.revision) || self.draft_changed + || (self.creation_dirty && !exit.save_requested) + { + if exit.save_requested { + exit.save_error = Some("仍有编辑未落盘,请检查保存状态".into()); + } else { + exit.save_requested = true; + if self.enqueue_project_draft(state, true) { return None; } + if let Some(exit) = &mut self.production_exit { + exit.save_error = Some("本机草稿保存服务已断开".into()); + } + } + } + } + if self.busy.as_deref() == Some("slot-product-export") || app.exporting() { return None; } + self.production_exit.as_mut()?.poll_receipts() + } + pub(super) fn stop_production(&mut self) { if let Some(run) = self.product_production.as_ref() { if let Some(pause) = self.pause_production_agent { @@ -935,11 +1010,14 @@ impl Workspace { pub(super) fn production_saved(&self, app: &mut PhotocraftApp, id: u64, revision: u64, meta: &Value, owned: bool) { // Mark only the confirmed project snapshot as saved. Crash recovery // should still collect edits made after this revision. - if owned && self.template_workflow["productionStages"].is_array() + if owned && let Some(path) = meta["savedPath"].as_str() && let Some(state) = app.session.active_mut().filter(|state| state.doc.id.0 == id && state.revision == revision) && state.path.as_deref().is_none_or(|source| std::path::Path::new(source) == std::path::Path::new(path)) - && super::canvas_workspace::document_mapping(&state.doc).is_some_and(|map| map["workspaceId"] == self.template_workflow["workspaceId"]) { + && (self.production_exit.is_some() || self.template_workflow["productionStages"].is_array() + && super::canvas_workspace::document_mapping(&state.doc) + .is_some_and(|map| map["workspaceId"] == self.template_workflow["workspaceId"])) + { state.saved_revision = revision; } } @@ -1434,6 +1512,107 @@ mod tests { use super::*; use std::sync::mpsc; + #[test] + fn exit_pauses_the_checkpoint_and_waits_for_draft_and_daemon_receipts() { + for timeout in [false, true] { + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":40,"height":50})).unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + let doc = app.session.active().unwrap().doc.id.0; + let (tx, requests) = mpsc::channel(); + let (events, rx) = mpsc::channel(); + let (daemon, receipt) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + requests.try_recv().unwrap(); + w.loaded_draft = Some(doc); + w.draft_changed = true; + let receipt = std::cell::RefCell::new(Some(receipt)); + w.prepare_daemon_exit = Some(Box::new(move || receipt.take().unwrap())); + w.product_production = Some(Run::new(doc, "account|project".into(), json!("workspace"), + VecDeque::from([Stage { output:"detail".into(), variant:"wood".into() }]), None, Phase::Agent)); + app.jiansun = Some(w); + + let ctx = egui::Context::default(); + let step = |app: &mut PhotocraftApp| { + ctx.run_logic(&Default::default(), |ctx| super::super::advance(app, ctx)) + .viewport_commands.remove(&egui::ViewportId::ROOT).unwrap_or_default() + }; + let _ = ctx.run_logic(&Default::default(), |ctx| assert!(super::super::guard_production_exit(&mut app, ctx))); + assert!(super::super::action(&mut app, "slot-append", json!({})).unwrap_err().contains("未派发")); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("exit checkpoint") }; + assert_eq!(method, "product-exit-checkpoint"); + assert_eq!(input["checkpoint"]["status"], "paused_on_exit"); + assert_eq!(input["checkpoint"]["active"], true); + assert!(!step(&mut app).contains(&egui::ViewportCommand::Close)); + let Request::Save(canvas, revision, _) = requests.try_recv().unwrap() else { panic!("final draft save") }; + assert_eq!(canvas.id.0, doc); + events.send(super::super::Event::Json(method, Ok(Value::Null))).unwrap(); + if timeout { + let exit = app.jiansun.as_mut().unwrap().production_exit.as_mut().unwrap(); + exit.deadline = Instant::now(); + } else { + events.send(super::super::Event::Saved(doc, revision, json!({"localId":"project"}))).unwrap(); + assert!(!step(&mut app).contains(&egui::ViewportCommand::Close)); + daemon.send(Ok(())).unwrap(); + } + assert!(step(&mut app).contains(&egui::ViewportCommand::Close)); + assert_eq!(app.ui.status_error, timeout); + assert_eq!(app.jiansun.as_ref().unwrap().persisted_revisions.get(&doc), (!timeout).then_some(&revision)); + assert!(requests.try_recv().is_err()); + } + } + + #[test] + fn window_close_parks_active_work_and_drains_the_completion_without_painting() { + use crate::{AppTray, TrayAction}; + #[derive(Default)] + struct Tray { + visible: bool, + menu: Arc>>, + } + impl AppTray for Tray { + fn visible(&self) -> bool { self.visible } + fn show(&mut self, _: &str) -> Result<(), String> { + self.visible = true; + Ok(()) + } + fn take_action(&mut self) -> Option { + let action = self.menu.lock().unwrap().take()?; + self.visible = false; + Some(action) + } + fn set_status(&mut self, _: &str) {} + } + let (tx, requests) = mpsc::channel(); + let (events, rx) = mpsc::channel(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let tray = Tray::default(); + let menu = tray.menu.clone(); + app.services.app_tray = Some(Box::new(tray)); + app.jiansun = Some(Workspace::new(tx, rx)); + requests.try_recv().unwrap(); + app.jiansun.as_mut().unwrap().busy = Some("image".into()); + + let ctx = egui::Context::default(); + let close = |app: &mut PhotocraftApp| { + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close); + ctx.run_logic(&input, |ctx| crate::discard_ui::guard_window_close(app, ctx)) + .viewport_commands.remove(&egui::ViewportId::ROOT).unwrap_or_default() + }; + let parked = close(&mut app); + assert!(parked.contains(&egui::ViewportCommand::CancelClose)); + assert!(parked.contains(&egui::ViewportCommand::Visible(false))); + assert!(!super::super::flushing_exit(&app)); + events.send(super::super::Event::Json("image".into(), Err("本轮已结束".into()))).unwrap(); + let _ = ctx.run_logic(&Default::default(), |ctx| super::super::advance(&mut app, ctx)); + assert!(super::super::background_status(&app).is_none()); + *menu.lock().unwrap() = Some(TrayAction::Restore); + let restored = ctx.run_logic(&Default::default(), |ctx| crate::discard_ui::poll_tray(&mut app, ctx)); + assert!(restored.viewport_commands[&egui::ViewportId::ROOT].contains(&egui::ViewportCommand::Visible(true))); + assert!(!close(&mut app).contains(&egui::ViewportCommand::CancelClose)); + } + #[test] fn the_project_budget_sets_the_deadline_and_is_recorded_for_resume() { assert_eq!(budget_minutes(&Value::Null), 45); diff --git a/apps/detail-photocraft/crates/ui-egui/src/lib.rs b/apps/detail-photocraft/crates/ui-egui/src/lib.rs index 241e97ce..b00fead4 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/lib.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/lib.rs @@ -257,6 +257,7 @@ pub(crate) use services::SAVE_OPTIONS_OPEN; #[cfg(test)] pub(crate) use services::saved_revision_after_write; pub use services::{ + AppTray, TrayAction, AdoptAutosaveFn, AgentDaemonFn, AppendTextFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationReadLimitedFn, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, CaptionStyleFn, ClipboardGetFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, @@ -711,6 +712,7 @@ pub struct PhotocraftApp { pub(crate) held_preset_import: Option, /// Set once the user has agreed to quit, so the resulting close request goes through. pub(crate) allow_close: bool, + pub(crate) explicit_exit: bool, /// Pen pressure/tilt from the platform (see `stylus`). pub stylus: stylus::Stylus, control_click: control_click::ControlClick, diff --git a/apps/detail-photocraft/crates/ui-egui/src/menus/invoke.rs b/apps/detail-photocraft/crates/ui-egui/src/menus/invoke.rs index 5e02d37c..d5b7321a 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/menus/invoke.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/menus/invoke.rs @@ -45,8 +45,16 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va { authorize(id, ¶ms)?; } - if id == "file.exit" && crate::jiansun::guard_production_exit(app, ctx) { - return Ok(Value::Null); + #[cfg(not(target_arch = "wasm32"))] + if id == "file.exit" { + app.explicit_exit = true; + if crate::jiansun::guard_production_exit(app, ctx) { + return Ok(Value::Null); + } + } + #[cfg(not(target_arch = "wasm32"))] + if crate::jiansun::flushing_exit(app) { + return Err("正在保存小壹进度,请等待退出".into()); } if crate::discard_ui::intercept(app, id, ¶ms) { return Ok(Value::Null); @@ -275,6 +283,7 @@ fn invoke_file_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, } } "file.exit" => { + app.explicit_exit = true; ctx.send_viewport_cmd(egui::ViewportCommand::Close); Ok(Value::Null) } diff --git a/apps/detail-photocraft/crates/ui-egui/src/services.rs b/apps/detail-photocraft/crates/ui-egui/src/services.rs index 5cae6cc9..99908309 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/services.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/services.rs @@ -486,6 +486,7 @@ pub struct Services { /// (Windows custom title bar, #2246). Called once per frame; `None` when the window is /// decorated or the platform needs no fixing. pub window_frame: Option, + pub app_tray: Option>, /// How the custom title bar's caption buttons look and where they sit (Linux: the desktop's /// style and button layout). Read every frame, with the context to wake when it changes; /// `None` keeps Windows' buttons at the right end. @@ -507,3 +508,16 @@ pub struct Services { /// Without one, eframe closes the window and the app ends with it. pub quit: Option, } + +/// The desktop shell owns the notification-area icon and its native event callbacks. +pub trait AppTray { + fn visible(&self) -> bool; + fn show(&mut self, status: &str) -> Result<(), String>; + fn take_action(&mut self) -> Option; + fn set_status(&mut self, status: &str); +} + +pub enum TrayAction { + Restore, + Exit, +} From 93df00c892890bbf08a72ac8de8d79742f91deb3 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Thu, 26 Nov 2026 18:30:42 +0800 Subject: [PATCH 3/4] fix(xiaoyi): isolate production writes and publish verified generations Fence stopped runs and bind background canvas activity to the production document and variant. Publish immutable export manifests atomically and correlate native and Pi execution events in the project journal. --- .../scripts/verify-production-exports.py | 9 + apps/detail-agent-pi/src/activity-event.mjs | 44 +++- apps/detail-agent-pi/src/agent.mjs | 57 ++++- apps/detail-agent-pi/src/desktop-daemon.mjs | 16 +- apps/detail-agent-pi/src/desktop-host.mjs | 63 +++++- .../src/production-operations.mjs | 31 ++- apps/detail-agent-pi/src/request-purpose.mjs | 1 + apps/detail-agent-pi/src/stdio-canvas.mjs | 10 +- apps/detail-agent-pi/src/store.mjs | 4 +- .../test/conversation.test.mjs | 36 ++++ .../test/desktop-daemon.test.mjs | 88 ++++++++ .../test/production-operations.test.mjs | 39 ++++ .../photocraft/src/jiansun_agent_daemon.rs | 8 +- .../apps/photocraft/src/jiansun_backend.rs | 33 ++- .../src/jiansun_canvas_workspace.rs | 197 ++++++++++++++++-- .../apps/photocraft/src/jiansun_pi_runtime.rs | 85 +++++++- .../photocraft/src/jiansun_project_file.rs | 2 +- .../crates/ui-egui/src/jiansun.rs | 71 ++++++- .../ui-egui/src/jiansun/canvas_workspace.rs | 7 +- .../crates/ui-egui/src/jiansun/pi_bridge.rs | 24 ++- .../ui-egui/src/jiansun/product_production.rs | 138 +++++++++++- .../ui-egui/src/jiansun/workflow_bridge.rs | 3 +- 22 files changed, 882 insertions(+), 84 deletions(-) diff --git a/apps/detail-agent-pi/scripts/verify-production-exports.py b/apps/detail-agent-pi/scripts/verify-production-exports.py index eca19eea..1a716e5c 100644 --- a/apps/detail-agent-pi/scripts/verify-production-exports.py +++ b/apps/detail-agent-pi/scripts/verify-production-exports.py @@ -48,6 +48,15 @@ def inspect_receipt(receipt_file): receipt = read_json(receipt_file) generation = receipt["generationId"] directory = receipt_file.parent / "generations" + if "publishedPointer" in receipt: + manifest = Path("generations") / generation / "manifest.json" + if Path(generation).name != generation or not generation.startswith("generation-") or Path(receipt["publishedPointer"]) != manifest: + raise ValueError("交付指针无效") + published = read_json(receipt_file.parent / manifest) + identity = ("generationId", "workspaceId", "outputId", "variantId") + if any(published[key] != receipt[key] for key in identity): + raise ValueError("交付指针与清单不一致") + receipt = published source = receipt["sourceDocument"] files = [] for photo in receipt["files"] + receipt.get("screenFiles", []): diff --git a/apps/detail-agent-pi/src/activity-event.mjs b/apps/detail-agent-pi/src/activity-event.mjs index ca5e3cc0..519080af 100644 --- a/apps/detail-agent-pi/src/activity-event.mjs +++ b/apps/detail-agent-pi/src/activity-event.mjs @@ -23,6 +23,46 @@ const labels = Object.freeze({ const safeId = value => typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(value) ? value : undefined; const safeNumber = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined; +const operationCategories = Object.freeze({ + 'pi-state':'ui_ack', 'pi-production-open':'canvas_read', 'pi-canvas-read':'canvas_read', + 'pi-product-screen':'canvas_read', 'pi-detail-copy-fields':'canvas_read', + 'pi-template-image':'canvas_read', 'pi-detail-images':'canvas_read', 'pi-workflow-read':'canvas_read', + 'pi-preview':'canvas_read', 'pi-native-catalog':'canvas_read', + 'pi-image-request':'remote_image', 'pi-detail-copy-apply':'canvas_write', 'pi-edit':'canvas_write', + 'pi-write-request':'canvas_write', 'pi-workflow-execute':'canvas_write', 'pi-native-call':'canvas_write', + canvas_read:'canvas_read', canvas_preview:'canvas_read', read_output_screen:'canvas_read', read_copy_fields:'canvas_read', + prepare_image_request:'remote_image', dispatch_image_request:'remote_image', + reconcile_image_slots:'remote_image', adopt_production_image:'canvas_write', + write_copy_fields:'canvas_write', canvas_edit:'canvas_write', finish_production:'export', + production_image_retired:'remote_image', whole_detail_review:'inference', +}); +export const executionCategory = action => operationCategories[action] ?? 'ui_ack'; + +const inferencePhases = Object.freeze({ + provider_prepared:['prepare','prepared'], serialized_request:['serialize','prepared'], + provider_started:['dispatch','running'], provider_finished:['receipt','completed'], + provider_error:['receipt','failed'], response_audit:['inspect','completed'], + usage:['usage','completed'], pi_retry:['retry','pending'], +}); + +export function executionEvent(event, scope, health, at = Date.now()) { + const inference = inferencePhases[event.type]; + const category = event.category ?? (inference ? 'inference' : executionCategory(event.toolName ?? event.type)); + const phase = event.phase ?? inference?.[0] ?? event.type; + const status = event.status ?? (event.consumption === 'discarded_after_cancel' ? 'cancelled' : + event.type === 'provider_finished' && event.phase ? event.phase : + inference?.[1] ?? (event.isError ? 'failed' : 'completed')); + // Keep legacy phase values on provider receipts and an independent lifecycle stage. + return {at,...event,category,phase,status,stage:event.stage ?? inference?.[0] ?? phase, + projectId:event.projectId ?? scope.projectId ?? null,runId:event.runId ?? scope.runId ?? null, + operationId:event.operationId ?? event.id ?? event.toolCallId ?? scope.runId ?? null, + attempt:event.attempt ?? 1,outputId:event.outputId ?? scope.outputId ?? null, + variantId:event.variantId ?? scope.variantId ?? null,revision:event.revision ?? scope.revision ?? null, + documentKey:event.documentKey ?? scope.documentKey ?? null, + agentHeartbeat:health.agentHeartbeat ?? null,uiHeartbeat:health.uiHeartbeat ?? null, + jobProgress:event.jobProgress ?? null,recentDurableCommit:health.recentDurableCommit ?? null}; +} + // Read this once from pi-begin, whose requestScope is frozen by the native host. // IDs outside the expected format are omitted instead of copied as free text. export function activityScope(identity, canvas, begun) { @@ -62,5 +102,7 @@ export function toolActivity(event, scope, timestampMs = Date.now()) { const toolCallId = safeId(event.toolCallId); if (!toolCallId || safeNumber(timestampMs) === undefined) return null; const durationMs = safeNumber(event.durationMs); - return { version: 1, type: 'tool', toolCallId, ...details(event), timestampMs, ...(durationMs === undefined ? {} : { durationMs }), scope }; + const activity = details(event); + return { version: 1, type: 'tool', toolCallId, ...activity, phase:activity.status, + category:executionCategory(activity.toolName),timestampMs, ...(durationMs === undefined ? {} : { durationMs }), scope }; } diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index c9bbd608..eddac750 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -1,4 +1,5 @@ import {setTimeout as delay} from 'node:timers/promises'; +import { randomUUID } from 'node:crypto'; import { confirmProductionResponse, confirmedProductionFailure, piRetryPolicy, productRequestScope, productionUsesAutomaticTools, ProductionOutputLimit, ProductionRequestFailed, ProductionRequestPending } from './production-recovery.mjs'; import { enterpriseTools } from './enterprise-knowledge.mjs'; import { executeWorkflow } from './workflow-execute.mjs'; @@ -86,6 +87,7 @@ function toolsFor(host) { if (name === 'memory_set' && !host.productionGoal && host.canvas?.workflowRead) await host.readWorkflow({section:'overview'}); if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧工具不会继续执行'); try { + host.productionSignal?.throwIfAborted(); const value = await execute(args, signal, ctx); return format(name==='canvas_read'&&args.revision!==undefined?{...value,changedSinceRevision:value.revision!==args.revision}:value); } catch(error) { @@ -421,7 +423,7 @@ export class DetailPiAgent { return; } round = (host.goalBroker ?? broker).round({inference:true}); - await store.appendEvent({ type: 'provider_prepared', id: round.id, model: model.id, bindingHash: store.hash, + await store.appendEvent({ type: 'provider_prepared', id: round.id, requestId:round.id, model: model.id, bindingHash: store.hash, purpose: host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation' }); host.inflight = round.id; if (!host.compacting) requiredTool = host.requiredTool; @@ -429,6 +431,8 @@ export class DetailPiAgent { let sentAt, headersAt, firstThinkingAt, firstTextAt, firstToolAt; const stream = apiImpl.streamSimple(model, wireContext, { ...options, apiKey: 'native-broker-only', fetch: async (...args) => { sentAt = Date.now(); + await store.appendEvent({type:'provider_started',id:round.id,requestId:round.id}); + host.productionSignal?.throwIfAborted(); const response = await round.fetch(...args); headersAt = Date.now(); wireCapture = response.clone().text().then(text => ({ text }), error => ({ error })); @@ -457,6 +461,7 @@ export class DetailPiAgent { if (event.type === 'text_delta' && firstTextAt === undefined) firstTextAt = Date.now(); // Finalize the durable journal BEFORE Pi can execute any returned tool. 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: [] }; @@ -477,7 +482,8 @@ export class DetailPiAgent { ? 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, ...settled, + await store.appendEvent({ type: 'provider_finished', id: round.id, requestId:round.id, ...settled, + ...(options.signal?.aborted || host.productionSignal?.aborted ? {consumption:'discarded_after_cancel'} : null), ...(sentAt === undefined ? {} : { ...(headersAt === undefined ? {} : {responseHeadersMs:headersAt-sentAt}), ...(firstThinkingAt === undefined ? {} : {firstThinkingMs:firstThinkingAt-sentAt}), @@ -488,6 +494,8 @@ export class DetailPiAgent { const failure = confirmedProductionFailure(settled, round.id); if (failure) throw failure; if (result.stopReason==='length' && ['complete','rejected'].includes(settled.phase)) { + 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); @@ -499,10 +507,14 @@ export class DetailPiAgent { const usage = responseUsage(wire.text); await store.appendEvent({ type: 'usage', id: round.id, model: model.id, purpose: host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation', ...usage }); + host.productionSignal?.throwIfAborted(); + options.signal?.throwIfAborted(); await onEvent({ type: 'usage', id: round.id, model: model.id, ...usage }); if (!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); await store.appendEvent({ type: 'response_audit', id: round.id, ...audit, calls: audit.calls.map(c => ({ name: c.name })) }); + 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) { @@ -514,7 +526,8 @@ export class DetailPiAgent { } else { output.push(finalEvent); output.end(result); } } catch (error) { 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)+' '+error.message : String(error.message), 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, reason: message.errorMessage }); + await store.appendEvent({ type: 'provider_error', id: round?.id, 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); } })(); @@ -595,6 +608,7 @@ export class DetailPiAgent { } }); agent.beforeToolCall=async ({toolCall})=>{ + if(productionSignal?.aborted)return {block:true,terminate:true,reason:'原制作回合已停止'}; if(host.productionRequests)return; const key=JSON.stringify([toolCall.name,toolCall.arguments]); const count=(used.get(key)??0)+1; @@ -606,8 +620,11 @@ export class DetailPiAgent { const output=createAssistantMessageEventStream(); (async()=>{ let round; + const operationId=randomUUID(); + let attempt=0; try { const result = await retryAssistantCall(async () => { + attempt++; round = undefined; let requestBytes, firstOutputMs, promptCacheKeyPresent; try { @@ -619,7 +636,8 @@ export class DetailPiAgent { const imageCount=context.messages.reduce((count,message)=>count+ (Array.isArray(message.content)?message.content.filter(item=>item.type==='image').length:0),0); const started=Date.now(); - await store.appendEvent({type:'provider_prepared',id:round.id,model:selected.id,purpose:'whole-detail-worker',slotId,requestScope,imageCount}); + await store.appendEvent({type:'provider_prepared',id:round.id,requestId:round.id,operationId,attempt, + model:selected.id,purpose:'whole-detail-worker',slotId,requestScope,imageCount}); let wire; const stream=apiImpl.streamSimple(selected,context,{...options,toolChoice,apiKey:'native-broker-only', onPayload:payload=>{ @@ -629,6 +647,8 @@ export class DetailPiAgent { fetch:async (...args)=>{ const body=args[1]?.body; if(typeof body==='string')requestBytes=Buffer.byteLength(body); + await store.appendEvent({type:'provider_started',id:round.id,requestId:round.id,operationId,attempt,slotId}); + productionSignal?.throwIfAborted(); const response=await round.fetch(...args); wire=response.clone().text().catch(()=>null); return response; @@ -638,7 +658,7 @@ export class DetailPiAgent { if(event.type==='done'||event.type==='error')finalEvent=event; else{ if(event.type==='text_delta'||event.type==='toolcall_delta')firstOutputMs??=Date.now()-started; - output.push(event); + if (!options.signal?.aborted && !productionSignal?.aborted) output.push(event); } } const message=await stream.result(); @@ -646,7 +666,9 @@ export class DetailPiAgent { const receipt=await round.finish(valid,message.stopReason); const raw=valid&&receipt.phase==='complete'?await wire:null; const usage=raw?responseUsage(raw):null; - await store.appendEvent({type:'provider_finished',id:round.id,slotId,...receipt,requestBytes,firstOutputMs,promptCacheKeyPresent, + await store.appendEvent({type:'provider_finished',id:round.id,requestId:round.id,operationId,attempt, + slotId,...receipt,requestBytes,firstOutputMs,promptCacheKeyPresent, + ...(options.signal?.aborted || productionSignal?.aborted ? {consumption:'discarded_after_cancel'} : null), ...(usage?{inputTokens:usage.inputTokens,outputTokens:usage.outputTokens,cachedTokens:usage.cachedTokens}:null)}); if(receipt.phase==='rejected'&&message.stopReason==='length')throw new ProductionOutputLimit(); const failure=confirmedProductionFailure(receipt,round.id); @@ -656,8 +678,10 @@ export class DetailPiAgent { if(!raw)throw Error('原始模型响应尚未读完,工具未执行'); const audit=auditResponse(raw,info.model.protocol); if(message.content.filter(item=>item.type==='toolCall').length!==audit.calls.length)throw Error('原模型工具调用未完整返回'); - await store.appendEvent({type:'usage',id:round.id,model:selected.id,purpose:'whole-detail-worker',slotId,...usage}); + await store.appendEvent({type:'usage',id:round.id,operationId,attempt,model:selected.id,purpose:'whole-detail-worker',slotId,...usage}); await onEvent({type:'usage',id:round.id,model:selected.id,...usage}); + productionSignal?.throwIfAborted(); + options.signal?.throwIfAborted(); return message; } catch(error) { if (error instanceof ProductionOutputLimit || error instanceof InvalidToolReply || options.signal?.aborted) throw error; @@ -666,13 +690,19 @@ export class DetailPiAgent { timestamp:Date.now(),usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{...cost,total:0}}}; } }, piRetryPolicy, options.signal, {onRetryScheduled:async(attempt,maxAttempts,delayMs)=>{ - await store.appendEvent({type:'pi_retry',id:round?.id,requestScope,slotId,attempt,maxAttempts,delayMs}); + await store.appendEvent({type:'pi_retry',id:round?.id,operationId,requestScope,slotId,attempt,maxAttempts,delayMs}); }}); + productionSignal?.throwIfAborted(); + options.signal?.throwIfAborted(); if (result.stopReason === 'error' || result.stopReason === 'aborted') { output.push({type:'error',reason:result.stopReason,error:result}); } else output.push({type:'done',reason:result.stopReason,message:result}); output.end(result); } catch (error) { + if (round && (productionSignal?.aborted || options.signal?.aborted)) { + await store.appendEvent({type:'provider_error',id:round.id,operationId,attempt,slotId, + status:'cancelled',consumption:'discarded_after_cancel'}); + } if(error instanceof ProductionRequestPending||error instanceof ProductionRequestFailed||error instanceof ProductionOutputLimit|| error instanceof InvalidToolReply)pendingError=error; const failure={role:'assistant',api,provider:selected.provider,model:selected.id,content:[],stopReason:'error', @@ -783,7 +813,8 @@ 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), activity).catch(()=>{}); - await store.appendEvent({ type: event.type, toolName: event.toolName, toolCallId: event.toolCallId, isError: event.isError ?? false }); + await store.appendEvent({ type: event.type, toolName: event.toolName, toolCallId: event.toolCallId, isError: event.isError ?? false, + ...(activity ? {status:activity.status,phase:activity.phase,category:activity.category,durationMs:activity.durationMs} : null) }); void Promise.resolve().then(() => onEvent({ type: event.type, toolName: event.toolName, isError: event.isError ?? false, ...(activity ? { activity } : {}) })).catch(()=>{}); } }); @@ -973,6 +1004,7 @@ export class DetailPiAgent { if (this.manager.getSessionFile()) await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() }); await running; await closeProductionTurn(this); + this.productionSignal?.throwIfAborted(); 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 useStageReceipt = last?.stopReason === 'error' && this.goalStageResult && !this.canvasOperations.writesBlocked; @@ -1127,6 +1159,13 @@ export class DetailPiAgent { } record = { id, ...await this.broker.read(id) }; } + if (purpose.kind === '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:record.requestId,reposted:false,toolsExecuted:0,canvasWrites:0,consumption:'discarded_after_cancel'}; + } if (['whole-detail-worker','product-goal','whole-detail-review'].includes(purpose.kind)) { const {requestId}=record; if (['failed','rejected'].includes(record.phase)) return {phase:'failed',requestId,reposted:false}; diff --git a/apps/detail-agent-pi/src/desktop-daemon.mjs b/apps/detail-agent-pi/src/desktop-daemon.mjs index e0279634..b2aca1fc 100644 --- a/apps/detail-agent-pi/src/desktop-daemon.mjs +++ b/apps/detail-agent-pi/src/desktop-daemon.mjs @@ -34,7 +34,8 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out if(value?.type==='production_pause') { const config=active?.config; if(config?.productProduction===true && value.documentId===config.documentId - && value.project===config.project && value.scope===config.scope) { + && value.project===config.project && value.scope===config.scope + && (value.writeEpoch??null)===(config.writeEpoch??null)) { active.abort(Error('本轮制作已停止,已保留原请求')); } return; @@ -59,6 +60,11 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out if(!task||value.runId!==task.runId||active?.runId!==task.runId)return; waiting.delete(value.id);clearTimeout(task.timer);value.error?task.reject(BridgeError.from(value.error)):task.resolve(value.value);return; } + if(value?.type==='canvas_accepted') { + const task=waiting.get(value.id); + if(task && value.runId===task.runId) task.accepted?.(); + return; + } if(value?.type!=='run'||!uuid.test(value.runId||'')||!value.config||typeof value.config!=='object'||Array.isArray(value.config)) {send({type:'fatal',error:'本地消息无效;不会重发'});return;} if(active){if(active.runId!==value.runId)failure(value.runId,'已有运行中的任务,未派发');return;} if(seen.has(value.runId)||seen.size>=10000){failure(value.runId,'会话编号已使用或达到上限,未派发');return;} @@ -70,16 +76,17 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out const abort = error => { controller.abort(error); for (const [id, task] of waiting) { - if (task.runId !== runId) continue; + if (task.runId !== runId || task.retainOriginal) continue; waiting.delete(id); clearTimeout(task.timer); task.reject(new BridgeError(error.message,'cancelled',{dispatched:true})); } }; active={runId,config,abort}; + config.runId=runId; const expire = () => abort(Error('整套制作已达到时限,已保留当前编辑和原请求')); const timer = deadline === null ? null : setTimeout(expire, Math.max(0, deadline - Date.now())); - const call=(action,input)=>new Promise((resolve,reject)=>{ + const call=(action,input,accepted)=>new Promise((resolve,reject)=>{ if(closed||active?.runId!==runId){reject(new BridgeError('客户端连接已关闭,原操作需核查','transport_interrupted',{retryable:true}));return;} if(controller?.signal.aborted){reject(new BridgeError(controller.signal.reason.message,'cancelled'));return;} if (action === 'pi-delta' || action === 'pi-activity') { @@ -88,7 +95,8 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out return; } const id=++serial; - waiting.set(id,{resolve,reject,runId});send({type:'canvas',runId,id,action,input}); + const retainOriginal=action==='pi-image-request' && input.action==='dispatch'; + waiting.set(id,{resolve,reject,runId,retainOriginal,accepted});send({type:'canvas',runId,id,action,input}); }); void (async()=>{ try { diff --git a/apps/detail-agent-pi/src/desktop-host.mjs b/apps/detail-agent-pi/src/desktop-host.mjs index 7dc278b7..3cef2d63 100644 --- a/apps/detail-agent-pi/src/desktop-host.mjs +++ b/apps/detail-agent-pi/src/desktop-host.mjs @@ -4,9 +4,52 @@ import { createInterface } from 'node:readline'; import path from 'node:path'; import { assertPiNodeVersion } from './runtime-policy.mjs'; import { pathToFileURL } from 'node:url'; +import { randomUUID } from 'node:crypto'; +import { executionCategory } from './activity-event.mjs'; assertPiNodeVersion(process.versions.node); +export function observeCanvasCalls(store, call) { + return async (action, input, execution) => { + if (action === 'pi-delta' || action === 'pi-activity') return call(action,input); + const identity={...store.executionScope,operationId:input.operationId ?? execution?.operationId ?? randomUUID(), + attempt:execution?.attempt ?? 1,requestId:execution?.requestId,revision:input.revision ?? store.executionScope.revision}; + const category=executionCategory(action); + const record=(type,phase,status,extra)=>store.appendEvent({type,action,...identity,phase,status,...extra}) + .catch(error=>console.warn('小壹画布事件写入失败',error.code ?? error.name)); + store.executionHealth.agentHeartbeat=Date.now(); + await record('canvas_enqueued','enqueue','pending',{category:'ui_ack'}); + let accepted; + try { + const value=await call(action,input,()=>{ + store.executionHealth.uiHeartbeat=Date.now(); + accepted=record('canvas_accepted','accept','completed',{category:'ui_ack'}) + .then(()=>record('canvas_started','execute','running',{category})); + }); + await accepted; + if (value?.conversationActive === true) store.executionHealth.uiHeartbeat=Date.now(); + const binding=value?.productionCanvas; + if (binding?.documentKey) Object.assign(store.executionScope,{ + outputId:binding.outputId,variantId:binding.variantId,documentKey:binding.documentKey, + }); + if (Number.isSafeInteger(value?.revision) && + (binding?.documentKey || value.revision >= (store.executionScope.revision ?? 0))) { + store.executionScope.revision=value.revision; + } + const status=value?.executed===false && value?.error ? 'failed' : + [value?.status,value?.phase].find(v=>typeof v==='string') ?? 'completed'; + await record('canvas_receipt','receipt',status,{category,revision:value?.revision ?? identity.revision, + ...(value?.requestId ? {requestId:value.requestId} : null)}); + return value; + } catch(error) { + await accepted; + const status=error.category==='cancelled'?'cancelled':error.category==='transport_interrupted'?'unknown':'failed'; + await record('canvas_receipt','receipt',status,{category:accepted?category:'ui_ack',failureCategory:error.category}); + throw error; + } + }; +} + // Explicit local QA only. Matching a pending real job consumes the switch; // model arguments can neither configure nor re-arm it. export function qaNativeTimeout(raw) { @@ -89,7 +132,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal) { return await recordProductionExport(config.sessionDir, config.goalId); } catch(error) { return {error:error.message}; } } - let host, broker, store, output; + let host, broker, store, output, heartbeat; let releaseRecovery; const productionGoal=config.mode==='prompt'&&config.wholeDetail===true&&config.productProduction===true ? {outputId:config.outputId,variantId:config.variantId,requestedOutputs:config.requestedOutputs, @@ -127,7 +170,16 @@ export async function runSession(config, call, sharedBroker, recovery, signal) { binding = resolveRules({ brandId: shop.brandId, shopId: shop.id, categoryId: combo.categoryId }, config.ruleCatalog); } store = await ProjectStore.open(config.root, { scope: info.accountScope, project: config.project }, binding, { continuous:true }); - const canvas = new StdioCanvas(call, config.documentId); + store.executionScope={runId:config.runId ?? randomUUID(),outputId:config.outputId,variantId:config.variantId, + revision:config.revision,documentKey:config.documentKey}; + store.executionHealth={agentHeartbeat:Date.now()}; + heartbeat=setInterval(()=>{ + store.executionHealth.agentHeartbeat=Date.now(); + void store.appendEvent({type:'agent_heartbeat',phase:'heartbeat',status:'running',category:'ui_ack'}) + .catch(error=>console.warn('小壹心跳事件写入失败',error.code ?? error.name)); + },15_000); + heartbeat.unref(); + const canvas = new StdioCanvas(observeCanvasCalls(store,call), config.documentId); const usage = []; host = await DetailPiAgent.open({ store, broker, productionGoal, productionSignal:signal, brokerInfo:info, canvas, projectEvidence:config.projectEvidence, documentId:config.documentId, onEvent: event => { if (event.type === 'usage') usage.push(event); @@ -175,6 +227,12 @@ export async function runSession(config, call, sharedBroker, recovery, signal) { const reviews = (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() }; + if (result.production?.complete) { + output.production.execution={...store.executionScope,...store.executionHealth, + operationId:randomUUID(),revision:result.production.canvasRevision}; + await store.appendEvent({type:'export_submitted',...output.production.execution,category:'export',phase:'enqueue',status:'pending'}) + .catch(error=>console.warn('小壹导出事件写入失败',error.code ?? error.name)); + } } catch (error) { let pending = [], unknown = false; if (broker) { try { pending = (await broker.status()).pending; unknown = pending.length > 0; } catch { unknown = broker.hasUnconfirmedRequest; } } @@ -192,6 +250,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal) { } } } finally { + clearInterval(heartbeat); signal?.removeEventListener('abort',abort); try { if (host) await host.dispose(); } finally { releaseRecovery?.(); if (broker && !sharedBroker) await broker.close(); } } diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 73c1ca24..d41093df 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -230,7 +230,7 @@ export async function openProductionOperations(host) { }; let displayEpoch=0; const progress=async ({heading,epoch})=>{ - if(epoch!==displayEpoch||host.canvasEndAttempted)return; + if(epoch!==displayEpoch||host.canvasEndAttempted||host.productionSignal?.aborted)return; const pictureCells=slots.map(({id,label})=>{ const item=journal.items[id]; const matched=filled.has(id); @@ -242,13 +242,18 @@ export async function openProductionOperations(host) { label,state:!templateSample&&evidenceMatches(plan)&&journal.copyEvidence?.[layer]?.text===currentText?'verified': !templateSample&¤tText?'filled':'empty', })); - if(epoch!==displayEpoch||host.canvasEndAttempted)return; - return canvas.delta('',undefined,{heading,outputId,variantId,workers:[...jobs.values()].map(job=>job.row), - reviews:pendingReviews().map(job=>job.row),candidateReviews:Object.fromEntries(candidates),pictureCells,copyCells, - total:slots.length,rendered:filled.size,copy:copyCells.filter(row=>row.state==='verified').length, + if(epoch!==displayEpoch||host.canvasEndAttempted||host.productionSignal?.aborted)return; + 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}); + Object.keys(item.pendingGenerations??{}).length).length}; + const category=jobs.size?'remote_image':pendingReviews().length?'inference':'canvas_read'; + await store.appendEvent({type:'production_progress',category,phase:'progress',status:'running',outputId,variantId,jobProgress}); + return canvas.delta('',undefined,{heading,outputId,variantId,category,phase:'progress',status:'running', + workers:[...jobs.values()].map(job=>job.row), + reviews:pendingReviews().map(job=>job.row),candidateReviews:Object.fromEntries(candidates),pictureCells,copyCells, + ...jobProgress}); }; const display=new PresentationBatch(progress); const notice=heading=>display.push({heading,epoch:displayEpoch}); @@ -372,7 +377,7 @@ export async function openProductionOperations(host) { } const {operationId}=original; let receipt; - try { receipt=await canvas.imageRequest('dispatch',{...approval,slotId:slot.id}); } + try { receipt=await canvas.imageRequest('dispatch',{...approval,slotId:slot.id},{operationId,requestId:candidateId}); } catch(error) { if (error.dispatched===false) { await update(journal=>{delete journal.items[slot.id].pendingGenerations[candidateId];}, @@ -384,17 +389,25 @@ export async function openProductionOperations(host) { } const phase=receipt.status??receipt.phase; const settled=settledImagePhases.includes(phase); + const late=signal?.aborted || 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]; + if(late)return; if(settled)Object.assign(item,{candidateId,state:phase==='complete'?'candidate':phase}); Object.assign(item,{prompt:request.prompt,source:'generate'}); 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}); rememberImageExpiry(item,candidateId,receipt); - },{receipt:[candidateId,settled?phase:'unknown',receipt], - evidence:[slot.id,candidateId,'candidate',{requestId:candidateId,...receipt,operationId,reworkOf:request.reworkOf}]}); + },{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), diff --git a/apps/detail-agent-pi/src/request-purpose.mjs b/apps/detail-agent-pi/src/request-purpose.mjs index 95a0f446..8bb4acdb 100644 --- a/apps/detail-agent-pi/src/request-purpose.mjs +++ b/apps/detail-agent-pi/src/request-purpose.mjs @@ -7,6 +7,7 @@ export async function requestPurpose(host, id) { const index = events.findIndex(event => event.type === 'provider_prepared' && event.id === id && (!event.bindingHash || event.bindingHash === host.store.hash)); if (index < 0) throw Error('原请求没有当前会话归属记录'); const event = events[index]; + if (events.some(row=>row.id===id && row.consumption==='discarded_after_cancel')) return {kind:'cancelled',event}; if (event.purpose === 'compaction') return {kind: 'compaction', event}; if (['whole-detail-review','whole-detail-worker','product-goal'].includes(event.purpose)) return {kind:event.purpose,event}; if (event.purpose === 'conversation') return {kind: 'conversation', event}; diff --git a/apps/detail-agent-pi/src/stdio-canvas.mjs b/apps/detail-agent-pi/src/stdio-canvas.mjs index 12fe0b00..06ab8428 100644 --- a/apps/detail-agent-pi/src/stdio-canvas.mjs +++ b/apps/detail-agent-pi/src/stdio-canvas.mjs @@ -10,14 +10,18 @@ export function canvasReplyTimedOut(error) { export class StdioCanvas { durableGenerationIds = true; constructor(call, documentId) { this.call = call; this.documentId = documentId; } - action(action, input = {}) { return this.call(action, { ...input, run: this.run, documentId: this.documentId }); } + action(action, input = {}, execution) { + return this.call(action, { ...input, run: this.run, documentId: this.documentId }, execution); + } async #observe(action, input = {}, signal) { const {run,documentId}=this; const deadline=Date.now()+120_000; + const operationId=randomUUID(); + let attempt=0; for(;;){ signal?.throwIfAborted(); if(this.run!==run||this.documentId!==documentId)throw Error('原回合已结束,未继续查询'); - try { return await this.call(action,{...input,run,documentId}); } + try { return await this.call(action,{...input,run,documentId},{operationId,attempt:++attempt}); } catch(error) { if(!canvasReplyTimedOut(error)||Date.now()>=deadline)throw error; await delay(500,undefined,{signal}); @@ -51,7 +55,7 @@ export class StdioCanvas { return binding; } readCanvas(input = {}) { return this.action('pi-canvas-read', input); } - imageRequest(action,request) { return this.action('pi-image-request',{action,request}); } + imageRequest(action,request,execution) { return this.action('pi-image-request',{action,request},execution); } detailRender(options) { return this.#observe('pi-product-screen', options); } detailCopyFields(options) { return this.#observe('pi-detail-copy-fields', options); } detailApplyCopy(items,revision) { return this.action('pi-detail-copy-apply',{items,revision}); } diff --git a/apps/detail-agent-pi/src/store.mjs b/apps/detail-agent-pi/src/store.mjs index e0e5d7d0..272c7bd8 100644 --- a/apps/detail-agent-pi/src/store.mjs +++ b/apps/detail-agent-pi/src/store.mjs @@ -3,6 +3,7 @@ import path from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import { createHash, randomUUID } from 'node:crypto'; import { ruleContext, templateConstraints } from './rule-context.mjs'; +import { executionEvent } from './activity-event.mjs'; export const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex'); export async function atomic(file, value) { @@ -117,7 +118,8 @@ export class ProjectStore { constraints: templateConstraints(this.binding, options) }; } async appendEvent(event) { - await fs.appendFile(path.join(this.dir, 'events.jsonl'), JSON.stringify({ at: Date.now(), ...event }) + '\n', { mode: 0o600 }); + const record = executionEvent(event, {projectId:this.identity.project,...this.executionScope}, this.executionHealth ?? {}); + await fs.appendFile(path.join(this.dir, 'events.jsonl'), JSON.stringify(record) + '\n', { mode: 0o600 }); } async ownsRequest(id) { let text; try { text = await fs.readFile(path.join(this.dir, 'events.jsonl'), 'utf8'); } catch { return false; } diff --git a/apps/detail-agent-pi/test/conversation.test.mjs b/apps/detail-agent-pi/test/conversation.test.mjs index 62662d2e..c3a585fc 100644 --- a/apps/detail-agent-pi/test/conversation.test.mjs +++ b/apps/detail-agent-pi/test/conversation.test.mjs @@ -110,6 +110,42 @@ test('the first desktop turn reuses its opening model check and logs first text }finally{await x.close();} }); +test('a model response arriving after cancellation keeps its receipt and cannot supply tools to the next turn',async()=>{ + const arrived=Promise.withResolvers(),release=Promise.withResolvers(); + const record='title-from-revoked-epoch'; + const abort=new AbortController(); + const x=await fixture((_payload,n)=>n===1?new Response(new ReadableStream({ + async start(stream){ + arrived.resolve(); + await release.promise; + stream.enqueue(new TextEncoder().encode(tool('canvas_edit',{revision:1,command:'type.edit',params:{layer:1,text:record},label:'旧内容'}))); + stream.close(); + }, + }),{headers:{'content-type':'text/event-stream'}}):sse({content:'新一轮正常完成。'})); + try { + x.host.productionSignal=abort.signal; + const first=x.host.prompt('旧回合'); + await arrived.promise; + abort.abort(Error('回合已停止')); + release.resolve(); + 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.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); + assert.ok(!JSON.stringify(x.requests[1]).includes(record)); + } finally { await x.close(); } +}); + test('project conversation survives restart and first rule binding while old-domain memory is not reinjected',async()=>{ const x=await fixture(()=>sse({content:'当前资料以本轮注入为准。'})); try{ diff --git a/apps/detail-agent-pi/test/desktop-daemon.test.mjs b/apps/detail-agent-pi/test/desktop-daemon.test.mjs index 3bc97d71..6d4018ba 100644 --- a/apps/detail-agent-pi/test/desktop-daemon.test.mjs +++ b/apps/detail-agent-pi/test/desktop-daemon.test.mjs @@ -3,10 +3,57 @@ import { PassThrough } from 'node:stream'; import { test } from 'node:test'; import { startDaemon } from '../src/desktop-daemon.mjs'; import { StdioCanvas } from '../src/stdio-canvas.mjs'; +import { observeCanvasCalls } from '../src/desktop-host.mjs'; +import { executionEvent } from '../src/activity-event.mjs'; +import { BridgeError } from '../src/bridge-error.mjs'; const runId = '9a1ba294-f2c4-4e5f-91e0-ef6002f50e22'; const tick = () => new Promise(resolve => setImmediate(resolve)); +test('canvas observations join enqueue, acceptance and execution without transferring the viewer identity',async()=>{ + const records=[]; + const executionScope={projectId:'project',runId,outputId:'detail',variantId:'oak',revision:7,documentKey:{variantId:'oak'}}; + const executionHealth={}; + const store={executionScope,executionHealth,async appendEvent(event){records.push(executionEvent(event,executionScope,executionHealth));}}; + const visible={outputId:'sku_images',variantId:'stone'}; + const call=observeCanvasCalls(store,async(_action,_input,accepted)=>{ + accepted(); + return {revision:8,viewing:visible}; + }); + await call('pi-detail-copy-apply',{operationId:'copy-1',revision:7}); + assert.deepEqual(records.map(event=>[event.category,event.phase,event.status,event.revision]),[ + ['ui_ack','enqueue','pending',7],['ui_ack','accept','completed',7], + ['canvas_write','execute','running',7],['canvas_write','receipt','completed',8], + ]); + for(const event of records){ + assert.equal(event.projectId,'project'); + assert.equal(event.runId,runId); + assert.equal(event.operationId,'copy-1'); + assert.equal(event.attempt,1); + assert.equal(event.outputId,'detail'); + assert.equal(event.variantId,'oak'); + assert.deepEqual(event.documentKey,{variantId:'oak'}); + assert.ok(Number.isFinite(event.agentHeartbeat)); + assert.equal(event.jobProgress,null); + assert.equal(event.recentDurableCommit,null); + } + assert.equal(records[0].uiHeartbeat,null); + assert.ok(Number.isFinite(records[1].uiHeartbeat)); +}); + +test('a retried canvas read keeps its operation ID and records the next attempt',async()=>{ + const attempts=[]; + const canvas=new StdioCanvas(async(action,_input,execution)=>{ + assert.equal(action,'pi-product-screen'); + attempts.push(execution); + if(attempts.length===1)throw new BridgeError('原读屏回执等待超时','transport_interrupted'); + return {revision:7}; + },27); + assert.deepEqual(await canvas.detailRender({page:0}),{revision:7}); + assert.deepEqual(attempts.map(row=>row.attempt),[1,2]); + assert.equal(attempts[0].operationId,attempts[1].operationId); +}); + function daemonFixture(t, { runSession, parentAlive = () => true } = {}) { const input = new PassThrough(); const output = new PassThrough(); @@ -148,6 +195,47 @@ test('presentation notifications do not wait for replies and the terminal comman assert.equal(frames.at(-1).type,'complete'); }); +test('cancellation retains the paid image receipt and rejects an old canvas reply or an old pause', async t => { + const nextRunId='9a1ba294-f2c4-4e5f-91e0-ef6002f50e23'; + const config={productProduction:true,documentId:27,project:'desk',scope:'account-a',writeEpoch:4}; + const accepted=[]; + const {frames,send}=daemonFixture(t,{ + runSession:async(config,call,_broker,_recovery,signal)=>{ + if(config.writeEpoch===5){ + const next=await call('pi-state',{}); + assert.equal(signal.aborted,false); + return next; + } + const image=call('pi-image-request',{action:'dispatch',request:{requestId:'original-image'}},()=>accepted.push('image')); + await assert.rejects(call('pi-detail-copy-apply',{}), {category:'cancelled'}); + assert.equal(signal.aborted,true); + return {archived:await image}; + }, + }); + send({type:'run',runId,config}); + await tick(); + const [image,write]=frames.filter(frame=>frame.type==='canvas'); + send({type:'canvas_accepted',runId,id:image.id}); + send({...config,type:'production_pause'}); + send({type:'canvas_result',runId,id:write.id,value:{applied:1}}); + await tick(); + assert.deepEqual(accepted,['image']); + assert.equal(frames.some(frame=>frame.type==='complete'),false); + const original={requestId:'original-image',status:'complete'}; + send({type:'canvas_result',runId,id:image.id,value:original}); + await tick(); + assert.deepEqual(frames.at(-1).value,{archived:original}); + + send({type:'run',runId:nextRunId,config:{...config,writeEpoch:5}}); + await tick(); + const next=frames.at(-1); + send({...config,type:'production_pause'}); + send({type:'canvas_result',runId,id:next.id,value:{revision:99}}); + send({type:'canvas_result',runId:nextRunId,id:next.id,value:{revision:7}}); + await tick(); + assert.deepEqual(frames.at(-1).value,{revision:7}); +}); + test('the stdio canvas settles save, cancel and state replies ahead of a pending render', async t => { const observed=[]; const {frames,send}=daemonFixture(t,{ diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index c86aa545..25daf81d 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -46,6 +46,45 @@ async function generateAndWait(actions, {source,...request}) { return generation[0]; } +test('a late image settles its original request after cancellation without selecting or adopting it',async t=>{ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-cancelled-image-')); + t.after(()=>cleanup(dir)); + const store=productionStore(dir); + const ledger=store.ledger('detail','oak'); + const started=Promise.withResolvers(),done=Promise.withResolvers(); + const abort=new AbortController(); + const events=[]; + store.appendEvent=async event=>events.push(event); + const host={store,productionSignal:abort.signal,productionGoal:{outputId:'detail',variantId:'oak'},canvas:{ + workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak', + template:{contentHash:'studio'},totalSlots:1,slots:[{id:'photo',fieldId:'cover'}]}), + 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 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'); + await started.promise; + abort.abort(); + done.resolve(); + 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', + }); + const fresh=await openProductionOperations({...host,productionSignal:new AbortController().signal}); + assert.equal((await fresh.plan_production()).outputId,'detail'); + await fresh.close(); +}); + test('P07 waits for both original images and persists the automatic adoption decision',async t=>{ for(const scenario of [ {verdicts:['pass','revise'],winner:0,reason:'only_pass',recoverA:true}, diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs index 7baa9018..972a1234 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs @@ -161,6 +161,10 @@ impl Daemon { } Ok(()) } + pub(super) fn canvas_accepted(&self, run: &str, id: &Value) -> R<()> { + self.send(&json!({"type":"canvas_accepted","runId":run,"id":id})) + } + pub(super) fn reply(&self, run: &str, id: &Value, reply: &Value) -> R<()> { let state = self.state.lock().map_err(|_| "本机Agent状态不可用")?; if !state.alive || state.active.as_ref().is_none_or(|(current, _)| current != run) { return Err("原Agent回合已关闭".into()); } @@ -273,12 +277,12 @@ pub(super) fn status() -> Value { "activeRun":state.active.as_ref().map(|(run,_)|run),"heartbeatAgeMs":state.last_ack.map(|at|at.elapsed().as_millis().min(u64::MAX as u128) as u64)}) } -pub(super) fn pause_production(doc: u64, project_identity: &str) { +pub(super) fn pause_production(doc: u64, project_identity: &str, write_epoch: Option) { let Some((account_identity, project)) = project_identity.rsplit_once('|') else { return; }; let service = registry().lock().ok().and_then(|registry| registry.service.clone()); if let Some(service) = service { let _ = service.send(&json!({"type":"production_pause","documentId":doc,"project":project, - "scope":super::hash(account_identity)})); + "scope":super::hash(account_identity),"writeEpoch":write_epoch})); } } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 1c795aee..cd5888ac 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -261,6 +261,14 @@ fn write_json(path: &Path, v: &Value) -> R<()> { let bytes = serde_json::to_vec(v).map_err(|_| "项目记录无法保存")?; photocraft_format::atomic_write(path, &bytes).map_err(|_| "本机保存失败,请检查磁盘空间和目录权限".into()) } + +fn bind_execution_epoch(result: R, epoch: &Value) -> R { + if !epoch.is_u64() { return result; } + let mut value = result.unwrap_or_else(|error| json!({"executionError":error})); + if value.is_null() { value = json!({}); } + value["writeEpoch"] = epoch.clone(); + Ok(value) +} fn project_not_trashed(dir: &Path) -> R<()> { if let (Some(account), Some(local)) = (dir.parent().and_then(Path::parent), dir.file_name()) && account.join("trash").join(local).exists() @@ -400,7 +408,7 @@ struct Backend { owners: HashMap, locations: HashMap, superseded_docs: Arc>>, - last_saved: HashMap, + last_saved: HashMap, draft_zip_writer: Arc>>, recovery_attempts: Arc>>, recovery_serial: Arc>, @@ -995,7 +1003,7 @@ impl Backend { if !canvas_workspace::save_edited_output(&dir, doc, &bytes)? { return Err("当前输出缺少原稿映射,未覆盖编辑稿".into()); } - Ok(json!({"productViewOnly":true})) + Ok(json!({"productViewOnly":true,"documentKey":photocraft_ui_egui::jiansun::product_document_key(doc)})) } fn save(&mut self, doc: Arc, revision: u64, meta: Value) -> R { @@ -1019,10 +1027,11 @@ impl Backend { format!("画布缺少 {first} 至 {last} 的原稿图层,已保留上一次保存的画布") }); let mut active_revision = Value::Null; - if canvas_problem.is_none() && (activate_view || self.last_saved.get(&doc.id.0) != Some(&revision)) { + let saved_identity = (photocraft_ui_egui::jiansun::product_document_key(&doc), revision); + if canvas_problem.is_none() && (activate_view || self.last_saved.get(&doc.id.0) != Some(&saved_identity)) { if activate_view && meta["reuseSavedProductView"] == true && canvas_workspace::reuse_saved_product_view(&dir, &doc)? { active_revision = canvas_workspace::activate_edited_output(&dir, &doc)?["revision"].clone(); - self.last_saved.insert(doc.id.0, revision); + self.last_saved.insert(doc.id.0, saved_identity.clone()); } else { let serialize_started = Instant::now(); let (bytes, _) = self.draft_zip_writer.lock().map_err(|_| "草稿保存服务不可用,旧草稿已保留")? @@ -1050,7 +1059,7 @@ impl Backend { log::info!("小壹画布保存 doc={} 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, revision); + self.last_saved.insert(doc.id.0, saved_identity.clone()); } } // UI snapshots may lag a completed sync or creation task. Preserve backend-owned @@ -1079,6 +1088,7 @@ impl Backend { self.remember_project(project)?; if let Some(reason) = canvas_problem { return Err(reason); } let mut receipt = json!({"time":value["time"],"localId":project,"status":value["status"],"project":value["project"],"cloudLink":value["project"],"syncedRevision":value["syncedRevision"],"syncDirty":value["syncDirty"],"projects":self.native_projects()?,"savedPath":dir.join("canvas.pcraft")}); + receipt["documentKey"] = saved_identity.0; if activate_view { receipt["activeProductViewRevision"] = active_revision; } self.bind_composer_draft(doc.id.0, &dir, &mut receipt)?; Ok(receipt) @@ -1474,7 +1484,7 @@ impl Backend { && meta["templateLayersRestored"].is_null() && meta["templateLayerProblem"].is_null() && let Some(revision) = meta["revision"].as_u64() { - self.last_saved.insert(doc.id.0, revision); + self.last_saved.insert(doc.id.0, (photocraft_ui_egui::jiansun::product_document_key(&doc), revision)); } meta["localId"] = json!(local); meta["autoResume"] = binding["autoResume"].clone(); @@ -1693,23 +1703,27 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let id = doc.id.0; let view_save = meta["activateProductView"] == true; let deliver = meta["deliverProject"].clone(); - let export = meta["exportProduct"].clone(); + let mut export = meta["exportProduct"].clone(); + pi_runtime::record_export_event(&backend, id, &export, "disk_persist", "save", "running", Value::Null); let event = match backend.save(doc.clone(), revision, meta) { Ok(value) if export.is_object() => { + pi_runtime::record_export_event(&backend, id, &export, "disk_persist", "save", "completed", Value::Null); + export["execution"]["recentDurableCommit"] = json!({"at":chrono::Utc::now().timestamp_millis(),"revision":revision}); let _ = events.send(Event::Saved(id, revision, value)); let worker = backend.clone(); let events = events.clone(); let ctx = ctx.clone(); std::thread::spawn(move || { - let result = worker.export_product_snapshot(&doc, &export); + let result = bind_execution_epoch(worker.export_product_snapshot(&doc, &export), &export["writeEpoch"]); let _ = events.send(Event::Json("slot-product-export".into(), result)); ctx.request_repaint(); }); continue; } Err(error) if export.is_object() => { + pi_runtime::record_export_event(&backend, id, &export, "disk_persist", "save", "failed", Value::Null); let _ = events.send(Event::Json("save".into(), Err(error.clone()))); - Event::Json("slot-product-export".into(), Err(error)) + Event::Json("slot-product-export".into(), bind_execution_epoch(Err(error), &export["writeEpoch"])) } Ok(mut value) if deliver.is_object() => { let worker = backend.clone(); @@ -1802,6 +1816,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { if method == "slot-product-view" { result = result.or_else(|error| Ok(json!({"productViewId":input["productViewId"],"error":error}))); } + result = bind_execution_epoch(result, &input["writeEpoch"]); let _ = task_events.send(Event::Json(method, result)); task_ctx.request_repaint(); }); 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 eaf7fa7e..9ec20b07 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -798,6 +798,13 @@ fn lock_candidate_dispatch(dir: &Path, id: &str) -> R> { } } +fn check_image_dispatch_cancelled(cancellation: Option<&std::sync::atomic::AtomicBool>) -> Result<(), BridgeFailure> { + if cancellation.is_some_and(|token| token.load(std::sync::atomic::Ordering::SeqCst)) { + return Err(BridgeFailure::new("cancelled", false, false, "原制作回合已停止,生图未派发")); + } + Ok(()) +} + fn pending_candidate(record: &Value) -> Value { let mut pending = record.clone(); pending["phase"] = json!("unknown"); @@ -2162,6 +2169,31 @@ fn receipt_path(dir: &Path, variant: &str, component: &str) -> PathBuf { dir.join("product-exports").join(variant).join(format!("{component}.json")) } +fn manifest_path(generation: &str) -> PathBuf { + Path::new("generations").join(generation).join("manifest.json") +} + +pub(super) fn published_receipt(path: &Path) -> R { + let pointer = read_json(path)?; + if pointer.get("publishedPointer").is_none() { + return Ok(pointer); + } + let id = pointer["generationId"].as_str().ok_or("交付版本缺失")?; + let manifest = manifest_path(id); + if !id.starts_with("generation-") || Path::new(id).components().count() != 1 + || pointer["publishedPointer"] != json!(manifest) + { + return Err("交付指针无效".into()); + } + let manifest = read_json(&path.parent().ok_or("交付目录缺失")?.join(manifest))?; + if ["generationId", "workspaceId", "outputId", "variantId"].iter() + .any(|field| manifest[*field] != pointer[*field]) + { + return Err("交付清单与发布指针不一致".into()); + } + Ok(manifest) +} + fn template_screen_regions<'a>(pages: impl IntoIterator) -> R> { let mut regions = Vec::new(); for page in pages { @@ -2381,7 +2413,7 @@ fn remaining_stages(dir: &Path, state: &Value, brief_revision: &Value, verify_ed production_stages(state).into_iter().filter(|stage| { let (Some(variant), Some(component)) = (stage["variantId"].as_str(), stage["outputId"].as_str()) else { return true }; if !state["productTemplateIssues"][component].is_null() { return true; } - let receipt = read_json(&receipt_path(dir,variant,component)).unwrap_or(Value::Null); + let receipt = published_receipt(&receipt_path(dir,variant,component)).unwrap_or(Value::Null); let pack = &state["productTemplates"][component]; let pages = pack["outputs"].as_array().into_iter().flatten().filter(|page| page["component"] == component); let Ok(regions) = product_export_regions(pages.clone(), component) else { return true }; @@ -2657,7 +2689,21 @@ impl Backend { self.ensure_owner(native.id.0)?; let dir = self.project_dir(native.id.0)?; let state = load(&dir)?; - export_product_stage_snapshot(&dir, native.id.0, &state, input, &self.scope(), Some(native)) + let doc = native.id.0; + super::pi_runtime::record_export_event(self, doc, input, "export", "validate", "running", Value::Null); + let result = export_product_stage_snapshot(&dir, doc, &state, input, &self.scope(), Some(native)); + match &result { + Ok(value) if value["publishedPointer"].is_string() => { + let progress = json!({"generationId":value["generationId"],"publishedPointer":value["publishedPointer"], + "filesVerified":value["validation"]["filesVerified"],"sourceHash":value["sourceDocument"]["sha256"]}); + super::pi_runtime::record_export_event(self, doc, input, "export", "validate", "completed", + json!({"generationId":value["generationId"],"validation":value["validation"]})); + super::pi_runtime::record_export_event(self, doc, input, "export", "publish", "completed", progress); + } + Ok(_) => super::pi_runtime::record_export_event(self, doc, input, "export", "validate", "blocked", Value::Null), + Err(_) => super::pi_runtime::record_export_event(self, doc, input, "export", "validate", "failed", Value::Null), + } + result } } @@ -2694,6 +2740,10 @@ fn publish_product_generation( { return Err(format!("{name} 内容或尺寸与导出结果不一致")); } + #[cfg(test)] + if std::env::var_os("PHOTOCRAFT_TEST_CRASH_EXPORT").as_deref() == Some(receipt.as_os_str()) { + std::process::exit(81); + } let mut artifact = json!({"path":file,"format":"jpg","role":role,"generationId":id,"top":top,"width":width,"height":height, "sizeBytes":saved.len(),"sha256":format!("{:x}",Sha256::digest(&saved))}); if role != "detail" @@ -2716,6 +2766,9 @@ fn publish_product_generation( photocraft_io::export_jpeg_with_screens(doc, &coordinates, &options) .map_err(|error| format!("长图和分屏导出失败:{error}")) })?; + if splits.len() != screens.len() { + return Err("导出的分屏数量与模板不一致".into()); + } let full = save_region("detail.jpg", component, *region, long.bytes)?; let split = screens.iter().zip(splits).enumerate().map(|(index, (®ion, image))| save_region(&format!("detail-S{:02}.jpg", index+1), "detail-screen", region, image.bytes)) @@ -2737,9 +2790,18 @@ fn publish_product_generation( result["files"] = json!(files); if !split.is_empty() { result["screenFiles"] = json!(split); } result["editable"] = json!(editable); - let _guard = sync::context_guard(); - write_json(receipt, result)?; + result["validation"] = json!({"mode":"full","editableReopened":true, + "filesVerified":1 + regions.len() + screens.len(),"validatedAt":chrono::Utc::now().timestamp_millis()}); + write_json(&generation.path().join("manifest.json"), result)?; + // A replacement can report a directory flush error after the rename. + // Keep the complete generation before attempting to publish its pointer. + let pointer = manifest_path(id); let _ = generation.keep(); + use photocraft_format::atomic::{AtomicFs, RealFs}; + RealFs.sync_dir(&root).map_err(|error| format!("成品版本目录保存未确认:{error}"))?; + let _guard = sync::context_guard(); + result["publishedPointer"] = json!(pointer); + write_json(receipt, result)?; Ok(()) } @@ -2747,10 +2809,28 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va let component = input["outputId"].as_str().filter(|kind| PRODUCTION_OUTPUTS.contains(kind)).ok_or("制作输出缺失")?; let variant_id = uuid(&input["variantId"], "制作款式")?; if !state["productTemplates"].is_object() || input["workspaceId"] != state["id"] - || input["outputId"] != state["activeOutput"] || input["variantId"] != state["activeVariantId"] - || (snapshot.is_none() && read_json(&dir.join("context.json"))?["revision"] != input["baseRevision"]) { + || (snapshot.is_none() && (input["outputId"] != state["activeOutput"] + || input["variantId"] != state["activeVariantId"] + || read_json(&dir.join("context.json"))?["revision"] != input["baseRevision"])) { return Err("已保存画布与制作任务不一致".into()); } + let scoped; + let state = if snapshot.is_some() { + let pack = state["productTemplates"].get(component).filter(|pack| pack.is_object()) + .ok_or("当前产品模板已变化")?; + if variant(state, &variant_id).is_err() || !output_uses_variant(&state["brief"], component, &variant_id) { + return Err("制作款式不属于当前输出".into()); + } + let mut bound = state.clone(); + bound["activeOutput"] = json!(component); + bound["activeVariantId"] = json!(variant_id); + if pack["contentHash"] != state["template"]["contentHash"] { + bound["structureHash"] = json!(hash(&json!([pack["contentHash"],state["width"]]).to_string())); + } + bound["template"] = pack.clone(); + scoped = bound; + &scoped + } else { state }; let mut result = json!({"doc":doc,"workspaceId":state["id"],"outputId":component,"variantId":variant_id,"files":[]}); if input["complete"] != true { result["originals"] = input["originals"].clone(); @@ -2772,8 +2852,12 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va } }; let meta = mapping(native).ok_or("可编辑画布缺少图层映射")?; - if meta["workspaceId"] != state["id"] || meta["templateHash"] != state["template"]["contentHash"] - || meta["component"] != component || meta["variantId"] != variant_id { + if snapshot.is_some() && input["canvasRevision"].is_u64() + && (native.id.0 != doc || input["canvasRevision"] != input["baseRevision"]) + || meta["workspaceId"] != state["id"] || meta["templateHash"] != state["template"]["contentHash"] + || meta["component"] != component || meta["variantId"] != variant_id + || input["documentKey"].is_object() + && input["documentKey"] != photocraft_ui_egui::jiansun::product_document_key(native) { return Err("可编辑画布属于其他款式或模板".into()); } let profile = production_profile::select(&state["template"], component)?; @@ -3095,7 +3179,9 @@ impl Backend { json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"workflow":workflow,"creation":enrich_creation(dir,creation::load(dir)?)?,"pending":workflow["pending"],"canvasFirst":true}), ) } - pub(super) fn production_image_request(&mut self, doc: u64, binding: &Value, events: &mpsc::Sender, ctx: &egui::Context) -> Result { + 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.ensure_owner(doc)?; let dir = self.project_dir(doc)?; original_project_present(&dir)?; @@ -3111,18 +3197,23 @@ impl Backend { return self.canvas_workspace_action("slot-prepare-image", &input, events, ctx).map_err(BridgeFailure::from); } if phase != "dispatch" { return Err("生图请求动作无效".into()); } - let receipt = self.dispatch_canvas_image_request(doc, &dir, request, Some(&binding["scope"]), events, ctx)?; - if receipt["status"].is_string() { - let snapshot = operation_receipt(self.canvas_workspace_result(doc, &dir) - .map_err(|error| BridgeFailure::new("image_request_failed", false, true, error))?, Some(receipt.clone()), None); - let _ = events.send(Event::Json("slot-append".into(), Ok(snapshot))); - ctx.request_repaint(); + let receipt = self.dispatch_canvas_image_request(doc, &dir, request, Some(&binding["scope"]), events, ctx, cancellation)?; + if receipt["status"].is_string() && check_image_dispatch_cancelled(cancellation).is_ok() { + match self.canvas_workspace_result(doc, &dir) { + Ok(workspace) => { + let mut snapshot = operation_receipt(workspace, Some(receipt.clone()), None); + snapshot["writeEpoch"] = binding["writeEpoch"].clone(); + let _ = events.send(Event::Json("slot-append".into(), Ok(snapshot))); + ctx.request_repaint(); + } + Err(error) => log::warn!("小壹原生图回执已保留,画布状态未刷新:{error}"), + } } Ok(receipt) } fn dispatch_canvas_image_request(&mut self, doc: u64, dir: &Path, request: &Value, scope: Option<&Value>, - events: &mpsc::Sender, ctx: &egui::Context) -> Result { + events: &mpsc::Sender, ctx: &egui::Context, cancellation: Option<&std::sync::atomic::AtomicBool>) -> Result { let id = uuid(&request["requestId"], "生图请求")?; let (task, _dispatch) = { let _guard = sync::context_guard(); @@ -3166,6 +3257,7 @@ impl Backend { publish_prepared(events, snapshot)?; ctx.request_repaint(); validate_image_context(dir, Some(slot))?; + check_image_dispatch_cancelled(cancellation)?; let call = self.image_job(None, &json!({"doc":doc,"frozenRequestId":id}), false, events, ctx); let dispatch_error = |error, backend: &Self| BridgeFailure::new("image_request_failed", false, backend.image_dispatch_may_have_started(doc, &id), error); let (mut receipt, failure) = self.settle_image_candidate(dir, doc, &id, slot, call, events, ctx) @@ -3451,6 +3543,7 @@ impl Backend { self.canvas_workspace_result(doc, &dir)? }; result["baseRevision"] = input["baseRevision"].clone(); + result["writeEpoch"] = input["writeEpoch"].clone(); result["outputId"] = json!(component); result["documentId"] = json!(document); result["variantId"] = json!(variant_id); @@ -3630,7 +3723,7 @@ impl Backend { if preparing { return Ok(draft); } // The native action is already confirmed by the operator. let receipt = self.dispatch_canvas_image_request(doc, &dir, &json!({"requestId":draft["requestId"], - "expectedRevision":draft["revision"], "expectedHash":draft["requestSpecHash"], "slotId":id}), None, events, ctx)?; + "expectedRevision":draft["revision"], "expectedHash":draft["requestSpecHash"], "slotId":id}), None, events, ctx, None)?; if receipt["status"] == "failed" { operation_error = receipt["message"].as_str().map(str::to_owned); } candidate_result = Some(receipt); } else if method == "slot-reuse" { @@ -4394,12 +4487,17 @@ mod tests { "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"))] { let prior = std::mem::replace(&mut approval["request"][field], value); - let failure = backend.production_image_request(doc, &approval, &events, &ctx).unwrap_err(); + let failure = backend.production_image_request(doc, &approval, &events, &ctx, None).unwrap_err(); assert!(!failure.dispatched); assert!(read_json(&file).unwrap()["frozenAt"].is_null()); approval["request"][field] = if field == "slotId" { json!(slot) } else { prior }; } - let failure = backend.production_image_request(doc, &approval, &events, &ctx).unwrap_err(); + let cancelled = std::sync::atomic::AtomicBool::new(true); + let stopped = backend.production_image_request(doc, &approval, &events, &ctx, Some(&cancelled)).unwrap_err(); + assert_eq!(stopped.category, "cancelled"); + assert!(!stopped.dispatched); + assert!(read_json(&file).unwrap()["frozenAt"].is_null()); + let failure = backend.production_image_request(doc, &approval, &events, &ctx, None).unwrap_err(); assert!(!failure.dispatched); assert!(read_json(&file).unwrap()["frozenAt"].is_number()); assert_eq!(read_json(&file).unwrap()["phase"], "prepared"); @@ -4696,7 +4794,12 @@ mod tests { assert_eq!(screen["revision"], 2); assert_eq!(screen["fields"], json!(["S01-I01","S01-T01","S01-T02"])); fs::write(&edited, b"older or unreadable editable file").unwrap(); - let snapshot = export_product_stage_snapshot(&fixture.dir, 1, &state, &input, "test-account", Some(&doc)).unwrap(); + let mut viewing = state.clone(); + viewing["activeOutput"] = json!("sku_images"); + viewing["activeVariantId"] = json!(Uuid::new_v4()); + let mut bound = input.clone(); + bound["documentKey"] = photocraft_ui_egui::jiansun::product_document_key(&doc); + let snapshot = export_product_stage_snapshot(&fixture.dir, 1, &viewing, &bound, "test-account", Some(&doc)).unwrap(); assert_ne!(snapshot["generationId"], ready["generationId"]); assert_eq!(snapshot["files"][0]["sha256"], ready["files"][0]["sha256"]); assert_eq!(snapshot["screenFiles"][0]["sha256"], ready["screenFiles"][0]["sha256"]); @@ -5442,7 +5545,22 @@ mod tests { state["brief"] = creation["brief"].clone(); state["variants"] = json!(variants(&dir, &creation["brief"], None).unwrap()); state["productTemplates"] = json!({"detail":state["template"]}); - persist(&dir, state, 0).unwrap(); + let state = persist(&dir, state, 0).unwrap(); + for color in [&oak, &white] { + let mut canvas = slot_canvas::skeleton(&state["template"], "detail", None, color).unwrap(); + canvas.id = photocraft_doc::DocId(doc); + let mut meta = mapping(&canvas).unwrap(); + meta["workspaceId"] = state["id"].clone(); + canvas.metadata.text.retain(|(key, _)| key != MAPPING); + canvas.metadata.text.push((MAPPING.into(), meta.to_string())); + let key = photocraft_ui_egui::jiansun::product_document_key(&canvas); + let saved = backend.save(std::sync::Arc::new(canvas), 4, json!({})).unwrap(); + 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(); + assert_eq!(photocraft_ui_egui::jiansun::product_document_key(&opened), key); + } let mut first = candidate(&dir, "prepared"); first["binding"]["detailBatch"] = json!(true); @@ -5797,4 +5915,41 @@ mod tests { state["brief"]["images"][0].as_object_mut().unwrap().remove("purpose"); assert!(generation_references(&fixture.dir, &state, &variant).is_err(), "the existing native reference contract requires an explicit purpose"); } + + #[test] + fn interrupted_reexport_keeps_previous_published_generation() { + const CRASH: &str = "PHOTOCRAFT_TEST_CRASH_EXPORT"; + if let Some(path) = std::env::var_os(CRASH) { + let path = PathBuf::from(path); + let old = published_receipt(&path).unwrap(); + let doc = photocraft_format::load_path(Path::new(old["editable"].as_str().unwrap())).unwrap(); + publish_product_generation(&path, &doc, &json!(2), &mut json!({"outputId":"detail"}), + &[(0, 8, 8)], &[(0, 8, 4), (4, 8, 4)]).unwrap(); + panic!("child must stop after writing the long image"); + } + let dir = tempfile::tempdir().unwrap(); + let receipt = dir.path().join("detail.json"); + let doc = Document::new("A08", photocraft_doc::Size::new(8, 8), + photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + let mut old = json!({"outputId":"detail"}); + publish_product_generation(&receipt, &doc, &json!(1), &mut old, + &[(0, 8, 8)], &[(0, 8, 4), (4, 8, 4)]).unwrap(); + let pointer_bytes = fs::read(&receipt).unwrap(); + let exit = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &format!("{}::interrupted_reexport_keeps_previous_published_generation", + module_path!().split_once("::").unwrap().1)]) + .env(CRASH, &receipt).output().unwrap(); + assert_eq!(exit.status.code(), Some(81), "{}", String::from_utf8_lossy(&exit.stdout)); + assert_eq!(fs::read(&receipt).unwrap(), pointer_bytes); + let current = published_receipt(&receipt).unwrap(); + assert_eq!(current["sourceDocument"]["revision"], 1); + assert!(artifact_matches(¤t["sourceDocument"], true)); + for file in current["files"].as_array().unwrap().iter().chain(current["screenFiles"].as_array().unwrap()) { + assert!(artifact_matches(file, true)); + } + let unfinished = fs::read_dir(dir.path().join("generations")).unwrap().map(Result::unwrap) + .find(|entry| entry.file_name().to_str() != old["generationId"].as_str()).unwrap().path(); + assert!(unfinished.join("detail.jpg").is_file()); + assert!(!unfinished.join("manifest.json").exists()); + } } 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 a64b114c..930a8970 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -398,13 +398,51 @@ pub(super) fn run(b: &mut Backend, input: &Value, method: &str, events: &mpsc::S json!({"engine":"pi","mode":"prompt","doc":doc,"accountId":b.auth["account"]["id"],"origin":b.origin,"error":error.message,"failure":error.wire(),"unknown":unknown}) } }; - let mut value = canonical_pi_result(b, value)?; + let epoch = &input["context"]["requestScope"]["writeEpoch"]; + let mut 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); + value + }); + observed["writeEpoch"] = epoch.clone(); + observed + } else { + canonical_pi_result(b, value)? + }; if method == "pi-recover" && input["automaticRecover"] == true { value["automaticRecover"] = json!(true); } Ok(value) } +pub(super) fn record_export_event( + b: &Backend, doc: u64, input: &Value, category: &str, phase: &str, status: &str, progress: Value, +) { + let trace = &input["execution"]; + let Some(project) = b.locations.get(&doc).filter(|_| trace["runId"].is_string()) else { return; }; + let Ok(dir) = b.project_dir(doc) else { return; }; + let at = chrono::Utc::now().timestamp_millis(); + let durably_committed = status == "completed" + && matches!((category, phase), ("disk_persist", "save") | ("export", "publish")); + let record = json!({"type":"production_execution","at":at,"projectId":project, + "runId":trace["runId"],"operationId":trace["operationId"],"attempt":1, + "outputId":input["outputId"],"variantId":input["variantId"],"revision":input["canvasRevision"], + "documentKey":input["documentKey"],"category":category,"phase":phase,"status":status, + "agentHeartbeat":trace["agentHeartbeat"],"uiHeartbeat":trace["uiHeartbeat"],"jobProgress":progress, + "recentDurableCommit":if durably_committed { json!({"at":at,"revision":input["canvasRevision"]}) } + else { trace["recentDurableCommit"].clone() }}); + let file = dir.join("agent").join(b.scope()).join(project).join("conversation-v1").join("events.jsonl"); + let mut line = record.to_string(); + line.push('\n'); + use std::io::Write as _; + if let Err(error) = std::fs::OpenOptions::new().append(true).open(file) + .and_then(|mut file| file.write_all(line.as_bytes())) + { + log::warn!("小壹制作观测事件保存失败:{}", error.kind()); + } +} + /// Pi journals affect template capabilities without incrementing the template /// revision. Read the canonical state after the SDK durably finishes, while the /// existing worker still owns model_busy; an eager second UI request can race @@ -459,6 +497,9 @@ fn workflow_receipt(delegation: &Value, result: R) -> R { Err(error) => json!({"__workflowError":error}), }; value["__workflowReceipt"] = json!({"operationId":delegation["operationId"],"run":delegation["run"]}); + if delegation["writeEpoch"].is_u64() { + value["__workflowReceipt"]["writeEpoch"] = delegation["writeEpoch"].clone(); + } Ok(value) } @@ -607,6 +648,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender "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, + "writeEpoch":scope["writeEpoch"],"documentKey":scope["documentKey"],"revision":input["context"]["revision"], "wholeDetail":input["context"]["requestScope"]["wholeDetail"] == true, "outputId":if scope["productProduction"] == true { scope["outputId"].as_str() } else { Some(scope["outputId"].as_str().unwrap_or("detail")) }, @@ -720,6 +762,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender ctx.request_repaint(); let reply = match rx.recv_timeout(Duration::from_secs(12)) { Ok(Ok((mut v, snapshot))) => { + daemon.canvas_accepted(&daemon_run, &value["id"])?; if action == "pi-image-request" { let mut worker = b.clone(); let transport = daemon.clone(); @@ -728,7 +771,8 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender let task_events = events.clone(); let task_ctx = ctx.clone(); workflow_children.workers.push(std::thread::spawn(move || { - let result = worker.production_image_request(doc, &v, &task_events, &task_ctx); + let cancellation = snapshot.as_ref().map(|snapshot| snapshot.cancellation.as_ref()); + let result = worker.production_image_request(doc, &v, &task_events, &task_ctx, cancellation); let reply = match result { Ok(value) => json!({"value":value}), Err(error) => json!({"error":error.wire()}), @@ -1010,6 +1054,43 @@ mod tests { backend.locations.insert(doc, local.clone()); (backend, doc, local) } + #[test] + fn save_and_export_observations_extend_the_same_agent_event_stream() { + let (mut backend, doc, project) = local_backend(); + let temp = tempfile::tempdir().unwrap(); + backend.root = temp.path().to_path_buf(); + let dir = backend.project_dir(doc).unwrap(); + let file = dir.join("agent").join(backend.scope()).join(&project).join("conversation-v1").join("events.jsonl"); + fs::create_dir_all(file.parent().unwrap()).unwrap(); + fs::write(&file, b"{\"type\":\"export_submitted\",\"runId\":\"original\",\"operationId\":\"delivery\"}\n").unwrap(); + let input = json!({"outputId":"sku_images","variantId":"wood","canvasRevision":17, + "documentKey":{"workspaceId":"workspace","outputId":"sku_images","variantId":"wood"}, + "execution":{"runId":"original","operationId":"delivery","agentHeartbeat":100,"uiHeartbeat":98}}); + record_export_event(&backend, doc, &input, "disk_persist", "save", "completed", Value::Null); + record_export_event(&backend, doc, &input, "export", "publish", "completed", json!({"filesVerified":3})); + let rows = fs::read_to_string(file).unwrap().lines() + .map(|line| serde_json::from_str::(line).unwrap()).collect::>(); + assert_eq!(rows.len(), 3); + assert_eq!(rows[0]["type"], "export_submitted"); + for row in &rows[1..] { + assert_eq!(row["projectId"], project); + assert_eq!(row["runId"], rows[0]["runId"]); + assert_eq!(row["operationId"], rows[0]["operationId"]); + assert_eq!(row["attempt"], 1); + assert_eq!(row["outputId"], "sku_images"); + assert_eq!(row["variantId"], "wood"); + assert_eq!(row["revision"], 17); + assert_eq!(row["documentKey"], input["documentKey"]); + assert_eq!(row["agentHeartbeat"], 100); + assert_eq!(row["uiHeartbeat"], 98); + assert_eq!(row["recentDurableCommit"]["revision"], 17); + } + assert_eq!(rows[1]["category"], "disk_persist"); + assert_eq!(rows[2]["category"], "export"); + assert_eq!(rows[2]["phase"], "publish"); + assert_eq!(rows[2]["status"], "completed"); + assert_eq!(rows[2]["jobProgress"]["filesVerified"], 3); + } fn pi_result(backend: &Backend, doc: u64) -> Value { json!({"engine":"pi","doc":doc,"accountId":backend.auth["account"]["id"],"origin":backend.origin,"unknown":false,"mode":"recover"}) } 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 ccef36da..2fa2cc29 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs @@ -72,7 +72,7 @@ fn copy_project( && relative_dir.file_name().is_some_and(|name| name == "generations")).then(|| { let variant = dir.parent().unwrap(); ["detail.json", "main_images.json", "sku_images.json"].into_iter() - .filter_map(|name| read_json(&variant.join(name)).ok()) + .filter_map(|name| super::canvas_workspace::published_receipt(&variant.join(name)).ok()) .filter_map(|receipt| receipt["generationId"].as_str().map(str::to_owned)) .collect::>() }); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index a08d4b61..644cd71c 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -1013,7 +1013,7 @@ pub struct Workspace { draft_changed: bool, product_checkpoint: Value, production_exit: Option, - pub pause_production_agent: Option, + pub pause_production_agent: Option)>, loaded_draft: Option, pub draft_flush: Option, composer_drafts: composer_drafts::State, @@ -1110,6 +1110,7 @@ pub struct Workspace { product_production: Option, product_views: product_production::Views, product_target_hidden: bool, + write_epoch: u64, product_start_queued: bool, product_export: Option, canvas_workspace: canvas_workspace::State, @@ -1265,6 +1266,9 @@ impl Workspace { input["baseRevision"] = json!(st.revision); input["slotRevision"] = self.template_workflow["revision"].as_u64().map(Value::from).unwrap_or(json!(0)); input["imageModel"] = json!(self.image_model); + if input["continueProduct"] == true && self.pi_request_scope["writeEpoch"].is_u64() { + input["writeEpoch"] = self.pi_request_scope["writeEpoch"].clone(); + } if local_adoption { if self.saving.is_some() {return Err("请等待本机保存完成,再采纳图片".into());} if self.canvas_workspace.pending_adoption.is_some() { @@ -1354,6 +1358,10 @@ impl Workspace { let Some(mut pending) = self.pending_slot_apply.take() else { return }; let method = pending["dispatchMethod"].as_str().unwrap_or("slot-apply").to_owned(); let resume_busy = pending["resumeBusy"].as_str().map(str::to_owned); + if !self.accepts_production_epoch(&pending["writeEpoch"]) { + if self.busy.as_deref() == Some("slot-apply-save") { self.busy = None; } + return; + } let waiting = self.busy.as_deref() == Some("slot-apply-save"); let live_handoff = pending["continueProduct"] == true && resume_busy.as_deref() == Some("pi-agent") && self.pi_run.is_some(); if waiting { @@ -1596,6 +1604,7 @@ impl Workspace { product_production: None, product_views: product_production::Views::default(), product_target_hidden: false, + write_epoch: 0, product_start_queued: false, product_export: None, canvas_workspace: canvas_workspace::State::default(), @@ -1852,6 +1861,7 @@ impl Workspace { } fn handover(&mut self) { + self.revoke_production_epoch(); self.product_production = None; self.product_start_queued = false; self.product_export = None; @@ -2381,6 +2391,11 @@ impl Workspace { if whole_detail { scope["wholeDetail"] = json!(true); } let mut text = text; if whole_detail && let Some(run) = self.product_production.as_mut() { + self.write_epoch += 1; + scope["writeEpoch"] = json!(self.write_epoch); + if run.output_selected() { + scope["documentKey"] = product_document_key(&active.doc); + } scope["productProduction"] = json!(true); scope["productionDeadline"] = json!(run.deadline()); scope["requestedOutputs"] = run.requested_outputs(); @@ -2730,6 +2745,20 @@ impl Workspace { } fn receive_json_event(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, method: String, mut result: Result) { + if let Ok(value) = &mut result { + if !self.accepts_production_epoch(&value["writeEpoch"]) { + if value["writeEpoch"] == self.pi_request_scope["writeEpoch"] + && (method == "agent" && matches!(self.busy.as_deref(), Some("agent" | "pi-agent")) + || self.busy.as_deref() == Some(method.as_str()) && matches!(method.as_str(), "slot-skeleton" | "slot-product-export")) + { + self.busy = None; + } + return; + } + if let Some(error) = value["executionError"].as_str() { + result = Err(error.to_owned()); + } + } if method == "project-operation" { self.project_operation_received(app, result); return; } match method.as_str() { "template-progress" => { self.receive_template_progress(app, result); return; } @@ -2769,6 +2798,14 @@ impl Workspace { let live_image_request = method == "image" && self.busy.as_deref() == Some("image"); self.receive_candidate_recovery(app, &method, &result); let workflow_receipt = self.workflow.operation_receipt(&workflow_envelope, &method, &result, &self.account["id"], &self.origin, app.session.active().map(|s|s.doc.id.0)); + if !self.accepts_production_epoch(&workflow_envelope["writeEpoch"]) { + if workflow_envelope["writeEpoch"] == self.pi_request_scope["writeEpoch"] + && self.busy.as_deref() == Some("slot-append") + { + self.busy = Some("agent".into()); + } + return; + } if !workflow_receipt && matches!(method.as_str(), "slot-append" | "slot-adopt-prep") && self.workflow.any_operation_in_flight() { return; // An unrelated late receipt cannot settle or clear this operation. @@ -3336,7 +3373,10 @@ impl Workspace { ctx.request_repaint_after(Duration::from_millis(60)); } if !self.queue.is_empty() { - if current != self.owner_doc.map(|id| (id, self.expected_revision)) { + let target = &self.pi_request_scope["documentKey"]; + if current != self.owner_doc.map(|id| (id, self.expected_revision)) + || target.is_object() && app.session.active().is_none_or(|state| product_document_key(&state.doc) != *target) + { if self.pi_run.is_some() { self.recording_edit_owner = None; self.queue.clear(); @@ -3406,7 +3446,7 @@ impl Workspace { } }); // Settle owned native apply receipts before manual-edit detection. - agent_native::settle_jobs(self, app); + self.with_product_target(app, |w, app| { agent_native::settle_jobs(w, app); }); self.professional_sync(app); self.enforce_canvas_scope(app); self.project_open_locals = self.live_project_locals(app); @@ -3460,8 +3500,10 @@ impl Workspace { return; } if !self.tick_context(app, ctx) { return; } - let current = app.session.active().map(|s| (s.doc.id.0, s.revision)); - self.tick_pending_edits(app, ctx, current); + self.with_product_target(app, |w, app| { + let current = app.session.active().map(|s| (s.doc.id.0, s.revision)); + w.tick_pending_edits(app, ctx, current); + }); self.creation_autosave(app, ctx); if painting && (self.busy.is_some() || self.saving.is_some()) { ctx.request_repaint_after(Duration::from_millis(100)); @@ -3551,7 +3593,8 @@ impl Workspace { { self.queue_canvas_feedback(doc, json!({"nativeLayerId":layer}), "图层已更新"); } - let snapshot = if method == "pi-product-screen" || method == "pi-detail-images" && value["adopted"] == true { + let snapshot = if matches!(method.as_str(), "pi-product-screen" | "pi-image-request") + || method == "pi-detail-images" && value["adopted"] == true { app.session.active().zip(self.agent_native.cancellation()).map(|(active, cancellation)| { PiCanvasSnapshot { document: active.doc.clone(), cancellation } }) @@ -3578,6 +3621,12 @@ impl Workspace { Event::Json(method, result) => self.receive_json_event(app, ctx, method, result), Event::Opened(doc, meta) => self.receive_opened(app, ctx, doc, meta), Event::Saved(id, rev, meta) => { + if meta["documentKey"].is_object() && app.session.active().is_some_and(|state| + state.doc.id.0 == id && product_document_key(&state.doc) != meta["documentKey"]) + { + if self.saving == Some((id, rev)) { self.saving = None; } + return; + } self.saving = None; self.saved = Some((id, rev, meta["time"].as_str().unwrap_or("").into())); self.persisted_revisions.insert(id, rev); @@ -4130,6 +4179,14 @@ pub(crate) fn advance(app: &mut PhotocraftApp, ctx: &egui::Context) { } } +pub fn product_document_key(doc: &Document) -> Value { + let Some(mapping) = canvas_workspace::document_mapping(doc) else { return Value::Null; }; + json!({"workspaceId":mapping["workspaceId"],"outputId":mapping["component"], + "variantId":mapping["variantId"],"templateId":mapping["templateId"], + "templateVersion":mapping["templateVersion"],"templateHash":mapping["templateHash"], + "mappingDocumentId":mapping["outputId"]}) +} + pub(crate) fn guard_production_exit(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { let Some(mut workspace) = app.jiansun.take() else { return false; }; let waiting = workspace.begin_production_exit(app, ctx); @@ -5182,7 +5239,7 @@ mod tests { && input["context"]["requestScope"]["outputId"].is_null() && input["context"]["requestScope"]["goalUserEntry"].is_null())); thread_local! { static PAUSED: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } - w.pause_production_agent = Some(|doc, project| PAUSED.with(|call| { + w.pause_production_agent = Some(|doc, project, _| PAUSED.with(|call| { *call.borrow_mut() = Some((doc, project.into())); })); let owner = w.local_identity("owned-product"); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs index 2cfc2c2e..f67748b0 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs @@ -965,6 +965,8 @@ fn valid_detail_adoption(w: &Workspace, doc: &Document, meta: &Value) -> bool { }); w.pi_request_scope["wholeDetail"] == true && w.pi_run.is_some() && !w.pi_write_blocked && !w.agent_effects_paused + && (!w.pi_request_scope["documentKey"].is_object() + || w.pi_request_scope["documentKey"] == super::product_document_key(doc)) && meta["variantId"] == w.canvas_workspace.variant && meta["outputId"] == w.canvas_workspace.output && variant_unchanged && w.detail_layer_unchanged(doc, layer) } @@ -5181,10 +5183,13 @@ mod tests { w.creation_brief = json!({"name":"展桌","variants":[oak,{"id":"white","colorName":"米白色"}]}); w.pi_canvas_basis = Some(state.doc.clone()); w.pi_run = Some("detail-run".into()); - w.pi_request_scope = json!({"wholeDetail":true}); + w.pi_request_scope = json!({"wholeDetail":true,"documentKey":crate::jiansun::product_document_key(&state.doc)}); let meta = json!({"variantId":"wood","outputId":"detail","nativeLayerId":layer, "variantBrief":{"row":oak,"shared":{"name":"展桌"}}}); assert!(valid_detail_adoption(&w, &state.doc, &meta)); + w.pi_request_scope["documentKey"]["variantId"] = json!("white"); + assert!(!valid_detail_adoption(&w, &state.doc, &meta)); + w.pi_request_scope["documentKey"]["variantId"] = json!("wood"); w.creation_brief["variants"][1]["colorName"] = json!("暖白色"); assert!(valid_detail_adoption(&w, &state.doc, &meta)); w.creation_brief["variants"][0]["colorName"] = json!("烟熏橡木"); 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 f500d213..9999e264 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 @@ -7,7 +7,9 @@ use super::{json, Workspace, Value, BridgeFailure, PhotocraftApp, Instant, workf mod core_smoke; fn identity(w: &Workspace, input: &Value) -> Result<(), String> { - if w.pi_run.as_deref().is_some_and(|s| input["run"].as_str() == Some(s)) && w.pi_binding == json!({"accountId":w.account["id"],"origin":w.origin}) { + if w.pi_run.as_deref().is_some_and(|s| input["run"].as_str() == Some(s)) + && w.accepts_production_epoch(&w.pi_request_scope["writeEpoch"]) + && w.pi_binding == json!({"accountId":w.account["id"],"origin":w.origin}) { Ok(()) } else { Err("本地Agent会话或账户已改变".into()) @@ -116,6 +118,11 @@ fn tool_activity(w: &Workspace, event: &Value) -> Result { } let mut clean = json!({"version":1,"type":"tool","toolCallId":call,"toolName":name,"status":state, "timestampMs":timestamp,"summary":format!("{prefix}:{label}"),"run":w.pi_run}); + if let Some(category) = event["category"].as_str().filter(|category| matches!(*category, + "inference" | "canvas_read" | "canvas_write" | "disk_persist" | "remote_image" | "ui_ack" | "export")) { + clean["category"] = json!(category); + clean["phase"] = json!(state); + } if !event["durationMs"].is_null() { let duration = event["durationMs"].as_u64().filter(|n| *n <= MAX_SAFE_INTEGER).ok_or("工具状态时长无效")?; clean["durationMs"] = json!(duration); @@ -218,6 +225,9 @@ fn image_linked_copy(doc: &photocraft_doc::Document, slot_id: &Value) -> Vec, method: &str, input: &Value, private: bool) -> Result { if matches!(method, "pi-production-open" | "pi-image-request" | "pi-workflow-execute" | "pi-detail-copy-fields" | "pi-detail-copy-apply" | "pi-product-screen") && !private { return Err("工作流执行仅允许当前本机Agent会话".into()); } if method == "pi-begin" { + if !w.accepts_production_epoch(&input["requestScope"]["writeEpoch"]) { + return Err(BridgeFailure::new("cancelled", false, false, "原制作回合已停止")); + } if (input["accountId"].is_string() && input["accountId"] != w.account["id"]) || (input["origin"].is_string() && input["origin"] != w.origin) { return Err("画布与模型账户不一致".into()); } @@ -299,6 +309,10 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co if method == "pi-edit-reconcile" { return super::agent_native::reconcile_edit(w, app, input).map_err(BridgeFailure::from); } if method == "pi-workflow-reconcile" { return workflow_bridge::reconcile(w, app, input).map_err(BridgeFailure::from); } identity(w, input)?; + let key = &w.pi_request_scope["documentKey"]; + if key.is_object() && app.session.active().is_none_or(|active| super::product_document_key(&active.doc) != *key) { + return Err(BridgeFailure::new("scope_changed", false, false, "原工作画布的输出、花色或模板映射已变化")); + } w.pi_touched = Instant::now(); w.track_pi_canvas(app); if method != "pi-state" && !app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc) { @@ -524,6 +538,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co return Err("图位不属于本轮制作画布".into()); } Ok(json!({"action":action,"request":request,"revision":w.expected_revision, + "writeEpoch":w.pi_request_scope["writeEpoch"], "scope":{"id":w.template_workflow["workspaceId"],"templateHash":w.template_workflow["templateHash"], "structureHash":w.template_workflow["structureHash"],"outputId":w.pi_request_scope["outputId"], "variantId":w.pi_request_scope["variantId"]}})) @@ -1129,6 +1144,8 @@ mod tests { let (_, rx) = mpsc::channel(); let mut w = Workspace::new(tx, rx); w.account = json!({"id":"qa"}); + w.model = "chat-qa".into(); + w.models = vec![json!({"id":"qa","key":"chat-qa"})]; w.busy = Some("agent".into()); w.pi_request_scope = w.context(&app)["requestScope"].clone(); w.owner_doc = Some(id); @@ -1498,6 +1515,7 @@ mod tests { w.canvas_workspace.variant = "wood".into(); w.template_workflow = json!({"templateId":"pack","templateVersion":"1","templateHash":"original"}); let original_layer = app.session.active().unwrap().active_layer.unwrap().0; + w.composer_reference_add_target(&app, &json!({"documentId":doc,"nativeLayerId":original_layer,"component":"layer"})).unwrap(); w.submit(&app, "分析这张候选,但不要直接修改".into()); let Request::Action(method, request) = requests.try_recv().unwrap() else { panic!("one explicit request") }; assert_eq!(method, "agent"); @@ -1535,12 +1553,14 @@ mod tests { w.unknown = false; w.model_ready = true; w.canvas_workspace.context = None; + let document = app.session.active().unwrap().doc.id.0; + let layer = app.session.execute("type.create", json!({"text":"原图位标题","size":24})).unwrap()["layer"].as_u64().unwrap(); + w.composer_reference_add_target(&app, &json!({"documentId":document,"nativeLayerId":layer,"component":"layer"})).unwrap(); w.submit(&app, "只解释原图位".into()); let Request::Action(_, request) = requests.try_recv().expect("submitted request") else { panic!("expected action") }; let snapshot = request["context"]["requestScope"].clone(); assert!(!snapshot["references"].as_array().unwrap().is_empty()); let run = "12345678-1234-1234-1234-123456789012"; - let document = app.session.active().unwrap().doc.id.0; for field in ["subject", "references", "component"] { let mut forged = snapshot.clone(); match field { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs index 50ac5095..7152fe22 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs @@ -92,6 +92,20 @@ impl Views { } impl Workspace { + pub(super) fn accepts_production_epoch(&self, epoch: &Value) -> bool { + epoch.is_null() || epoch.as_u64() == Some(self.write_epoch) + } + + pub(super) fn revoke_production_epoch(&mut self) { + if self.pi_request_scope["writeEpoch"].as_u64() != Some(self.write_epoch) { return; } + self.write_epoch += 1; + self.pi_write_blocked = true; + self.allow_apply = false; + self.agent_native.cancel(); + self.pi_run = None; + self.stream_reply.clear(); + } + pub(super) fn resume_saved_production(&mut self, app: &PhotocraftApp) -> bool { let Some(canvas) = app.session.active() else { return false }; let doc = canvas.doc.id.0; @@ -337,6 +351,9 @@ impl Workspace { && let Some(state) = app.session.active_mut().filter(|state| state.doc.id.0 == id) { self.product_views.saving = None; + if meta["documentKey"].is_object() && meta["documentKey"] != super::product_document_key(&state.doc) { + return true; + } state.saved_revision = revision; if meta["activeProductViewRevision"].is_u64() { state.path = meta["savedPath"].as_str().map(str::to_owned); @@ -401,6 +418,7 @@ impl Workspace { } pub(super) fn continue_product_canvas(&mut self, app: &mut PhotocraftApp, doc: Box, meta: Value) { + if !self.accepts_production_epoch(&meta["writeEpoch"]) { return; } let Some(stage) = Stage::read(&meta) else { return; }; let Some(run) = self.product_production.as_ref() else { return; }; if !run.current(self, app) || !run.accepts_canvas(&meta) @@ -436,6 +454,9 @@ impl Workspace { let Some(active) = app.session.active_mut() else { return; }; let mut worker = DocState::new(*doc, active.path.clone()); worker.revision = active.revision + 1; + // The replacement shares the native tab ID. The previous output's + // saved revision cannot acknowledge this new working canvas. + self.persisted_revisions.remove(&worker.doc.id.0); active.path = meta["previousViewPath"].as_str().map(str::to_owned); self.canvas_workspace.scope_switch_in_flight = false; self.product_views.editor_basis = Some(active.doc.clone()); @@ -819,7 +840,7 @@ impl Workspace { if self.production_exit.is_some() { return true; } let Some(run) = self.product_production.take() else { return false; }; if let Some(pause) = self.pause_production_agent { - pause(run.doc, &run.project); + pause(run.doc, &run.project, self.pi_request_scope["writeEpoch"].as_u64()); } self.with_product_target(app, |w, _| { w.pi_ui_cancel("客户端正在退出"); @@ -882,7 +903,7 @@ impl Workspace { pub(super) fn stop_production(&mut self) { if let Some(run) = self.product_production.as_ref() { if let Some(pause) = self.pause_production_agent { - pause(run.doc, &run.project); + pause(run.doc, &run.project, self.pi_request_scope["writeEpoch"].as_u64()); } self.write_production_checkpoint(run, false); } @@ -1004,6 +1025,7 @@ impl Workspace { return Value::Null; } json!({"outputId":stage.output,"variantId":stage.variant,"revision":self.expected_revision, + "documentKey":self.pi_request_scope["documentKey"], "pendingOutputs":run.pending_outputs()}) } @@ -1044,6 +1066,7 @@ impl Workspace { let Some(stage) = run.stages.front() else { return; }; self.pi_request_scope["outputId"] = json!(stage.output); self.pi_request_scope["variantId"] = json!(stage.variant); + self.pi_request_scope["documentKey"] = super::product_document_key(&canvas.doc); self.pi_request_scope["template"] = json!({"id":self.template_workflow["templateId"], "version":self.template_workflow["templateVersion"],"hash":self.template_workflow["templateHash"]}); self.expected_revision = canvas.revision; @@ -1138,6 +1161,8 @@ impl Workspace { } let mut input = value["production"].clone(); input["workspaceId"] = run.workspace.clone(); + input["writeEpoch"] = self.pi_request_scope["writeEpoch"].clone(); + input["documentKey"] = self.pi_request_scope["documentKey"].clone(); // Autosave may already be finishing a stage snapshot. Dispatch through // the same save lane as a user changing outputs. if let Some(run) = self.product_production.as_mut() { @@ -1228,12 +1253,13 @@ impl Workspace { // Stop the local Pi turn and keep the original identities of outstanding jobs. if self.pi_request_scope["productProduction"] == true { if let Some(pause) = self.pause_production_agent { - pause(run.doc, &run.project); + pause(run.doc, &run.project, self.pi_request_scope["writeEpoch"].as_u64()); } self.pi_write_blocked = true; self.allow_apply = false; self.pi_ui_cancel("已到制作时限"); self.agent_native.cancel(); + self.revoke_production_epoch(); } for stage in &run.stages { run.drafts.push(json!({"outputId":stage.output,"variantId":stage.variant,"reason":"达到制作时限,保留当前草稿和原请求"})); @@ -1434,6 +1460,54 @@ mod tests { use super::*; use std::sync::mpsc; + #[test] + fn revoked_production_epoch_cannot_update_a_new_run() { + let (tx, _requests) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":40,"height":50})).unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + let doc = app.session.active().unwrap().doc.id.0; + let revision = app.session.active().unwrap().revision; + w.account = json!({"id":"local"}); + w.origin = "https://example.test".into(); + w.owner_doc = Some(doc); + w.pi_binding = json!({"accountId":"local","origin":w.origin}); + let old = "f78cef80-2da4-4b84-9a43-843735428d93"; + w.pi_run = Some(old.into()); + w.write_epoch = 1; + w.pi_request_scope = json!({"productProduction":true,"wholeDetail":true,"writeEpoch":1}); + w.agent_native.reset_for_run(old); + w.stop_production(); + assert!(w.agent_native.cancelled(old)); + assert!(w.pi_run.is_none()); + + w.write_epoch = 3; + w.pi_run = Some("new-run".into()); + w.pi_request_scope["writeEpoch"] = json!(3); + w.busy = Some("pi-agent".into()); + w.stream_reply = "当前回合".into(); + let ctx = egui::Context::default(); + for (method, value) in [ + ("agent", json!({"engine":"pi","doc":doc,"unknown":true,"error":"原回复"})), + ("slot-append", json!({"doc":doc,"candidateResult":{"id":"old-image","status":"complete"}})), + ("slot-product-export", json!({"doc":doc,"files":[{"path":"old.jpg"}]})), + ] { + let mut value = value; + value["writeEpoch"] = json!(1); + w.receive_event(&mut app, &ctx, super::super::Event::Json(method.into(), Ok(value))); + } + let delayed = json!({"run":old,"documentId":doc,"revision":revision,"items":[]}); + assert!(super::super::pi_bridge::private_action_in_ui(&mut w, &mut app, &ctx, "pi-detail-copy-apply", &delayed).is_err()); + assert_eq!(w.busy.as_deref(), Some("pi-agent")); + assert_eq!(w.pi_run.as_deref(), Some("new-run")); + assert_eq!(w.stream_reply, "当前回合"); + assert!(!w.unknown); + assert!(w.error.is_empty()); + assert_eq!(app.session.active().unwrap().revision, revision); + } + #[test] fn the_project_budget_sets_the_deadline_and_is_recorded_for_resume() { assert_eq!(budget_minutes(&Value::Null), 45); @@ -1494,7 +1568,7 @@ mod tests { run.deadline = production_time(); w.product_production = Some(run); thread_local! { static PAUSED: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } - w.pause_production_agent = Some(|doc, project| PAUSED.with(|call| { + w.pause_production_agent = Some(|doc, project, _| PAUSED.with(|call| { assert!(call.replace(Some((doc, project.into()))).is_none()); })); w.busy = Some("pi-agent".into()); @@ -1800,13 +1874,23 @@ mod tests { let mut session = photocraft_engine::Session::new(); session.execute("file.new", json!({"width":40,"height":50,"name":"详情页"})).unwrap(); let label = session.execute("type.create", json!({"text":"主图标题","size":12})).unwrap()["layer"].as_u64().unwrap(); + session.edit("登记详情工作画布", |doc, _| { + doc.metadata.text.push(("jiansun.slot-mapping.v1".into(), json!({ + "workspaceId":"workspace","component":"detail","variantId":"wood", + "templateId":"catalog","templateVersion":"v1","templateHash":"detail-hash", + "outputs":[{"documentId":"D01","mapping":{"fields":[{"kind":"text","nativeLayerId":label}]}}] + }).to_string())); + Ok(()) + }).unwrap(); let state = session.active_mut().unwrap(); state.saved_revision = state.revision; let mut app = PhotocraftApp::new(session, crate::Services::default()); let doc = app.session.active().unwrap().doc.id.0; let mut opened = app.session.active().unwrap().doc.as_ref().clone(); opened.name = "主图".into(); - opened.metadata.text.push(("jiansun.slot-mapping.v1".into(), json!({"outputs":[ + opened.metadata.text.retain(|(key, _)| key != "jiansun.slot-mapping.v1"); + opened.metadata.text.push(("jiansun.slot-mapping.v1".into(), json!({"workspaceId":"workspace", + "component":"main_images","variantId":"wood","templateHash":"main-hash","outputs":[ {"documentId":"M01","mapping":{"fields":[{"kind":"text","nativeLayerId":label}]}} ]}).to_string())); w.account = json!({"id":"local"}); @@ -1816,6 +1900,10 @@ mod tests { w.open_projects.insert(doc, project.clone()); w.owner_doc = Some(doc); w.pi_run = Some("original-run".into()); + w.pi_binding = json!({"accountId":"local","origin":w.origin}); + w.pi_request_scope = json!({"productProduction":true, + "documentKey":super::super::product_document_key(&app.session.active().unwrap().doc)}); + w.agent_native.reset_for_run("original-run"); w.busy = Some("pi-agent".into()); w.template_workflow = json!({"workspaceId":"workspace","outputId":"detail","variantId":"wood","revision":1}); let stage = Stage::read(&w.template_workflow).unwrap(); @@ -1841,22 +1929,38 @@ mod tests { assert_eq!(worker.template_workflow["outputId"], "detail"); assert_eq!(app.session.active().unwrap().doc.name, "小壹首轮详情"); app.session.edit("小壹保存详情", |doc, _| { doc.name = "小壹已更新详情".into(); Ok(()) }).unwrap(); + worker.pi_canvas_basis = Some(app.session.active().unwrap().doc.clone()); + let revision = app.session.active().unwrap().revision; + worker.expected_revision = revision; + let request = json!({"run":"original-run","revision":revision}); + let receipt = super::super::pi_bridge::action(worker, app, "pi-write-request", &request).unwrap(); + assert_eq!(receipt["allowed"], true); + let mut edit = request; + edit["edit"] = json!({"command":"type.edit","params":{"layer":label,"text":"详情更新"},"label":"回填详情"}); + super::super::pi_bridge::action(worker, app, "pi-edit", &edit).unwrap(); + worker.next_step = Instant::now(); + worker.tick_pending_edits(app, &egui::Context::default(), Some((doc, revision))); }); assert_eq!(app.session.active().unwrap().doc.name, "主图"); + let text = |doc: &Document| match &doc.layer(LayerId(label)).unwrap().content { + photocraft_doc::LayerContent::Text(layer) => layer.text.clone(), + _ => panic!("expected the mapped text layer"), + }; + assert_eq!(text(&app.session.active().unwrap().doc), "主图标题"); app.session.edit("改主图", |doc, _| { doc.name = "用户主图".into(); doc.layer_mut(LayerId(label)).unwrap().visible = false; Ok(()) }).unwrap(); - w.slot_action(&app, "slot-skeleton", json!({"outputId":"sku_images"})).unwrap(); + w.slot_action(&app, "slot-skeleton", json!({"outputId":"sku_images","variantId":"stone"})).unwrap(); let Request::Action(method, input) = requests.recv().unwrap() else { panic!("read the SKU view"); }; assert_eq!(method, "slot-product-view"); let mut sku = app.session.active().unwrap().doc.as_ref().clone(); sku.name = "SKU 图".into(); w.product_view_received(&app, Box::new(sku), json!({"productViewId":input["productViewId"], "doc":doc,"workspaceId":"workspace","accountId":"local","origin":w.origin, - "outputId":"sku_images","variantId":"wood","viewPath":"sku-edited.pcraft", - "workflow":{"workspaceId":"workspace","outputId":"sku_images","variantId":"wood"}})); + "outputId":"sku_images","variantId":"stone","viewPath":"sku-edited.pcraft", + "workflow":{"workspaceId":"workspace","outputId":"sku_images","variantId":"stone"}})); ctx.run_ui(egui::RawInput::default(), |ui| w.product_view_tick(&mut app, ui.ctx())).drop_without_applying_deltas(); let Request::Save(saved, revision, meta) = requests.recv().unwrap() else { panic!("save the displayed user's draft"); }; assert_eq!(saved.name, "用户主图"); @@ -1866,10 +1970,24 @@ mod tests { ctx.run_ui(egui::RawInput::default(), |ui| w.product_view_tick(&mut app, ui.ctx())).drop_without_applying_deltas(); assert_eq!(app.session.active().unwrap().doc.name, "SKU 图"); assert_eq!(w.product_view_state()["working"]["outputId"], "detail"); + assert_eq!(w.product_view_state()["viewing"]["variantId"], "stone"); + assert_eq!(w.product_view_state()["working"]["variantId"], "wood"); assert_eq!(w.pi_run.as_deref(), Some("original-run")); - w.slot_action(&app, "slot-skeleton", json!({"outputId":"detail"})).unwrap(); + let read = json!({"run":"original-run","documentId":doc,"page":0}); + assert!(super::super::pi_bridge::private_action_in_ui(&mut w, &mut app, &ctx, "pi-product-screen", &read).is_err()); + let (reply, receipt) = mpsc::channel(); + w.with_product_target(&mut app, |w, app| { + w.receive_event(app, &ctx, super::super::Event::PiAction("pi-product-screen".into(), read, reply)); + }); + let (_, snapshot) = receipt.recv().unwrap().unwrap(); + let snapshot = snapshot.unwrap(); + assert_eq!(super::super::product_document_key(&snapshot.document), w.pi_request_scope["documentKey"]); + assert_eq!(text(&snapshot.document), "详情更新"); + assert_eq!(text(&app.session.active().unwrap().doc), "主图标题"); + w.slot_action(&app, "slot-skeleton", json!({"outputId":"detail","variantId":"wood"})).unwrap(); ctx.run_ui(egui::RawInput::default(), |ui| w.product_view_tick(&mut app, ui.ctx())).drop_without_applying_deltas(); assert_eq!(app.session.active().unwrap().doc.name, "小壹已更新详情"); + assert_eq!(text(&app.session.active().unwrap().doc), "详情更新"); assert!(!w.product_view_detached()); assert_eq!(w.pi_run.as_deref(), Some("original-run")); @@ -1906,10 +2024,12 @@ mod tests { assert!(requests.try_recv().is_err(), "a delayed template read must settle before trying again"); let mut next = app.session.active().unwrap().doc.as_ref().clone(); next.name = "后台主图".into(); + w.persisted_revisions.insert(doc, app.session.active().unwrap().revision + 1); w.continue_product_canvas(&mut app, Box::new(next), json!({"continueProduct":true, "doc":doc,"workspaceId":"workspace","accountId":"local","origin":w.origin, "outputId":"main_images","variantId":"wood","previousViewPath":"detail-edited.pcraft", "workflow":{"workspaceId":"workspace","outputId":"main_images","variantId":"wood"}})); + w.with_product_target(&mut app, |w, app| w.production_tick(app)); assert!(requests.try_recv().is_err(), "an unsaved stage cannot start a model request"); w.with_product_target(&mut app, |w, app| { let revision = app.session.active().unwrap().revision; 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 def68955..94d3f471 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 @@ -847,7 +847,8 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u }; let delegated = submitted.get("delegatedInput").filter(|value| value.is_object()).ok_or("本机委托未创建")?; Ok(json!({"operationId":id,"phase":"submitted","__workflowDelegation":{"method":method,"input":delegated, - "run":run,"operationId":id,"accountId":w.account["id"],"origin":w.origin,"projectLocalId":w.pi_request_scope["project"]["localId"]}})) + "run":run,"operationId":id,"accountId":w.account["id"],"origin":w.origin, + "writeEpoch":w.pi_request_scope["writeEpoch"],"projectLocalId":w.pi_request_scope["project"]["localId"]}})) } pub(super) fn action(w: &mut Workspace, app: &mut PhotocraftApp, method: &str, input: &Value) -> Result { From 60a5351ec2373ee56584b9bf91d90174dda34566 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Thu, 26 Nov 2026 19:15:48 +0800 Subject: [PATCH 4/4] feat(xiaoyi): publish verified production bundles to a chosen folder --- apps/detail-photocraft/Cargo.lock | 1 + .../apps/photocraft/src/jiansun_backend.rs | 17 +- .../src/jiansun_canvas_workspace.rs | 75 ++- .../apps/photocraft/src/jiansun_creation.rs | 21 +- .../apps/photocraft/src/jiansun_delivery.rs | 429 ++++++++++++++++++ .../apps/photocraft/src/jiansun_pi_runtime.rs | 16 +- .../photocraft/src/jiansun_project_file.rs | 37 +- .../crates/ui-egui/Cargo.toml | 1 + .../crates/ui-egui/src/jiansun.rs | 14 +- .../crates/ui-egui/src/jiansun/creation.rs | 79 +++- .../crates/ui-egui/src/jiansun/pi_bridge.rs | 19 +- .../ui-egui/src/jiansun/product_production.rs | 271 +++++++++-- 12 files changed, 910 insertions(+), 70 deletions(-) create mode 100644 apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs diff --git a/apps/detail-photocraft/Cargo.lock b/apps/detail-photocraft/Cargo.lock index 138368ff..260b8f6c 100644 --- a/apps/detail-photocraft/Cargo.lock +++ b/apps/detail-photocraft/Cargo.lock @@ -5491,6 +5491,7 @@ dependencies = [ "unicode-bidi", "unicode-general-category", "unicode-segmentation", + "uuid", "web-time", "winsafe", ] diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 12f37b96..7a4264ef 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -86,6 +86,8 @@ pub fn start_agent_daemon() -> R { mod context_usage; #[path = "jiansun_prompt_library.rs"] mod prompt_library; +#[path = "jiansun_delivery.rs"] +mod delivery; #[path = "jiansun_project_file.rs"] mod project_file; #[path = "jiansun_transfer.rs"] @@ -1825,13 +1827,26 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { std::thread::spawn(move || b.scan_recovery(&tx, &ctx)); } for request in rx { - if backend.exiting() && !matches!(&request, Request::Save(..)) + if backend.exiting() && !matches!(&request, Request::Save(..) | Request::DeliverProductionBundle(..)) && !matches!(&request, Request::Action(method, _) if matches!(method.as_str(), "product-run-checkpoint" | "product-exit-checkpoint" | "slot-adopted")) { continue; } match request { + Request::DeliverProductionBundle(input, cancellation) => { + let worker = backend.clone(); + let events = events.clone(); + let ctx = ctx.clone(); + std::thread::spawn(move || { + let receipt = worker.deliver_bundle(&input, &cancellation) + .unwrap_or_else(|error| json!({"state":"failed","error":transfer::redact_text(&error)})); + let event = json!({"doc":input["doc"],"deliveryId":input["deliveryId"], + "accountEpoch":input["accountEpoch"],"writeEpoch":input["writeEpoch"],"productionDelivery":receipt}); + let _ = events.send(Event::Json("production-deliver-bundle".into(), Ok(event))); + ctx.request_repaint_of(egui::ViewportId::ROOT); + }); + } Request::OpenedResult { binding, result } => { let label = if binding["autoResume"] == true { "startup-open" } else { "open" }; let adopted = result.and_then(|(doc, meta)| backend.accept_opened(&binding, doc, meta)); 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 f5a17631..5ec04b29 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -2166,11 +2166,11 @@ pub(super) fn activate_edited_output(dir: &Path, doc: &Document) -> R { persist_locked(dir, &mut state, expected) } -fn receipt_path(dir: &Path, variant: &str, component: &str) -> PathBuf { +pub(super) fn receipt_path(dir: &Path, variant: &str, component: &str) -> PathBuf { dir.join("product-exports").join(variant).join(format!("{component}.json")) } -fn manifest_path(generation: &str) -> PathBuf { +pub(super) fn manifest_path(generation: &str) -> PathBuf { Path::new("generations").join(generation).join("manifest.json") } @@ -2341,7 +2341,7 @@ fn artifact_matches(artifact: &Value, verify_hash: bool) -> bool { && (!verify_hash || file_digest(path).is_ok_and(|actual| actual == expected)) } -fn file_digest(path: &Path) -> std::io::Result { +pub(super) fn file_digest(path: &Path) -> std::io::Result { let mut file = fs::File::open(path)?; let mut sha = Sha256::new(); std::io::copy(&mut file, &mut sha)?; @@ -2713,7 +2713,42 @@ fn export_product_stage(dir: &Path, doc: u64, state: &Value, input: &Value, scop export_product_stage_snapshot(dir, doc, state, input, scope, None) } -fn publish_product_generation( +pub(super) fn layered_format(bytes: &[u8]) -> R<&'static str> { + match bytes.get(..6) { + Some(b"8BPS\0\x01") => Ok("psd"), + Some(b"8BPS\0\x02") => Ok("psb"), + _ => Err("PSD / PSB 文件头无效".into()), + } +} + +pub(super) fn layered_size(name: &str, bytes: &[u8]) -> R<(u32, u32)> { + let format = layered_format(bytes)?; + if Path::new(name).extension().and_then(|ext| ext.to_str()) != Some(format) { + return Err("分层文件扩展名与文件头不一致".into()); + } + let imported = photocraft_io::import(name, bytes) + .map_err(|error| format!("无法重开分层文件:{error}"))?; + Ok((imported.document.size.width, imported.document.size.height)) +} + +fn export_layered_document(dir: &Path, component: &str, generation: &str, doc: &Document) -> R { + let exported = photocraft_io::export(doc, "psd", &Default::default()) + .map_err(|error| format!("分层文件导出失败:{error}"))?; + let format = layered_format(&exported.bytes)?; + let name = format!("{component}.{format}"); + let path = dir.join(&name); + photocraft_format::atomic_write(&path, &exported.bytes) + .map_err(|error| format!("分层文件写入失败:{error}"))?; + let saved = fs::read(&path).map_err(|error| format!("分层文件读取失败:{error}"))?; + if saved != exported.bytes || layered_size(&name, &saved)? != (doc.size.width, doc.size.height) { + return Err("分层文件与本轮画布的内容或尺寸不一致".into()); + } + Ok(json!({"path":path,"format":format,"role":"layered","generationId":generation, + "width":doc.size.width,"height":doc.size.height,"sizeBytes":saved.len(), + "sha256":format!("{:x}",Sha256::digest(&saved))})) +} + +pub(super) fn publish_product_generation( receipt: &Path, native: &Document, document_revision: &Value, result: &mut Value, regions: &[(u64, u64, u64)], screens: &[(u64, u64, u64)], ) -> R<()> { @@ -2732,6 +2767,8 @@ fn publish_product_generation( || reopened.layer_count() != native.layer_count() || reopened.metadata.text != native.metadata.text { return Err("成品工程重开后与本轮画布的身份、图层或页面信息不一致".into()); } + super::transfer::check_pcraft_file(&editable)?; + let layered = export_layered_document(generation.path(), component, id, &reopened)?; let exported_mapping = mapping(&reopened); let save_region = |name: &str, role: &str, (top, width, height): (u64, u64, u64), bytes: Vec| -> R { let file = generation.path().join(name); @@ -2790,12 +2827,13 @@ fn publish_product_generation( result["sourceDocument"] = json!({"path":editable,"format":"pcraft","role":"editable","generationId":id, "revision":document_revision,"reopened":true,"width":reopened.size.width,"height":reopened.size.height, "sizeBytes":size,"sha256":sha}); + result["layeredDocument"] = layered; result["files"] = json!(files); if !split.is_empty() { result["screenFiles"] = json!(split); } result["editable"] = json!(editable); result["productionDelivery"] = delivery; result["validation"] = json!({"mode":"full","editableReopened":true, - "filesVerified":1 + regions.len() + screens.len(),"validatedAt":chrono::Utc::now().timestamp_millis()}); + "filesVerified":2 + regions.len() + screens.len(),"validatedAt":chrono::Utc::now().timestamp_millis()}); write_json(&generation.path().join("manifest.json"), result)?; // A replacement can report a directory flush error after the rename. // Keep the complete generation before attempting to publish its pointer. @@ -3368,7 +3406,11 @@ impl Backend { return Err("当前花色不属于所填产品资料".into()); } let c = creation::load(&dir)?; - self.creation_action("creation-save", &json!({"doc":doc,"revision":c["revision"],"brief":common,"width":width,"productionBudgetMinutes":input["productionBudgetMinutes"]}), None, events, ctx)?; + let mut changes = json!({"doc":doc,"revision":c["revision"],"brief":common,"width":width,"productionBudgetMinutes":input["productionBudgetMinutes"]}); + if let Some(path) = input.get("deliveryDir") { + changes["deliveryDir"] = path.clone(); + } + self.creation_action("creation-save", &changes, None, events, ctx)?; let c = creation::load(&dir)?; let mut next = previous.unwrap_or_else( || json!({"version":1,"canvasFirst":true,"id":Uuid::new_v4().to_string(),"revision":0, @@ -3434,6 +3476,9 @@ impl Backend { .collect::>().into_iter().collect::>().join("。"); return Err(format!("所选模板暂无可制作的输出。{reasons}。请核对模板资源后选用新版本。")); } + if input["resumeProduct"] == true && let Some(path) = input.get("deliveryDir") { + creation::save_delivery_directory(&dir, path)?; + } let mut prepared = self.canvas_workspace_result(doc, &dir)?; prepared["workflow"]["productionStages"] = json!(stages); prepared["productionPreparation"] = json!(true); @@ -5936,6 +5981,21 @@ mod tests { assert!(generation_references(&fixture.dir, &state, &variant).is_err(), "the existing native reference contract requires an explicit purpose"); } + #[test] + fn layered_production_export_uses_the_real_psd_and_psb_boundary() { + let folder = tempfile::tempdir().unwrap(); + for (height, expected) in [(30_000, "psd"), (30_001, "psb")] { + let doc = Document::new("Layered test", photocraft_doc::Size::new(2, height), + photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + let artifact = export_layered_document(folder.path(), "detail", "generation-test", &doc).unwrap(); + assert_eq!(artifact["format"], expected); + let name = format!("detail.{expected}"); + let bytes = fs::read(folder.path().join(&name)).unwrap(); + assert_eq!(layered_format(&bytes).unwrap(), expected); + assert_eq!(layered_size(&name, &bytes).unwrap(), (2, height)); + } + } + #[test] fn interrupted_reexport_keeps_previous_published_generation() { const CRASH: &str = "PHOTOCRAFT_TEST_CRASH_EXPORT"; @@ -5964,6 +6024,9 @@ mod tests { let current = published_receipt(&receipt).unwrap(); assert_eq!(current["sourceDocument"]["revision"], 1); assert!(artifact_matches(¤t["sourceDocument"], true)); + let layered = ¤t["layeredDocument"]; + let bytes = fs::read(layered["path"].as_str().unwrap()).unwrap(); + assert_eq!(layered_size(layered["path"].as_str().unwrap(), &bytes).unwrap(), (8, 8)); for file in current["files"].as_array().unwrap().iter().chain(current["screenFiles"].as_array().unwrap()) { assert!(artifact_matches(file, true)); } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs index 9ecac6c6..60aa4eec 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs @@ -45,6 +45,16 @@ pub(super) fn load(dir: &Path) -> R { pub(super) fn save(dir: &Path, c: &mut Value) -> R<()> { save_with_revision(dir, c, true) } +pub(super) fn save_delivery_directory(dir: &Path, value: &Value) -> R<()> { + let path = json!(super::project_file::delivery_directory(dir, value)?); + let mut creation = load(dir)?; + if creation["deliveryDir"] != path { + creation["deliveryDir"] = path; + save_with_revision(dir, &mut creation, false)?; + } + Ok(()) +} + fn save_with_revision(dir: &Path, c: &mut Value, advance_revision: bool) -> R<()> { let _guard = sync::context_guard(); project_not_trashed(dir)?; @@ -628,6 +638,8 @@ impl Backend { "creation-save" => { let mut c = load(&dir)?; revision(&c, input)?; + let delivery_dir = input.get("deliveryDir") + .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() { @@ -672,12 +684,15 @@ impl Backend { model::invalidate(&mut c, &before); let budget = input["productionBudgetMinutes"].as_u64().filter(|minutes| *minutes > 0) .filter(|minutes| Some(*minutes) != before["productionBudgetMinutes"].as_u64()); - let budget_only = budget.is_some() && c == before; + let preferences_only = c == before && (budget.is_some() || delivery_dir.is_some()); + if let Some(path) = delivery_dir { + c["deliveryDir"] = json!(path); + } if let Some(minutes) = budget { c["productionBudgetMinutes"] = json!(minutes); } - save_with_revision(&dir, &mut c, !budget_only)?; - if !budget_only { + save_with_revision(&dir, &mut c, !preferences_only)?; + if !preferences_only { super::canvas_workspace::apply_saved_variant_edits(&dir)?; } self.creation_result(doc, &dir) diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs new file mode 100644 index 00000000..cee12a03 --- /dev/null +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs @@ -0,0 +1,429 @@ +use super::{Backend, R, canvas_workspace, creation, original_project_present, pi_runtime, project_file, read_json, sync, transfer, write_json}; +use photocraft_format::atomic::{AtomicFs, RealFs}; +use serde_json::{Value, json}; +use std::{ + collections::{BTreeMap, HashSet}, + fs, + path::{Path, PathBuf}, + sync::atomic::{AtomicBool, Ordering}, +}; +use uuid::Uuid; + +fn disk(error: std::io::Error) -> String { + format!("成品目录写入或读取失败:{error}") +} + +fn name_component(name: &str) -> String { + let cleaned: String = name.chars().take(70).map(|ch| if ch.is_control() || "<>:\"/\\|?*".contains(ch) { '_' } else { ch }).collect(); + let name = cleaned.trim_matches(|ch: char| ch == '.' || ch.is_whitespace()); + let stem = name.split('.').next().unwrap_or_default().to_ascii_uppercase(); + if name.is_empty() { + return "小壹项目".into(); + } + if matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") + || stem + .strip_prefix("COM") + .or_else(|| stem.strip_prefix("LPT")) + .is_some_and(|number| matches!(number, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³")) + { + return format!("_{name}"); + } + name.into() +} + +fn file_record(root: &Path, path: &Path, category: &str, size: Option<(u32, u32)>) -> R { + let relative = path.strip_prefix(root).map_err(|_| "交付文件不在成品目录内")?; + let format = path.extension().and_then(|extension| extension.to_str()).ok_or("交付文件格式缺失")?; + Ok(json!({"category":category,"relativePath":relative.to_string_lossy().replace('\\', "/"), + "format":format,"width":size.map(|(width, _)| width),"height":size.map(|(_, height)| height), + "sizeBytes":fs::metadata(path).map_err(disk)?.len(), + "sha256":canvas_workspace::file_digest(path).map_err(disk)?,"verified":true})) +} + +fn artifact_size(path: &Path, format: &str) -> R> { + let size = match format { + "jpg" => { + let bytes = fs::read(path).map_err(disk)?; + if !bytes.starts_with(&[0xff, 0xd8, 0xff]) { + return Err("JPG 文件头无效".into()); + } + photocraft_codecs::probe_size(&bytes).map_err(|error| format!("无法读取 JPG 尺寸:{error}"))? + } + "psd" | "psb" => canvas_workspace::layered_size(&path.to_string_lossy(), &fs::read(path).map_err(disk)?)?, + "pcraft" => { + transfer::check_pcraft_file(path)?; + let doc = photocraft_format::load_path(path).map_err(|error| format!("无法重开成品原稿:{error}"))?; + (doc.size.width, doc.size.height) + } + "jpeg" | "png" | "webp" => { + photocraft_codecs::probe_size(&fs::read(path).map_err(disk)?).map_err(|error| format!("无法读取工程资源图像尺寸:{error}"))? + } + _ => return Ok(None), + }; + Ok(Some(size)) +} + +fn copy_artifact(root: &Path, generation: &Path, source: &Value, category: &str, folder: &Path, name: &str) -> R { + let format = source["format"].as_str().filter(|format| matches!(*format, "jpg" | "pcraft" | "psd" | "psb")).ok_or("成品格式无效")?; + let filename = source["path"].as_str().and_then(|path| Path::new(path).file_name()).ok_or("成品路径缺失")?; + let from = generation.join(filename); + let parent = root.join(category).join(folder); + fs::create_dir_all(&parent).map_err(disk)?; + let to = parent.join(format!("{name}.{format}")); + if to.exists() { + return Err("成品清单含重复文件名".into()); + } + fs::copy(&from, &to).map_err(disk)?; + let size = artifact_size(&to, format)?.ok_or("成品清单含不支持的格式")?; + let record = file_record(root, &to, category, Some(size))?; + if ["width", "height", "sizeBytes", "sha256"].iter().any(|field| record[*field] != source[*field]) { + return Err(format!("{name}.{format} 与已验证成品不一致")); + } + Ok(record) +} + +fn copy_generation(root: &Path, project: &Path, input: &Value, output: &Value, folder: &Path, files: &mut Vec) -> R<()> { + let component = output["outputId"].as_str().ok_or("成品类型缺失")?; + let label = match component { + "detail" => "详情页", + "main_images" => "主图", + "sku_images" => "SKU", + _ => return Err("成品类型无效".into()), + }; + let variant = output["variantId"].as_str().ok_or("成品花色缺失")?; + if Uuid::parse_str(variant).is_err() { + return Err("成品花色标识无效".into()); + } + let id = output["generationId"] + .as_str() + .filter(|id| id.strip_prefix("generation-").is_some_and(|suffix| !suffix.is_empty() && suffix.bytes().all(|byte| byte.is_ascii_alphanumeric()))) + .ok_or("成品版本无效")?; + let receipt = canvas_workspace::receipt_path(project, variant, component); + let manifest = receipt.with_file_name(canvas_workspace::manifest_path(id)); + let generation = manifest.parent().ok_or("成品版本目录无效")?; + let data = read_json(&manifest)?; + if data["workspaceId"] != input["workspaceId"] + || data["outputId"] != component + || data["variantId"] != variant + || data["generationId"] != id + || data["validation"]["mode"] != "full" + { + return Err("制作输出与已验证成品版本不一致".into()); + } + files.push(copy_artifact(root, generation, &data["sourceDocument"], "工程文件", folder, label)?); + files.push(copy_artifact(root, generation, &data["layeredDocument"], "PSD", folder, label)?); + let images = data["files"].as_array().filter(|rows| !rows.is_empty()).ok_or("成品 JPG 缺失")?; + if component == "detail" { + let mut screens = data["screenFiles"].as_array().filter(|rows| !rows.is_empty()).ok_or("详情页切片缺失")?.iter().collect::>(); + screens.sort_by_key(|screen| screen["top"].as_u64()); + if images.len() != 1 { + return Err("详情页长图数量无效".into()); + } + files.push(copy_artifact(root, generation, &images[0], "详情页长图", folder, "详情页长图")?); + for (index, screen) in screens.into_iter().enumerate() { + files.push(copy_artifact(root, generation, screen, "详情页切片", folder, &format!("详情页-{:02}", index + 1))?); + } + } else { + for (index, image) in images.iter().enumerate() { + files.push(copy_artifact(root, generation, image, label, folder, &format!("{label}-{:02}", index + 1))?); + } + } + Ok(()) +} + +fn sync_tree(dir: &Path) -> R<()> { + for entry in fs::read_dir(dir).map_err(disk)? { + let entry = entry.map_err(disk)?; + if entry.file_type().map_err(disk)?.is_dir() { + sync_tree(&entry.path())?; + } else { + fs::OpenOptions::new().write(true).open(entry.path()).and_then(|file| file.sync_all()).map_err(disk)?; + } + } + RealFs.sync_dir(dir).map_err(disk) +} + +fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, input: &Value, admitted: impl Fn() -> R<()>) -> R { + admitted()?; + let dir = project_file::delivery_directory(project, &input["deliveryDir"])?.ok_or("未选择成品目录")?; + let delivery_id = input["deliveryId"].as_str().filter(|id| Uuid::parse_str(id).is_ok()).ok_or("本轮交付编号无效")?; + let outputs = input["published"].as_array().filter(|rows| !rows.is_empty()).ok_or("本轮没有已验证成品")?; + let creation = creation::load(project)?; + let name = name_component(creation["brief"]["name"].as_str().unwrap_or_default()); + transfer::no_credentials(&json!(name))?; + fs::create_dir_all(&dir).map_err(disk)?; + let destination = |number| { + let basename = if number == 1 { format!("{name}-成品") } else { format!("{name}-成品 ({number})") }; + dir.join(basename) + }; + let existing_receipt = |target: &Path| { + read_json(&target.join("交付清单.json")) + .ok() + .filter(|saved| saved["deliveryId"] == delivery_id) + .map(|saved| json!({"state":"bundle_saved","path":target,"allOutputsCompleted":saved["allOutputsCompleted"],"counts":saved["counts"]})) + }; + // Recover a committed directory if the client lost the completion event. + for number in 1.. { + let target = destination(number); + if !target.try_exists().map_err(disk)? { + break; + } + if let Some(receipt) = existing_receipt(&target) { + return Ok(receipt); + } + } + let stage = tempfile::Builder::new().prefix(".xiaoyi-deliver-tmp-").tempdir_in(&dir).map_err(disk)?; + let root = stage.path(); + let package_root = root.join("工程文件"); + fs::create_dir(&package_root).map_err(disk)?; + 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)?; + let reopened = read_json(&project_file)?; + if reopened != package { + return Err("小壹工程清单读回不一致".into()); + } + transfer::no_credentials(&reopened)?; + let snapshot = project_file::resource_checkpoint(&project_file, &reopened)?; + let doc = photocraft_format::load_path(&snapshot.join("canvas.pcraft")).map_err(|error| format!("无法重开小壹工程画布:{error}"))?; + let mut files = vec![file_record(root, &project_file, "工程文件", Some((doc.size.width, doc.size.height)))?]; + for entry in reopened["projectManifest"]["included"].as_array().ok_or("工程资源清单缺失")? { + let relative = entry.as_str().ok_or("工程资源路径无效")?; + let file = snapshot.join(relative); + 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 and stops any active run. + if !matches!(relative, "context.json" | "production-run.json") + && record["sha256"] != canvas_workspace::file_digest(&project.join(relative)).map_err(disk)? + { + return Err("工程资源与本机草稿内容不一致".into()); + } + files.push(record); + } + + let variants: HashSet<_> = outputs.iter().filter_map(|output| output["variantId"].as_str()).collect(); + let mut variant_folders = BTreeMap::new(); + let mut seen = HashSet::new(); + for output in outputs { + admitted()?; + let variant = output["variantId"].as_str().ok_or("成品花色缺失")?; + let component = output["outputId"].as_str().ok_or("成品类型缺失")?; + if !seen.insert((variant, component)) { + return Err("本轮交付含重复输出".into()); + } + let index = variant_folders.len() + 1; + let folder = variant_folders.entry(variant).or_insert_with(|| { + if variants.len() == 1 { + return PathBuf::new(); + } + let label = creation["brief"]["variants"] + .as_array() + .into_iter() + .flatten() + .find(|row| row["id"] == variant) + .and_then(|row| row["name"].as_str()) + .unwrap_or("花色"); + PathBuf::from(format!("{index:02} {}", name_component(label))) + }); + copy_generation(root, project, input, output, folder, &mut files)?; + } + let all_outputs_completed = input["total"].as_u64() == Some(outputs.len() as u64); + let mut counts = BTreeMap::new(); + for category in files.iter().filter_map(|file| file["category"].as_str()) { + *counts.entry(category.to_owned()).or_insert(0) += 1; + } + let manifest = json!({"version":1,"deliveryId":delivery_id,"allOutputsCompleted":all_outputs_completed, + "completedOutputs":outputs.len(),"totalOutputs":input["total"],"counts":counts,"files":files}); + transfer::no_credentials(&manifest)?; + write_json(&root.join("交付清单.json"), &manifest)?; + sync_tree(root)?; + let _guard = sync::context_guard(); + admitted()?; + for number in 1.. { + let target = destination(number); + if target.try_exists().map_err(disk)? { + if let Some(receipt) = existing_receipt(&target) { + return Ok(receipt); + } + continue; + } + match fs::rename(root, &target) { + Ok(()) => { + let flush = RealFs.sync_dir(&dir).err().map(|error| disk(error)); + return Ok(json!({"state":"bundle_saved","path":target,"allOutputsCompleted":all_outputs_completed, + "counts":counts,"durabilityWarning":flush})); + } + Err(_) if target.exists() => continue, + Err(error) => return Err(disk(error)), + } + } + unreachable!() +} + +impl Backend { + pub(super) fn deliver_bundle(&self, input: &Value, cancellation: &AtomicBool) -> R { + let doc = input["doc"].as_u64().ok_or("项目编号无效")?; + self.ensure_owner(doc)?; + let project = self.locations.get(&doc).filter(|project| input["project"] == project.as_str()).ok_or("制作任务属于其他项目")?; + let dir = self.project_dir(doc)?; + let admitted = || { + if cancellation.load(Ordering::Acquire) { + return Err("原制作回合已停止".into()); + } + self.check_dispatch()?; + self.ensure_owner(doc)?; + original_project_present(&dir) + }; + admitted()?; + if input["accountEpoch"].as_u64() != Some(self.access.epoch) + || input["writeEpoch"].as_u64().is_none() + || input["accountId"] != self.auth["account"]["id"] + || input["origin"] != self.origin + { + return Err("账号或制作回合已切换".into()); + } + let scope = self.scope(); + let policy = transfer::Policy { chat: false, scope: &scope, project }; + pi_runtime::record_export_event(self, doc, input, "export", "deliver_bundle", "running", Value::Null); + let result = deliver_production_bundle(&dir, &policy, input, admitted); + let (status, progress) = match &result { + Ok(receipt) => { + let status = if receipt["durabilityWarning"].is_string() { "unconfirmed" } else { "completed" }; + (status, json!({"counts":receipt["counts"],"allOutputsCompleted":receipt["allOutputsCompleted"]})) + } + Err(_) => ("failed", Value::Null), + }; + pi_runtime::record_export_event(self, doc, input, "export", "deliver_bundle", status, progress); + result + } +} + +#[cfg(test)] +mod tests { + use super::*; + use photocraft_doc::{ColorMode, Document, SampleType, Size}; + + fn fixture() -> (tempfile::TempDir, PathBuf, String, Value) { + let root = tempfile::tempdir().unwrap(); + 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(); + write_json(&project.join("context.json"), &json!({"localId":local,"owner":"owner"})).unwrap(); + write_json(&project.join("creation.json"), &json!({"version":1,"brief":{"name":"天青椅"}})).unwrap(); + let variant = Uuid::new_v4().to_string(); + let workspace = Uuid::new_v4().to_string(); + let mut published = Vec::new(); + for (component, regions, screens) in [ + ("detail", vec![(0, 8, 10)], vec![(0, 8, 4), (4, 8, 6)]), + ("main_images", vec![(0, 8, 4), (4, 8, 6)], vec![]), + ("sku_images", vec![(0, 8, 10)], vec![]), + ] { + let receipt = canvas_workspace::receipt_path(&project, &variant, component); + let mut result = json!({"workspaceId":workspace,"variantId":variant,"outputId":component}); + canvas_workspace::publish_product_generation(&receipt, &canvas, &json!(7), &mut result, ®ions, &screens).unwrap(); + assert_eq!(result["layeredDocument"]["format"], "psd"); + assert_eq!(result["validation"]["filesVerified"], 2 + regions.len() + screens.len()); + published.push(json!({"variantId":variant,"outputId":component,"generationId":result["generationId"]})); + } + let input = json!({"workspaceId":workspace,"deliveryId":Uuid::new_v4().to_string(), + "deliveryDir":root.path().join("deliveries"),"total":3,"published":published}); + (root, project, local, input) + } + + #[test] + fn delivery_preference_reopens_and_clears_without_revising_creation_inputs() { + let root = tempfile::tempdir().unwrap(); + let project = root.path().join("drafts").join("project"); + fs::create_dir_all(&project).unwrap(); + let path = root.path().join("deliveries"); + write_json(&project.join("creation.json"), &json!({"version":1,"revision":9,"brief":{"name":"天青椅"}})).unwrap(); + assert!(creation::load(&project).unwrap()["deliveryDir"].is_null()); + creation::save_delivery_directory(&project, &json!(path)).unwrap(); + let saved = creation::load(&project).unwrap(); + assert_eq!(saved["deliveryDir"], json!(path)); + assert_eq!(saved["revision"], 9); + assert!(creation::save_delivery_directory(&project, &json!(project.join("nested"))).is_err()); + assert_eq!(creation::load(&project).unwrap(), saved); + creation::save_delivery_directory(&project, &Value::Null).unwrap(); + assert!(creation::load(&project).unwrap()["deliveryDir"].is_null()); + } + + #[test] + fn locally_published_outputs_form_a_reopenable_verified_bundle_and_keep_older_deliveries() { + let (root, project, local, mut input) = fixture(); + let policy = transfer::Policy { chat: false, scope: "owner", project: &local }; + let delivered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap(); + assert_eq!(delivered["allOutputsCompleted"], true); + let counts = &delivered["counts"]; + for (category, count) in [("工程文件", 4), ("PSD", 3), ("详情页长图", 1), ("详情页切片", 2), ("主图", 2), ("SKU", 1)] { + assert_eq!(counts[category], count, "{category}"); + } + let final_dir = PathBuf::from(delivered["path"].as_str().unwrap()); + let manifest_path = final_dir.join("交付清单.json"); + let manifest = read_json(&manifest_path).unwrap(); + transfer::no_credentials(&manifest).unwrap(); + for entry in manifest["files"].as_array().unwrap() { + let path = final_dir.join(entry["relativePath"].as_str().unwrap()); + assert!(path.is_file(), "{}", path.display()); + assert_eq!(entry["sizeBytes"], fs::metadata(&path).unwrap().len()); + assert_eq!(entry["sha256"], canvas_workspace::file_digest(&path).unwrap()); + assert_eq!(entry["verified"], true); + } + for (path, width, height) in [ + ("详情页长图/详情页长图.jpg", 8, 10), + ("详情页切片/详情页-01.jpg", 8, 4), + ("详情页切片/详情页-02.jpg", 8, 6), + ("主图/主图-01.jpg", 8, 4), + ("主图/主图-02.jpg", 8, 6), + ("SKU/SKU-01.jpg", 8, 10), + ] { + let bytes = fs::read(final_dir.join(path)).unwrap(); + assert_eq!(photocraft_codecs::probe_size(&bytes).unwrap(), (width, height)); + } + for name in ["详情页", "主图", "SKU"] { + let filename = format!("{name}.psd"); + let bytes = fs::read(final_dir.join("PSD").join(&filename)).unwrap(); + assert_eq!(canvas_workspace::layered_size(&filename, &bytes).unwrap(), (8, 10)); + } + let clean = root.path().join("clean"); + fs::create_dir(&clean).unwrap(); + assert_eq!(project_file::open(&final_dir.join("工程文件/天青椅.xiaoyi"), &clean, "owner").unwrap(), local); + let original = fs::read(manifest_path).unwrap(); + assert_eq!(deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap()["path"], delivered["path"]); + input["deliveryId"] = json!(Uuid::new_v4().to_string()); + let second = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap(); + assert!(second["path"].as_str().unwrap().ends_with("天青椅-成品 (2)")); + assert_eq!(fs::read(final_dir.join("交付清单.json")).unwrap(), original); + } + + #[test] + fn invalid_destination_cancellation_and_credentials_leave_generations_intact() { + let (root, project, local, mut input) = fixture(); + let policy = transfer::Policy { chat: false, scope: "owner", project: &local }; + let previous = input["deliveryDir"].clone(); + for invalid in [json!("relative"), json!(project.join("delivery")), json!(project.join("canvas.pcraft"))] { + input["deliveryDir"] = invalid; + assert!(deliver_production_bundle(&project, &policy, &input, || Ok(())).is_err()); + } + input["deliveryDir"] = previous; + let calls = std::cell::Cell::new(0); + let result = deliver_production_bundle(&project, &policy, &input, || { + calls.set(calls.get() + 1); + if calls.get() >= 5 { Err("cancelled".into()) } else { Ok(()) } + }); + assert_eq!(result.unwrap_err(), "cancelled"); + let destination = root.path().join("deliveries"); + assert_eq!(fs::read_dir(&destination).unwrap().count(), 0); + write_json(&project.join("creation.json"), &json!({"version":1,"brief":{"name":"天青椅","apiKey":"fixture-secret"}})).unwrap(); + assert!(deliver_production_bundle(&project, &policy, &input, || Ok(())).is_err()); + assert_eq!(fs::read_dir(&destination).unwrap().count(), 0); + for output in input["published"].as_array().unwrap() { + let pointer = canvas_workspace::receipt_path(&project, output["variantId"].as_str().unwrap(), output["outputId"].as_str().unwrap()); + assert_eq!(canvas_workspace::published_receipt(&pointer).unwrap()["generationId"], output["generationId"]); + } + } +} 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 d1550a52..431c3a53 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -426,9 +426,13 @@ pub(super) fn record_export_event( let trace = &input["execution"]; let Some(project) = b.locations.get(&doc).filter(|_| trace["runId"].is_string()) else { return; }; let Ok(dir) = b.project_dir(doc) else { return; }; + let _delivery_guard = (phase == "deliver_bundle").then(super::sync::context_guard); + if phase == "deliver_bundle" && (b.check_dispatch().is_err() || super::original_project_present(&dir).is_err()) { + return; + } let at = chrono::Utc::now().timestamp_millis(); let durably_committed = status == "completed" - && matches!((category, phase), ("disk_persist", "save") | ("export", "publish")); + && matches!((category, phase), ("disk_persist", "save") | ("export", "publish" | "deliver_bundle")); let record = json!({"type":"production_execution","at":at,"projectId":project, "runId":trace["runId"],"operationId":trace["operationId"],"attempt":1, "outputId":input["outputId"],"variantId":input["variantId"],"revision":input["canvasRevision"], @@ -440,8 +444,14 @@ pub(super) fn record_export_event( let mut line = record.to_string(); line.push('\n'); use std::io::Write as _; - if let Err(error) = std::fs::OpenOptions::new().append(true).open(file) - .and_then(|mut file| file.write_all(line.as_bytes())) + let append = || { + if phase == "deliver_bundle" { + std::fs::create_dir_all(file.parent().expect("event directory"))?; + } + std::fs::OpenOptions::new().append(true).create(phase == "deliver_bundle").open(file) + .and_then(|mut file| file.write_all(line.as_bytes())) + }; + if let Err(error) = append() { log::warn!("小壹制作观测事件保存失败:{}", error.kind()); } 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 7400f94c..65f533ca 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs @@ -31,7 +31,8 @@ fn project_entry(relative: &Path) -> bool { match root { "creation-assets" | "creation-generated" | "creation-tasks" | "template-outputs" | "product-exports" | "composer-attachments" | "reference-previews" => - matches!(relative.extension().and_then(|ext| ext.to_str()), Some("json" | "png" | "jpg" | "jpeg" | "webp" | "pcraft")), + matches!(relative.extension().and_then(|ext| ext.to_str()), Some("json" | "png" | "jpg" | "jpeg" | "webp" | "pcraft")) + || root == "product-exports" && matches!(relative.extension().and_then(|ext| ext.to_str()), Some("psd" | "psb")), "image-jobs" => relative.file_name().and_then(|name| name.to_str()).is_some_and(|name| matches!(name, "canvas-candidate.json" | "task.json" | "generated.png" | "failure.json" | "scene-product.png") || name.starts_with("reference-") && name.ends_with(".png")), @@ -39,7 +40,37 @@ fn project_entry(relative: &Path) -> bool { } } -fn resource_checkpoint(file: &Path, manifest: &Value) -> R { +pub(super) fn delivery_directory(project: &Path, value: &Value) -> R> { + if value.is_null() { return Ok(None); } + transfer::no_credentials(value)?; + let path = value.as_str().map(Path::new).filter(|path| path.is_absolute()) + .ok_or("请选择绝对路径的成品目录")?; + let draft_store = project.parent().ok_or("项目草稿目录无效")?.canonicalize().map_err(disk)?; + // Resolve existing ancestors before creating anything, including Windows junctions. + let mut ancestor = path; + while !ancestor.try_exists().map_err(disk)? { + ancestor = ancestor.parent().ok_or("成品保存位置不存在")?; + } + let existing = ancestor.canonicalize().map_err(disk)?; + if !existing.is_dir() { return Err("成品保存位置必须是文件夹".into()); } + let mut resolved = existing; + let tail = path.strip_prefix(ancestor).map_err(|_| "成品保存位置无效")?; + let mut normalized = false; + for part in tail.components() { + if part == std::path::Component::ParentDir { + resolved.pop(); + normalized = true; + } else { + resolved.push(part.as_os_str()); + } + } + if resolved.starts_with(&draft_store) { + return Err("请选择项目草稿目录以外的位置".into()); + } + Ok(Some(if normalized { resolved } else { path.to_path_buf() })) +} + +pub(super) fn resource_checkpoint(file: &Path, manifest: &Value) -> R { let resources = manifest["resources"].as_str().map(Path::new).filter(|path| matches!(path.components().next(), Some(std::path::Component::Normal(_))) && path.components().count() == 1 ).ok_or("工程资源目录无效")?; @@ -149,7 +180,7 @@ fn copy_project( Ok(()) } -fn write_project(dir: &Path, file: &Path, manifest: &mut Value, policy: &Policy<'_>) -> R<()> { +pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, policy: &Policy<'_>) -> R<()> { let checkpoint = resource_checkpoint(file, manifest)?; let resource_dir = checkpoint.parent().ok_or("工程资源目录无效")?; fs::create_dir_all(resource_dir).map_err(disk)?; diff --git a/apps/detail-photocraft/crates/ui-egui/Cargo.toml b/apps/detail-photocraft/crates/ui-egui/Cargo.toml index 37aeefc9..b9e56e74 100644 --- a/apps/detail-photocraft/crates/ui-egui/Cargo.toml +++ b/apps/detail-photocraft/crates/ui-egui/Cargo.toml @@ -55,6 +55,7 @@ craft-update = { workspace = true } rayon = { workspace = true } # Safe native UI-language APIs (Windows/macOS); no subprocess or web dependency. sys-locale = "=0.3.2" +uuid = { version = "1", features = ["v4"] } # Installed RAM for the GPU memory budget (`gpu_canvas::physical_memory`) and the user's decimal # symbol (`i18n::decimal_separator`, a registry read): the safe binding the desktop app already diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index eeaa6f27..6d5aeae7 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -57,6 +57,7 @@ pub enum Request { Save(Arc, u64, Value), Generate(Arc, Value), SlotPreview(Arc, Value), + DeliverProductionBundle(Value, Arc), OpenedResult { binding: Value, result: Result<(Box, Value), String> }, } #[derive(Clone, Debug)] @@ -1102,6 +1103,7 @@ pub struct Workspace { creation_width: u32, creation_count: usize, creation_budget_minutes: u64, + creation_delivery_dir: Option, creation_catalog: std::collections::HashMap>, creation_reads: creation_reads::UiState, creation_view_geometry: Value, @@ -1301,6 +1303,11 @@ impl Workspace { self.busy = Some(method.into()); return Ok(json!({"submitted":true,"saving":true})); } + if method == "slot-skeleton" && input.get("deliveryDir").is_none() + && input["brief"].is_object() + { + input["deliveryDir"] = json!(self.creation_delivery_dir); + } if matches!(method, "slot-apply" | "slot-skeleton" | "slot-product-export") { if method == "slot-skeleton" && (input["generateProduct"] == true || input["resumeProduct"] == true) && let Some(problem) = self.production_model_problem() { @@ -1601,6 +1608,7 @@ impl Workspace { creation_width: 1440, creation_count: 3, creation_budget_minutes: product_production::DEFAULT_BUDGET_MINUTES, + creation_delivery_dir: None, creation_catalog: Default::default(), creation_reads: Default::default(), creation_view_geometry: json!({}), @@ -1985,6 +1993,7 @@ impl Workspace { 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_budget_minutes = product_production::budget_minutes(&retained.draft); + self.creation_delivery_dir = product_production::delivery_dir(&retained.draft); self.creation_dirty = true; self.draft_changed = true; self.sync_dirty = true; @@ -3498,7 +3507,7 @@ impl Workspace { if self.production_exit.is_some() && !matches!(&event, Event::Saved(..) | Event::PiAction(..)) && !matches!(&event, Event::Json(method, _) if matches!(method.as_str(), - "save" | "product-exit-checkpoint" | "slot-product-view-save" | "slot-product-export")) + "save" | "product-exit-checkpoint" | "slot-product-view-save" | "slot-product-export" | "production-deliver-bundle")) { continue; } @@ -3509,6 +3518,9 @@ impl Workspace { app.remember_original_preview(doc.id, &preview); } match event { + Event::Json(method, Ok(value)) if method == "production-deliver-bundle" => { + self.production_bundle_received(&value); + } Event::Json(method, result) if method == "product-exit-checkpoint" => { if let Some(exit) = &mut self.production_exit { exit.checkpoint = Some(result.map(|_| ())); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs index 6e08f7d3..9507dc45 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs @@ -585,6 +585,7 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val w.creation_width = w.creation["width"].as_u64().unwrap_or(1440) as u32; w.creation_count = w.creation["screenCount"].as_u64().unwrap_or(3).clamp(1, 12) as usize; w.creation_budget_minutes = super::product_production::budget_minutes(&w.creation); + w.creation_delivery_dir = super::product_production::delivery_dir(&w.creation); if method == "creation-save" && let Some(plan) = edited_plan { @@ -597,6 +598,7 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val w.creation_width = draft["width"].as_u64().unwrap_or(1440) as u32; w.creation_count = draft["screenCount"].as_u64().unwrap_or(3) as usize; w.creation_budget_minutes = super::product_production::budget_minutes(&draft); + w.creation_delivery_dir = super::product_production::delivery_dir(&draft); w.creation_plan = draft["screens"].clone(); w.creation_direction = draft["direction"].as_str().unwrap_or("").into(); w.creation_selected = draft["selected"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); @@ -618,10 +620,12 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val } w.creation_count = draft["screenCount"].as_u64().filter(|n| [3, 5, 6, 8, 12].contains(n)).unwrap_or(w.creation_count as u64) as usize; w.creation_budget_minutes = super::product_production::budget_minutes(&draft); + w.creation_delivery_dir = super::product_production::delivery_dir(&draft); w.creation_dirty = w.creation_brief != w.creation["brief"] || w.creation_plan != w.creation["plan"]["screens"] || w.creation_direction != w.creation["sellingPoints"]["direction"].as_str().unwrap_or("") || w.creation_count as u64 != w.creation["screenCount"].as_u64().unwrap_or(3) + || w.creation_delivery_dir != super::product_production::delivery_dir(&w.creation) || w.creation_budget_minutes != super::product_production::budget_minutes(&w.creation); w.restored_creation_signature = w.creation_dirty.then(|| w.creation_draft().to_string()); } @@ -735,7 +739,17 @@ impl Workspace { if self.creation_restore_draft.is_object() { return self.creation_restore_draft.clone(); } - json!({"revision":self.creation["revision"],"brief":self.creation_brief,"width":self.creation_width,"screens":self.creation_plan,"direction":self.creation_direction,"selected":self.creation_selected,"screenCount":self.creation_count,"productionBudgetMinutes":self.creation_budget_minutes}) + let mut draft = json!({"revision":self.creation["revision"],"brief":self.creation_brief,"width":self.creation_width, + "screens":self.creation_plan,"direction":self.creation_direction,"selected":self.creation_selected,"screenCount":self.creation_count}); + if self.creation_budget_minutes != super::product_production::DEFAULT_BUDGET_MINUTES + || self.creation["productionBudgetMinutes"].is_number() + { + draft["productionBudgetMinutes"] = json!(self.creation_budget_minutes); + } + if let Some(path) = &self.creation_delivery_dir { + draft["deliveryDir"] = json!(path); + } + draft } fn can_save_creation(&self) -> bool { self.busy.is_none() && (!self.unknown || self.scoped_production_pending()) @@ -766,6 +780,7 @@ impl Workspace { let brief_changed = self.creation_brief != self.creation["brief"] || self.creation["width"].as_u64() != Some(u64::from(self.creation_width)) || self.creation["screenCount"].as_u64() != Some(self.creation_count as u64) + || super::product_production::delivery_dir(&self.creation) != self.creation_delivery_dir || super::product_production::budget_minutes(&self.creation) != self.creation_budget_minutes; let plan_changed = self.creation_plan != self.creation["plan"]["screens"]; let method = if brief_changed { @@ -937,6 +952,9 @@ impl Workspace { if input["screenCount"].is_null() { input["screenCount"] = json!(self.creation_count); } + if method == "creation-save" && input.get("deliveryDir").is_none() { + input["deliveryDir"] = json!(self.creation_delivery_dir); + } if method == "creation-save" && input["productionBudgetMinutes"].is_null() { input["productionBudgetMinutes"] = json!(self.creation_budget_minutes); } @@ -1337,6 +1355,7 @@ impl Workspace { self.creation_dirty |= response.changed(); self.control_geometry("production-budget", response.rect); }); + self.delivery_directory_control(app, ui, editable); ui.add_space(6.0); ui.horizontal_wrapped(|ui| { let save = stitch_ui::action_button( @@ -1482,6 +1501,52 @@ impl Workspace { }) } + fn delivery_directory_control(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, editable: bool) { + ui.label("成品自动保存目录"); + let path = self.creation_delivery_dir.as_deref().unwrap_or("未选择"); + ui.add(egui::Label::new(path).wrap()).on_hover_text(path); + ui.horizontal_wrapped(|ui| { + let choose = stitch_ui::action_button(ui, "选择文件夹", stitch_ui::ButtonRole::Secondary, editable); + self.control_geometry("choose-delivery-directory", choose.rect); + if choose.clicked() { + let initial_dir = self.creation_delivery_dir.clone(); + let doc = self.creation_doc; + let identity = self.local_identity(""); + if let Err(error) = app.ask_file(crate::FileDialogRequest::Folder { initial_dir }, move |app, answer| { + let path = match answer { + crate::FileDialogAnswer::FolderTo(path) => path, + crate::FileDialogAnswer::Unavailable(error) => return Err(error), + _ => return Ok(Value::Null), + }; + let w = app.jiansun.as_mut().filter(|w| w.creation_doc == doc && w.local_identity("") == identity) + .ok_or("账号或项目已切换,未修改保存目录")?; + if !std::path::Path::new(&path).is_absolute() { + return Err("请选择绝对路径的成品目录".into()); + } + if app.session.active().and_then(|state| state.path.as_deref()) + .map(std::path::Path::new).and_then(std::path::Path::parent) + .is_some_and(|draft| std::path::Path::new(&path).starts_with(draft) && draft.ends_with( + w.open_projects.get(&doc.unwrap_or_default()).and_then(|id| id.rsplit('|').next()).unwrap_or_default())) + { + return Err("请选择项目草稿目录以外的位置".into()); + } + w.creation_delivery_dir = Some(path); + w.creation_dirty = true; + Ok(Value::Null) + }) { + self.error = error; + } + } + let clear = stitch_ui::action_button(ui, "清除", stitch_ui::ButtonRole::Secondary, + editable && self.creation_delivery_dir.is_some()); + self.control_geometry("clear-delivery-directory", clear.rect); + if clear.clicked() { + self.creation_delivery_dir = None; + self.creation_dirty = true; + } + }); + } + fn add_reference_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { let supported = ui.input(|input| { let files = &input.raw.hovered_files; @@ -1543,7 +1608,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,"productionBudgetMinutes":self.creation_budget_minutes})) { + if let Err(error) = self.slot_action(app, "slot-skeleton", json!({"brief":brief,"width":self.creation_width,"template":template,"outputId":"detail","generateProduct":generate,"productionBudgetMinutes":self.creation_budget_minutes,"deliveryDir":self.creation_delivery_dir})) { self.error = error; } } @@ -3437,18 +3502,23 @@ mod tests { let (mut w, mut app, requests) = brief_fixture(); w.creation["revision"] = json!(1); w.creation_dirty = true; + let delivery = std::env::temp_dir().join("成品"); + w.creation_delivery_dir = Some(delivery.to_string_lossy().into_owned()); w.creation_action(&mut app, "creation-save", json!({})).unwrap(); assert!(form_editable(w.busy.as_deref(), false)); let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("save request") }; assert_eq!(method, "creation-save"); + assert_eq!(input["deliveryDir"], json!(delivery)); + w.creation_delivery_dir = None; w.creation_brief["name"] = json!("保存过程中继续输入的产品名"); w.creation_brief["categoryName"] = json!("新选品类"); let draft = w.creation_draft(); let value = json!({"doc":w.creation_doc,"accountId":w.account["id"],"origin":w.origin, - "creation":{"revision":2,"brief":input["brief"],"width":input["width"],"screenCount":input["screenCount"],"plan":{"screens":input["screens"]}}}); + "creation":{"revision":2,"deliveryDir":input["deliveryDir"],"brief":input["brief"],"width":input["width"],"screenCount":input["screenCount"],"plan":{"screens":input["screens"]}}}); received(&mut w, &app, "creation-save", &value); assert_eq!(w.creation_brief, draft["brief"]); assert!(w.creation_dirty); + assert!(w.creation_delivery_dir.is_none(), "clearing the folder supersedes the in-flight save"); assert_eq!(w.creation["revision"], 2); assert!(!form_editable(Some("creation-import"), false)); assert!(!form_editable(None, true)); @@ -3580,10 +3650,13 @@ mod tests { let search = control_rect(&w, "source-search"); let hint = control_rect(&w, "entry-hint"); let budget = control_rect(&w, "production-budget"); + let delivery = control_rect(&w, "choose-delivery-directory"); let enter = control_rect(&w, "enter-canvas"); assert_eq!(w.creation_budget_minutes, 45); assert!(hint.bottom() <= budget.top() && budget.bottom() <= enter.top()); assert!(budget.right() <= width); + assert!(budget.bottom() <= delivery.top() && delivery.bottom() <= enter.top()); + assert!(delivery.right() <= width); if width >= 900.0 { assert!(source.right() < search.left() && source.top() < search.bottom() && search.top() < source.bottom(), "wide source and lookup share a row"); assert!(hint.bottom() <= enter.top(), "entry actions follow the save status"); 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 4280fa41..0703dc5d 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 @@ -6,14 +6,19 @@ use super::{json, Workspace, Value, BridgeFailure, PhotocraftApp, Instant, workf #[path = "pi_core_smoke.rs"] mod core_smoke; -fn identity(w: &Workspace, input: &Value) -> Result<(), String> { - if w.pi_run.as_deref().is_some_and(|s| input["run"].as_str() == Some(s)) - && w.accepts_production_epoch(&w.pi_request_scope["writeEpoch"]) - && w.pi_binding == json!({"accountId":w.account["id"],"origin":w.origin}) { - Ok(()) - } else { - Err("本地Agent会话或账户已改变".into()) +fn identity(w: &Workspace, input: &Value) -> Result<(), BridgeFailure> { + let run = input["run"].as_str(); + if w.pi_binding == json!({"accountId":w.account["id"],"origin":w.origin}) { + if run.is_some() && run == w.pi_run.as_deref() + && w.accepts_production_epoch(&w.pi_request_scope["writeEpoch"]) + { + return Ok(()); + } + if w.pi_request_scope["productProduction"] == true && run.is_some_and(|id| w.agent_native.cancelled(id)) { + return Err(BridgeFailure::new("cancelled", false, false, "当前制作会话已取消")); + } } + Err("本地Agent会话或账户已改变".into()) } fn status(w: &Workspace, app: &PhotocraftApp) -> Value { let same = app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc && s.revision == w.expected_revision); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs index 03c3d3d6..eeaf36bd 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs @@ -125,8 +125,9 @@ impl Workspace { self.messages.push(json!({"role":"user","text":text})); self.note("已接续制作,正在核对当前画布和原请求。"); self.agent_effects_paused = false; - let run = Run::new(doc, project, workspace, stages, Some(text.into()), Phase::AwaitingSave) + let mut run = Run::new(doc, project, workspace, stages, Some(text.into()), Phase::AwaitingSave) .with_budget(self.creation_budget_minutes); + run.delivery_dir = self.creation_delivery_dir.clone(); self.begin_prepared_production(run, &self.template_workflow["productionBlocks"].clone()); self.production_tick(app); true @@ -651,6 +652,7 @@ enum Phase { AwaitingSave, Agent, Export, + DeliveringBundle, WaitingOriginals { models: Vec, images: Vec, goal: Option }, } @@ -670,6 +672,12 @@ pub(super) struct Run { drafts: Vec, deadline: u64, budget_minutes: u64, + delivery_dir: Option, + delivery_id: Option, + published: Vec, + delivery_receipt: Value, + delivery_cancellation: Option>, + delivery_write_epoch: Option, restarted: bool, } @@ -712,7 +720,9 @@ impl Run { Self { doc, project, workspace, total: stages.len(), requested_outputs: stages.iter().cloned().collect(), stages, completed: 0, goal_user_entry, export_feedback: None, output_selected: true, phase, deferred: HashSet::new(), drafts: Vec::new(), deadline: production_time() + DEFAULT_BUDGET_MINUTES * 60, - budget_minutes: DEFAULT_BUDGET_MINUTES, restarted: false } + budget_minutes: DEFAULT_BUDGET_MINUTES, restarted: false, + delivery_dir: None, delivery_id: None, published: Vec::new(), delivery_receipt: Value::Null, + delivery_cancellation: None, delivery_write_epoch: None } } fn with_budget(mut self, minutes: u64) -> Self { @@ -722,6 +732,18 @@ impl Run { } } +impl Drop for Run { + fn drop(&mut self) { + if let Some(cancellation) = &self.delivery_cancellation { + cancellation.store(true, Ordering::Release); + } + } +} + +pub(super) fn delivery_dir(value: &Value) -> Option { + value["deliveryDir"].as_str().filter(|path| !path.is_empty()).map(str::to_owned) +} + fn production_time() -> u64 { SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs() } @@ -763,6 +785,9 @@ impl Run { } pub(super) fn progress_label(&self) -> Option { + if self.phase == Phase::DeliveringBundle { + return Some("正在保存成品到指定目录".into()); + } let label = self.stages.front()?.label(); Some(match self.phase { Phase::Canvas | Phase::CanvasRequested => format!("正在准备{label}画布"), @@ -772,6 +797,7 @@ impl Run { Phase::Agent if !self.output_selected => "正在规划本轮输出".into(), Phase::Agent => format!("正在制作{label}"), Phase::Export => format!("正在保存{label}"), + Phase::DeliveringBundle => unreachable!(), Phase::WaitingOriginals { .. } => format!("{label}等待原请求结果,确认后自动继续"), }) } @@ -839,6 +865,8 @@ impl Workspace { fn production_checkpoint_request(run: &Run, active: bool) -> Value { let project = run.project.rsplit('|').next().unwrap_or_default(); let checkpoint = json!({ + "deliveryDir":run.delivery_dir,"deliveryId":run.delivery_id,"published":run.published, + "productionDelivery":run.delivery_receipt, "active":active,"project":project,"workspaceId":run.workspace,"deadline":run.deadline, "productionBudgetMinutes":run.budget_minutes,"outputSelected":run.output_selected, "requestedOutputs":run.requested_outputs(), @@ -875,17 +903,21 @@ impl Workspace { let deadline = Instant::now() + Duration::from_secs(90); let daemon = self.prepare_daemon_exit.as_ref().map(|prepare| prepare()); let composers = self.save_exit_composers(ctx); - let run = self.product_production.take(); - self.with_product_target(app, |w, _| { - w.pi_ui_cancel("客户端正在退出"); - w.handover(); - }); + let delivering = self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle); + let run = if delivering { None } else { self.product_production.take() }; + if !delivering { + self.with_product_target(app, |w, _| { + w.pi_ui_cancel("客户端正在退出"); + w.handover(); + }); + } self.pending_slot_apply = None; self.pi_write_blocked = true; self.agent_effects_paused = true; self.product_checkpoint = Value::Null; let input = run.map(|run| Self::production_checkpoint_request(&run, true)).or_else(|| { + if delivering { return None; } let (doc, _) = draft?; let identity = self.open_projects.get(&doc)?; let project = identity.strip_prefix(&self.local_identity(""))?; @@ -913,6 +945,9 @@ impl Workspace { pub(super) fn advance_production_exit(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) { let Some(exit) = &self.production_exit else { return }; + if self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle) { + return; + } let remaining = exit.deadline.saturating_duration_since(Instant::now()); let result = if remaining.is_zero() { Some(Err("退出等待超时,保存结果未确认".to_owned())) @@ -971,7 +1006,9 @@ impl Workspace { } } } - if self.busy.as_deref() == Some("slot-product-export") || app.exporting() { return None; } + if self.busy.as_deref() == Some("slot-product-export") || app.exporting() + || self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle) + { return None; } self.production_exit.as_mut()?.poll_receipts() } @@ -1001,7 +1038,7 @@ impl Workspace { fn restore_production_checkpoint(&mut self, app: &PhotocraftApp) { if self.product_checkpoint["active"] != true || self.busy.is_some() || self.saving.is_some() - || !self.model_ready || !self.image_ready + || self.product_checkpoint["deliveryId"].is_null() && (!self.model_ready || !self.image_ready) { return; } let Some(canvas) = app.session.active() else { return; }; let doc = canvas.doc.id.0; @@ -1011,8 +1048,8 @@ impl Workspace { || workspace.is_null() || workspace != self.product_checkpoint["workspaceId"] || self.persisted_revisions.get(&doc) != Some(&canvas.revision) { return; } - let Some(stages) = self.template_workflow["productionStages"].as_array() else { return; }; - let remaining: HashSet<_> = stages.iter().filter_map(Stage::read).collect(); + let remaining: HashSet<_> = self.template_workflow["productionStages"].as_array() + .into_iter().flatten().filter_map(Stage::read).collect(); let checkpoint = std::mem::take(&mut self.product_checkpoint); let stages: VecDeque<_> = checkpoint["stages"].as_array().into_iter().flatten() .filter_map(Stage::read).filter(|stage| remaining.contains(stage)).collect(); @@ -1025,6 +1062,9 @@ impl Workspace { }; let mut run = Run::new(doc, project, workspace, stages, None, phase).with_budget(budget_minutes(&checkpoint)); run.deadline = checkpoint["deadline"].as_u64().unwrap_or(run.deadline); + run.delivery_dir = delivery_dir(&checkpoint); + run.delivery_id = checkpoint["deliveryId"].as_str().map(str::to_owned); + run.published = checkpoint["published"].as_array().cloned().unwrap_or_default(); run.output_selected = output_selected; if let Some(requested) = checkpoint["requestedOutputs"].as_array() { run.requested_outputs = requested.iter().filter_map(Stage::read).collect(); @@ -1034,7 +1074,7 @@ impl Workspace { run.completed = run.total.saturating_sub(run.stages.len() + run.drafts.len()); run.deferred.extend(checkpoint["deferred"].as_array().into_iter().flatten().filter_map(Stage::read)); if run.stages.is_empty() { - self.note_production_summary(run); + self.finish_production_outputs(run); } else { self.product_production = Some(run); self.note("已从上次的制作进度接续"); @@ -1076,8 +1116,9 @@ impl Workspace { .and_then(|message| message["text"].as_str()) .filter(|text| matches!(*text, "制作详情、主图和 SKU" | "继续整套制作")).map(str::to_owned); let minutes = budget_minutes(&meta["creation"]); - let run = Run::new(doc, project, meta["workflow"]["workspaceId"].clone(), stages, goal_user_entry, Phase::AwaitingSave) + let mut run = Run::new(doc, project, meta["workflow"]["workspaceId"].clone(), stages, goal_user_entry, Phase::AwaitingSave) .with_budget(minutes); + run.delivery_dir = delivery_dir(&meta["creation"]); self.begin_prepared_production(run, &meta["workflow"]["productionBlocks"]); self.production_tick(app); } @@ -1339,6 +1380,7 @@ impl Workspace { self.product_export = None; return; } + if run.phase == Phase::DeliveringBundle { return; } if production_time() >= run.deadline { let Some(mut run) = self.product_production.take() else { return; }; // Stop the local Pi turn and keep the original identities of outstanding jobs. @@ -1487,6 +1529,10 @@ impl Workspace { if let Some(error) = value["goalSyncError"].as_str() { self.note(error.to_owned()); } + if value["generationId"].is_string() && let Some(run) = self.product_production.as_mut() { + run.published.push(json!({"outputId":value["outputId"],"variantId":value["variantId"], + "generationId":value["generationId"]})); + } self.advance_production_stage(app, true); } @@ -1497,7 +1543,7 @@ impl Workspace { } run.completed += usize::from(exported); if run.stages.is_empty() { - self.note_production_summary(run); + self.finish_production_outputs(run); } else { run.phase = Phase::Canvas; run.restarted = false; @@ -1507,14 +1553,83 @@ impl Workspace { } } + fn finish_production_outputs(&mut self, mut run: Run) { + if run.delivery_dir.is_none() || run.completed == 0 { + self.note_production_summary(run); + return; + } + if !self.authority_active() { + run.delivery_receipt = json!({"state":"failed","error":"授权已失效,成品仍保存在本机项目中"}); + self.note_production_summary(run); + return; + } + if run.published.len() != run.completed { + run.delivery_receipt = json!({"state":"failed","error":"本轮部分成品缺少已验证的版本记录"}); + self.note_production_summary(run); + return; + } + let id = run.delivery_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone(); + let cancellation = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + run.delivery_cancellation = Some(cancellation.clone()); + run.delivery_write_epoch = Some(self.write_epoch); + run.phase = Phase::DeliveringBundle; + let input = json!({"doc":run.doc,"project":run.project.rsplit('|').next(), + "workspaceId":run.workspace,"accountId":self.account["id"],"origin":self.origin, + "accountEpoch":self.accepted_account_epoch, + "writeEpoch":self.write_epoch,"deliveryDir":run.delivery_dir,"deliveryId":id, + "published":run.published,"total":run.total,"execution":{"runId":id,"operationId":id,"uiHeartbeat":production_time() * 1000}}); + self.write_production_checkpoint(&run, true); + if self.tx.send(Request::DeliverProductionBundle(input, cancellation)).is_err() { + run.delivery_receipt = json!({"state":"failed","error":"本机交付服务已断开"}); + self.note_production_summary(run); + } else { + self.product_production = Some(run); + } + } + + pub(super) fn production_bundle_received(&mut self, value: &Value) { + if !self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle + && value["doc"].as_u64() == Some(run.doc) && value["deliveryId"].as_str() == run.delivery_id.as_deref() + && value["writeEpoch"].as_u64() == run.delivery_write_epoch + && run.delivery_write_epoch == Some(self.write_epoch) + && value["accountEpoch"].as_u64() == Some(self.accepted_account_epoch)) + { + return; + } + let mut run = self.product_production.take().expect("matching delivery run"); + if let Some(exit) = &mut self.production_exit { + exit.deadline = Instant::now() + Duration::from_secs(90); + } + if !self.authority_active() { return; } + run.delivery_receipt = value["productionDelivery"].clone(); + self.note_production_summary(run); + } + fn note_production_summary(&mut self, run: Run) { - self.write_production_checkpoint(&run, false); - let text = if run.drafts.is_empty() { + if let Some(exit) = &mut self.production_exit { + exit.checkpoint = self.tx.send(Request::Action("product-exit-checkpoint".into(), Self::production_checkpoint_request(&run, false))) + .err().map(|_| Err("本机制作记录保存服务已断开".into())); + } else { + self.write_production_checkpoint(&run, false); + } + let mut text = if run.drafts.is_empty() { format!("整套制作完成 · {} 份可编辑画布与 JPG 已保存", run.total) } else { format!("本轮已交付 {}/{} 份,还有 {} 份待完成。已有编辑已保存。", run.completed, run.total, run.drafts.len()) }; + let receipt = &run.delivery_receipt; + if let Some(path) = receipt["path"].as_str() { + let counts = ["工程文件", "PSD", "详情页长图", "详情页切片", "主图", "SKU"] + .map(|category| format!("{category} {} 份", receipt["counts"][category].as_u64().unwrap_or(0))); + text.push_str(&format!("\n成品已保存到 {path}\n{}", counts.join("、"))); + if let Some(warning) = receipt["durabilityWarning"].as_str() { + text.push_str(&format!("\n目录已落位,写入确认失败。{warning}")); + } + } else if let Some(error) = receipt["error"].as_str() { + text.push_str(&format!("\n自动保存成品失败。{error}。可通过「保存工程」手动保存。")); + } self.messages.push(json!({"role":"assistant","kind":"reply","text":text, + "productionDelivery":receipt, "productionSummary":{"exported":run.completed,"total":run.total,"drafts":run.drafts,"productionBudgetMinutes":run.budget_minutes}})); self.draft_changed = true; } @@ -1551,6 +1666,101 @@ mod tests { use super::*; use std::sync::mpsc; + use crate::{AppTray, TrayAction}; + #[derive(Default)] + struct Tray { + visible: bool, + menu: Arc>>, + } + impl AppTray for Tray { + fn visible(&self) -> bool { self.visible } + fn show(&mut self, _: &str) -> Result<(), String> { + self.visible = true; + Ok(()) + } + fn take_action(&mut self) -> Option { + let action = self.menu.lock().unwrap().take()?; + self.visible = false; + Some(action) + } + fn set_status(&mut self, _: &str) {} + } + + fn close_commands(app: &mut PhotocraftApp, ctx: &egui::Context) -> Vec { + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close); + ctx.run_logic(&input, |ctx| crate::discard_ui::guard_window_close(app, ctx)) + .viewport_commands.remove(&egui::ViewportId::ROOT).unwrap_or_default() + } + + #[test] + fn last_output_dispatches_the_bundle_and_exit_waits_for_its_scoped_receipt() { + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":40,"height":50})).unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + let doc = app.session.active().unwrap().doc.id.0; + let (tx, requests) = mpsc::channel(); + let (events, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + requests.try_recv().unwrap(); + let project = w.local_identity("project"); + w.open_projects.insert(doc, project.clone()); + w.template_workflow = json!({"workspaceId":"workspace"}); + let mut run = Run::new(doc, project, json!("workspace"), + ["detail", "main_images", "sku_images"].into_iter() + .map(|output| Stage { output:output.into(), variant:"wood".into() }).collect(), + None, Phase::Export); + run.delivery_dir = Some(std::env::temp_dir().join("成品").to_string_lossy().into_owned()); + w.product_production = Some(run); + for output in ["detail", "main_images", "sku_images"] { + w.busy = (output != "sku_images").then(|| "save".to_owned()); + w.product_production.as_mut().unwrap().phase = Phase::Export; + w.production_export_received(&app, &json!({"doc":doc,"workspaceId":"workspace", + "outputId":output,"variantId":"wood","generationId":format!("generation-{output}"),"files":[{"path":"local.jpg"}]})); + } + let (request, cancellation) = requests.try_iter().find_map(|item| match item { + Request::DeliverProductionBundle(input, cancellation) => Some((input, cancellation)), + _ => None, + }).expect("last export should dispatch delivery once"); + assert_eq!(request["published"].as_array().unwrap().len(), 3); + assert_eq!(request["total"], 3); + assert_eq!(request["deliveryDir"], w.product_production.as_ref().unwrap().delivery_dir.as_deref().unwrap()); + assert_eq!(w.product_production.as_ref().unwrap().progress_label().as_deref(), Some("正在保存成品到指定目录")); + let mut receipt = json!({"doc":doc,"deliveryId":request["deliveryId"],"writeEpoch":request["writeEpoch"], + "accountEpoch":1,"productionDelivery":{"state":"bundle_saved","path":request["deliveryDir"], + "counts":{"工程文件":4,"PSD":3,"详情页长图":1,"详情页切片":2,"主图":2,"SKU":1}}}); + w.production_bundle_received(&receipt); + assert!(w.product_production.is_some(), "old account receipt must be ignored"); + receipt["accountEpoch"] = request["accountEpoch"].clone(); + app.jiansun = Some(w); + assert_eq!(super::super::background_status(&app).as_deref(), Some("正在保存成品到指定目录")); + app.services.app_tray = Some(Box::new(Tray::default())); + let ctx = egui::Context::default(); + let parked = close_commands(&mut app, &ctx); + assert!(parked.contains(&egui::ViewportCommand::Visible(false))); + assert!(parked.contains(&egui::ViewportCommand::CancelClose)); + app.explicit_exit = true; + let _ = ctx.run_logic(&Default::default(), |ctx| assert!(super::super::guard_production_exit(&mut app, ctx))); + assert!(!cancellation.load(Ordering::Acquire)); + let step = |app: &mut PhotocraftApp| { + ctx.run_logic(&Default::default(), |ctx| super::super::advance(app, ctx)) + .viewport_commands.remove(&egui::ViewportId::ROOT).unwrap_or_default() + }; + assert!(!step(&mut app).contains(&egui::ViewportCommand::Close)); + events.send(super::super::Event::Json("production-deliver-bundle".into(), Ok(receipt))).unwrap(); + assert!(!step(&mut app).contains(&egui::ViewportCommand::Close)); + let Request::Action(method, checkpoint) = requests.try_recv().unwrap() else { panic!("final delivery checkpoint") }; + assert_eq!(method, "product-exit-checkpoint"); + assert_eq!(checkpoint["checkpoint"]["active"], false); + assert_eq!(checkpoint["checkpoint"]["productionDelivery"]["state"], "bundle_saved"); + events.send(super::super::Event::Json(method, Ok(Value::Null))).unwrap(); + assert!(step(&mut app).contains(&egui::ViewportCommand::Close)); + let workspace = app.jiansun.as_ref().unwrap(); + assert!(workspace.product_production.is_none()); + assert_eq!(workspace.messages.last().unwrap()["productionDelivery"]["state"], "bundle_saved"); + assert!(workspace.messages.last().unwrap()["text"].as_str().unwrap().contains("详情页切片 2 份")); + } + #[test] fn exit_pauses_the_checkpoint_and_waits_for_draft_and_daemon_receipts() { for timeout in [false, true] { @@ -1603,25 +1813,6 @@ mod tests { #[test] fn window_close_parks_active_work_and_drains_the_completion_without_painting() { - use crate::{AppTray, TrayAction}; - #[derive(Default)] - struct Tray { - visible: bool, - menu: Arc>>, - } - impl AppTray for Tray { - fn visible(&self) -> bool { self.visible } - fn show(&mut self, _: &str) -> Result<(), String> { - self.visible = true; - Ok(()) - } - fn take_action(&mut self) -> Option { - let action = self.menu.lock().unwrap().take()?; - self.visible = false; - Some(action) - } - fn set_status(&mut self, _: &str) {} - } let (tx, requests) = mpsc::channel(); let (events, rx) = mpsc::channel(); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -1633,13 +1824,7 @@ mod tests { app.jiansun.as_mut().unwrap().busy = Some("image".into()); let ctx = egui::Context::default(); - let close = |app: &mut PhotocraftApp| { - let mut input = egui::RawInput::default(); - input.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close); - ctx.run_logic(&input, |ctx| crate::discard_ui::guard_window_close(app, ctx)) - .viewport_commands.remove(&egui::ViewportId::ROOT).unwrap_or_default() - }; - let parked = close(&mut app); + let parked = close_commands(&mut app, &ctx); assert!(parked.contains(&egui::ViewportCommand::CancelClose)); assert!(parked.contains(&egui::ViewportCommand::Visible(false))); assert!(!super::super::flushing_exit(&app)); @@ -1649,7 +1834,7 @@ mod tests { *menu.lock().unwrap() = Some(TrayAction::Restore); let restored = ctx.run_logic(&Default::default(), |ctx| crate::discard_ui::poll_tray(&mut app, ctx)); assert!(restored.viewport_commands[&egui::ViewportId::ROOT].contains(&egui::ViewportCommand::Visible(true))); - assert!(!close(&mut app).contains(&egui::ViewportCommand::CancelClose)); + assert!(!close_commands(&mut app, &ctx).contains(&egui::ViewportCommand::CancelClose)); } #[test]