perf(xiaoyi): unblock canvas reads and match copy fields
This commit is contained in:
parent
f88776dd7c
commit
dce921b363
@ -3,7 +3,8 @@ import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { SessionManager, VERSION } from '@earendil-works/pi-coding-agent';
|
||||
import { ProjectStore, atomic } from '../src/store.mjs';
|
||||
import { Native98kBroker, NativeCanvas } from '../src/native-bridge.mjs';
|
||||
import { Native98kBroker } from '../src/native-bridge.mjs';
|
||||
import { NativeControlClient } from '../src/native-control-client.mjs';
|
||||
import { DetailPiAgent } from '../src/agent.mjs';
|
||||
|
||||
const configFile = process.argv[2];
|
||||
@ -17,7 +18,7 @@ const broker = new Native98kBroker(config.broker), info = await broker.info();
|
||||
const binding = phase === 'shop' ? config.otherBinding : ['canvas', 'canvas-finish', 'handover'].includes(phase) && config.canvasBinding ? config.canvasBinding : config.binding;
|
||||
const store = await ProjectStore.open(config.output, { scope: info.accountScope, project: config.broker.project }, binding);
|
||||
let canvas;
|
||||
if (['canvas', 'canvas-finish', 'handover'].includes(phase)) canvas = await NativeCanvas.connect(config.canvas);
|
||||
if (['canvas', 'canvas-finish', 'handover'].includes(phase)) canvas = await NativeControlClient.connect(config.canvas);
|
||||
let host;
|
||||
const events = [];
|
||||
try {
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { NativeCanvas } from '../src/native-bridge.mjs';
|
||||
import { NativeControlClient } from '../src/native-control-client.mjs';
|
||||
import { atomic } from '../src/store.mjs';
|
||||
const config = JSON.parse(await fs.readFile(process.argv[2], 'utf8'));
|
||||
const canvas = await NativeCanvas.connect(config.canvas);
|
||||
const canvas = await NativeControlClient.connect(config.canvas);
|
||||
const command = (command, params = {}) => canvas.call('engine.execute', { command, params });
|
||||
try {
|
||||
let state = await canvas.begin('本地画布机制验收:逐步编辑、接手和共享撤销(不计入模型验收)');
|
||||
|
||||
@ -3,7 +3,7 @@ import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { SessionManager } from '@earendil-works/pi-coding-agent';
|
||||
import lockfile from 'proper-lockfile';
|
||||
import { NativeCanvas } from '../src/native-bridge.mjs';
|
||||
import { NativeControlClient } from '../src/native-control-client.mjs';
|
||||
import { atomic } from '../src/store.mjs';
|
||||
import { promptChars } from '../src/context-budget.mjs';
|
||||
|
||||
@ -11,7 +11,7 @@ const [outputPath, phase] = process.argv.slice(2);
|
||||
if (!outputPath || !['correction','outline','canvas','long-prepare','long-recall','restart-recall','handover','tool-live'].includes(phase)) throw Error('指定本轮独立验收目录与阶段');
|
||||
const output = path.resolve(outputPath);
|
||||
const native = JSON.parse(await fs.readFile(path.join(output, 'native-process.json'), 'utf8'));
|
||||
const canvas = await NativeCanvas.connect({ port: native.port, tokenFile: path.join(output, 'control.token') });
|
||||
const canvas = await NativeControlClient.connect({ port: native.port, tokenFile: path.join(output, 'control.token') });
|
||||
const flatten = layers => layers.flatMap(layer => { const { children, selected, ...row } = layer; return [row, ...flatten(children || [])]; });
|
||||
const cmd = (command, params = {}) => canvas.call('engine.execute', { command, params });
|
||||
const cases = {
|
||||
|
||||
@ -2,7 +2,7 @@ import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import assert from 'node:assert/strict';
|
||||
import { NativeCanvas } from '../src/native-bridge.mjs';
|
||||
import { NativeControlClient } from '../src/native-control-client.mjs';
|
||||
import { atomic } from '../src/store.mjs';
|
||||
|
||||
const output = path.resolve(process.argv[2]);
|
||||
@ -16,7 +16,7 @@ const scopes = await fs.readdir(accounts); assert.equal(scopes.length,1);
|
||||
const ids = await fs.readdir(path.join(accounts,scopes[0],'projects')); assert.equal(ids.length,1);
|
||||
const requests = path.join(accounts, scopes[0], 'pi-validation', ids[0], 'requests');
|
||||
const initialIds = new Set(await fs.readdir(requests));
|
||||
const canvas = await NativeCanvas.connect({ port:native.port, tokenFile:path.join(output,'control.token') });
|
||||
const canvas = await NativeControlClient.connect({ port:native.port, tokenFile:path.join(output,'control.token') });
|
||||
const records = async () => Promise.all((await fs.readdir(requests)).filter(n=>!initialIds.has(n)&&n.endsWith('.json')).map(async name=>({name,...JSON.parse(await fs.readFile(path.join(requests,name),'utf8'))})));
|
||||
try {
|
||||
const state = await canvas.call('jiansun.state');
|
||||
|
||||
@ -1,13 +1,14 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { Native98kBroker, NativeCanvas } from '../src/native-bridge.mjs';
|
||||
import { Native98kBroker } from '../src/native-bridge.mjs';
|
||||
import { NativeControlClient } from '../src/native-control-client.mjs';
|
||||
import { ProjectStore, atomic } from '../src/store.mjs';
|
||||
import { DetailPiAgent } from '../src/agent.mjs';
|
||||
const config = JSON.parse(await fs.readFile(process.argv[2], 'utf8')), id = process.argv[3];
|
||||
if (!id) throw Error('请提供原幂等键;仅查询原请求,不会发起推理');
|
||||
const broker = new Native98kBroker(config.broker), info = await broker.info();
|
||||
const store = await ProjectStore.open(config.output, { scope: info.accountScope, project: config.broker.project }, config.canvasBinding || config.binding);
|
||||
const canvas = await NativeCanvas.connect(config.canvas);
|
||||
const canvas = await NativeControlClient.connect(config.canvas);
|
||||
const host = await DetailPiAgent.open({ store, broker, canvas, protocolMode: config.protocolMode });
|
||||
try {
|
||||
const result = await host.recover(id, { executeReadOnly: true });
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { NativeCanvas } from '../src/native-bridge.mjs';
|
||||
import { NativeControlClient } from '../src/native-control-client.mjs';
|
||||
import { atomic } from '../src/store.mjs';
|
||||
const config = JSON.parse(await fs.readFile(process.argv[2], 'utf8'));
|
||||
const canvas = await NativeCanvas.connect(config.canvas);
|
||||
const canvas = await NativeControlClient.connect(config.canvas);
|
||||
const cmd = (command, params = {}) => canvas.call('engine.execute', { command, params });
|
||||
const flatten = layers => layers.flatMap(layer => { const { children, selected, ...row } = layer; return [row, ...flatten(children || [])]; });
|
||||
try {
|
||||
|
||||
@ -15,6 +15,7 @@ export function links(document) {
|
||||
export class EnterpriseContext {
|
||||
constructor(store, client = new EnterpriseKnowledge({store})) { this.store=store; this.client=client; }
|
||||
async load({task,brandName,categoryName,templateId,releaseId,resourceSetId,skillSources,turn,outputId}, {signal, read = execute => execute(), deferVisual = false, pins} = {}) {
|
||||
signal?.throwIfAborted();
|
||||
if (!tasks[task] && task!=='production') return null;
|
||||
const key=JSON.stringify([task,brandName,categoryName,templateId,releaseId,resourceSetId,skillSources,turn,outputId,deferVisual]);
|
||||
if (this.key===key) return this.value;
|
||||
@ -31,8 +32,8 @@ export class EnterpriseContext {
|
||||
return this.commit(key,{...published,skillDirectory:directory});
|
||||
}
|
||||
const query=`通用详情页 ${tasks[task]}`.slice(0,500);
|
||||
const taskResult=(await this.client.call('query_knowledge',{query,...(directory?{directory}:{}),limit:3,maxCharacters:8000})).result;
|
||||
const brandResult=(await this.client.call('query_knowledge',{query:`${brandName} 品牌规范 ${tasks[task]}`.slice(0,500),...(directory?{directory}:{}),limit:2,maxCharacters:6000})).result;
|
||||
const taskResult=(await this.client.call('query_knowledge',{query,...(directory?{directory}:{}),limit:3,maxCharacters:8000},{signal})).result;
|
||||
const brandResult=(await this.client.call('query_knowledge',{query:`${brandName} 品牌规范 ${tasks[task]}`.slice(0,500),...(directory?{directory}:{}),limit:2,maxCharacters:6000},{signal})).result;
|
||||
const applicable=item=>{
|
||||
const name=path.posix.basename(item.path || '');
|
||||
return !item.path?.includes('/template-adapter/references/') || /^\d/.test(name) || name.includes(templateId);
|
||||
@ -43,10 +44,10 @@ export class EnterpriseContext {
|
||||
const skills=[];
|
||||
// Search only the selected skill roots, rather than downloading the library.
|
||||
for (const root of roots) {
|
||||
const found=(await this.client.call('search_files',{query:'SKILL.md',directory:root,limit:20})).result;
|
||||
const found=(await this.client.call('search_files',{query:'SKILL.md',directory:root,limit:20},{signal})).result;
|
||||
const entry=found.page?.entries?.find(item=>item.path===root+'/SKILL.md');
|
||||
if (!entry) throw Error('企业知识库缺少本任务所选Skill入口');
|
||||
skills.push(await this.document(entry.id,entry.revision,entry.path,'skill'));
|
||||
skills.push(await this.document(entry.id,entry.revision,entry.path,'skill',signal));
|
||||
for (const match of skills.at(-1).text.matchAll(/\]\((\.\.\/[^/]+)\/references\//g)) {
|
||||
const dependency=path.posix.normalize(root+'/'+match[1]);
|
||||
if (roots.length<2 && !roots.includes(dependency)) roots.push(dependency);
|
||||
@ -54,20 +55,20 @@ export class EnterpriseContext {
|
||||
}
|
||||
if (!skills.length) throw Error('企业知识库未匹配到本任务Skill,未将普通搜索结果冒充Skill');
|
||||
const rules=[];
|
||||
const brands=(await this.client.call('search_files',{query:brandName,...(directory?{directory}:{}),limit:100})).result;
|
||||
const brands=(await this.client.call('search_files',{query:brandName,...(directory?{directory}:{}),limit:100},{signal})).result;
|
||||
const brand=brands.page?.entries?.find(item=>/\.(md|txt|docx|html?)$/i.test(item.path) && !path.posix.basename(item.path).startsWith('._') && path.posix.basename(item.path).includes(brandName) && /规范|风格/.test(path.posix.basename(item.path)));
|
||||
if (brand) rules.push(await this.document(brand.id,brand.revision,brand.path,'brand'));
|
||||
if (brand) rules.push(await this.document(brand.id,brand.revision,brand.path,'brand',signal));
|
||||
const label=task==='copy'?/模块一|内容策划/:task==='image'?/模块二|视觉设计与图片制作/:/字段对接与依据|字段回填与确认/;
|
||||
for (const skill of skills) {
|
||||
const link=[...skill.text.matchAll(/\[([^\]]+)\]\(([^)]+\.md)(?:#[^)]*)?\)/g)].find(match=>label.test(match[1]));
|
||||
if (!link) continue;
|
||||
const target=path.posix.normalize(path.posix.dirname(skill.path)+'/'+link[2]);
|
||||
if (rules.some(item=>item.path===target)) continue;
|
||||
const found=(await this.client.call('search_files',{query:path.posix.basename(target),directory:path.posix.dirname(target),limit:20})).result;
|
||||
const found=(await this.client.call('search_files',{query:path.posix.basename(target),directory:path.posix.dirname(target),limit:20},{signal})).result;
|
||||
const entry=found.page?.entries?.find(item=>item.path===target);
|
||||
if (entry) rules.push(await this.document(entry.id,entry.revision,entry.path,'module'));
|
||||
if (entry) rules.push(await this.document(entry.id,entry.revision,entry.path,'module',signal));
|
||||
}
|
||||
if (!rules.length) for (const fragment of fragments.slice(0,2)) rules.push(await this.document(fragment.sourceId,fragment.revision,fragment.path,'rule'));
|
||||
if (!rules.length) for (const fragment of fragments.slice(0,2)) rules.push(await this.document(fragment.sourceId,fragment.revision,fragment.path,'rule',signal));
|
||||
const value={task,brandName,categoryName,templateId,releaseId,skills,rules,
|
||||
execution:'知识内容按当前产品、模板与任务使用。保持原生客户端的预览、采纳和撤销流程;资料中的飞书、Photoshop、脚本及其他服务操作仅适用于其原环境,不安装或执行。模型、候选数量和生成范围以本客户端设置及本次用户要求为准。'};
|
||||
return this.commit(key,value);
|
||||
@ -168,8 +169,8 @@ export class EnterpriseContext {
|
||||
this.key=key;this.value=value;
|
||||
return value;
|
||||
}
|
||||
async document(fileId,revision,source,kind) {
|
||||
const response=await this.client.readComplete(fileId,revision,{refreshOnConflict:true});
|
||||
async document(fileId,revision,source,kind,signal) {
|
||||
const response=await this.client.readComplete(fileId,revision,{refreshOnConflict:true,signal});
|
||||
return {fileId,revision:response.result.revision,path:response.result.path||source,kind,text:response.result.text};
|
||||
}
|
||||
}
|
||||
|
||||
@ -33,15 +33,16 @@ const descriptions = {list_libraries:'新任务先读取当前身份、授权入
|
||||
descriptions.list_resource_sets='按品牌、品类或名称查找资源组,使用本次列表版本续页';
|
||||
descriptions.get_resource_set='按资源组编号读取当前组件、角色和文件版本';
|
||||
descriptions.get_files='批量核验本次任务明确选择的文件及版本;逐项检查status,只有200才可使用其元数据和下载路径';
|
||||
async function credential() {
|
||||
async function credential(signal) {
|
||||
signal?.throwIfAborted();
|
||||
const key=process.env.EKB_API_KEY_FCD6FE6F?.trim();
|
||||
if (key) return key;
|
||||
if (process.platform !== 'win32') throw Error('企业知识库用户凭据未配置');
|
||||
try {
|
||||
const {stdout}=await execFileAsync(path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'reg.exe'),['query','HKCU\\Environment','/v','EKB_API_KEY_FCD6FE6F'],{windowsHide:true,maxBuffer:16384});
|
||||
const {stdout}=await execFileAsync(path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'reg.exe'),['query','HKCU\\Environment','/v','EKB_API_KEY_FCD6FE6F'],{windowsHide:true,maxBuffer:16384,signal});
|
||||
const match=stdout.match(/^\s*EKB_API_KEY_FCD6FE6F\s+REG_(?:SZ|EXPAND_SZ)\s+(.+)$/mi);
|
||||
if (match?.[1]?.trim()) return match[1].trim();
|
||||
} catch { /* Do not reveal subprocess diagnostics. */ }
|
||||
} catch { signal?.throwIfAborted(); }
|
||||
throw Error('企业知识库用户凭据未配置');
|
||||
}
|
||||
function boundedJSON(raw, contentType) {
|
||||
@ -87,6 +88,7 @@ function fileMetadata(value,fileId,origin) {
|
||||
return {...Object.fromEntries(['id','sourceId','fileId','releaseId','assetId','kind','path','name','size','sha256','revision','updatedAt','downloadPath'].filter(k=>value[k]!==undefined).map(k=>[k,value[k]])),...(virtualInfo?{contentPath:virtualPath,readTool:'read_text'}:{}),...(match===undefined?{}:{downloadHeaders:{'If-Match':match}})};
|
||||
}
|
||||
async function request(origin,path,{body,key,session,protocol='2025-11-25',fetchImpl=fetch,timeoutMs=15000,maxBytes=2_000_000,signal}={}) {
|
||||
signal?.throwIfAborted();
|
||||
if (!path.startsWith('/') || path.startsWith('//')) throw Error('企业知识库路径无效');
|
||||
let response;
|
||||
try { response=await fetchImpl(origin+path,{method:body===undefined?'GET':'POST',redirect:'manual',signal:signal?AbortSignal.any([signal,AbortSignal.timeout(timeoutMs)]):AbortSignal.timeout(timeoutMs),headers:{Accept:'application/json, text/event-stream',...(body===undefined?{}:{'Content-Type':'application/json'}),...(key?{Authorization:`Bearer ${key}`} : {}),...(session?{'Mcp-Session-Id':session}:{}),'MCP-Protocol-Version':protocol},...(body===undefined?{}:{body:JSON.stringify(body)})}); }
|
||||
@ -99,13 +101,14 @@ async function request(origin,path,{body,key,session,protocol='2025-11-25',fetch
|
||||
}
|
||||
export class EnterpriseKnowledge {
|
||||
constructor({fetchImpl=fetch,credentialProvider=credential,endpoints=origins,store}={}) { Object.assign(this,{fetchImpl,credentialProvider,endpoints,store}); }
|
||||
async connect(token) {
|
||||
async connect(token, {signal} = {}) {
|
||||
signal?.throwIfAborted();
|
||||
if(this.connection?.token===token)return this.connection;
|
||||
this.connection=null;
|
||||
let origin;
|
||||
for (const candidate of this.endpoints) {
|
||||
try { const health=await request(candidate,'/healthz',{fetchImpl:this.fetchImpl}); if (health.value?.status!=='ok'||health.value?.service!=='enterprise-knowledge-base') throw Error('企业知识库身份校验失败'); origin=candidate;break; }
|
||||
catch(error) { if (!error.network || candidate===this.endpoints.at(-1)) throw error; }
|
||||
try { const health=await request(candidate,'/healthz',{fetchImpl:this.fetchImpl,signal}); if (health.value?.status!=='ok'||health.value?.service!=='enterprise-knowledge-base') throw Error('企业知识库身份校验失败'); origin=candidate;break; }
|
||||
catch(error) { signal?.throwIfAborted(); if (!error.network || candidate===this.endpoints.at(-1)) throw error; }
|
||||
}
|
||||
let seq=0, session, protocol='2025-11-25';
|
||||
const rpc=async(method,params,notification=false,options={})=>{
|
||||
@ -116,36 +119,37 @@ export class EnterpriseKnowledge {
|
||||
if(!value || value.jsonrpc!=='2.0'||value.id!==id||value.error||!value.result) throw Error('企业知识库协议错误');
|
||||
return value.result;
|
||||
};
|
||||
const init=await rpc('initialize',{protocolVersion:protocol,capabilities:{},clientInfo:{name:'photocraft-enterprise-readonly',version:'1.1'}});
|
||||
const init=await rpc('initialize',{protocolVersion:protocol,capabilities:{},clientInfo:{name:'photocraft-enterprise-readonly',version:'1.1'}},false,{signal});
|
||||
if(!['2025-03-26','2025-06-18','2025-11-25'].includes(init.protocolVersion))throw Error('企业知识库协议版本不支持');
|
||||
protocol=init.protocolVersion;
|
||||
await rpc('notifications/initialized',undefined,true);
|
||||
await rpc('notifications/initialized',undefined,true,{signal});
|
||||
const connection={token,origin,rpc,protocol,tools:new Map()};
|
||||
await this.discover(connection);
|
||||
await this.discover(connection,{signal});
|
||||
this.connection=connection;
|
||||
return connection;
|
||||
}
|
||||
async discover(connection) {
|
||||
const result=await connection.rpc('tools/list');
|
||||
async discover(connection, options) {
|
||||
const result=await connection.rpc('tools/list',undefined,false,options);
|
||||
if(!Array.isArray(result.tools))throw Error('企业知识库工具发现无效');
|
||||
connection.tools=new Map(result.tools.filter(t=>typeof t.name==='string'&&t.inputSchema?.type==='object').map(t=>[t.name,t]));
|
||||
}
|
||||
async page(name, args = {}) {
|
||||
async page(name, args = {}, options = {}) {
|
||||
options.signal?.throwIfAborted();
|
||||
if (!['search_files','list_directory'].includes(name)) throw Error('该操作不是目录或搜索分页');
|
||||
if (!Value.Check(schemas[name],args)) throw Error('企业知识库查询参数无效');
|
||||
const token=await this.credentialProvider();
|
||||
const connection=await this.connect(token);
|
||||
const token=await this.credentialProvider(options.signal);
|
||||
const connection=await this.connect(token,options);
|
||||
connection.pages ??= new Map();
|
||||
const {revision:_revision,offset=0,...query}=args;
|
||||
const key=JSON.stringify([name,...(name==='search_files'?[query.query,query.directory??null]:[query.path])]);
|
||||
const previous=connection.pages.get(key);
|
||||
let restart=offset>0&&!previous;
|
||||
let reply;
|
||||
try { reply=await this.call(name,{...query,offset:restart?0:offset,...(offset>0&&previous?{revision:previous}:{})}); }
|
||||
try { reply=await this.call(name,{...query,offset:restart?0:offset,...(offset>0&&previous?{revision:previous}:{})},options); }
|
||||
catch(error) {
|
||||
if(offset===0||![409,412].includes(error.status))throw error;
|
||||
restart=true;
|
||||
reply=await this.call(name,{...query,offset:0});
|
||||
reply=await this.call(name,{...query,offset:0},options);
|
||||
}
|
||||
if(typeof reply.result.revision!=='string')throw Error('企业知识库目录或搜索缺少本次查询版本');
|
||||
connection.pages.set(key,reply.result.revision);
|
||||
@ -163,6 +167,7 @@ export class EnterpriseKnowledge {
|
||||
async readDocument(fileId, revision, {pageLimit,...options}={}, read=fn=>fn()) {
|
||||
let offset=0, pages=0, result, chunks=[];
|
||||
for(;;) {
|
||||
options.signal?.throwIfAborted();
|
||||
const reply=await read(()=>this.call('read_text',{fileId,offset,...(revision?{revision}:{}),...(pageLimit?{limit:pageLimit}:{})},options));
|
||||
result=reply.result; revision=result.revision; pages++;chunks.push(result.text);
|
||||
if(result.isLastPage===true&&result.nextOffset===null){
|
||||
@ -186,21 +191,22 @@ export class EnterpriseKnowledge {
|
||||
const matches=async p=>{
|
||||
let stat;try{stat=await fs.stat(p);}catch(e){if(e.code==='ENOENT')return false;throw e;}
|
||||
if(stat.size!==metadata.size)return false;
|
||||
const hash=createHash('sha256');for await(const bytes of createReadStream(p)){signal?.throwIfAborted();hash.update(bytes);}
|
||||
const hash=createHash('sha256');for await(const bytes of createReadStream(p,{signal}))hash.update(bytes);
|
||||
return hash.digest('hex')===metadata.sha256.toLowerCase();
|
||||
};
|
||||
const receipt=cached=>({...reply,notice:'附件已按固定版本保存,尚未导入画布。',result:{...metadata,localPath:file,downloaded:true,cached,imported:false}});
|
||||
if(await matches(file)){onProgress?.({phase:'download',fileId:args.fileId,received:metadata.size,total:metadata.size,cached:true});return receipt(true);}
|
||||
if(await matches(file)){signal?.throwIfAborted();onProgress?.({phase:'download',fileId:args.fileId,received:metadata.size,total:metadata.size,cached:true});return receipt(true);}
|
||||
const part=file+'.part';
|
||||
let received=await fs.stat(part).then(s=>s.size,e=>{if(e.code==='ENOENT')return 0;throw e;});
|
||||
if(received===metadata.size&&await matches(part)){await fs.rename(part,file);return receipt(false);}
|
||||
if(received===metadata.size&&await matches(part)){signal?.throwIfAborted();await fs.rename(part,file);return receipt(false);}
|
||||
signal?.throwIfAborted();
|
||||
if(received>=metadata.size){await fs.rm(part,{force:true});received=0;}
|
||||
const {origin,token}=this.connection;
|
||||
let response;
|
||||
try { response=await this.fetchImpl(origin+metadata.downloadPath,{method:'GET',redirect:'manual',signal:signal?AbortSignal.any([signal,AbortSignal.timeout(180000)]):AbortSignal.timeout(180000),headers:{Authorization:`Bearer ${token}`,...metadata.downloadHeaders,...(received?{Range:`bytes=${received}-`}:{})}}); }
|
||||
catch { signal?.throwIfAborted();throw Error('企业知识库附件下载中断,可继续同一版本'); }
|
||||
if(!response.ok){
|
||||
let value;try{value=await response.json();}catch{}
|
||||
let value;try{value=await response.json();}catch{signal?.throwIfAborted();}
|
||||
const error=failure(response.status,value,response.headers.get('retry-after'));
|
||||
if(error.status===429&&error.retryAfterSeconds){this.connection.retryAt=Date.now()+error.retryAfterSeconds*1000;this.connection.usage=error.usage;}
|
||||
throw error;
|
||||
@ -213,8 +219,11 @@ export class EnterpriseKnowledge {
|
||||
let progressAt=0;
|
||||
try {
|
||||
if(response.body)for await(const bytes of response.body){signal?.throwIfAborted();received+=bytes.byteLength;if(received>metadata.size)throw Error('企业知识库附件大小不匹配');await handle.writeFile(bytes);if(Date.now()-progressAt>=100||received===metadata.size){progressAt=Date.now();onProgress?.({phase:'download',fileId:args.fileId,received,total:metadata.size});}}
|
||||
} finally {await handle.close();}
|
||||
} catch(error) { signal?.throwIfAborted(); throw error; }
|
||||
finally {await handle.close();}
|
||||
signal?.throwIfAborted();
|
||||
if(!await matches(part)){if(received>=metadata.size)await fs.rm(part,{force:true});throw Error('企业知识库附件未完整或字节版本不匹配,未交付');}
|
||||
signal?.throwIfAborted();
|
||||
await fs.rename(part,file);
|
||||
await this.store.appendEvent?.({type:'enterprise_knowledge_download',server:ENTERPRISE_SERVER,reference:args.fileId,revision:metadata.revision,releaseId:metadata.releaseId,bytes:metadata.size,localPath:file});
|
||||
return receipt(false);
|
||||
@ -226,12 +235,12 @@ export class EnterpriseKnowledge {
|
||||
if (name==='read_text' && (args.offset??0)>0 && !args.revision) throw Error('文档续页必须携带原revision');
|
||||
if (name==='list_directory' && (args.offset??0)>0 && !args.revision) throw Error('目录续页必须携带原revision');
|
||||
if (name==='search_files' && (args.offset??0)>0 && !args.revision) throw Error('搜索续页必须携带原revision');
|
||||
const token=await this.credentialProvider(); if(typeof token!=='string'||!token.trim()||/[\r\n]/.test(token))throw Error('企业知识库用户凭据未配置');
|
||||
const token=await this.credentialProvider(options.signal); if(typeof token!=='string'||!token.trim()||/[\r\n]/.test(token))throw Error('企业知识库用户凭据未配置');
|
||||
if (name==='read_text') args={...args,limit:args.limit??16000};
|
||||
if (name==='query_knowledge') args={...args,limit:args.limit??3,maxCharacters:args.maxCharacters??8000};
|
||||
if (name==='search_files') args={...args,limit:args.limit??5};
|
||||
if (name==='list_directory') args={...args,limit:args.limit??10};
|
||||
const connection=await this.connect(token), {origin,rpc}=connection;
|
||||
const connection=await this.connect(token,options), {origin,rpc}=connection;
|
||||
if(name==='query_knowledge'&&args.maxCharacters>0&&Number.isSafeInteger(connection.maxResponseCharacters))args={...args,maxCharacters:Math.min(args.maxCharacters,connection.maxResponseCharacters)};
|
||||
if(connection.retryAt>Date.now())throw failure(429,{retryAfterSeconds:Math.ceil((connection.retryAt-Date.now())/1000),usage:connection.usage});
|
||||
const tool=connection.tools.get(name);
|
||||
@ -267,7 +276,7 @@ export class EnterpriseKnowledge {
|
||||
});
|
||||
if(name==='read_image'&&!images.length)throw Error('企业知识库未返回实际图片内容');
|
||||
if(name==='list_libraries') {
|
||||
if((connection.serverVersion&&connection.serverVersion!==value.serverVersion)||(Array.isArray(value.expectedTools)&&value.expectedTools.some(n=>!connection.tools.has(n))))await this.discover(connection);
|
||||
if((connection.serverVersion&&connection.serverVersion!==value.serverVersion)||(Array.isArray(value.expectedTools)&&value.expectedTools.some(n=>!connection.tools.has(n))))await this.discover(connection,options);
|
||||
connection.serverVersion=value.serverVersion;
|
||||
connection.maxResponseCharacters=value.policy?.maxResponseCharacters;
|
||||
}
|
||||
@ -306,19 +315,21 @@ export class EnterpriseKnowledge {
|
||||
export function enterpriseTools(host, make, client = new EnterpriseKnowledge({store:host.store})) {
|
||||
const namespace={name:ENTERPRISE_SERVER,description:'企业知识库:按通用契约读取知识、图片与附件'};
|
||||
let taskEpoch=Symbol();
|
||||
const execute=async(name,args)=>{
|
||||
const execute=async(name,args,signal)=>{
|
||||
const options={signal};
|
||||
const epoch=host.turnEpoch;
|
||||
try {
|
||||
if(taskEpoch!==host.turnEpoch&&name!=='list_libraries'){await client.call('list_libraries');taskEpoch=host.turnEpoch;}
|
||||
const result=await (name==='download_file'?client.download(args):['search_files','list_directory'].includes(name)?client.page(name,args):client.call(name,args));
|
||||
if(name==='list_libraries')taskEpoch=host.turnEpoch;
|
||||
if(taskEpoch!==epoch&&name!=='list_libraries'){await client.call('list_libraries',{},options);taskEpoch=epoch;}
|
||||
const result=await (name==='download_file'?client.download(args,options):['search_files','list_directory'].includes(name)?client.page(name,args,options):client.call(name,args,options));
|
||||
if(name==='list_libraries')taskEpoch=epoch;
|
||||
return result;
|
||||
} catch(error) {
|
||||
if(error.status!==429)throw error;
|
||||
return {server:ENTERPRISE_SERVER,error:{status:429,code:'usage_limit',retryAfterSeconds:error.retryAfterSeconds,usage:error.usage},notice:error.message};
|
||||
}
|
||||
};
|
||||
const tools=names.map(name=>({...make('ekb_'+name, descriptions[name], schemas[name], args=>execute(name,args),enterpriseToolResult),namespace,exposure:'deferred',...(name==='read_image'?{promptGuidelines:['读取图片时,通过tool_search启用后直接调用ekb_read_image,让实际image内容进入视觉上下文;不要放进只返回文字的CodeMode嵌套调用。']}:{})}));
|
||||
tools.push({...make('ekb_download_file','下载选定附件到当前项目;保留同一revision或release引用,核对完整字节后返回本地路径,不导入画布',schemas.get_file,args=>execute('download_file',args),enterpriseToolResult),namespace,exposure:'deferred',executionMode:'sequential'});
|
||||
const tools=names.map(name=>({...make('ekb_'+name, descriptions[name], schemas[name], (args,signal)=>execute(name,args,signal),enterpriseToolResult),namespace,exposure:'deferred',...(name==='read_image'?{promptGuidelines:['读取图片时,通过tool_search启用后直接调用ekb_read_image,让实际image内容进入视觉上下文;不要放进只返回文字的CodeMode嵌套调用。']}:{})}));
|
||||
tools.push({...make('ekb_download_file','下载选定附件到当前项目;保留同一revision或release引用,核对完整字节后返回本地路径,不导入画布',schemas.get_file,(args,signal)=>execute('download_file',args,signal),enterpriseToolResult),namespace,exposure:'deferred',executionMode:'sequential'});
|
||||
return tools;
|
||||
}
|
||||
export function enterpriseToolResult(value) {
|
||||
|
||||
@ -183,7 +183,7 @@ export class EnterpriseTemplates {
|
||||
const entries=[];
|
||||
let offset=0,more=true;
|
||||
while(more) {
|
||||
const {result}=await waitForQuota(()=>this.client.page('search_files',{query:'品牌风格索引',limit:100,offset}),task);
|
||||
const {result}=await waitForQuota(()=>this.client.page('search_files',{query:'品牌风格索引',limit:100,offset},{signal:task.signal}),task);
|
||||
if(result.pageRestarted)entries.length=0;
|
||||
const page=result.page;
|
||||
entries.push(...page.entries.filter(entry=>entry.kind==='file'&&
|
||||
|
||||
@ -1,9 +1,7 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs/promises';
|
||||
import net from 'node:net';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import path from 'node:path';
|
||||
|
||||
/** Keep an explicit local upstream exception consistent across Windows casing. */
|
||||
@ -207,152 +205,5 @@ export class Native98kBroker {
|
||||
knowledge(brandId) { return this.start('knowledge', { brandId: brandId ?? null }); }
|
||||
}
|
||||
|
||||
/** Trusted host adapter; the agent receives only read/edit tools, not this socket. */
|
||||
export class NativeCanvas {
|
||||
constructor(socket, options = {}) {
|
||||
this.socket = null; this.serial = 0; this.pending = new Map();
|
||||
this.connection = options.connection;
|
||||
this.rpcTimeoutMs = options.rpcTimeoutMs ?? 15000;
|
||||
this.connecting = null; this.closed = false; this.authenticated = Boolean(socket);
|
||||
if (socket) this.attach(socket);
|
||||
}
|
||||
attach(socket) {
|
||||
this.socket = socket;
|
||||
const reader = createInterface({ input: socket });
|
||||
reader.on('error', () => this.disconnect(socket)).on('line', line => {
|
||||
let value; try { value = JSON.parse(line); } catch { this.disconnect(socket); return; }
|
||||
const task = this.pending.get(value.id);
|
||||
// A late reply on a previous socket cannot settle a newer generation.
|
||||
if (!task || task.socket !== socket) return;
|
||||
this.pending.delete(value.id); clearTimeout(task.timer);
|
||||
if (value.error || value.ok === false) task.reject(Error(value.error || '原生操作失败'));
|
||||
else task.resolve(value.result ?? value);
|
||||
});
|
||||
socket.on('error', () => this.disconnect(socket));
|
||||
socket.on('end', () => this.disconnect(socket));
|
||||
socket.on('close', () => { reader.close(); this.disconnect(socket); });
|
||||
}
|
||||
disconnect(socket) {
|
||||
// Keep the last socket inspectable (destroyed/writable) for existing hosts.
|
||||
if (this.socket === socket) this.authenticated = false;
|
||||
this.rejectPending(socket);
|
||||
if (socket && !socket.destroyed) socket.destroy();
|
||||
}
|
||||
rejectPending(socket) {
|
||||
for (const [id, task] of this.pending) {
|
||||
if (socket && task.socket !== socket) continue;
|
||||
this.pending.delete(id); clearTimeout(task.timer);
|
||||
task.reject(Error('画布连接中断,已发送操作结果需核查;不会重发'));
|
||||
}
|
||||
}
|
||||
static async connect({ port, tokenFile, connectTimeoutMs = 3000, rpcTimeoutMs = 15000 }) {
|
||||
if (!Number.isInteger(port) || port < 1024 || port > 65535 || typeof tokenFile !== 'string' || !tokenFile
|
||||
|| !Number.isFinite(connectTimeoutMs) || connectTimeoutMs <= 0 || !Number.isFinite(rpcTimeoutMs) || rpcTimeoutMs <= 0) throw Error('画布连接配置无效,未派发操作');
|
||||
const client = new NativeCanvas(null, { connection: { port, tokenFile, connectTimeoutMs }, rpcTimeoutMs });
|
||||
try { await client.ensureConnected(); return client; }
|
||||
catch (error) { client.close(); throw error; }
|
||||
}
|
||||
async ensureConnected() {
|
||||
if (this.closed) throw Error('画布连接已关闭,未派发新操作');
|
||||
if (this.connecting) return this.connecting;
|
||||
if (this.socket && !this.socket.destroyed && this.socket.writable && this.authenticated) return;
|
||||
if (this.pending.size) {
|
||||
this.disconnect(this.socket);
|
||||
throw Error('原画布操作结果需核查,未派发新操作;不会重发');
|
||||
}
|
||||
if (!this.connection) throw Error('画布连接已断开,未派发新操作');
|
||||
const attempt = this.openAndAuthenticate();
|
||||
this.connecting = attempt;
|
||||
try { await attempt; }
|
||||
finally { if (this.connecting === attempt) this.connecting = null; }
|
||||
}
|
||||
async openAndAuthenticate() {
|
||||
const { port, tokenFile, connectTimeoutMs } = this.connection;
|
||||
const socket = net.createConnection({ host: '127.0.0.1', port });
|
||||
this.attach(socket);
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
const finish = (error) => {
|
||||
clearTimeout(timer); socket.off('connect', connected); socket.off('error', failed); socket.off('close', failed);
|
||||
if (error) reject(error); else resolve();
|
||||
};
|
||||
const connected = () => finish();
|
||||
const failed = () => finish(Error('画布连接无法建立,未派发新操作'));
|
||||
const timer = setTimeout(() => finish(Error('画布连接建立超时,未派发新操作')), connectTimeoutMs);
|
||||
socket.once('connect', connected); socket.once('error', failed); socket.once('close', failed);
|
||||
});
|
||||
if (this.closed || this.socket !== socket || socket.destroyed || !socket.writable) throw Error('画布连接已关闭,未派发新操作');
|
||||
const token = (await fs.readFile(tokenFile, 'utf8')).trim();
|
||||
if (!token || token.length > 8192) throw Error('画布授权文件无效,未派发新操作');
|
||||
try { await this.send(socket, 'auth', { token }, connectTimeoutMs); }
|
||||
catch { throw Error('画布重新授权未完成,未派发新操作'); }
|
||||
if (this.closed || this.socket !== socket || socket.destroyed || !socket.writable) throw Error('画布授权连接已关闭,未派发新操作');
|
||||
this.authenticated = true;
|
||||
} catch (error) { this.disconnect(socket); throw error; }
|
||||
}
|
||||
send(socket, method, params, timeoutMs = this.rpcTimeoutMs) {
|
||||
if (!socket || this.closed || this.socket !== socket || socket.destroyed || !socket.writable) return Promise.reject(Error('画布连接已断开,未派发新操作'));
|
||||
const id = ++this.serial;
|
||||
const message = JSON.stringify({ id, method, params }) + '\n';
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pending.delete(id); reject(Error('画布操作结果未知,禁止重复操作;不会重发'));
|
||||
// Do not reuse a timed-out transport or let its late reply affect a
|
||||
// subsequent command. This never resubmits the timed-out RPC.
|
||||
this.disconnect(socket);
|
||||
}, timeoutMs);
|
||||
this.pending.set(id, { resolve, reject, timer, socket });
|
||||
try { socket.write(message, error => { if (error) this.disconnect(socket); }); }
|
||||
catch { this.disconnect(socket); }
|
||||
});
|
||||
}
|
||||
async call(method, params = {}) {
|
||||
// Only a NEW caller command reaches send. No pending RPC is queued/replayed
|
||||
// during reauthentication, and run/identity/edit counters stay unchanged.
|
||||
await this.ensureConnected();
|
||||
return this.send(this.socket, method, params);
|
||||
}
|
||||
action(action, input = {}) { return this.call('jiansun.action', { action, input: { ...input, run: this.run, documentId: this.documentId } }); }
|
||||
async begin(text) {
|
||||
this.run = randomUUID();
|
||||
const state = await this.action('pi-begin', { text, ...(this.identity || {}) });
|
||||
const documentId = state?.context?.id;
|
||||
if (!Number.isSafeInteger(documentId) || documentId < 1 || (this.documentId !== undefined && this.documentId !== documentId)) throw Error('原生会话文档身份尚未确认,未派发后续操作');
|
||||
this.documentId = documentId;
|
||||
return state;
|
||||
}
|
||||
read() { return this.action('pi-state'); }
|
||||
readCanvas(input = {}) { return this.action('pi-canvas-read', input); }
|
||||
nativeCatalog(input = {}) { return this.action('pi-native-catalog', input); }
|
||||
nativeCall(input) { return this.action('pi-native-call', input); }
|
||||
nativePoll(job) { return this.action('pi-native-poll', { job }); }
|
||||
nativeReconcile({ run, documentId, job }) { return this.call('jiansun.action', { action:'pi-native-reconcile', input:{ run, documentId, job } }); }
|
||||
editReconcile({run,documentId,beforeRevision,command,targetLayerId}) { return this.call('jiansun.action', {action:'pi-edit-reconcile',input:{run,documentId,beforeRevision,command,targetLayerId}}); }
|
||||
copyOptions(input) { return this.action('pi-copy-options', input); }
|
||||
copyFields(input) { return this.action('pi-copy-fields',input); }
|
||||
uiRequest(request) { return this.action('pi-ui-request', { request }); }
|
||||
uiPoll(id) { return this.action('pi-ui-poll', { id }); }
|
||||
uiCancel(id) { return this.action('pi-ui-cancel', { id }); }
|
||||
delta(text, thinking, production, output) { return this.action('pi-delta', { text, ...(thinking === undefined ? {} : { thinking }), ...(production ? { production } : {}), ...(output ? { output } : {}) }); }
|
||||
activity(text, event) { return this.action('pi-activity', { text, ...(event ? { event } : {}) }); }
|
||||
requestWrite(revision) { return this.action('pi-write-request', { revision }); }
|
||||
workflowRead(input = {}) { return this.action('pi-workflow-read', input); }
|
||||
workflowNavigate(input) { return this.action('pi-workflow-navigate', input); }
|
||||
workflowPropose(input) { return this.action('pi-workflow-propose', input); }
|
||||
workflowExecute(input) { return this.action('pi-workflow-execute', input); }
|
||||
workflowPoll(operationId) { return this.action('pi-workflow-poll', { operationId }); }
|
||||
workflowReconcile({ run, documentId, operationId, adoption }) { return this.call('jiansun.action', { action:'pi-workflow-reconcile', input:{ run, documentId, operationId, ...(adoption?{adoption}:null) } }); }
|
||||
async edit(edit, revision, signal) {
|
||||
signal?.throwIfAborted();
|
||||
await this.action('pi-edit', { edit, revision });
|
||||
for (;;) {
|
||||
await delay(90, undefined, {signal});
|
||||
const state = await this.read();
|
||||
if (!state.allowed) throw Error('用户已接手,后续画布操作已停止');
|
||||
if (state.error) throw Error(state.error);
|
||||
if (!state.queued && state.revision !== revision) return state;
|
||||
}
|
||||
}
|
||||
end(text) { return this.action('pi-end', { text }); }
|
||||
close() { this.closed = true; this.disconnect(this.socket); }
|
||||
}
|
||||
// Compatibility entry point for external desktop drivers.
|
||||
export {NativeControlClient as NativeCanvas} from './native-control-client.mjs';
|
||||
|
||||
155
apps/detail-agent-pi/src/native-control-client.mjs
Normal file
155
apps/detail-agent-pi/src/native-control-client.mjs
Normal file
@ -0,0 +1,155 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import net from 'node:net';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
|
||||
/** External QA and desktop automation client for PhotoCraft's control port. */
|
||||
export class NativeControlClient {
|
||||
constructor(socket, options = {}) {
|
||||
this.socket = null; this.serial = 0; this.pending = new Map();
|
||||
this.connection = options.connection;
|
||||
this.rpcTimeoutMs = options.rpcTimeoutMs ?? 15000;
|
||||
this.connecting = null; this.closed = false; this.authenticated = Boolean(socket);
|
||||
if (socket) this.attach(socket);
|
||||
}
|
||||
attach(socket) {
|
||||
this.socket = socket;
|
||||
const reader = createInterface({ input: socket });
|
||||
reader.on('error', () => this.disconnect(socket)).on('line', line => {
|
||||
let value; try { value = JSON.parse(line); } catch { this.disconnect(socket); return; }
|
||||
const task = this.pending.get(value.id);
|
||||
// A late reply on a previous socket cannot settle a newer generation.
|
||||
if (!task || task.socket !== socket) return;
|
||||
this.pending.delete(value.id); clearTimeout(task.timer);
|
||||
if (value.error || value.ok === false) task.reject(Error(value.error || '原生操作失败'));
|
||||
else task.resolve(value.result ?? value);
|
||||
});
|
||||
socket.on('error', () => this.disconnect(socket));
|
||||
socket.on('end', () => this.disconnect(socket));
|
||||
socket.on('close', () => { reader.close(); this.disconnect(socket); });
|
||||
}
|
||||
disconnect(socket) {
|
||||
// Keep the last socket inspectable (destroyed/writable) for existing hosts.
|
||||
if (this.socket === socket) this.authenticated = false;
|
||||
this.rejectPending(socket);
|
||||
if (socket && !socket.destroyed) socket.destroy();
|
||||
}
|
||||
rejectPending(socket) {
|
||||
for (const [id, task] of this.pending) {
|
||||
if (socket && task.socket !== socket) continue;
|
||||
this.pending.delete(id); clearTimeout(task.timer);
|
||||
task.reject(Error('画布连接中断,已发送操作结果需核查;不会重发'));
|
||||
}
|
||||
}
|
||||
static async connect({ port, tokenFile, connectTimeoutMs = 3000, rpcTimeoutMs = 15000 }) {
|
||||
if (!Number.isInteger(port) || port < 1024 || port > 65535 || typeof tokenFile !== 'string' || !tokenFile
|
||||
|| !Number.isFinite(connectTimeoutMs) || connectTimeoutMs <= 0 || !Number.isFinite(rpcTimeoutMs) || rpcTimeoutMs <= 0) throw Error('画布连接配置无效,未派发操作');
|
||||
const client = new NativeControlClient(null, { connection: { port, tokenFile, connectTimeoutMs }, rpcTimeoutMs });
|
||||
try { await client.ensureConnected(); return client; }
|
||||
catch (error) { client.close(); throw error; }
|
||||
}
|
||||
async ensureConnected() {
|
||||
if (this.closed) throw Error('画布连接已关闭,未派发新操作');
|
||||
if (this.connecting) return this.connecting;
|
||||
if (this.socket && !this.socket.destroyed && this.socket.writable && this.authenticated) return;
|
||||
if (this.pending.size) {
|
||||
this.disconnect(this.socket);
|
||||
throw Error('原画布操作结果需核查,未派发新操作;不会重发');
|
||||
}
|
||||
if (!this.connection) throw Error('画布连接已断开,未派发新操作');
|
||||
const attempt = this.openAndAuthenticate();
|
||||
this.connecting = attempt;
|
||||
try { await attempt; }
|
||||
finally { if (this.connecting === attempt) this.connecting = null; }
|
||||
}
|
||||
async openAndAuthenticate() {
|
||||
const { port, tokenFile, connectTimeoutMs } = this.connection;
|
||||
const socket = net.createConnection({ host: '127.0.0.1', port });
|
||||
this.attach(socket);
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
const finish = (error) => {
|
||||
clearTimeout(timer); socket.off('connect', connected); socket.off('error', failed); socket.off('close', failed);
|
||||
if (error) reject(error); else resolve();
|
||||
};
|
||||
const connected = () => finish();
|
||||
const failed = () => finish(Error('画布连接无法建立,未派发新操作'));
|
||||
const timer = setTimeout(() => finish(Error('画布连接建立超时,未派发新操作')), connectTimeoutMs);
|
||||
socket.once('connect', connected); socket.once('error', failed); socket.once('close', failed);
|
||||
});
|
||||
if (this.closed || this.socket !== socket || socket.destroyed || !socket.writable) throw Error('画布连接已关闭,未派发新操作');
|
||||
const token = (await fs.readFile(tokenFile, 'utf8')).trim();
|
||||
if (!token || token.length > 8192) throw Error('画布授权文件无效,未派发新操作');
|
||||
try { await this.send(socket, 'auth', { token }, connectTimeoutMs); }
|
||||
catch { throw Error('画布重新授权未完成,未派发新操作'); }
|
||||
if (this.closed || this.socket !== socket || socket.destroyed || !socket.writable) throw Error('画布授权连接已关闭,未派发新操作');
|
||||
this.authenticated = true;
|
||||
} catch (error) { this.disconnect(socket); throw error; }
|
||||
}
|
||||
send(socket, method, params, timeoutMs = this.rpcTimeoutMs) {
|
||||
if (!socket || this.closed || this.socket !== socket || socket.destroyed || !socket.writable) return Promise.reject(Error('画布连接已断开,未派发新操作'));
|
||||
const id = ++this.serial;
|
||||
const message = JSON.stringify({ id, method, params }) + '\n';
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pending.delete(id); reject(Error('画布操作结果未知,禁止重复操作;不会重发'));
|
||||
// Do not reuse a timed-out transport or let its late reply affect a
|
||||
// subsequent command. This never resubmits the timed-out RPC.
|
||||
this.disconnect(socket);
|
||||
}, timeoutMs);
|
||||
this.pending.set(id, { resolve, reject, timer, socket });
|
||||
try { socket.write(message, error => { if (error) this.disconnect(socket); }); }
|
||||
catch { this.disconnect(socket); }
|
||||
});
|
||||
}
|
||||
async call(method, params = {}) {
|
||||
// Only a NEW caller command reaches send. No pending RPC is queued/replayed
|
||||
// during reauthentication, and run/identity/edit counters stay unchanged.
|
||||
await this.ensureConnected();
|
||||
return this.send(this.socket, method, params);
|
||||
}
|
||||
action(action, input = {}) { return this.call('jiansun.action', { action, input: { ...input, run: this.run, documentId: this.documentId } }); }
|
||||
async begin(text) {
|
||||
this.run = randomUUID();
|
||||
const state = await this.action('pi-begin', { text, ...(this.identity || {}) });
|
||||
const documentId = state?.context?.id;
|
||||
if (!Number.isSafeInteger(documentId) || documentId < 1 || (this.documentId !== undefined && this.documentId !== documentId)) throw Error('原生会话文档身份尚未确认,未派发后续操作');
|
||||
this.documentId = documentId;
|
||||
return state;
|
||||
}
|
||||
read() { return this.action('pi-state'); }
|
||||
readCanvas(input = {}) { return this.action('pi-canvas-read', input); }
|
||||
nativeCatalog(input = {}) { return this.action('pi-native-catalog', input); }
|
||||
nativeCall(input) { return this.action('pi-native-call', input); }
|
||||
nativePoll(job) { return this.action('pi-native-poll', { job }); }
|
||||
nativeReconcile({ run, documentId, job }) { return this.call('jiansun.action', { action:'pi-native-reconcile', input:{ run, documentId, job } }); }
|
||||
editReconcile({run,documentId,beforeRevision,command,targetLayerId}) { return this.call('jiansun.action', {action:'pi-edit-reconcile',input:{run,documentId,beforeRevision,command,targetLayerId}}); }
|
||||
copyOptions(input) { return this.action('pi-copy-options', input); }
|
||||
copyFields(input) { return this.action('pi-copy-fields',input); }
|
||||
uiRequest(request) { return this.action('pi-ui-request', { request }); }
|
||||
uiPoll(id) { return this.action('pi-ui-poll', { id }); }
|
||||
uiCancel(id) { return this.action('pi-ui-cancel', { id }); }
|
||||
delta(text, thinking, production, output) { return this.action('pi-delta', { text, ...(thinking === undefined ? {} : { thinking }), ...(production ? { production } : {}), ...(output ? { output } : {}) }); }
|
||||
activity(text, event) { return this.action('pi-activity', { text, ...(event ? { event } : {}) }); }
|
||||
requestWrite(revision) { return this.action('pi-write-request', { revision }); }
|
||||
workflowRead(input = {}) { return this.action('pi-workflow-read', input); }
|
||||
workflowNavigate(input) { return this.action('pi-workflow-navigate', input); }
|
||||
workflowPropose(input) { return this.action('pi-workflow-propose', input); }
|
||||
workflowExecute(input) { return this.action('pi-workflow-execute', input); }
|
||||
workflowPoll(operationId) { return this.action('pi-workflow-poll', { operationId }); }
|
||||
workflowReconcile({ run, documentId, operationId, adoption }) { return this.call('jiansun.action', { action:'pi-workflow-reconcile', input:{ run, documentId, operationId, ...(adoption?{adoption}:null) } }); }
|
||||
async edit(edit, revision, signal) {
|
||||
signal?.throwIfAborted();
|
||||
await this.action('pi-edit', { edit, revision });
|
||||
for (;;) {
|
||||
await delay(90, undefined, {signal});
|
||||
const state = await this.read();
|
||||
if (!state.allowed) throw Error('用户已接手,后续画布操作已停止');
|
||||
if (state.error) throw Error(state.error);
|
||||
if (!state.queued && state.revision !== revision) return state;
|
||||
}
|
||||
}
|
||||
end(text) { return this.action('pi-end', { text }); }
|
||||
close() { this.closed = true; this.disconnect(this.socket); }
|
||||
}
|
||||
@ -41,7 +41,7 @@ export const productionOperationTools = [
|
||||
['read_copy_fields','读取画布文字格、当前文案和修订号。指定 pageId 或 fieldId 时一并读取该范围的模板样稿与发布要求,供撰写和复核。',obj({
|
||||
pageId:optional(Type.String()),fieldId:optional(Type.String()),
|
||||
})],
|
||||
['write_copy_fields','写入指定文字格并记录与实拍、配图的关联。原生命令已经写过时可用 recordOnly 登记现有文字。retryWrite 表示本次没写入,请查看原因后继续。模板规定缺资料时留空的字段,可传空文字并用 reason 记录依据。',obj({
|
||||
['write_copy_fields','用 read_copy_fields 回执的 revision 写入已读文字格,并记录与实拍、配图的关联。原生命令已经写过时可用 recordOnly 登记现有文字。retryWrite 表示画布暂不可写,rejected 列出保留原文的格子。模板规定缺资料时留空的字段,可传空文字并用 reason 记录依据。',obj({
|
||||
revision:rev,recordOnly:optional(Type.Boolean()),items:optional(Type.Array(obj({layer,text:Type.String(),sources:ids,pictures:ids,reason:optional(Type.String())}))),
|
||||
})],
|
||||
['read_slot_images','查看当前图位的同款实拍和模板构图。候选只返回候选画面;需要同时查看或重新查看参考时传 includeReferences=true。',obj({
|
||||
@ -394,11 +394,6 @@ export async function openProductionOperations(host) {
|
||||
const reason=receipt?.id===candidateId?receipt?.message??operation.message:operation.message;
|
||||
return {slotId:slot.id,phase,candidateId,operationId:original.operationId,reason};
|
||||
};
|
||||
const deferredCopyWrite=({revision},expected)=>({
|
||||
revision,appliedLayers:[],retryWrite:true,
|
||||
reason:revision===expected?'写入时画布暂不可用。可先处理其他图位,稍后继续写入。':
|
||||
'画布修订已变化,请重新读取文字格和修订号后再写入。',
|
||||
});
|
||||
async function check(slot,candidateId,adopted,signal){
|
||||
const item=journal.items[slot.id];
|
||||
const source=item?.candidateId===candidateId?item.source:undefined;
|
||||
@ -449,54 +444,28 @@ export async function openProductionOperations(host) {
|
||||
async read_copy_fields({pageId,fieldId}){
|
||||
pageId=pageId?.trim()||undefined;
|
||||
fieldId=fieldId?.trim()||undefined;
|
||||
const {revision}=await canvas.read();
|
||||
const current=await canvas.detailCopyFields({includeFilled:true,pageId,fieldId});
|
||||
const end=await canvas.read();
|
||||
if(end.revision===revision){
|
||||
const snapshot=copyReads.get(revision)??new Map();
|
||||
for(const field of current.fields??[])snapshot.set(field.layer,field.currentText);
|
||||
copyReads.set(revision,snapshot);
|
||||
}
|
||||
return {...current,revision:end.revision};
|
||||
const snapshot=copyReads.get(current.revision)??new Map();
|
||||
for(const field of current.fields)snapshot.set(field.layer,field.currentText);
|
||||
copyReads.set(current.revision,snapshot);
|
||||
return current;
|
||||
},
|
||||
write_copy_fields({revision,recordOnly,items=[]},signal){
|
||||
return serialize(async()=>{
|
||||
if(!items.length)return {appliedLayers:[],revision:(await canvas.read()).revision};
|
||||
const inputPlan=await current();
|
||||
const targetFields=async()=>new Map((await fields()).map(field=>[field.layer,field]));
|
||||
let result={appliedLayers:[]};
|
||||
if(!recordOnly){
|
||||
const submit=async(expected,before)=>{
|
||||
signal?.throwIfAborted();
|
||||
const receipt=await canvas.requestWrite(expected);
|
||||
if(receipt.retryWrite)return deferredCopyWrite(receipt,expected);
|
||||
if(!receipt.allowed||receipt.revision!==expected)throw Error('画布修订已变化或用户已接手');
|
||||
const reply=await canvas.detailApplyCopy(items.map(({layer,text})=>({layer,text,expectedText:before.get(layer)?.currentText})),expected);
|
||||
return reply.retryWrite?deferredCopyWrite(await canvas.read(),expected):reply;
|
||||
};
|
||||
let expected=(await canvas.read()).revision;
|
||||
let before=await targetFields();
|
||||
if(expected===revision){
|
||||
result=await submit(expected,before);
|
||||
if(!result.retryWrite)return await registerCopy(result);
|
||||
expected=result.revision;
|
||||
if(expected===revision)return result;
|
||||
}
|
||||
const sampled=copyReads.get(revision);
|
||||
await current();
|
||||
before=await targetFields();
|
||||
const live=await canvas.read();
|
||||
if(live.revision!==expected||live.writeBlocked||live.conversationActive===false||
|
||||
!items.every(({layer})=>sampled?.has(layer)&&before.has(layer)&&sampled.get(layer)===before.get(layer).currentText)){
|
||||
return deferredCopyWrite(live,revision);
|
||||
}
|
||||
result=await submit(expected,before);
|
||||
if(result.retryWrite)return result;
|
||||
if(!items.every(({layer})=>sampled?.has(layer)))throw Error('请先读取这些文字格,并使用该次读取返回的修订号');
|
||||
result=await canvas.commitDetailCopy(items.map(({layer,text})=>({layer,text,expectedText:sampled.get(layer)})),revision,signal);
|
||||
if(result.retryWrite)return {...result,appliedLayers:[],reason:'写入时画布暂不可用。可先处理其他图位,稍后继续写入。'};
|
||||
}
|
||||
return await registerCopy(result);
|
||||
|
||||
async function registerCopy(result){
|
||||
const after=new Map((await fields()).map(field=>[field.layer,field]));
|
||||
const snapshot=await canvas.detailCopyFields({includeFilled:true});
|
||||
const after=new Map(snapshot.fields.map(field=>[field.layer,field]));
|
||||
const applied=items.filter(row=>(recordOnly||result.appliedLayers?.includes(row.layer))&&after.get(row.layer)?.currentText===row.text);
|
||||
await update(()=>{
|
||||
syncCopyEvidence(inputPlan);
|
||||
@ -510,8 +479,8 @@ export async function openProductionOperations(host) {
|
||||
for(const {layer,mapping} of result.styleMappings)journal.copyStyleMappings[layer]=mapping;
|
||||
}
|
||||
});
|
||||
notice('文字已更新');
|
||||
return {...result,appliedLayers:applied.map(row=>row.layer),revision:(await canvas.read()).revision};
|
||||
if(applied.length)notice('文字已更新');
|
||||
return {...result,appliedLayers:applied.map(row=>row.layer),revision:snapshot.revision};
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
@ -55,6 +55,10 @@ export class StdioCanvas {
|
||||
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}); }
|
||||
commitDetailCopy(items,revision,signal) {
|
||||
signal?.throwIfAborted();
|
||||
return this.action('pi-detail-copy-apply',{items,revision,matchFields:true});
|
||||
}
|
||||
detailRetire(slotId,candidateId,reason) { return this.action('pi-detail-archive',{slotId,source:{candidateId,retireReason:reason}}); }
|
||||
detailHistory(options) { return this.action('pi-detail-archive',options); }
|
||||
detailArchive(slotId,{projectId,candidateId,forReview}) { return this.action('pi-detail-archive',{slotId,source:{projectId,candidateId,forReview}}); }
|
||||
|
||||
@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
|
||||
import { PassThrough } from 'node:stream';
|
||||
import { test } from 'node:test';
|
||||
import { startDaemon } from '../src/desktop-daemon.mjs';
|
||||
import { StdioCanvas } from '../src/stdio-canvas.mjs';
|
||||
|
||||
const runId = '9a1ba294-f2c4-4e5f-91e0-ef6002f50e22';
|
||||
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||
@ -146,3 +147,32 @@ test('presentation notifications do not wait for replies and the terminal comman
|
||||
await tick();
|
||||
assert.equal(frames.at(-1).type,'complete');
|
||||
});
|
||||
|
||||
test('the stdio canvas settles save, cancel and state replies ahead of a pending render', async t => {
|
||||
const observed=[];
|
||||
const {frames,send}=daemonFixture(t,{
|
||||
runSession:async(_config,call)=>{
|
||||
const canvas=new StdioCanvas(call,27);
|
||||
const screen=canvas.detailRender({page:0}).then(receipt=>observed.push(receipt));
|
||||
await Promise.all([
|
||||
canvas.nativeCall({method:'engine.execute',revision:7,params:{command:'file.save',params:{}}}),
|
||||
canvas.uiCancel('pending-interaction'),
|
||||
canvas.read(),
|
||||
].map(promise=>promise.then(receipt=>observed.push(receipt))));
|
||||
await screen;
|
||||
return {};
|
||||
},
|
||||
});
|
||||
send({type:'run',runId,config:{}});
|
||||
await tick();
|
||||
const requests=frames.filter(frame=>frame.type==='canvas');
|
||||
assert.deepEqual(requests.map(frame=>frame.action),['pi-product-screen','pi-native-call','pi-ui-cancel','pi-state']);
|
||||
for(const {id,action} of requests.slice(1))send({type:'canvas_result',runId,id,value:action});
|
||||
await tick();
|
||||
assert.deepEqual(observed,['pi-native-call','pi-ui-cancel','pi-state']);
|
||||
assert.equal(frames.some(frame=>frame.type==='complete'),false);
|
||||
send({type:'canvas_result',runId,id:requests[0].id,value:{revision:7}});
|
||||
await tick();
|
||||
assert.deepEqual(observed.at(-1),{revision:7});
|
||||
assert.equal(frames.at(-1).type,'complete');
|
||||
});
|
||||
|
||||
110
apps/detail-agent-pi/test/enterprise-cancellation.test.mjs
Normal file
110
apps/detail-agent-pi/test/enterprise-cancellation.test.mjs
Normal file
@ -0,0 +1,110 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {createServer} from 'node:http';
|
||||
import {once} from 'node:events';
|
||||
import {createHash} from 'node:crypto';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {setTimeout as delay} from 'node:timers/promises';
|
||||
import {EnterpriseKnowledge,enterpriseTools} from '../src/enterprise-knowledge.mjs';
|
||||
|
||||
async function fixture(t, stall) {
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-ekb-abort-'));
|
||||
const calls=[];
|
||||
const started=Promise.withResolvers();
|
||||
const closed=Promise.withResolvers();
|
||||
const bytes=Buffer.from('complete attachment');
|
||||
const sha256=createHash('sha256').update(bytes).digest('hex');
|
||||
const downloadPath='/api/agent/files/file-1/download';
|
||||
const inputSchema={type:'object',additionalProperties:true};
|
||||
const server=createServer(async (req,res)=>{
|
||||
const hold=()=>{
|
||||
res.once('close',()=>closed.resolve());
|
||||
started.resolve();
|
||||
};
|
||||
if(req.url==='/healthz'){
|
||||
res.end(JSON.stringify({status:'ok',service:'enterprise-knowledge-base'}));
|
||||
return;
|
||||
}
|
||||
if(req.url===downloadPath){
|
||||
calls.push('download');
|
||||
res.writeHead(200,{'Content-Length':bytes.length});
|
||||
res.write(bytes.subarray(0,4));
|
||||
hold();
|
||||
return;
|
||||
}
|
||||
const chunks=[];
|
||||
for await(const chunk of req)chunks.push(chunk);
|
||||
const {id,method,params}=JSON.parse(Buffer.concat(chunks));
|
||||
calls.push(params?.name??method);
|
||||
if(stall===method||stall==='page'&¶ms?.name==='search_files'&¶ms.arguments.offset>0){hold();return;}
|
||||
if(method==='notifications/initialized'){res.writeHead(202).end();return;}
|
||||
const result=method==='initialize'?{protocolVersion:'2025-11-25'}:
|
||||
method==='tools/list'?{tools:['list_libraries','get_file','search_files'].map(name=>({name,inputSchema}))}:
|
||||
{structuredContent:{
|
||||
list_libraries:{serverVersion:'1'},
|
||||
get_file:{id:'file-1',name:'file.bin',size:bytes.length,sha256,revision:'1',downloadPath,downloadHeaders:{'If-Match':'1'}},
|
||||
search_files:{revision:'page-1',page:{entries:[{id:'file-1'}],hasMore:true}},
|
||||
}[params.name]};
|
||||
res.end(JSON.stringify({jsonrpc:'2.0',id,result}));
|
||||
});
|
||||
t.after(async()=>{
|
||||
server.closeAllConnections();
|
||||
await new Promise(resolve=>server.close(resolve));
|
||||
await fs.rm(root,{recursive:true,force:true});
|
||||
});
|
||||
server.listen(0,'127.0.0.1');
|
||||
await once(server,'listening');
|
||||
const events=[];
|
||||
const store={root,appendEvent:async event=>events.push(event)};
|
||||
const client=new EnterpriseKnowledge({store,endpoints:[`http://127.0.0.1:${server.address().port}`],credentialProvider:async()=> 'test-token'});
|
||||
const tools=enterpriseTools({store,turnEpoch:1},(name,_description,_parameters,execute)=>({name,
|
||||
execute:(_id,args,signal)=>execute(args,signal),
|
||||
}),client);
|
||||
return {tool:name=>tools.find(tool=>tool.name===name),root,sha256,started:started.promise,closed:closed.promise,calls,events};
|
||||
}
|
||||
|
||||
test('Pi abort closes a live attachment download and keeps the partial file', {timeout:5000}, async t=>{
|
||||
const f=await fixture(t);
|
||||
const controller=new AbortController();
|
||||
const reason=Error('用户停止下载');
|
||||
const downloading=f.tool('ekb_download_file').execute('download',{fileId:'file-1',revision:'1'},controller.signal);
|
||||
const rejected=assert.rejects(downloading,error=>error===reason);
|
||||
await f.started;
|
||||
const dir=path.join(f.root,'knowledge-files');
|
||||
const part=path.join(dir,f.sha256+'.bin.part');
|
||||
for(let attempt=0;attempt<100;attempt++){
|
||||
if(await fs.stat(part).then(stat=>stat.size===4,()=>false))break;
|
||||
await delay(10);
|
||||
}
|
||||
assert.equal((await fs.stat(part)).size,4);
|
||||
controller.abort(reason);
|
||||
await Promise.all([rejected,f.closed]);
|
||||
assert.deepEqual(await fs.readdir(dir),[f.sha256+'.bin.part']);
|
||||
assert.equal(f.events.some(event=>event.type==='enterprise_knowledge_download'),false);
|
||||
});
|
||||
|
||||
test('Pi abort closes preflight discovery before issuing the requested tool', {timeout:5000}, async t=>{
|
||||
const f=await fixture(t,'tools/list');
|
||||
const controller=new AbortController();
|
||||
const reading=f.tool('ekb_search_files').execute('search',{query:'title'},controller.signal);
|
||||
const rejected=assert.rejects(reading,{name:'AbortError'});
|
||||
await f.started;
|
||||
controller.abort();
|
||||
await Promise.all([rejected,f.closed]);
|
||||
assert.deepEqual(f.calls,['initialize','notifications/initialized','tools/list']);
|
||||
});
|
||||
|
||||
test('Pi abort closes the active search continuation page', {timeout:5000}, async t=>{
|
||||
const f=await fixture(t,'page');
|
||||
const controller=new AbortController();
|
||||
const tool=f.tool('ekb_search_files');
|
||||
await tool.execute('first',{query:'title'},controller.signal);
|
||||
const reading=tool.execute('next',{query:'title',offset:1},controller.signal);
|
||||
const rejected=assert.rejects(reading,{name:'AbortError'});
|
||||
await f.started;
|
||||
controller.abort();
|
||||
await Promise.all([rejected,f.closed]);
|
||||
assert.deepEqual(f.calls.slice(-3),['list_libraries','search_files','search_files']);
|
||||
});
|
||||
@ -178,10 +178,10 @@ test('explicit tools share one Pi transcript and submit each real canvas revisio
|
||||
workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:stage,
|
||||
productVariantId:variantId,totalSlots:0,slots:[],template:{contentHash:stage},
|
||||
productEvidence:{accountScope:id.scope,project:id.project,documentId:13,brief:{}}}),
|
||||
detailCopyFields:async()=>({fields:structuredClone(fields)}),
|
||||
requestWrite:async revision=>({allowed:true,revision}),
|
||||
detailApplyCopy:async(items,expected)=>{
|
||||
detailCopyFields:async()=>({fields:structuredClone(fields),revision}),
|
||||
commitDetailCopy:async(items,expected)=>{
|
||||
assert.equal(expected,revision);
|
||||
assert.equal(items[0].expectedText,fields[0].currentText);
|
||||
copyWrites++;
|
||||
revision++;
|
||||
fields[0].currentText=items[0].text;
|
||||
@ -205,7 +205,7 @@ test('explicit tools share one Pi transcript and submit each real canvas revisio
|
||||
productionGoal:{outputId,variantId,workspaceId,requestedOutputs,deadline:Date.now()/1000+20}});
|
||||
try {
|
||||
steps.push(['plan_production'],['review_image_slots',{slotIds:[]}],null);
|
||||
if(outputId==='main_images')steps.push(['write_copy_fields',{revision,items:[{
|
||||
if(outputId==='main_images')steps.push(['read_copy_fields'],['write_copy_fields',{revision,items:[{
|
||||
layer:1,text:'木纹沿桌面延伸',sources:['P01'],pictures:[],
|
||||
}]}]);
|
||||
steps.push(['finish_production',{revision:revision+Number(outputId==='main_images')}]);
|
||||
|
||||
@ -420,7 +420,7 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
const templatePixels={...pixels,data:'template-preview'};
|
||||
const candidatePixels={...pixels,data:'candidate-preview'};
|
||||
const submissions=[], lookups=[], copyReads=[];
|
||||
let revision=3,modelCalls=0,recovered=false,reopened=false,reviewGate,waitingAt;
|
||||
let revision=3,modelCalls=0,recovered=false,reopened=false,reviewGate,copyWaiting=false,stateReads=0;
|
||||
const identity={scope:'scope',project:'project',documentId:23,accountId:'account',origin:'local'};
|
||||
const canvas={
|
||||
run:'native-run',documentId:23,identity,
|
||||
@ -429,7 +429,7 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
revisions:{creation:1},totalSlots:slots.length,slots}),
|
||||
detailCopyFields:async options=>{
|
||||
copyReads.push(options);
|
||||
return {fields:structuredClone(fields)};
|
||||
return {fields:structuredClone(fields),revision};
|
||||
},
|
||||
detailRender:async({page})=>{
|
||||
if(page===9)throw Error('此屏不属于当前工作画布');
|
||||
@ -446,13 +446,12 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
return {id:candidateId,status:recovered?'complete':'unknown',
|
||||
message:recovered?undefined:'网关确认原结果暂不可取回'};
|
||||
},
|
||||
read:async()=>({conversationActive:true,revision,detailWriteWaiting:!!waitingAt}),delta:async()=>{},
|
||||
requestWrite:async(expected)=>waitingAt==='permission'
|
||||
?{allowed:false,revision,retryWrite:true,detailWriteWaiting:true}:{allowed:revision===expected,revision},
|
||||
detailApplyCopy:async(items,expected)=>{
|
||||
if(waitingAt==='apply')return {retryWrite:true};
|
||||
assert.equal(expected,revision);
|
||||
assert.equal(items[0].expectedText,fields[0].currentText);
|
||||
read:async()=>{stateReads++;return {conversationActive:true,revision};},delta:async()=>{},
|
||||
requestWrite:async expected=>({allowed:revision===expected,revision}),
|
||||
commitDetailCopy:async(items,expected)=>{
|
||||
if(copyWaiting)return {retryWrite:true,revision};
|
||||
assert.ok(expected<=revision);
|
||||
if(items[0].expectedText!==fields[0].currentText)return {revision,appliedLayers:[],rejected:[{layer:7,reason:'原文已变化'}]};
|
||||
fields[0].currentText=items[0].text;
|
||||
revision++;
|
||||
return {appliedLayers:[7]};
|
||||
@ -493,7 +492,9 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
assert.deepEqual(plan.template,{contentHash:'lamp-template'});
|
||||
const focusedPlan=await actions.plan_production({slotIds:['lamp']});
|
||||
assert.deepEqual(focusedPlan.pictures.map(row=>row.requirements),['灯具原片和室内实景']);
|
||||
const readsBeforeCopy=stateReads;
|
||||
assert.deepEqual(await actions.read_copy_fields({pageId:'',fieldId:' '}), await actions.read_copy_fields({}));
|
||||
assert.equal(stateReads,readsBeforeCopy,'read_copy_fields must return the revision from the field snapshot');
|
||||
await actions.read_copy_fields({pageId:' one ',fieldId:' compact '});
|
||||
assert.deepEqual(copyReads.at(-1),{includeFilled:true,pageId:'one',fieldId:'compact'});
|
||||
assert.deepEqual(await actions.write_copy_fields({revision,items:[]}), {appliedLayers:[],revision});
|
||||
@ -532,16 +533,14 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
assert.equal(modelCalls,0);
|
||||
|
||||
const proposal={revision,items:[{layer:7,text:'光线落在桌面',sources:['P01'],pictures:['lamp']}]};
|
||||
for(const phase of ['permission','apply']){
|
||||
waitingAt=phase;
|
||||
const result=await actions.write_copy_fields(proposal);
|
||||
assert.equal(result.retryWrite,true);
|
||||
assert.equal(result.revision,revision);
|
||||
assert.deepEqual(result.appliedLayers,[]);
|
||||
assert.match(result.reason,/画布暂不可用/u);
|
||||
assert.equal(fields[0].currentText,'');
|
||||
}
|
||||
waitingAt=undefined;
|
||||
copyWaiting=true;
|
||||
const waiting=await actions.write_copy_fields(proposal);
|
||||
assert.equal(waiting.retryWrite,true);
|
||||
assert.equal(waiting.revision,revision);
|
||||
assert.deepEqual(waiting.appliedLayers,[]);
|
||||
assert.match(waiting.reason,/画布暂不可用/u);
|
||||
assert.equal(fields[0].currentText,'');
|
||||
copyWaiting=false;
|
||||
const beforeIndependentEdit=await actions.read_copy_fields({});
|
||||
revision++;
|
||||
assert.deepEqual((await actions.write_copy_fields({...proposal,revision:beforeIndependentEdit.revision})).appliedLayers,[7]);
|
||||
@ -549,8 +548,8 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
fields[0].currentText='用户手改';
|
||||
revision++;
|
||||
const rejected=await actions.write_copy_fields({...proposal,revision:beforeUserEdit.revision});
|
||||
assert.equal(rejected.retryWrite,true);
|
||||
assert.deepEqual(rejected.appliedLayers,[]);
|
||||
assert.deepEqual(rejected.rejected,[{layer:7,reason:'原文已变化'}]);
|
||||
assert.equal(fields[0].currentText,'用户手改');
|
||||
const first=await generateAndWait(actions,{slotId:'lamp',source:'generate',prompt:'场景桌面上的一盏灯',prefer2k:true});
|
||||
assert.equal(first.phase,'unknown');
|
||||
@ -626,14 +625,16 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
const [{checks:lampChecks},{checks:switchChecks}]=(await actions.review_image_slots({slotIds:['lamp','switch']})).pictures;
|
||||
assert.equal(lampChecks.at(-1).verdict,'pass');
|
||||
assert.equal(switchChecks.at(-1).phase,'checking');
|
||||
await actions.write_copy_fields({revision,items:[{layer:7,text:'台灯照亮桌面',sources:['P01'],pictures:['lamp']}]});
|
||||
const beforeWrite=await actions.read_copy_fields({});
|
||||
await actions.write_copy_fields({revision:beforeWrite.revision,items:[{layer:7,text:'台灯照亮桌面',sources:['P01'],pictures:['lamp']}]});
|
||||
assert.equal(fields[0].currentText,'台灯照亮桌面');
|
||||
assert.equal(modelCalls,3,'reading progress must not start another reviewer');
|
||||
gate.resolve();
|
||||
await actions.await_image_slots({slotIds:['switch']});
|
||||
assert.equal((await actions.review_image_slots({slotIds:['switch']})).pictures[0].checks[0].verdict,'pass');
|
||||
const reason='模板允许缺规格时留空';
|
||||
const cleared=await actions.write_copy_fields({revision,items:[{layer:7,text:'',sources:[],pictures:[],reason}]});
|
||||
const beforeClear=await actions.read_copy_fields({});
|
||||
const cleared=await actions.write_copy_fields({revision:beforeClear.revision,items:[{layer:7,text:'',sources:[],pictures:[],reason}]});
|
||||
assert.deepEqual(cleared.appliedLayers,[7]);
|
||||
assert.equal(fields[0].currentText,'');
|
||||
const saved=JSON.parse(await fs.readFile(path.join(dir,'production-detail-ink.json'),'utf8'));
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
//! Pi owns the local conversation. Rust owns credentials, identity and native commands.
|
||||
use photocraft_ui_egui::jiansun::BridgeFailure;
|
||||
use photocraft_ui_egui::jiansun::{BridgeFailure, PiCanvasSnapshot};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use super::{json, Backend, PathBuf, R, Value, now, fs, Duration, write_json, Path, read_json, UPSTREAM, hash, mpsc, Event, Uuid, Arc, agent_daemon};
|
||||
#[path = "jiansun_rule_cache.rs"]
|
||||
mod rule_cache;
|
||||
@ -524,7 +525,26 @@ fn combined_unknown(reported: bool, pending: R<Vec<Value>>) -> bool {
|
||||
reported || pending.map_or(true, |items| !items.is_empty())
|
||||
}
|
||||
|
||||
type CanvasReply = Result<(Value, Option<Arc<super::Document>>), BridgeFailure>;
|
||||
type CanvasReply = Result<(Value, Option<PiCanvasSnapshot>), BridgeFailure>;
|
||||
|
||||
fn queue_canvas_screen(
|
||||
pool: &super::reads::ReadPool,
|
||||
cancellation: Arc<AtomicBool>,
|
||||
render: impl FnOnce() -> R<Value> + Send + 'static,
|
||||
reply: impl FnOnce(Value) + Send + 'static,
|
||||
) -> Result<(), &'static str> {
|
||||
pool.submit(move || {
|
||||
let cancelled = || BridgeFailure::new("cancelled", false, false, "原制作回合已停止,未返回画面");
|
||||
let result = if cancellation.load(Ordering::SeqCst) { Err(cancelled()) } else {
|
||||
let rendered = render();
|
||||
if cancellation.load(Ordering::SeqCst) { Err(cancelled()) } else { rendered.map_err(BridgeFailure::from) }
|
||||
};
|
||||
reply(match result {
|
||||
Ok(value) => json!({"value":value}),
|
||||
Err(error) => json!({"error":error.wire()}),
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
fn take_late_workflow_delegations(replies: &mut Vec<mpsc::Receiver<CanvasReply>>) -> Vec<Value> {
|
||||
let mut ready = Vec::new();
|
||||
@ -641,6 +661,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
|
||||
let mut request_ids = std::collections::HashSet::new();
|
||||
let mut workflow_children = WorkflowChildren::default();
|
||||
let mut detail_image_reads = None;
|
||||
let mut canvas_screen_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())
|
||||
@ -730,7 +751,7 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
|
||||
let archive_ctx = ctx.clone();
|
||||
pool.submit(move || {
|
||||
let result = if archive { reader.detail_archive(doc, &v, &archive_events, &archive_ctx) }
|
||||
else { reader.read_detail_review_images(doc, &v, snapshot.as_deref()) };
|
||||
else { reader.read_detail_review_images(doc, &v, snapshot.as_ref().map(|snapshot| snapshot.document.as_ref())) };
|
||||
let reply = match result {
|
||||
Ok(value) => json!({"value":value}),
|
||||
Err(error) => json!({"error":BridgeFailure::from(error).wire()}),
|
||||
@ -744,13 +765,18 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
|
||||
continue;
|
||||
}
|
||||
if action == "pi-product-screen" {
|
||||
let result = snapshot.as_deref().ok_or("缺少实际工作画布".to_owned())
|
||||
.and_then(|canvas| super::canvas_workspace::read_production_screen(canvas, &v));
|
||||
let reply = match result {
|
||||
Ok(value) => json!({"value":value}),
|
||||
Err(error) => json!({"error":BridgeFailure::from(error).wire()}),
|
||||
};
|
||||
daemon.reply(&daemon_run, &value["id"], &reply)?;
|
||||
let queued = if let Some(PiCanvasSnapshot { document, cancellation }) = snapshot {
|
||||
let pool = canvas_screen_reads.get_or_insert_with(super::reads::ReadPool::canvas_screens);
|
||||
let transport = daemon.clone();
|
||||
let run = daemon_run.clone();
|
||||
let id = value["id"].clone();
|
||||
queue_canvas_screen(pool, cancellation,
|
||||
move || super::canvas_workspace::read_production_screen(&document, &v),
|
||||
move |reply| { let _ = transport.reply(&run, &id, &reply); })
|
||||
} else { Err("缺少实际工作画布") };
|
||||
if let Err(error) = queued {
|
||||
daemon.reply(&daemon_run, &value["id"], &json!({"error":BridgeFailure::from(error).wire()}))?;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if action == "pi-template-image" {
|
||||
@ -823,6 +849,40 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pi_screen_render_does_not_hold_save_cancel_or_read_receipts() {
|
||||
let pool = super::super::reads::ReadPool::canvas_screens();
|
||||
let cancellation = Arc::new(AtomicBool::new(false));
|
||||
let render_cancellation = cancellation.clone();
|
||||
let (started, running) = mpsc::channel();
|
||||
let (release, gate) = mpsc::channel();
|
||||
let (reply, receipts) = mpsc::channel();
|
||||
let screen = reply.clone();
|
||||
let dispatch = std::thread::spawn(move || {
|
||||
queue_canvas_screen(&pool, render_cancellation, move || {
|
||||
started.send(()).unwrap();
|
||||
gate.recv().unwrap();
|
||||
Ok(json!({"revision":7}))
|
||||
}, move |value| screen.send((1, value)).unwrap()).unwrap();
|
||||
for (id, action) in [(2, "save"), (3, "pi-ui-cancel"), (4, "pi-state")] {
|
||||
reply.send((id, json!({"value":action}))).unwrap();
|
||||
}
|
||||
});
|
||||
let timeout = Duration::from_secs(2);
|
||||
running.recv_timeout(timeout).unwrap();
|
||||
for (id, action) in [(2, "save"), (3, "pi-ui-cancel"), (4, "pi-state")] {
|
||||
assert_eq!(receipts.recv_timeout(timeout).unwrap(), (id, json!({"value":action})));
|
||||
}
|
||||
assert!(receipts.try_recv().is_err());
|
||||
cancellation.store(true, Ordering::SeqCst);
|
||||
release.send(()).unwrap();
|
||||
let (id, receipt) = receipts.recv_timeout(timeout).unwrap();
|
||||
assert_eq!(id, 1);
|
||||
assert_eq!(receipt["error"]["category"], "cancelled");
|
||||
assert!(receipt.get("value").is_none(), "the cancelled round must not receive the rendered data");
|
||||
dispatch.join().unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn knowledge_selection_uses_the_resource_set_without_a_platform_rule_binding() {
|
||||
let creation=json!({"brief":{"brandId":"ekb:brand:顾家","brandName":"顾家","categoryId":"ekb:category:电脑桌","categoryName":"电脑桌"},
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
//! Bounded workers for authenticated catalogue/image GETs. Never run model tasks here.
|
||||
//! Bounded workers for catalogue, image and canvas evidence reads.
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
|
||||
type Task = Box<dyn FnOnce() + Send + 'static>;
|
||||
@ -21,6 +21,11 @@ impl ReadPool {
|
||||
Self::with_limits(2, 9)
|
||||
}
|
||||
|
||||
pub(super) fn canvas_screens() -> Self {
|
||||
// Keep full-screen compositing separate from candidate and reference reads.
|
||||
Self::with_limits(1, 4)
|
||||
}
|
||||
|
||||
fn with_limits(workers: usize, pending: usize) -> Self {
|
||||
let (queue, receive) = mpsc::sync_channel::<Task>(pending);
|
||||
let receive = Arc::new(Mutex::new(receive));
|
||||
|
||||
@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::{HashMap, VecDeque},
|
||||
sync::{Arc, mpsc},
|
||||
sync::{Arc, atomic::AtomicBool, mpsc},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
@ -97,12 +97,18 @@ impl std::fmt::Display for BridgeFailure {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.message.fmt(f) }
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PiCanvasSnapshot {
|
||||
pub document: Arc<Document>,
|
||||
pub cancellation: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
pub enum Event {
|
||||
Json(String, Result<Value, String>),
|
||||
Opened(Box<Document>, Value),
|
||||
Saved(u64, u64, Value),
|
||||
Preview(Value, egui::ColorImage),
|
||||
PiAction(String, Value, mpsc::Sender<Result<(Value, Option<Arc<Document>>), BridgeFailure>>),
|
||||
PiAction(String, Value, mpsc::Sender<Result<(Value, Option<PiCanvasSnapshot>), BridgeFailure>>),
|
||||
CreationCanvas(Box<Document>, Value),
|
||||
SlotCanvas(Box<Document>, Value),
|
||||
SlotPreview(Value, Option<Box<photocraft_doc::Layer>>),
|
||||
@ -3530,7 +3536,7 @@ impl Workspace {
|
||||
let _ = reply.send(Err(BridgeFailure::new("cancelled", false, false, "客户端正在退出,原操作可在重新打开后核查")));
|
||||
return;
|
||||
}
|
||||
let result = if matches!(method.as_str(), "pi-write-request" | "pi-edit" | "pi-workflow-propose" | "pi-workflow-execute" | "pi-native-call") && !self.enforce_canvas_scope(app) {
|
||||
let result = if matches!(method.as_str(), "pi-write-request" | "pi-edit" | "pi-workflow-propose" | "pi-workflow-execute" | "pi-native-call" | "pi-detail-copy-apply") && !self.enforce_canvas_scope(app) {
|
||||
Err(BridgeFailure::new("revision_conflict", false, false, "画布与当前模板或花色不一致,本轮未获画布写入许可"))
|
||||
} else if method == "creation-allowed" {
|
||||
creation::allowed(self, app, &input).map_err(BridgeFailure::from)
|
||||
@ -3545,8 +3551,11 @@ impl Workspace {
|
||||
{
|
||||
self.queue_canvas_feedback(doc, json!({"nativeLayerId":layer}), "图层已更新");
|
||||
}
|
||||
let snapshot = (method == "pi-product-screen" || method == "pi-detail-images" && value["adopted"] == true)
|
||||
.then(|| app.session.active().map(|active| active.doc.clone())).flatten();
|
||||
let snapshot = if method == "pi-product-screen" || method == "pi-detail-images" && value["adopted"] == true {
|
||||
app.session.active().zip(self.agent_native.cancellation()).map(|(active, cancellation)| {
|
||||
PiCanvasSnapshot { document: active.doc.clone(), cancellation }
|
||||
})
|
||||
} else { None };
|
||||
(value, snapshot)
|
||||
});
|
||||
let _ = reply.send(result);
|
||||
|
||||
@ -78,6 +78,10 @@ impl State {
|
||||
if let Some(token) = &self.cancellation { token.store(true, Ordering::SeqCst); }
|
||||
}
|
||||
|
||||
pub(super) fn cancellation(&self) -> Option<Arc<AtomicBool>> {
|
||||
self.cancellation.clone()
|
||||
}
|
||||
|
||||
pub(super) fn last_receipt(&self) -> Option<&Value> { self.receipt.as_ref() }
|
||||
|
||||
pub(super) fn recent_receipts(&self) -> Value {
|
||||
@ -259,10 +263,8 @@ fn identity(w: &Workspace, app: &PhotocraftApp, input: &Value) -> Result<(u64, u
|
||||
pub(super) fn guard_with_background_save(w: &Workspace, app: &PhotocraftApp, input: &Value, read_only: bool) -> Result<(u64, usize, u64), String> {
|
||||
let current = identity(w, app, input)?;
|
||||
if w.pi_request_scope["productProduction"] == true {
|
||||
if w.agent_native.cancelled(input["run"].as_str().unwrap_or("")) || current.2 > MAX_INTEGER {
|
||||
return Err("当前制作会话已取消".into());
|
||||
}
|
||||
if !read_only && (w.pi_write_blocked || w.agent_effects_paused || current.2 != w.expected_revision) {
|
||||
guard_production_access(w, input, current.2, read_only)?;
|
||||
if !read_only && current.2 != w.expected_revision {
|
||||
return Err("写入修订已变化,请重新读取画布".into());
|
||||
}
|
||||
return Ok(current);
|
||||
@ -285,6 +287,22 @@ pub(super) fn guard_with_background_save(w: &Workspace, app: &PhotocraftApp, inp
|
||||
Ok(current)
|
||||
}
|
||||
|
||||
fn guard_production_access(w: &Workspace, input: &Value, revision: u64, read_only: bool) -> Result<(), String> {
|
||||
if w.agent_native.cancelled(input["run"].as_str().unwrap_or("")) || revision > MAX_INTEGER {
|
||||
return Err("当前制作会话已取消".into());
|
||||
}
|
||||
if !read_only && (w.pi_write_blocked || w.agent_effects_paused) {
|
||||
return Err("本轮制作画布写入已停止".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn guard_production_field_write(w: &Workspace, app: &PhotocraftApp, input: &Value) -> Result<u64, String> {
|
||||
let (_, _, revision) = identity(w, app, input)?;
|
||||
guard_production_access(w, input, revision, false)?;
|
||||
Ok(revision)
|
||||
}
|
||||
|
||||
fn safe_services(app: &PhotocraftApp) -> Result<(), String> {
|
||||
if app.services.automation_command.is_none() || app.services.automation_authorize.is_none() {
|
||||
return Err("原生自动化安全门禁未配置".into());
|
||||
|
||||
@ -344,7 +344,8 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
}
|
||||
"pi-detail-copy-fields" => {
|
||||
if w.pi_request_scope["wholeDetail"] != true || w.pi_write_blocked { return Err("当前回合无整套详情页文案授权".into()); }
|
||||
let doc = &app.session.active().ok_or("原项目未打开")?.doc;
|
||||
let active = app.session.active().ok_or("原项目未打开")?;
|
||||
let doc = &active.doc;
|
||||
let production = w.pi_request_scope["productProduction"] == true;
|
||||
let include_filled = input["includeFilled"] == true && production;
|
||||
let scope = |key: &str| input[key].as_str().map(str::trim)
|
||||
@ -354,23 +355,29 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
let mapping = super::canvas_workspace::document_mapping(doc).ok_or("缺少模板文案映射")?;
|
||||
let pages: Vec<_> = mapping["outputs"].as_array().into_iter().flatten()
|
||||
.filter_map(|page| page["documentId"].as_str()).collect();
|
||||
return Ok(json!({"fields":fields,"pages":pages}));
|
||||
return Ok(json!({"fields":fields,"pages":pages,"revision":active.revision}));
|
||||
}
|
||||
Ok(json!(fields.into_iter().filter(|field| pending_detail_copy(w, doc, field)).collect::<Vec<_>>()))
|
||||
}
|
||||
"pi-detail-copy-apply" => {
|
||||
if w.pi_request_scope["wholeDetail"] != true || w.pi_write_blocked || !w.allow_apply || !w.queue.is_empty() {
|
||||
let production = w.pi_request_scope["productProduction"] == true;
|
||||
let match_fields = input["matchFields"] == true;
|
||||
if w.pi_request_scope["wholeDetail"] != true || w.pi_write_blocked || !w.queue.is_empty()
|
||||
|| match_fields && !production || !match_fields && !w.allow_apply
|
||||
{
|
||||
return Err("文案未取得当前画布写入许可,原内容保留".into());
|
||||
}
|
||||
let active = app.session.active().ok_or("原项目未打开")?;
|
||||
if active.revision != w.expected_revision || input["revision"].as_u64() != Some(active.revision)
|
||||
|| super::canvas_workspace::detail_write_waiting(w, app)
|
||||
{
|
||||
let revision = active.revision;
|
||||
w.allow_apply = false;
|
||||
return Ok(json!({"retryWrite":true,"revision":revision}));
|
||||
if match_fields {
|
||||
let live = super::agent_native::guard_production_field_write(w, app, input)?;
|
||||
input["revision"].as_u64().filter(|revision| *revision <= live).ok_or("请先读取本轮文字格及其修订号")?;
|
||||
}
|
||||
if super::canvas_workspace::detail_write_waiting(w, app)
|
||||
|| !match_fields && (active.revision != w.expected_revision || input["revision"].as_u64() != Some(active.revision))
|
||||
{
|
||||
if !match_fields { w.allow_apply = false; }
|
||||
return Ok(json!({"retryWrite":true,"revision":active.revision}));
|
||||
}
|
||||
let production = w.pi_request_scope["productProduction"] == true;
|
||||
let fields = detail_copy_fields(&active.doc, production, None, None);
|
||||
let items = input["items"].as_array().ok_or("文字格应为列表")?;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
@ -385,15 +392,20 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
continue;
|
||||
};
|
||||
let current = field["currentText"].as_str().unwrap_or_default();
|
||||
if w.product_layer_protected(id) { continue; }
|
||||
if current.trim().is_empty() {
|
||||
let writable = || active.doc.path_of(id).is_some_and(|path| {
|
||||
let locks = active.doc.locks_at(&path);
|
||||
!(locks.all || locks.position || locks.pixels)
|
||||
});
|
||||
if match_fields {
|
||||
if w.product_layer_protected(id) || item["expectedText"].as_str() != Some(current) || !writable() {
|
||||
rejected.push(json!({"layer":layer,"reason":"文字格原文或编辑权限已变化,保留当前内容"}));
|
||||
continue;
|
||||
}
|
||||
} else if w.product_layer_protected(id) {
|
||||
continue;
|
||||
} else if current.trim().is_empty() {
|
||||
if !w.detail_layer_unchanged(&active.doc, id) { continue; }
|
||||
} else if item["expectedText"].as_str() != Some(current)
|
||||
|| active.doc.path_of(id).is_none_or(|path| {
|
||||
let locks = active.doc.locks_at(&path);
|
||||
locks.all || locks.position || locks.pixels
|
||||
})
|
||||
{
|
||||
} else if item["expectedText"].as_str() != Some(current) || !writable() {
|
||||
continue;
|
||||
}
|
||||
let text = item["text"].as_str().filter(|text| production || !text.trim().is_empty()).ok_or("缺少填写文字")?;
|
||||
@ -426,7 +438,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
let count = edits.len();
|
||||
let remaining = fields.iter().filter(|field| pending_detail_copy(w, &active.doc, field)
|
||||
&& !edits.iter().any(|(layer, _)| field["layer"] == layer.0)).count();
|
||||
if count == 0 { return Ok(json!({"applied":0,"appliedLayers":[],"pending":remaining,"rejected":rejected})); }
|
||||
if count == 0 { return Ok(json!({"applied":0,"appliedLayers":[],"pending":remaining,"rejected":rejected,"revision":active.revision})); }
|
||||
if production {
|
||||
photocraft_engine::type_cmds::replace_template_layer_texts(&mut app.session, "回填商品文案", &edits)
|
||||
} else {
|
||||
@ -457,7 +469,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
w.draft_changed=true;
|
||||
w.sync_dirty=true;
|
||||
Ok(json!({"applied":count,"appliedLayers":edits.iter().map(|(layer, _)| layer.0).collect::<Vec<_>>(),
|
||||
"pending":remaining,"rejected":rejected,"layoutWarnings":layout_warnings,"styleMappings":style_mappings}))
|
||||
"pending":remaining,"rejected":rejected,"layoutWarnings":layout_warnings,"styleMappings":style_mappings,"revision":active.revision}))
|
||||
}
|
||||
"pi-detail-archive" => {
|
||||
if w.pi_request_scope["productProduction"] != true || w.pi_write_blocked || w.agent_effects_paused {
|
||||
@ -797,6 +809,25 @@ mod tests {
|
||||
assert!(error.contains("仅允许当前本机Agent会话"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_screen_receipt_freezes_the_document_and_carries_its_run_cancellation() {
|
||||
let (mut w, mut app, input) = activity_fixture();
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
let (reply, receive) = mpsc::channel();
|
||||
let revision = app.session.active().unwrap().revision;
|
||||
w.receive_event(&mut app, &egui::Context::default(), crate::jiansun::Event::PiAction(
|
||||
"pi-product-screen".into(), json!({"run":input["run"],"page":0}), reply));
|
||||
let (metadata, snapshot) = receive.try_recv().unwrap().unwrap();
|
||||
let snapshot = snapshot.unwrap();
|
||||
assert_eq!(metadata["revision"], revision);
|
||||
assert!(std::sync::Arc::ptr_eq(&snapshot.document, &app.session.active().unwrap().doc));
|
||||
app.session.execute("type.create", json!({"text":"后续手改","size":18})).unwrap();
|
||||
assert_ne!(snapshot.document.layer_count(), app.session.active().unwrap().doc.layer_count());
|
||||
w.handover();
|
||||
assert!(snapshot.cancellation.load(std::sync::atomic::Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thinking_status_updates_its_entry_and_keeps_private_text_out_of_the_transcript() {
|
||||
let (mut w, mut app, mut input) = activity_fixture();
|
||||
@ -1237,6 +1268,65 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_copy_matches_the_sampled_fields_instead_of_the_document_revision() {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"width":200,"height":300})).unwrap();
|
||||
let [title, subtitle, locked] = ["原始标题", "原始副标题", "原始规格"].map(|text|
|
||||
session.execute("type.create", json!({"text":text,"size":18})).unwrap()["layer"].as_u64().unwrap());
|
||||
session.edit("映射文字格", |doc, _| {
|
||||
doc.metadata.text.push(("jiansun.slot-mapping.v1".into(), json!({"outputs":[
|
||||
{"documentId":"S01","mapping":{"fields":[
|
||||
{"kind":"text","nativeLayerId":title,"fieldId":"title"},
|
||||
{"kind":"text","nativeLayerId":subtitle,"fieldId":"subtitle"},
|
||||
{"kind":"text","nativeLayerId":locked,"fieldId":"spec"}
|
||||
]}}
|
||||
]}).to_string()));
|
||||
Ok(())
|
||||
}).unwrap();
|
||||
let doc = session.active().unwrap().doc.id.0;
|
||||
let mut app = PhotocraftApp::new(session, crate::Services::default());
|
||||
let (tx, _) = mpsc::channel();
|
||||
let (_, rx) = mpsc::channel();
|
||||
let mut w = Workspace::new(tx, rx);
|
||||
w.busy = None;
|
||||
w.account = json!({"id":"acct"});
|
||||
w.open_projects.insert(doc, "copy-fixture".into());
|
||||
let run = "12345678-1234-1234-1234-123456789012";
|
||||
action(&mut w, &mut app, "pi-begin", &json!({"run":run,"text":"制作详情页"})).unwrap();
|
||||
w.pi_request_scope["wholeDetail"] = json!(true);
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
let snapshot = action_impl(&mut w, &mut app, None, "pi-detail-copy-fields",
|
||||
&json!({"run":run,"documentId":doc,"includeFilled":true}), true).unwrap();
|
||||
assert_eq!(snapshot["revision"], app.session.active().unwrap().revision);
|
||||
assert_eq!(snapshot["fields"][0]["currentText"], "原始标题");
|
||||
app.session.execute("type.edit", json!({"layer":title,"text":"用户标题"})).unwrap();
|
||||
app.session.edit("锁定规格", |doc, _| {
|
||||
doc.layer_mut(photocraft_doc::LayerId(locked)).unwrap().locks.all = true;
|
||||
Ok(())
|
||||
}).unwrap();
|
||||
let revision = app.session.active().unwrap().revision;
|
||||
assert!(snapshot["revision"].as_u64().unwrap() < revision);
|
||||
let apply = json!({"run":run,"documentId":doc,"revision":snapshot["revision"],"matchFields":true,"items":[
|
||||
{"layer":title,"text":"小壹标题","expectedText":snapshot["fields"][0]["currentText"]},
|
||||
{"layer":subtitle,"text":"小壹副标题","expectedText":snapshot["fields"][1]["currentText"]},
|
||||
{"layer":locked,"text":"小壹规格","expectedText":snapshot["fields"][2]["currentText"]}
|
||||
]});
|
||||
assert!(!w.allow_apply, "field writes must not depend on an earlier global write grant");
|
||||
let receipt = action_impl(&mut w, &mut app, None, "pi-detail-copy-apply", &apply, true).unwrap();
|
||||
assert_eq!(receipt["appliedLayers"], json!([subtitle]));
|
||||
assert_eq!(receipt["revision"], revision + 1);
|
||||
assert_eq!(receipt["rejected"].as_array().unwrap().iter().map(|rejection| rejection["layer"].as_u64().unwrap())
|
||||
.collect::<Vec<_>>(), vec![title, locked]);
|
||||
let read = action_impl(&mut w, &mut app, None, "pi-detail-copy-fields",
|
||||
&json!({"run":run,"documentId":doc,"includeFilled":true}), true).unwrap();
|
||||
assert_eq!(read["fields"][0]["currentText"], "用户标题");
|
||||
assert_eq!(read["fields"][1]["currentText"], "小壹副标题");
|
||||
assert_eq!(read["fields"][2]["currentText"], "原始规格");
|
||||
w.agent_native.cancel();
|
||||
assert!(action_impl(&mut w, &mut app, None, "pi-detail-copy-apply", &apply, true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detail_copy_preserves_a_user_edit_and_applies_the_rest_at_the_new_revision() {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user