diff --git a/apps/detail-agent-pi/src/enterprise-knowledge.mjs b/apps/detail-agent-pi/src/enterprise-knowledge.mjs index 95758fcb..f5684fbe 100644 --- a/apps/detail-agent-pi/src/enterprise-knowledge.mjs +++ b/apps/detail-agent-pi/src/enterprise-knowledge.mjs @@ -5,6 +5,7 @@ import fs from 'node:fs/promises'; import { createReadStream } from 'node:fs'; import { createHash } from 'node:crypto'; import { nativeKnowledgeFetch } from './native-knowledge-http.mjs'; +import { knowledgeTiming, networkFailure, retryKnowledgeRead } from './knowledge-network.mjs'; import origins from './enterprise-knowledge-origins.json' with { type: 'json' }; import toolNames from './enterprise-tool-names.json' with { type: 'json' }; @@ -40,7 +41,7 @@ function boundedJSON(raw, contentType) { try { return JSON.parse(payload); } catch { throw Error('企业知识库响应格式无效'); } } function httpFailure(status) { - const label = status === 401 ? '认证失败' : status === 403 ? '无权限' : status === 404 ? '资料不存在或不可读取' : status === 410 ? '资料已下线' : status === 409 || status === 412 ? '版本冲突' : status === 428 ? '续读需要revision' : status === 429 ? '额度或访问频率受限' : '请求失败'; + const label = status === 401 ? '登录已失效,请重新登录' : status === 403 ? '无权限' : status === 404 ? '资料不存在或不可读取' : status === 410 ? '资料已下线' : status === 409 || status === 412 ? '版本冲突' : status === 428 ? '续读需要revision' : status === 429 ? '额度或访问频率受限' : status >= 500 ? '服务端异常,请稍后重试' : '请求失败'; return `企业知识库${label}(HTTP ${status})`; } function toolFailure(reply) { @@ -57,9 +58,10 @@ function toolFailure(reply) { } function failure(status, value={}, retryAfter) { const seconds=Number(value?.retryAfterSeconds??retryAfter); - const reason = typeof value?.error === 'string' ? ':' + value.error : ''; + const reason = status < 500 && typeof value?.error === 'string' ? ':' + value.error : ''; const error=Error(httpFailure(status)+reason+(status===429&&seconds>0?`,${Math.ceil(seconds)}秒后可重试`:'')); error.status=status; + error.code=value?.code; if(status===429&&Number.isFinite(seconds)&&seconds>0) { error.retryAfterSeconds=Math.ceil(seconds); error.usage=value.usage; } return error; } @@ -77,22 +79,19 @@ async function request(origin,path,{body,session,protocol='2025-11-25',fetchImpl signal?.throwIfAborted(); if (!path.startsWith('/') || path.startsWith('//')) throw Error('企业知识库路径无效'); // The native pool starts its request timeout when a host becomes available. - const timing = fetchImpl === nativeKnowledgeFetch ? {signal,timeoutMs} : - {signal:AbortSignal.any([signal,AbortSignal.timeout(timeoutMs)].filter(Boolean))}; + const timing = knowledgeTiming(fetchImpl, signal, timeoutMs); let response; try { response=await fetchImpl(origin+path,{method:body===undefined?'GET':'POST',redirect:'manual',...timing,headers:{Accept:'application/json, text/event-stream',...(body===undefined?{}:{'Content-Type':'application/json'}),...(session?{'Mcp-Session-Id':session}:{}),'MCP-Protocol-Version':protocol},...(body===undefined?{}:{body:JSON.stringify(body)})}); } - catch (cause) { signal?.throwIfAborted(); if(cause.network===false)throw cause; const error=Error('企业知识库网络不可达');error.network=true;throw error; } + catch (cause) { throw networkFailure(cause, signal); } + if ([401,403,404].includes(response.status)) { + await response.body?.cancel(); + throw failure(response.status); + } const reader=response.body?.getReader(); if (!reader) {if(!response.ok)throw failure(response.status);return {value:null,headers:response.headers};} let size=0; const chunks=[]; for (;;) { - const {done,value}=await reader.read().catch(cause => { - signal?.throwIfAborted(); - if(cause.network===false)throw cause; - const error=Error('企业知识库网络不可达'); - error.network=true; - throw error; - }); + const {done,value}=await reader.read().catch(cause => { throw networkFailure(cause, signal); }); if (done) break; size+=value.byteLength; if (size>maxBytes) { @@ -120,13 +119,15 @@ export class EnterpriseKnowledge { if (this.connection?.intranet === endpoints[0]) return this.connection; let origin; for (const candidate of endpoints) { - try { const health=await request(candidate,'/healthz',{fetchImpl:this.fetchImpl,signal,timeoutMs:2500}); if (health.value?.status!=='ok'||health.value?.service!=='enterprise-knowledge-base') throw Error('企业知识库身份校验失败'); origin=candidate;break; } + try { const health=await retryKnowledgeRead(() => request(candidate,'/healthz',{fetchImpl:this.fetchImpl,signal,timeoutMs:2500}),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===endpoints.at(-1)) throw error; } } let seq=0, session, protocol='2025-11-25'; const rpc=async(method,params,notification=false,options={})=>{ const id=notification?undefined:++seq; - const {value,headers}=await request(origin,'/mcp',{session,protocol,fetchImpl:this.fetchImpl,signal:options.signal,maxBytes:params?.name==='read_image'?12_000_000:2_000_000,body:{jsonrpc:'2.0',method,...(params?{params}:{}),...(id?{id}:{})}}); + const read=()=>request(origin,'/mcp',{session,protocol,fetchImpl:this.fetchImpl,signal:options.signal,maxBytes:params?.name==='read_image'?12_000_000:2_000_000,body:{jsonrpc:'2.0',method,...(params?{params}:{}),...(id?{id}:{})}}); + const {value,headers}=await (method==='tools/list'||method==='tools/call'&&names.includes(params.name) + ? retryKnowledgeRead(read, options.signal) : read()); if(method==='initialize')session=headers.get('mcp-session-id')||undefined; if(notification) {if(value?.error)throw Error('企业知识库协议错误');return;} if(!value || value.jsonrpc!=='2.0'||value.id!==id||value.error||!value.result) throw Error('企业知识库协议错误'); @@ -227,12 +228,19 @@ export class EnterpriseKnowledge { if(received>=metadata.size){await fs.rm(part,{force:true});received=0;} const {origin}=reply; let response; - try { response=await this.fetchImpl(origin+metadata.downloadPath,{method:'GET',redirect:'manual',signal,headers:{...metadata.downloadHeaders,...(received?{Range:`bytes=${received}-`}:{})}}); } + try { + response=await retryKnowledgeRead(async()=>{ + const reply=await this.fetchImpl(origin+metadata.downloadPath,{method:'GET',redirect:'manual', + ...knowledgeTiming(this.fetchImpl,signal,210_000), + headers:{...metadata.downloadHeaders,...(received?{Range:`bytes=${received}-`}:{})}}); + if (![502,503,504].includes(reply.status)) return reply; + const value=await reply.json().catch(error=>{if(!(error instanceof SyntaxError))throw error;}); + throw failure(reply.status,value,reply.headers.get('retry-after')); + },signal); + } catch (cause) { - signal?.throwIfAborted(); - if(cause.network===false)throw cause; - if(this.connection===connection)this.connection=undefined; - throw Object.assign(Error('企业知识库附件下载中断,可继续同一版本',{cause}),{network:true}); + if(cause.network && this.connection===connection)this.connection=undefined; + throw cause; } if(!response.ok){ let value;try{value=await response.json();}catch{signal?.throwIfAborted();} @@ -255,9 +263,9 @@ export class EnterpriseKnowledge { 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});}} } catch(error) { - signal?.throwIfAborted(); - if(error.network && this.connection===connection)this.connection=undefined; - throw error; + const failure = networkFailure(error,signal); + if(failure.network && this.connection===connection)this.connection=undefined; + throw failure; } finally {await handle.close();} signal?.throwIfAborted(); diff --git a/apps/detail-agent-pi/src/enterprise-templates.mjs b/apps/detail-agent-pi/src/enterprise-templates.mjs index 76ff4f60..3fb0a102 100644 --- a/apps/detail-agent-pi/src/enterprise-templates.mjs +++ b/apps/detail-agent-pi/src/enterprise-templates.mjs @@ -4,10 +4,11 @@ import {setTimeout as delay} from 'node:timers/promises'; import { EnterpriseKnowledge } from './enterprise-knowledge.mjs'; import { openXiaoyiSkills } from './xiaoyi-release.mjs'; import { normalizeTemplateMapping } from './template-mapping.mjs'; -import { digest } from './store.mjs'; +import { atomic, digest } from './store.mjs'; import { EnterpriseContext } from './enterprise-context.mjs'; import {resourceRequest,resourceSnapshot} from './enterprise-resource-map.mjs'; import {nativeKnowledgeFetch} from './native-knowledge-http.mjs'; +import {knowledgeTiming, retryKnowledgeRead, transientStatus} from './knowledge-network.mjs'; import origins from './enterprise-knowledge-origins.json' with {type:'json'}; async function waitForQuota(read, task) { @@ -17,7 +18,7 @@ async function waitForQuota(read, task) { task.signal?.throwIfAborted(); try { return await read(); } catch(error) { - if(error.network===true&&transientFailures { const ids = new Set(); return fields.map(field => { - if (!field || typeof field.id !== 'string' || !field.id.trim() || typeof field.label !== 'string' || !field.label.trim() || - !['text','number','select','boolean'].includes(field.type) || + const id=field?.id ?? field?.key, type=field?.type ?? field?.kind; + if (!field || typeof id !== 'string' || !id.trim() || typeof field.label !== 'string' || !field.label.trim() || + !['text','number','select','boolean','image'].includes(type) || + (field.imageRole !== undefined && typeof field.imageRole !== 'string') || + (field.multiple !== undefined && typeof field.multiple !== 'boolean') || (field.required !== undefined && typeof field.required !== 'boolean') || + (field.multiline !== undefined && typeof field.multiline !== 'boolean') || + (field.placeholder !== undefined && typeof field.placeholder !== 'string') || (field.help !== undefined && typeof field.help !== 'string') || (field.unit !== undefined && typeof field.unit !== 'string') || (field.options !== undefined && (!Array.isArray(field.options) || field.options.some(option => typeof option !== 'string'))) || - (field.type === 'select' && (!field.options || !field.options.length))) { + (type === 'select' && (!field.options || !field.options.length))) { throw Error('小壹模板产品资料字段格式无效'); } - if (ids.has(field.id)) throw Error('小壹模板产品资料字段编号重复'); - ids.add(field.id); + if (ids.has(id)) throw Error('小壹模板产品资料字段编号重复'); + ids.add(id); return { - id:field.id, label:field.label, type:field.type, + id, label:field.label, type, + ...(type === 'image' && {multiple:field.multiple ?? true}), + ...(field.imageRole !== undefined && {imageRole:field.imageRole}), ...(field.required !== undefined && {required:field.required}), + ...(field.multiline !== undefined && {multiline:field.multiline}), + ...(field.placeholder !== undefined && {placeholder:field.placeholder}), ...(field.help !== undefined && {help:field.help}), ...(field.unit !== undefined && {unit:field.unit}), ...(field.options !== undefined && {options:field.options}), @@ -430,20 +440,43 @@ export async function xiaoyiCatalog(input, {signal,fetch = nativeKnowledgeFetch, return origins[0]; }); } - let response; + const cache = input.root && path.join(input.root, 'catalog', 'index-' + digest(origin) + '.json'); + let rows, notice; try { - response = await fetch(new URL('/api/xiaoyi/v1/templates', origin), {method:'GET',signal}); + rows = await retryKnowledgeRead(async () => { + const response = await fetch(new URL('/api/xiaoyi/v1/templates', origin), { + method:'GET', redirect:'manual', ...knowledgeTiming(fetch, signal, 45_000), + }); + if (!response.ok) { + const messages = {401:'小壹知识库连接已失效,请重新登录素材库',403:'当前连接无权读取模板目录,请联系知识库管理员'}; + if (messages[response.status]) { + await response.body?.cancel(); + throw Object.assign(Error(messages[response.status]), {status:response.status}); + } + const body = await response.json().catch(error => { + if (!(error instanceof SyntaxError)) throw error; + }); + const message = body?.code === 'knowledge_session_misconfigured' ? '小壹知识库自动授权配置错误,请联系管理员' + : response.status >= 500 ? '模板目录服务端异常,请稍后重试' : '模板目录无法读取(HTTP ' + response.status + ')'; + throw Object.assign(Error(message), {status:response.status, code:body?.code, network:false}); + } + const data = await response.json(); + if (!Array.isArray(data.items)) throw Error('小壹模板目录格式无效'); + return data.items; + }, signal); } catch (error) { + signal?.throwIfAborted(); if (error.category === 'credential') throw Error('小壹知识库未连接,请在小壹设置中检测连接', {cause:error}); - throw error; + if (!cache || !(error.network || error.retryable || transientStatus(error.status, error.code))) throw error; + rows = await fs.readFile(cache, 'utf8').then(JSON.parse, e => { + if (e.code !== 'ENOENT') throw e; + }); + if (!Array.isArray(rows)) throw error; + notice = error.message + '。正在使用本机缓存模板,表单草稿已保留。'; } - if (!response.ok) { - const messages = {401:'小壹知识库连接已失效,请在小壹设置中检测连接',403:'当前连接无权读取模板目录,请联系知识库管理员'}; - throw Object.assign(Error(messages[response.status] ?? '模板目录读取失败(HTTP ' + response.status + ')'),{status:response.status}); - } - const data = await response.json(); - if (!Array.isArray(data.items)) throw Error('小壹模板目录格式无效'); - const rows = data.items; + signal?.throwIfAborted(); + if (cache && !notice) await atomic(cache, rows); + const diagnostic = notice ? {notice} : {}; const brandId = name => 'ekb:brand:' + name; const categoryId = name => 'ekb:category:' + name; if (input.action === 'choices' || input.action === 'brand') { @@ -464,24 +497,24 @@ export async function xiaoyiCatalog(input, {signal,fetch = nativeKnowledgeFetch, if (input.action === 'brand') { const brand = brands.get(selected); if (!brand) throw Error('当前制作模板目录没有所选品牌'); - return {brand}; + return {brand,...diagnostic}; } - return {catalog:{kind:input.kind,items:input.kind === 'brands' ? [...brands.values()] : brands.get(selected)?.categories ?? []}}; + return {catalog:{kind:input.kind,items:input.kind === 'brands' ? [...brands.values()] : brands.get(selected)?.categories ?? []},...diagnostic}; } const entries = rows.filter(item => item.brand === input.brandName && item.category === input.categoryName); if (input.action === 'catalog') { const query = input.query?.trim().toLocaleLowerCase() ?? ''; return {items:entries.filter(item => !query || (item.name + ' ' + item.templateId).toLocaleLowerCase().includes(query)) .map(item => ({id:item.templateId,key:item.templateId,name:item.name,brandId:input.brandId,categoryId:input.categoryId, - ...(item.intake != null && {intake:intakeMetadata(item.intake)})}))}; + ...(item.intake != null && {intake:intakeMetadata(item.intake)})})),...diagnostic}; } const item = entries.find(row => row.templateId === input.resourceSetId); if (!item) throw Error('所选模板已不在当前发布目录,请重新选择'); const labels = {detail:'详情页',main_images:'主图',sku_images:'SKU'}; const components = item.components.map(part => ({ - id:part.id,name:labels[part.id] ?? part.id,kind:part.id,status:'available',issues:[],previews:[] + id:part.id,name:labels[part.id] ?? part.id,kind:part.id,status:'available',issues:notice ? [notice] : [],previews:[] })); - if (input.action === 'resource-set') return {items:components}; + if (input.action === 'resource-set') return {items:components,...diagnostic}; const component = components.find(part => part.id === input.componentId); if (!component) throw Error('当前模板没有所选组件'); const projectDir = path.join(input.root,'catalog',digest([item.templateId,item.version])); @@ -491,10 +524,20 @@ export async function xiaoyiCatalog(input, {signal,fetch = nativeKnowledgeFetch, knowledgeVersion:item.knowledgeVersion,metadataOnly:true,intake:intakeMetadata(item.intake), },{signal,fetch,onProgress}); if (!packs[component.id]) throw Error('制作包缺少所选组件,请联系知识库管理员'); - return {items:[{...component,pack:packs[component.id]}]}; + return {items:[{...component,pack:packs[component.id]}],...diagnostic}; } export async function templateRequest(input,options) { + if (input.action === 'workbench-query') { + const query = typeof input.query === 'string' ? input.query.trim() : ''; + if ([...query].length < 2 || [...query].length > 500) throw Error('请填写 2 到 500 字的规范问题'); + const client = new EnterpriseKnowledge(); + await client.call('list_libraries', {}, options); + const { result } = await client.call('query_knowledge', { query, limit: 3, maxCharacters: 4000 }, options); + const sources = (result.fragments ?? []).slice(0, 3).flatMap(({ path, text }) => + typeof path === 'string' && typeof text === 'string' ? [{ path, text }] : []); + return { sources }; + } if (input.action === 'xiaoyi-pack') return xiaoyiPacks(input,options); if (['choices','brand','catalog','resource-set','resource-component'].includes(input.action)) { return xiaoyiCatalog(input,options); diff --git a/apps/detail-agent-pi/src/knowledge-network.mjs b/apps/detail-agent-pi/src/knowledge-network.mjs new file mode 100644 index 00000000..9142ae42 --- /dev/null +++ b/apps/detail-agent-pi/src/knowledge-network.mjs @@ -0,0 +1,44 @@ +import { setTimeout as delay } from 'node:timers/promises'; +import { nativeKnowledgeFetch } from './native-knowledge-http.mjs'; + +const timeoutCodes = new Set(['ETIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT']); +const connectionCodes = new Set(['ECONNRESET', 'ECONNREFUSED', 'EPIPE', 'EAI_AGAIN', 'ENOTFOUND', 'UND_ERR_SOCKET']); + +export function knowledgeTiming(fetch, signal, timeoutMs) { + if (fetch === nativeKnowledgeFetch) return {signal, timeoutMs}; + const timeout = AbortSignal.timeout(timeoutMs); + return {signal: signal ? AbortSignal.any([signal, timeout]) : timeout}; +} + +export function networkFailure(cause, signal) { + signal?.throwIfAborted(); + if (cause.network === true && cause.category) return cause; + const code = cause.code ?? cause.cause?.code; + const timeout = cause.name === 'TimeoutError' || timeoutCodes.has(code); + if (cause.network === false || !(timeout || cause.network || connectionCodes.has(code) || + cause instanceof TypeError && cause.cause)) return cause; + const message = timeout + ? '企业知识库请求超时,请检查网络后重试' + : '连不上企业知识库服务器,请检查网络、VPN 或代理'; + return Object.assign(Error(message, {cause}), {network:true, category:timeout ? 'timeout' : 'network'}); +} + +export function transientStatus(status, code) { + return [502, 503, 504].includes(status) && code !== 'knowledge_session_misconfigured'; +} + +export async function retryKnowledgeRead(read, signal) { + for (let attempt = 0; ; attempt++) { + signal?.throwIfAborted(); + try { return await read(); } + catch (cause) { + const error = networkFailure(cause, signal); + if (error.retryExhausted || !(error.network || error.retryable || transientStatus(error.status, error.code))) throw error; + if (attempt === 2) { + error.retryExhausted = true; + throw error; + } + await delay(150 * (attempt + 1) + Math.random() * 80, undefined, {signal}); + } + } +} diff --git a/apps/detail-agent-pi/src/native-bridge.mjs b/apps/detail-agent-pi/src/native-bridge.mjs index 21ee34ee..f008db26 100644 --- a/apps/detail-agent-pi/src/native-bridge.mjs +++ b/apps/detail-agent-pi/src/native-bridge.mjs @@ -175,6 +175,8 @@ export class Native98kBroker { if (sent) throw Error('每次模型调用只接受一个请求'); sent = true; init.signal?.throwIfAborted(); + const timeout = AbortSignal.timeout(600_000); + const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout; const url = new URL(typeof address === 'string' || address instanceof URL ? address : address.url); if (url.origin !== 'https://api.vip98k.com' || !['/v1/messages', '/v1/chat/completions', '/v1/responses'].includes(url.pathname) || init.method?.toUpperCase() !== 'POST' || typeof init.body !== 'string') throw Error('模型请求边界无效'); let controller, resolveHeaders, rejectHeaders; @@ -187,17 +189,18 @@ export class Native98kBroker { if (event.type === 'headers') { resolveHeaders(new Response(body, { status: event.status, headers: event.headers })); } else if (event.type === 'chunk') enqueue(Buffer.from(event.data, 'base64')); - }, init.signal); + }, signal); const abort = () => { if (!this.authority.error && this.active?.requestId === id) this.child?.kill(); }; - init.signal?.addEventListener('abort', abort, {once:true}); + signal.addEventListener('abort', abort, {once:true}); const completed = request().catch(error=>{ + if (timeout.aborted && !init.signal?.aborted) throw Error('模型请求超时,原请求待核查'); if (error.retryPreparation || /^98k(?:连接|响应)中断$/u.test(error.message)) { throw Error('network error: '+error.message); } throw error; - }).finally(()=>init.signal?.removeEventListener('abort',abort)); + }).finally(()=>signal.removeEventListener('abort',abort)); completed.then(() => { try { controller.close(); } catch {} }, error => { rejectHeaders(error); try { controller.error(error); } catch {} diff --git a/apps/detail-agent-pi/src/native-control-client.mjs b/apps/detail-agent-pi/src/native-control-client.mjs index f2eec10f..b84898f0 100644 --- a/apps/detail-agent-pi/src/native-control-client.mjs +++ b/apps/detail-agent-pi/src/native-control-client.mjs @@ -65,7 +65,8 @@ export class NativeControlClient { } async openAndAuthenticate() { const { port, tokenFile, connectTimeoutMs } = this.connection; - const socket = net.createConnection({ host: '127.0.0.1', port }); + // The native control protocol uses raw loopback TCP and bypasses HTTP(S) proxies. + const socket = net.createConnection({ host: '127.0.0.1', port, keepAlive:true, keepAliveInitialDelay:20_000 }); this.attach(socket); try { await new Promise((resolve, reject) => { diff --git a/apps/detail-agent-pi/src/native-knowledge-http.mjs b/apps/detail-agent-pi/src/native-knowledge-http.mjs index dc1d3604..8579289f 100644 --- a/apps/detail-agent-pi/src/native-knowledge-http.mjs +++ b/apps/detail-agent-pi/src/native-knowledge-http.mjs @@ -7,8 +7,15 @@ delete process.env.PHOTOCRAFT_XIAOYI_BRIDGE_TOKEN; const errors = { 'session-missing': '素材库未部署小壹知识库签发接口(HTTP 404),请联系管理员', 'session-unavailable': '素材库小壹知识库签发服务不可用(HTTP 503),请联系管理员核对配置', + 'session-login': '素材库授权已失效,请重新登录', + 'session-forbidden': '当前账户无权使用小壹知识库', + 'session-network': '连不上素材库服务器,请检查网络、VPN 或代理', + 'session-timeout': '素材库换签请求超时,请检查网络后重试', unconfigured: '企业知识库宿主未配置', - network: '企业知识库网络不可达', + network: '连不上企业知识库服务器,请检查网络、VPN 或代理', + timeout: '企业知识库请求超时,请检查网络后重试', + server: '素材库换签服务端异常,请稍后重试', + gateway: '小壹知识库服务端异常,请稍后重试', credential: '企业知识库用户凭据未配置或不可读取', boundary: '企业知识库请求边界无效', response: '企业知识库响应无效', @@ -16,7 +23,9 @@ const errors = { function transportError(category) { const error = Error(errors[category] ?? errors.response); - error.network = category === 'network'; + error.retryExhausted = category === 'session-network' || category === 'session-timeout'; + error.retryable = category === 'gateway'; + error.network = category === 'network' || category === 'timeout' || error.retryExhausted; error.category = category; return error; } diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 169667f1..07786111 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -1198,7 +1198,10 @@ export async function openProductionOperations(host,{target=host.productionGoal, if(!canvasReady)recordProductionInputs(repository,plan,slots); const {requested,matched,unmatched}=readSelection(slotIds); const {brief,variant}=scopedProductionBrief(plan.productEvidence?.brief??{},variantId,outputId); - const {name,spu,dimensions,note,intake,barcodes,detailBarcode}=brief; + const {name,spu,dimensions,note,intake,barcodes,detailBarcode,platformFacts}=brief; + const imageBindings=[...(brief.images??[]),...(variant?.images??[])] + .filter(image=>image.imageRole||image.barcode) + .map(({name,purpose,imageRole,fieldKey,barcode})=>({name,purpose,imageRole,fieldKey,barcode})); const settings=productionSettings(store,plan.template.production); const {plannedSlots,...picturePlan}=productionPicturePlan(outputId,await liveSlots(),settings); const selected=plannedSlots.filter(slot=>!requested.size||matched.has(slot.id)); @@ -1218,7 +1221,8 @@ export async function openProductionOperations(host,{target=host.productionGoal, return {outputId,variantId,workingOutput:workingOutputId?{outputId:workingOutputId,variantId:workingVariantId}:null, fieldConflicts:await fieldConflicts(await copySnapshot(),plan),fieldRequirements:fieldRequirements(plan), template,product:{name,dimensions,note,...(spu?{spu}:null),variant:variant&&{id:variant.id,colorName:variant.colorName}, - ...(intake?{intake}:null),...(barcodes?{barcodes}:null),...(detailBarcode?{detailBarcode}:null)}, + ...(intake?{intake}:null),...(barcodes?{barcodes}:null),...(detailBarcode?{detailBarcode}:null), + ...(platformFacts?{platformFacts}:null),...(imageBindings.length?{imageBindings}:null)}, candidatesPerSlot,maxCandidatesPerSlot,maxGenerationAttempts,generationLimitSource,...picturePlan,...facts(),...(productUpdate?{productUpdate}:null),pictures, inFlightImages:(await pendingNative()).map(row=>row.candidateId), ...(includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null), @@ -1510,16 +1514,18 @@ export async function openProductionOperations(host,{target=host.productionGoal, const screenCopy=await liveSlotCopy(slot); const references=await readReferences(['template-base','composition-only'].includes(referenceMode)) .catch(error=>({unavailable:error.message})); - const {images=[],referenceCount=0,layoutCount=0,layoutIssue,unavailable,prompt:templatePrompt,outputSpec}=references; + const {images=[],referenceCount=0,layoutCount=0,layoutIssue,unavailable,prompt:templatePrompt,outputSpec, + referenceBindings=[],supplementalBindings=[]}=references; const productIds=productReferences(referenceCount); - const attachments=[...images.slice(0,referenceCount+layoutCount),...(rejectedImage?[rejectedImage]:[])]; + const attachments=[...images.slice(0,referenceCount+layoutCount), + ...(supplementalBindings.length?images.slice(-supplementalBindings.length):[]),...(rejectedImage?[rejectedImage]:[])]; const captions=[...productIds,...Array.from({length:layoutCount},()=> '模板构图参考'), ...(rejectedImage?['退回候选原图']:[])]; delegateSignal.throwIfAborted(); await runDetailAgent(slot.id,instructions, JSON.stringify({rework,goal,referenceMode,screenCopy,pendingCopyFields,target:slotTarget(live), product:scopedProductionBrief((await current()).productEvidence?.brief??{},variantId,outputId), - productReferences:productIds,layoutCount,layoutIssue,templatePrompt,outputSpec,referenceError:unavailable,...status,...(grouped?{groupTargets}:null),field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements}),[readTool,...workerTools], + productReferences:productIds,referenceBindings,supplementalBindings,layoutCount,layoutIssue,templatePrompt,outputSpec,referenceError:unavailable,...status,...(grouped?{groupTargets}:null),field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements}),[readTool,...workerTools], attachments,productRequestScope('slot',slot.id),captions,delegateSignal); if(!produced)generation.set(workerId,{slotId:slot.id,phase:'no_candidate'}); }).catch(async error=>{ diff --git a/apps/detail-agent-pi/src/production-repository.mjs b/apps/detail-agent-pi/src/production-repository.mjs index 5eee6723..75d23113 100644 --- a/apps/detail-agent-pi/src/production-repository.mjs +++ b/apps/detail-agent-pi/src/production-repository.mjs @@ -53,6 +53,11 @@ export function scopedProductionBrief(source, variantId, outputId) { const barcodes = selected ? [selected] : boundBarcodes; if (selected) brief.detailBarcode = selected; if (barcodeBindings) brief.barcodes = barcodes; + if (Array.isArray(brief.images)) brief.images = brief.images.filter(image => !image.barcode || barcodes.includes(image.barcode)); + if (brief.platformFacts) { + const {shared,barcodes:rows}=brief.platformFacts; + brief.platformFacts={shared,barcodes:Object.fromEntries(barcodes.filter(code=>Object.hasOwn(rows,code)).map(code=>[code,rows[code]]))}; + } if (intake) { const values = intake.barcodeValues ?? {}; const barcodeValues = Object.fromEntries(barcodes diff --git a/apps/detail-agent-pi/src/project-context.mjs b/apps/detail-agent-pi/src/project-context.mjs index bbf4fdbc..fd841047 100644 --- a/apps/detail-agent-pi/src/project-context.mjs +++ b/apps/detail-agent-pi/src/project-context.mjs @@ -15,7 +15,9 @@ const images=(value,variantId)=>list(value).filter(image=>image&&typeof image=== ...(safeText(image.name)?{name:safeText(image.name)}:{}), ...(safeText(image.description)?{description:safeText(image.description)}:{}), ...(!(typeof image.ref==='string'&&/^sha256:[a-f0-9]{64}$/.test(image.ref))?{missing:['参考图稳定身份未提供']}:{}), - scope:variantId?'variant':'common',...(variantId?{variantId}:{}), + ...Object.fromEntries(['imageRole','fieldKey','templateId','barcode'].filter(key=>typeof image[key]==='string') + .map(key=>[key,image[key]])), + scope:image.barcode?'barcode':variantId?'variant':'common',...(variantId?{variantId}:{}), })); /** Data-only product evidence. Never includes pixels, complete brand prompts, @@ -49,6 +51,7 @@ export function productContext(value,identity){ factsStatus:text(facts.status),facts:list(facts.items).map(f=>({text:text(f.text),source:text(f.source)})), missing:list(facts.missing).map(v=>text(v)),selectedSellingPoints:selling.stale?[]:selected, plan:{status:text(plan.status),screens:list(plan.screens).map(s=>({name:text(s.name||s.title),body:text(s.body)}))}}; + if(brief.platformFacts) result.platformFacts=brief.platformFacts; if(brief.intake) result.intake=brief.intake; if(brief.barcodeBindings) result.barcodeBindings=Object.fromEntries( Object.entries(brief.barcodeBindings).map(([variantId, binding])=>[variantId,splitBarcodes(binding)])); diff --git a/apps/detail-agent-pi/src/xiaoyi-release.mjs b/apps/detail-agent-pi/src/xiaoyi-release.mjs index 69cd15db..457daece 100644 --- a/apps/detail-agent-pi/src/xiaoyi-release.mjs +++ b/apps/detail-agent-pi/src/xiaoyi-release.mjs @@ -10,9 +10,10 @@ import { atomic, digest } from './store.mjs'; import { loadSkills } from '@earendil-works/pi-coding-agent'; import lockfile from 'proper-lockfile'; import { nativeKnowledgeFetch } from './native-knowledge-http.mjs'; +import { knowledgeTiming, networkFailure, transientStatus } from './knowledge-network.mjs'; import origins from './enterprise-knowledge-origins.json' with { type: 'json' }; -const delays = [2000, 5000, 12000]; +const delays = [200, 500]; const hash = bytes => createHash('sha256').update(bytes).digest('hex'); function fileAt(root, relative) { @@ -38,21 +39,25 @@ async function matches(file, item) { } async function httpError(response) { - const body = await response.json().catch(() => ({})); + const body = await response.json().catch(error => { + if (error instanceof SyntaxError) return {}; + throw error; + }); const messages = { - 401: '小壹知识库连接已失效,请在小壹设置中检测连接', + 401: '小壹知识库连接已失效,请重新登录素材库后检测连接', 403: '当前连接无权读取小壹知识,请联系知识库管理员', 410: '此小壹知识版本已撤回。已完整校验的本地工程可继续使用原版本', }; - const message = body.code === 'not_published' ? '此模板还没有发布小壹版本' + const message = body.code === 'knowledge_session_misconfigured' ? '小壹知识库自动授权配置错误,请联系管理员' + : body.code === 'not_published' ? '此模板还没有发布小壹版本' : response.status === 404 && !body.code ? '当前知识库地址没有提供小壹制作通道,请联系知识库管理员' - : messages[response.status] ?? body.error ?? '小壹知识库请求失败'; + : messages[response.status] ?? (response.status >= 500 ? '小壹知识库服务端异常,请稍后重试' : body.error ?? '小壹知识库请求失败'); const retry = response.headers.get('retry-after'); const retryMs = retry === null ? Number(body.retryAfterSeconds) * 1000 : /^\d+$/.test(retry) ? Number(retry) * 1000 : Date.parse(retry) - Date.now(); return Object.assign(Error(message), { status: response.status, code: body.code, - retryable: response.status === 429 || response.status >= 500 && body.retryable !== false, + retryable: response.status === 429 || transientStatus(response.status, body.code) && body.retryable !== false, retryMs: Number.isFinite(retryMs) ? Math.max(0, retryMs) : undefined, }); } @@ -70,10 +75,10 @@ export async function acquireXiaoyiRelease(options) { signal?.throwIfAborted(); try { return await operation(); - } catch (error) { - signal?.throwIfAborted(); - if (attempt >= delays.length || !(error.network || error.retryable)) throw error; - await sleep(error.retryMs ?? delays[attempt], undefined, {signal}); + } catch (cause) { + const error = networkFailure(cause, signal); + if (attempt >= delays.length || error.retryExhausted || !(error.network || error.retryable)) throw error; + await sleep(error.retryMs ?? delays[attempt] + Math.random() * 100, undefined, {signal}); } } } @@ -252,7 +257,9 @@ export async function openXiaoyiSkills(store, templateId, signal, finishedGoal, } const {manifest, root, productionProfiles} = await acquireXiaoyiRelease({ templateId, directory, cache:store.xiaoyiCache ?? path.join(path.dirname(store.dir), 'xiaoyi-blobs'), signal, pinnedKnowledgeVersion, metadataOnly, onProgress:store.xiaoyiProgress, - fetch:(route, init) => fetch(new URL(route, origin), init), + fetch:(route, init) => fetch(new URL(route, origin), { + ...init, redirect:'manual', ...knowledgeTiming(fetch, signal, /\/bundle$|\/blobs\//.test(route) ? 240_000 : 45_000), + }), }); const entry = fileAt(root, manifest.entrypoint); const resource = loadSkills({cwd:store.dir, agentDir:store.dir, skillPaths:[entry], includeDefaults:false}); diff --git a/apps/detail-agent-pi/test/native-canvas-transport.test.mjs b/apps/detail-agent-pi/test/native-canvas-transport.test.mjs index 94d8be7a..f47bf49e 100644 --- a/apps/detail-agent-pi/test/native-canvas-transport.test.mjs +++ b/apps/detail-agent-pi/test/native-canvas-transport.test.mjs @@ -5,6 +5,8 @@ import path from 'node:path'; import os from 'node:os'; import net from 'node:net'; import {createInterface} from 'node:readline'; +import {execFile} from 'node:child_process'; +import {promisify} from 'node:util'; import {NativeControlClient as NativeCanvas} from '../src/native-control-client.mjs'; const pause=ms=>new Promise(resolve=>setTimeout(resolve,ms)); @@ -34,6 +36,22 @@ async function fixture(handle,authorize=()=>true){ }; } +test('native loopback connects directly even with Node environment proxy enabled',async()=>{ + const f=await fixture(({reply})=>reply({revision:7})); + try{ + const client=new URL('../src/native-control-client.mjs',import.meta.url).href; + const code=`import {NativeControlClient} from ${JSON.stringify(client)}; + const bridge=await NativeControlClient.connect(${JSON.stringify({...f.options,connectTimeoutMs:2000,rpcTimeoutMs:2000})}); + try { console.log((await bridge.read()).revision); } finally { bridge.close(); }`; + const proxy='http://127.0.0.1:9'; + const {stdout}=await promisify(execFile)(process.execPath,['--input-type=module','-e',code],{ + env:{...process.env,NODE_USE_ENV_PROXY:'1',HTTP_PROXY:proxy,HTTPS_PROXY:proxy,ALL_PROXY:proxy,NO_PROXY:''},timeout:8000, + }); + assert.equal(stdout.trim(),'7'); + assert.equal(f.connections,1); + }finally{await f.close();} +}); + test('an idle EOF reconnects and authenticates only before a new read/edit, preserving run and CAS',async()=>{ let revision=7; const f=await fixture(({q,socket,reply})=>{ diff --git a/apps/detail-agent-pi/test/product-brief.test.mjs b/apps/detail-agent-pi/test/product-brief.test.mjs index 95904624..9fadd8cb 100644 --- a/apps/detail-agent-pi/test/product-brief.test.mjs +++ b/apps/detail-agent-pi/test/product-brief.test.mjs @@ -3,6 +3,7 @@ import assert from 'node:assert/strict'; import fixture from '../../../lib/__tests__/fixtures/xiaoyi-free-barcode.json' with { type: 'json' }; import { detailBarcode, projectSpu, splitBarcodes } from '../src/product-brief.mjs'; import { scopedProductionBrief } from '../src/production-repository.mjs'; +import { intakeMetadata } from '../src/enterprise-templates.mjs'; import { productContext } from '../src/project-context.mjs'; const white = 'DNZ030516N717V01'; @@ -61,3 +62,25 @@ test('free barcodes survive project context and scoped production without splitt } assert.deepEqual(splitBarcodes(fixture.legacyBinding), ['CY001307N35V01', 'cy001307n35v01']); }); + +test('template image fields and scoped evidence preserve role, slot, and barcode', () => { + const schema = intakeMetadata({version:1, + productFields:[{key:'hero',kind:'image',label:'产品图片',imageRole:'product',placeholder:'拖入产品图'}], + barcodeFields:[{key:'fabric',kind:'image',label:'材质图片',imageRole:'material',multiple:false}]}); + assert.deepEqual(schema.productFields[0], {id:'hero',type:'image',label:'产品图片',imageRole:'product',placeholder:'拖入产品图',multiple:true}); + assert.equal(schema.barcodeFields[0].multiple, false); + assert.throws(() => intakeMetadata({...schema,barcodeFields:[{...schema.barcodeFields[0],multiple:'false'}]}), /字段格式无效/); + const images = [ + {name:'产品参考',imageRole:'product',purpose:'product',fieldKey:'hero'}, + {name:'材质参考',imageRole:'material',purpose:'scene',fieldKey:'fabric',barcode:other}, + {name:'其他条码',imageRole:'product',purpose:'product',barcode:white}, + ]; + const source = {...brief,images,intake:{...brief.intake,schema},platformFacts:{shared:{material:'棉'},barcodes:{[other]:{colorName:'白色'},[white]:{colorName:'蓝色'}}}}; + const context = productContext({accountScope:'a',project:'p',documentId:1,brief:source},{scope:'a',project:'p',documentId:1}); + assert.equal(context.references.commonImages[1].scope,'barcode'); + assert.equal(context.references.commonImages[1].barcode,other); + assert.equal(context.references.commonImages[1].imageRole,'material'); + const {brief:detail} = scopedProductionBrief(source,'white','detail'); + assert.deepEqual(detail.images,images.slice(0,2)); + assert.deepEqual(detail.platformFacts,{shared:{material:'棉'},barcodes:{[other]:{colorName:'白色'}}}); +}); diff --git a/apps/detail-agent-pi/test/xiaoyi-release.test.mjs b/apps/detail-agent-pi/test/xiaoyi-release.test.mjs index e148ef58..5c8ac66d 100644 --- a/apps/detail-agent-pi/test/xiaoyi-release.test.mjs +++ b/apps/detail-agent-pi/test/xiaoyi-release.test.mjs @@ -112,11 +112,58 @@ test('honors Retry-After before retrying', async t => { assert.deepEqual(pauses,[7000]); }); -test('backs off 2, 5 and 12 seconds and reports failure to start', async t => { +test('backs off twice with jitter and reports a network diagnosis', async t => { const {options,pauses} = await fixture(t); options.fetch = async () => {throw Object.assign(Error('offline'),{network:true});}; - await assert.rejects(acquireXiaoyiRelease(options),/无法开工/); - assert.deepEqual(pauses,[2000,5000,12000]); + await assert.rejects(acquireXiaoyiRelease(options),/无法开工:连不上企业知识库服务器/); + assert.equal(pauses.length,2); + assert.ok(pauses[0] >= 200 && pauses[0] < 300); + assert.ok(pauses[1] >= 500 && pauses[1] < 600); +}); + +test('catalog retries a timeout and a 503, then preserves cached fields and the draft offline', async t => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'xiaoyi-catalog-offline-')); + t.after(() => fs.rm(root,{recursive:true,force:true})); + const fields = [ + {id:'description',label:'产品说明',type:'text',placeholder:'填写产品亮点',multiline:true}, + {id:'name',label:'名称',type:'text',placeholder:'',multiline:false}, + {id:'legacy',label:'旧字段',type:'text'}, + ]; + const input = {root,action:'catalog',brandName:'品牌',categoryName:'椅子'}; + const draft = path.join(root,'draft.json'); + await fs.writeFile(draft,'{"description":"手工填写"}'); + let calls = 0; + const fetch = async () => { + calls++; + if (calls === 1) throw new DOMException('fixture timeout','TimeoutError'); + if (calls === 2) return Response.json({}, {status:503}); + return Response.json({items:[{templateId:'CHAIR',name:'椅子',brand:'品牌',category:'椅子', + intake:{version:1,productFields:fields,barcodeFields:[]}}]}); + }; + const online = await templateRequest(input,{fetch}); + assert.equal(calls,3); + assert.deepEqual(online.items[0].intake.productFields,fields); + calls = 0; + const offline = await templateRequest(input,{fetch:async()=>{ + calls++; + throw new TypeError('fetch failed',{cause:Object.assign(Error('reset'),{code:'ECONNRESET'})}); + }}); + assert.equal(calls,3); + assert.deepEqual(offline.items,online.items); + assert.match(offline.notice,/检查网络、VPN 或代理.*本机缓存模板.*草稿已保留/); + assert.equal(await fs.readFile(draft,'utf8'),'{"description":"手工填写"}'); + for (const [status,code,diagnosis] of [ + [401,'authentication_required',/重新登录/], + [403,'forbidden',/无权/], + [503,'knowledge_session_misconfigured',/配置错误/], + ]) { + calls = 0; + await assert.rejects(templateRequest(input,{fetch:async()=>{ + calls++; + return Response.json({code},{status}); + }}),diagnosis); + assert.equal(calls,1); + } }); test('a rejected range restarts the same bundle without a range header', async t => { diff --git a/apps/detail-photocraft/Cargo.lock b/apps/detail-photocraft/Cargo.lock index 759d2b36..a6441264 100644 --- a/apps/detail-photocraft/Cargo.lock +++ b/apps/detail-photocraft/Cargo.lock @@ -5465,6 +5465,7 @@ dependencies = [ "epaint_default_fonts", "flate2", "log", + "percent-encoding", "photocraft-algo", "photocraft-cms", "photocraft-codecs", @@ -5485,6 +5486,7 @@ dependencies = [ "photocraft-text", "photocraft-vector", "rayon", + "regex", "serde", "serde_json", "sha2", diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 7b3882ab..b00e5db1 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -109,6 +109,8 @@ mod slot_canvas; mod stream; #[path = "jiansun_sync.rs"] mod sync; +#[path = "jiansun_feedback.rs"] +mod feedback; #[path = "jiansun_template_cache.rs"] mod template_cache; #[cfg(test)] @@ -362,18 +364,32 @@ fn adopt_open_mapping( fn remember_open(binding: &Value) -> bool { binding["autoResume"] != true } -fn body(response: Response, limit: u64) -> R<(u16, Value)> { +fn body(mut response: Response, limit: u64) -> R<(u16, Value)> { + let status = response.status().as_u16(); + Ok((status, response_json(&mut response, limit).map_err(|error| error.to_string())?)) +} + +#[derive(Debug, thiserror::Error)] +enum JsonResponseError { + #[error("{}", read_network_message(.0))] + Read(#[from] std::io::Error), + #[error("服务响应超过客户端限制")] + TooLarge, + #[error("服务没有返回有效结果(HTTP {0})")] + Invalid(u16), +} + +fn response_json(response: &mut Response, limit: u64) -> Result { let status = response.status().as_u16(); if response.content_length().is_some_and(|n| n > limit) { - return Err("服务响应超过客户端限制".into()); + return Err(JsonResponseError::TooLarge); } let mut bytes = Vec::new(); - response.take(limit + 1).read_to_end(&mut bytes).map_err(|_| "服务连接中断")?; + response.take(limit + 1).read_to_end(&mut bytes)?; if bytes.len() as u64 > limit { - return Err("服务响应超过客户端限制".into()); + return Err(JsonResponseError::TooLarge); } - let v = serde_json::from_slice(&bytes).map_err(|_| format!("服务没有返回有效结果(HTTP {status})"))?; - Ok((status, v)) + serde_json::from_slice(&bytes).map_err(|_| JsonResponseError::Invalid(status)) } /// The public retained-result endpoint returns the ORIGINAL JSON body. Some documented /// envelopes also nest that original body under `data`; never discard a raw images.data array. @@ -409,23 +425,105 @@ fn upstream_bypass_enabled(value: Option<&str>) -> bool { value == Some("1") } struct NetworkClient { normal: Client, upstream: Client, + direct: Client, + bypass_upstream: bool, } + +fn network_builder(timeout: Duration) -> reqwest::blocking::ClientBuilder { + Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .retry(reqwest::retry::never()) + .connect_timeout(timeout.min(Duration::from_secs(5))) + .timeout(timeout) + .tcp_keepalive(Duration::from_secs(20)) + .tcp_keepalive_interval(Duration::from_secs(5)) + .tcp_keepalive_retries(3) + .pool_idle_timeout(Duration::from_secs(15)) +} + +fn network_message(error: &reqwest::Error) -> &'static str { + if error.is_timeout() { "请求超时,请检查网络后重试" } + else if error.is_builder() { "网络请求配置无效,请检查连接地址" } + else { "连不上服务器,请检查网络、VPN 或代理" } +} + +fn read_timed_out(error: &std::io::Error) -> bool { + error.kind() == std::io::ErrorKind::TimedOut || + error.get_ref().and_then(|cause| cause.downcast_ref::()).is_some_and(reqwest::Error::is_timeout) +} + +const READ_TIMEOUT: &str = "读取响应超时,请检查网络后重试"; +const READ_INTERRUPTED: &str = "服务连接中断,请检查网络、VPN 或代理"; + +fn read_network_message(error: &std::io::Error) -> &'static str { + if read_timed_out(error) { READ_TIMEOUT } else { READ_INTERRUPTED } +} + +fn transient_status(status: u16) -> bool { matches!(status, 502..=504) } + impl NetworkClient { + fn build(direct: bool) -> reqwest::Result { + let builder = network_builder(Duration::from_secs(30)); + if direct { builder.no_proxy().build() } else { builder.build() } + } + fn new(bypass_upstream: bool) -> R { - let build = |direct: bool| { - let builder = Client::builder().redirect(reqwest::redirect::Policy::none()).retry(reqwest::retry::never()).timeout(Duration::from_secs(30)); - (if direct { builder.no_proxy() } else { builder }).build().map_err(|_| "本机网络服务无法初始化".to_owned()) - }; + let build = |direct| Self::build(direct).map_err(|_| "本机网络服务无法初始化".to_owned()); let normal = build(false)?; - let upstream = if bypass_upstream { build(true)? } else { normal.clone() }; - Ok(Self { normal, upstream }) + let direct = build(true)?; + let upstream = if bypass_upstream { direct.clone() } else { normal.clone() }; + Ok(Self { normal, upstream, direct, bypass_upstream }) } fn is_upstream(raw: &str) -> bool { url::Url::parse(raw).ok().is_some_and(|url| url.scheme() == "https" && url.host_str() == Some("api.vip98k.com") && url.port_or_known_default() == Some(443) && url.username().is_empty() && url.password().is_none()) } + fn is_loopback(url: &url::Url) -> bool { + match url.host() { + Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), + Some(url::Host::Ipv4(ip)) => ip.is_loopback(), + Some(url::Host::Ipv6(ip)) => ip.is_loopback(), + None => false, + } + } fn client(&self, raw: &str) -> &Client { - if Self::is_upstream(raw) { &self.upstream } else { &self.normal } + if url::Url::parse(raw).is_ok_and(|url| Self::is_loopback(&url)) { &self.direct } + else if Self::is_upstream(raw) { &self.upstream } else { &self.normal } + } + fn read(&self, request: reqwest::blocking::RequestBuilder) -> reqwest::Result { + self.read_until(request, None) + } + fn read_until(&self, request: reqwest::blocking::RequestBuilder, deadline: Option) -> reqwest::Result { + self.read_with(request, deadline, |response| transient_status(response.status().as_u16())) + } + fn read_with(&self, request: reqwest::blocking::RequestBuilder, deadline: Option, mut retry_status: impl FnMut(&mut Response) -> bool) -> reqwest::Result { + let (client, request) = request.build_split(); + let request = request?; + if request.method() != reqwest::Method::GET { return client.execute(request); } + let retry = request.try_clone().expect("GET requests have replayable bodies"); + let direct = Self::is_loopback(request.url()) || self.bypass_upstream && Self::is_upstream(request.url().as_str()); + let mut result = client.execute(request); + for delay in [Some(150), Some(350), None] { + let retryable = match &mut result { + Ok(response) => retry_status(response), + Err(error) => error.is_timeout() || error.is_connect() || error.is_request(), + }; + let Some(delay) = delay.filter(|_| retryable) else { break; }; + let pause = Duration::from_millis(delay + u64::from(Uuid::new_v4().as_bytes()[0] % 80)); + let remaining = deadline.map(|deadline| deadline.saturating_duration_since(Instant::now())); + if remaining.is_some_and(|remaining| remaining <= pause) { break; } + drop(result); + std::thread::sleep(pause); + // A fresh client also resolves again after a network or proxy switch. + let fresh = Self::build(direct)?; + let mut request = retry.try_clone().expect("GET requests have replayable bodies"); + if let Some(deadline) = deadline { + let remaining = deadline.saturating_duration_since(Instant::now()); + *request.timeout_mut() = Some(request.timeout().copied().unwrap_or(Duration::from_secs(30)).min(remaining)); + } + result = fresh.execute(request); + } + result } fn get(&self, url: impl std::fmt::Display) -> reqwest::blocking::RequestBuilder { let url = url.to_string(); self.client(&url).get(url) } fn post(&self, url: impl std::fmt::Display) -> reqwest::blocking::RequestBuilder { let url = url.to_string(); self.client(&url).post(url) } @@ -434,7 +532,7 @@ impl NetworkClient { } #[cfg(test)] impl From for NetworkClient { - fn from(client: Client) -> Self { Self { normal: client.clone(), upstream: client } } + fn from(client: Client) -> Self { Self { normal: client.clone(), upstream: client.clone(), direct: client, bypass_upstream: false } } } #[derive(Clone)] @@ -522,6 +620,7 @@ impl PortalFailure { (401, _) => ("sign_in_required", "素材库授权已过期或被撤销,请重新连接;本机作品已保留".into()), (403, _) => ("forbidden", "当前账户没有素材库访问权限,请核对账户或联系管理员;本机作品已保留".into()), (404, _) => ("unavailable", "资源不存在或无权访问".into()), + (500..=599, _) => ("unavailable", format!("素材库服务端异常(HTTP {status}),请稍后重试")), _ => ("unavailable", format!("素材库请求失败(HTTP {status})")), }; Self { state, http_status: Some(status), message } @@ -636,29 +735,51 @@ impl Backend { } fn portal_json(&self, path: &str) -> Result { let token = self.auth["access_token"].as_str().ok_or_else(|| PortalFailure::local("sign_in_required", "请先在素材库登录"))?; - let r = self - .http - .get(format!("{}/api/desktop/{path}", self.origin)) - .bearer_auth(token) - .send() - .map_err(|_| PortalFailure::local("unavailable", "素材库暂时无法连接,本机草稿已保留"))?; + let request = self.http.get(format!("{}/api/desktop/{path}", self.origin)).bearer_auth(token) + .timeout(Duration::from_secs(8)); + let mut payload = Ok(Value::Null); + let r = self.http.read_with(request, None, |response| { + let status = response.status().as_u16(); + if transient_status(status) { return true; } + if status == 401 { self.revoke_access("auth_revoked"); return false; } + payload = response_json(response, MAX_JSON); + status == 200 && matches!(payload, Err(JsonResponseError::Read(_))) + }) + .map_err(|error| PortalFailure::local("unavailable", format!("素材库{};本机草稿已保留", network_message(&error))))?; let status = r.status().as_u16(); - if status == 401 { self.revoke_access("auth_revoked"); } - let (code, v) = body(r, MAX_JSON).map_err(|error| { - if status != 200 { - PortalFailure::http(status, None) - } else { - PortalFailure::local("unavailable", format!("素材库连接失败:{error}")) - } - })?; - if code != 200 { - return Err(PortalFailure::http(code, v["code"].as_str())); + if status != 200 { + return Err(PortalFailure::http(status, payload.as_ref().ok().and_then(|value| value["code"].as_str()))); } - Ok(v) + payload.map_err(|error| PortalFailure::local("unavailable", format!("素材库{error};本机草稿已保留"))) } fn json(&self, path: &str) -> R { self.portal_json(path).map_err(|failure| failure.message) } + fn product_platform_spu(&self, spu: &str) -> R { + let token = self.auth["access_token"].as_str().ok_or("请先登录素材库账号")?; + let mut url = reqwest::Url::parse(&format!("{}/api/desktop/product-platform/spu", self.origin)) + .map_err(|_| "素材库地址无效")?; + url.query_pairs_mut().append_pair("spu", spu); + let mut response = self.http.get(url).bearer_auth(token).timeout(Duration::from_secs(20)) + .send().map_err(|error| if error.is_timeout() { + "产品平台请求超时,请稍后重试" + } else { + "产品平台暂时无法连接,请稍后重试" + })?; + match response.status().as_u16() { + 200 => response_json(&mut response, MAX_JSON).map_err(|_| "产品平台返回的资料格式异常".into()), + 400 => Err("请输入有效的 SPU 型号".into()), + 401 => { + self.revoke_access("auth_revoked"); + Err("请重新登录素材库账号".into()) + } + 404 => Err("产品平台未找到该 SPU 资料".into()), + 503 => Err("产品平台联动未配置,请联系管理员".into()), + 504 => Err("产品平台请求超时,请稍后重试".into()), + _ => Err("产品平台暂时无法连接,请稍后重试".into()), + } + } + fn validate_connection(&mut self) -> Result<(), PortalFailure> { let v = match self.portal_json("session") { Ok(value) => value, @@ -679,7 +800,7 @@ impl Backend { self.check_dispatch()?; match self.validate_connection() { // 素材库只负责登录。暂时连不上时沿用本机已有登录;授权撤销或换号仍会拦下。 - Err(failure) if failure.state == "unavailable" => {} + Err(failure) if failure.state == "unavailable" && failure.http_status.is_none_or(|status| status >= 500) => {} result => result.map_err(|failure| match failure.state { "sign_in_required" if failure.http_status == Some(401) => AUTH_REVOKED.into(), "sign_in_required" if failure.message == "账户状态不一致,请重新授权" => ACCOUNT_CHANGED.into(), @@ -705,8 +826,6 @@ impl Backend { Err("项目操作账户已变化,未处理其他账户项目".to_owned()) } else { match operation["kind"].as_str() { - Some("sync") => backend.sync_project(&input), - Some("pull") => backend.open_with_recovery(&input, &events, &ctx).and_then(|_| backend.projects().map(|projects| json!({"projects":projects}))), Some("delete") => backend.delete_project(&input), _ => Err("项目操作无效".into()), } @@ -740,8 +859,14 @@ impl Backend { if Uuid::parse_str(&id).is_err() && id.parse::().is_err() { return Err("本机项目编号无效".into()); } + let brief = creation::load(&entry.path()).ok().map(|value| value["brief"].clone()).unwrap_or_default(); + let updated = v["time"].as_str().and_then(|value| value.parse::().ok()) + .and_then(|time| chrono::DateTime::from_timestamp(time, 0)) + .map(|value| value.format("%Y-%m-%d %H:%M UTC").to_string()); out.push( - json!({"id":id,"source":"native","name":v["name"],"revision":v["revision"].as_u64().unwrap_or(0),"updatedAt":v["time"],"hasDraft":v["status"]!="completed","status":v["status"].as_str().unwrap_or("draft"),"cloudLink":v["project"],"cloudPresent":false,"syncedRevision":v["syncedRevision"],"syncDirty":v["syncDirty"].as_bool().unwrap_or(true),"localPending":projects::idle(&entry.path()).is_err()}), + json!({"id":id,"source":"native","name":v["name"],"brandName":brief["brandName"], + "productModel":brief["platformFacts"]["productModel"].as_str().or(brief["identifier"].as_str().filter(|text| !text.is_empty())).or(brief["name"].as_str()), + "updatedLabel":updated,"revision":v["revision"].as_u64().unwrap_or(0),"updatedAt":v["time"],"hasDraft":v["status"]!="completed","status":v["status"].as_str().unwrap_or("draft"),"cloudLink":v["project"],"cloudPresent":false,"syncedRevision":v["syncedRevision"],"syncDirty":v["syncDirty"].as_bool().unwrap_or(true),"localPending":projects::idle(&entry.path()).is_err()}), ); } } @@ -854,9 +979,9 @@ impl Backend { let catalog = serde_json::from_slice(&bytes).map_err(|_| "本地模型目录格式无效")?; return Ok((catalog, json!({"source":"local","elapsedMs":start.elapsed().as_millis()}))); } - let response = self.http.get(format!("{UPSTREAM}/api/v2/catalog/models")) - .header(reqwest::header::ACCEPT_ENCODING, "gzip") - .send().map_err(|_| "98k公开模型目录暂不可用")?; + let request = self.http.get(format!("{UPSTREAM}/api/v2/catalog/models")) + .header(reqwest::header::ACCEPT_ENCODING, "gzip"); + let response = self.http.read(request).map_err(|error| catalog_transport_error(&error))?; let headers_ms = start.elapsed().as_millis(); let status = response.status().as_u16(); if status != 200 { return Err(format!("98k公开模型目录暂不可用(HTTP {status})")); } @@ -911,7 +1036,8 @@ impl Backend { } } fn key_catalog(&self, key: &str) -> R> { - let response = self.http.get(format!("{UPSTREAM}/v1/models")).bearer_auth(key).send().map_err(|error| catalog_transport_error(&error))?; + let request = self.http.get(format!("{UPSTREAM}/v1/models")).bearer_auth(key); + let response = self.http.read(request).map_err(|error| catalog_transport_error(&error))?; if response.status().as_u16() == 401 { return Err("个人Key校验失败(HTTP 401)".into()); } let (status, value) = body(response, MAX_JSON).map_err(|error| format!("98k模型目录读取失败:{error}"))?; if status != 200 { @@ -1058,7 +1184,8 @@ impl Backend { Ok(result) } fn authorization_config(&self, origin: &str) -> R { - let (status, config) = body(self.http.get(format!("{origin}/api/desktop/config")).send().map_err(|_| "素材库暂时无法连接")?, MAX_JSON)?; + let request = self.http.get(format!("{origin}/api/desktop/config")).timeout(Duration::from_secs(8)); + let (status, config) = body(self.http.read(request).map_err(|error| network_message(&error))?, MAX_JSON)?; authorization_enabled(status, &config) } fn login(&mut self, input: &Value, tx: &mpsc::Sender, ctx: &egui::Context) -> R { @@ -1134,7 +1261,8 @@ impl Backend { } fn bytes(&self, path: &str) -> R> { let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?; - let r = self.http.get(format!("{}/api/desktop/{path}", self.origin)).bearer_auth(token).send().map_err(|_| "素材下载连接中断")?; + let request = self.http.get(format!("{}/api/desktop/{path}", self.origin)).bearer_auth(token); + let r = self.http.read(request).map_err(|error| network_message(&error))?; if r.status().as_u16() == 401 { self.revoke_access("auth_revoked"); let _ = self.clone().renew_portal_session(); @@ -1220,7 +1348,9 @@ impl Backend { let metadata_only = meta["metadataOnly"] == true; if activate_view { self.ensure_owner(doc.id.0)?; } let _guard = sync::context_guard(); - if !meta["creationDraft"].is_null() && (!meta["creationDraft"].is_object() || meta["creationDraft"].to_string().len() > 100_000) { + let creation_draft = &meta["creationDraft"]; + let draft_limit = if creation_draft["brief"]["platformFacts"].is_object() { 1_500_000 } else { 100_000 }; + if !creation_draft.is_null() && (!creation_draft.is_object() || creation_draft.to_string().len() > draft_limit) { return Err("产品资料草稿超过限制,原草稿已保留".into()); } self.bind_new(doc.id.0); @@ -1425,7 +1555,7 @@ impl Backend { if !recover { transfer::redact(&mut task); } let response = if recover { let id = task["requestId"].as_str().filter(|s| Uuid::parse_str(s).is_ok()).ok_or("原请求没有可公开查询的编号;保持待核查,不会重发")?; - self.http.get(format!("{UPSTREAM}/api/external/requests/{id}/result")).bearer_auth(key).send() + self.http.read(self.http.get(format!("{UPSTREAM}/api/external/requests/{id}/result")).bearer_auth(key)) } else { let system = format!( "你是由壹点详情页画布 Agent。使用中文,简洁,不虚构产品事实。只能修改当前已存在且未锁定的图层。返回严格 JSON:{{\"reply\":\"简短说明\",\"edits\":[{{\"command\":\"type.edit\",\"params\":{{\"layer\":数字图层ID,\"text\":\"新文字\"}},\"label\":\"修改标题\"}}]}}。最多20步。可用命令仅 type.edit(layer,text,size,color,name)、layer.translate(layer,dx,dy,整数像素)、layer.setProps(layer,name,opacity 0到1,visible)。不能执行文件、终端、代码、脚本、网络。未要求改变的参数保持原样。分析产品或生成图片的请求不要伪装成已完成。文档:{}", @@ -1459,7 +1589,7 @@ impl Backend { r.send() }; let result = (|| -> R { - let response = response.map_err(|_| "98k连接中断,执行结果待核查")?; + let response = response.map_err(|error| format!("{};原请求保留待核查", network_message(&error)))?; if !recover && let Some(id) = response.headers().get("x-request-id").and_then(|v| v.to_str().ok()).filter(|s| Uuid::parse_str(s).is_ok()) { task["requestId"] = json!(id); write_json(&file, &task)?; @@ -1587,7 +1717,19 @@ impl Backend { Ok(json!({"doc":doc,"localId":local})) } "project-delete" => self.delete_project(input), - "project-sync" => self.sync_project(input), + "project-sync" if input["status"] == "completed" => self.sync_project(input), + "desktop-feedback" => feedback::submit(self, input), + "workbench-knowledge" => { + if input["accountId"] != self.auth["account"]["id"] || input["origin"] != self.origin { + return Err("账号已切换,请重新提问".into()); + } + self.check_dispatch()?; + let mut request = json!({"action":"workbench-query","query":input["query"], + "accountId":input["accountId"],"origin":input["origin"]}); + let result = self.enterprise_template_read(&mut request, |_| {})?; + self.check_dispatch()?; + Ok(result) + } "delivery-status" => self.delivery_status(input), "project-state" => self.project_state(input), "configure-xiaoyi-knowledge" => Ok(knowledge_http::configure_for_account(input)), @@ -2063,6 +2205,23 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let _ = events.send(event); } Request::Action(method, input) => { + if matches!(method.as_str(), "desktop-feedback" | "workbench-knowledge") { + let mut worker = backend.clone(); + let task_events = events.clone(); + let task_ctx = ctx.clone(); + let reference = json!({"accountId":input["accountId"],"origin":input["origin"],"readId":input["readId"]}); + let result_ref = reference.clone(); + let result_method = method.clone(); + if let Err(error) = prompt_ops.submit(move || { + let result = worker.action(&result_method, &input, &task_events, &task_ctx); + let _ = task_events.send(Event::Json(result_method, Ok(bound_material_read(result, &result_ref)))); + task_ctx.request_repaint_of(egui::ViewportId::ROOT); + }) { + let _ = events.send(Event::Json(method, Ok(bound_material_read(Err(error.into()), &reference)))); + ctx.request_repaint_of(egui::ViewportId::ROOT); + } + continue; + } if method == "client-update" { let reader = backend.clone(); let task_events = events.clone(); @@ -2158,6 +2317,27 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { } return true; } + if method == "creation-product-platform" { + if let Some(doc) = input["doc"].as_u64() { + backend.bind_new(doc); + } + let mut reader = backend.clone(); + let task_events = events.clone(); + let task_ctx = ctx.clone(); + let task_method = method.clone(); + if let Err(error) = catalog_reads.submit(move || { + let result = reader.creation_action(&task_method, &input, None, &task_events, &task_ctx); + let _ = task_events.send(Event::Json(task_method, result.clone())); + if let Ok(receipt) = result { + reader.platform_previews(&receipt, &task_events); + } + task_ctx.request_repaint(); + }) { + let _ = events.send(Event::Json(method, Err(error.into()))); + ctx.request_repaint(); + } + return true; + } if matches!(method.as_str(), "materials" | "creation-catalog" | "creation-thumbnail" | "preview" | "delivery-status") { if method.starts_with("creation-") && let Some(doc) = input["doc"].as_u64() @@ -2215,10 +2395,10 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let result = backend.slot_action(&method, &input, &events, &ctx); let _ = events.send(Event::Json(method, result)); ctx.request_repaint_of(egui::ViewportId::ROOT); - } else if method == "project-sync" { + } else if method == "project-sync" && input["status"] == "completed" { use std::sync::atomic::Ordering; if model_busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { - let _ = events.send(Event::Json(method, Err("原任务仍在处理,未重复同步".into()))); + let _ = events.send(Event::Json(method, Err("原任务仍在处理,未重复提交成品".into()))); } else { let mut b = backend.clone(); let events = events.clone(); @@ -2509,6 +2689,46 @@ mod tests { assert!(std::ptr::eq(cloned.client("https://api.vip98k.com/v1/models"), &cloned.upstream)); } + #[test] + fn jiansun_loopback_http_bypasses_proxy_environment() { + const FIXTURE: &str = "JIANSUN_LOOPBACK_HTTP_FIXTURE"; + if let Ok(url) = std::env::var(FIXTURE) { + let http = NetworkClient::new(false).unwrap(); + assert!(http.get(url).timeout(Duration::from_secs(2)).send().unwrap().status().is_success()); + return; + } + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + listener.set_nonblocking(true).unwrap(); + let server = std::thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(8); + loop { + match listener.accept() { + Ok((mut stream, _)) => { + stream.set_nonblocking(false).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let mut request = [0; 1024]; + assert!(stream.read(&mut request).unwrap() > 0); + stream.write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n").unwrap(); + return; + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock && Instant::now() < deadline => + std::thread::sleep(Duration::from_millis(10)), + Err(error) => panic!("direct loopback connection missing: {error}"), + } + } + }); + let bad_proxy = TcpListener::bind("127.0.0.1:0").unwrap(); + let proxy = format!("http://{}", bad_proxy.local_addr().unwrap()); + let child = std::process::Command::new(std::env::current_exe().unwrap()) + .arg("jiansun_loopback_http_bypasses_proxy_environment") + .env(FIXTURE, format!("http://{address}/")) + .env("HTTP_PROXY", &proxy).env("HTTPS_PROXY", &proxy).env("ALL_PROXY", &proxy) + .env("NO_PROXY", "").output().unwrap(); + assert!(child.status.success(), "{}", String::from_utf8_lossy(&child.stdout)); + server.join().unwrap(); + } + #[test] fn model_catalog_failure_exposes_only_fixed_categories() { let classify = |timeout, connect, messages: &[&str]| catalog_failure_category(timeout, connect, messages.iter().map(|s| (*s).to_owned())); @@ -2541,7 +2761,9 @@ mod tests { let origin = format!("http://{}", listener.local_addr().unwrap()); let server = std::thread::spawn(move || { for (status, code) in [(401, Some("session_expired")), (403, Some("forbidden")), - (503, Some("service_unavailable")), (502, None), (403, Some("feature_disabled"))] { + (503, Some("service_unavailable")), (502, None), (403, Some("feature_disabled"))] + .into_iter().flat_map(|entry| std::iter::repeat_n(entry, if transient_status(entry.0) { 3 } else { 1 })) + { let (mut stream, _) = listener.accept().unwrap(); stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); let mut bytes = [0; 8192]; diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index 80524abb..4b03c700 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -461,7 +461,8 @@ fn references(dir: &Path, images: &Value) -> R> { for image in images { let source = image["source"].as_str().ok_or("参考图来源缺失")?; let hash = source.strip_prefix("local:").filter(|s| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())).ok_or("参考图须为本项目本机资产")?; - if !seen.insert(source) || !matches!(image["purpose"].as_str(), Some("product" | "scene")) { + if !seen.insert((source, image["fieldKey"].as_str(), image["barcode"].as_str())) + || !matches!(image["purpose"].as_str(), Some("product" | "scene")) { return Err("参考图重复或用途无效".into()); } let file = dir.join("creation-assets").join(format!("{hash}.png")); @@ -482,20 +483,35 @@ fn references(dir: &Path, images: &Value) -> R> { if format!("{:x}", Sha256::digest(&bytes)) != hash { return Err("参考图内容已变化,未使用错误花色图片".into()); } - out.push(json!({"source":source,"purpose":image["purpose"],"name":text(&image["name"],200,"参考图名称")?})); + let mut row = json!({"source":source,"purpose":image["purpose"],"name":text(&image["name"],200,"参考图名称")?}); + for key in ["imageRole","fieldKey","templateId","barcode"] { + if let Some(value) = image.get(key) { row[key] = value.clone(); } + } + out.push(row); } Ok(out) } fn generation_references(dir: &Path, state: &Value, variant_id: &str) -> R { + generation_references_for_output(dir, state, variant_id, state["activeOutput"].as_str().unwrap_or("detail")) +} + +fn generation_references_for_output(dir: &Path, state: &Value, variant_id: &str, component: &str) -> R { let selected = variant(state, variant_id)?; let mut images = state["brief"]["images"].as_array().ok_or("共用参考图记录无效")?.clone(); + let selected_barcode = (component == "detail").then(|| creation::detail_barcode(&state["brief"])).flatten(); + let barcode_matches = |image: &Value| image["barcode"].as_str().is_none_or(|code| { + selected_barcode.is_none_or(|selected| selected == code) && creation::variant_barcodes(&state["brief"], variant_id, + state["variants"].as_array().map_or(0, Vec::len)).any(|barcode| barcode == code) + }); + images.retain(barcode_matches); if state["productTemplates"].is_object() && state["variants"].as_array().is_some_and(|rows| rows.len() > 1) { // Common scene references are useful across colours. Product pixels // must come from the current colour when more than one is registered. - images.retain(|image| image["purpose"] != "product"); + images.retain(|image| image["purpose"] != "product" || image["barcode"].is_string()); } for image in selected["images"].as_array().ok_or("当前花色参考图记录无效")? { - if !images.iter().any(|common| common["source"] == image["source"]) { + if barcode_matches(image) && !images.iter().any(|common| common["source"] == image["source"] + && common["fieldKey"] == image["fieldKey"] && common["barcode"] == image["barcode"]) { images.push(image.clone()); } } @@ -503,7 +519,7 @@ fn generation_references(dir: &Path, state: &Value, variant_id: &str) -> R bool { let Some(cause) = error.strip_prefix("本次生图未提交。") else { return false }; let cause = cause.strip_prefix("模型权限检查失败:").unwrap_or(cause); matches!(cause, "服务连接中断" | "98k模型目录读取失败:服务连接中断" | "98k公开模型目录暂不可用") + || cause.strip_prefix("98k模型目录读取失败:").is_some_and(|error| + matches!(error, super::READ_TIMEOUT | super::READ_INTERRUPTED)) || cause.starts_with("98k暂时无法连接(") || [408, 429, 502, 503, 504].iter().any(|status| { cause == format!("98k公开模型目录暂不可用(HTTP {status})") @@ -2225,7 +2243,7 @@ impl Backend { "retired":!record["retirement"].is_null(),"candidateSlotId":record["binding"]["slotId"]})); } } - let references = generation_references(&dir, &state, &variant_id)?; + let references = generation_references_for_output(&dir, &state, &variant_id, component)?; let mut images = Vec::new(); let reference_limit = if state["productTemplates"].is_object() { 8 } else { 3 }; let originals: Vec<_> = references.as_array().into_iter().flatten() @@ -2266,6 +2284,24 @@ impl Backend { } } let reference_count = images.len(); + let reference_binding = |image: &Value| { + let mut binding = json!({}); + for key in ["imageRole","fieldKey","barcode"] { + if let Some(value) = image.get(key) { binding[key] = value.clone(); } + } + binding + }; + let reference_bindings: Vec<_> = if include_product { originals.iter().map(|image| reference_binding(image)).collect() } else { Vec::new() }; + let mut supplemental = Vec::new(); + let mut supplemental_bindings = Vec::new(); + if include_product && candidate_record.is_none() && target["originalsOnly"] != true { + for image in references.as_array().into_iter().flatten().filter(|image| image["purpose"] == "scene" && image["imageRole"].is_string()) { + let bytes = local_product_photo(&dir, image)?; + let preview = super::images::decode_agent_image(&bytes)?; + supplemental.push(json!({"type":"image","data":photocraft_ui_egui::jiansun::reference_jpeg(&preview,768)?,"mimeType":"image/jpeg"})); + supplemental_bindings.push(reference_binding(image)); + } + } let candidate_prompt = candidate_record.as_ref().map(|record| record["prompt"].clone()); let is_production_review = state["productTemplates"].is_object() && candidate_record.is_some(); let template_base = candidate_record.as_ref().is_some_and(|record| record["templateBase"] == true); @@ -2378,7 +2414,9 @@ impl Backend { } let mapping = cached_prompt_mapping(&dir, &state["template"]); let aspect = specified_image_ratio(field).map(|(w,h)| format!("{w}:{h}")); + images.extend(supplemental); Ok(json!({"images":images,"referenceCount":reference_count,"layoutCount":layout_count,"layoutIssue":layout_issue, + "referenceBindings":reference_bindings,"supplementalBindings":supplemental_bindings, "layoutSource":(fixed_layout && layout_count>0).then_some("pinnedTemplateOriginal"), "relatedCopy":target["relatedCopy"],"adopted":adopted_canvas.is_some(), "outputId":target["outputId"],"variantId":variant_id, @@ -4786,7 +4824,9 @@ impl Backend { next["productTemplateIssues"] = json!({}); } for stage in runnable_stages(&next, production_stages(&next)) { - generation_references(&dir, &next, stage["variantId"].as_str().ok_or("制作款式缺失")?)?; + generation_references_for_output(&dir, &next, + stage["variantId"].as_str().ok_or("制作款式缺失")?, + stage["outputId"].as_str().ok_or("制作成品缺失")?)?; } } next["template"] = pack; diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_client_update.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_client_update.rs index a7c8c3e3..4e983b76 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_client_update.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_client_update.rs @@ -143,15 +143,16 @@ fn download(backend: &Backend, root: &Path, latest: &Value, progress: impl Fn(u6 if received < size { let query = release_query("version", &version); let endpoint = format!("{}/api/desktop/client-release/download?{query}", backend.origin); - let response = backend.http.get(&endpoint).bearer_auth(token).send().map_err(|e| update_network_error(&e))?; + let request = backend.http.get(&endpoint).bearer_auth(token).timeout(Duration::from_secs(8)); + let response = backend.http.read(request).map_err(|e| update_network_error(&e))?; if response.status() != StatusCode::FOUND { return Err(format!("素材库下载入口返回 HTTP {}", response.status().as_u16())); } let location = response.headers().get(header::LOCATION).and_then(|value| value.to_str().ok()).ok_or("素材库下载地址缺失")?; let target = response.url().join(location).map_err(|_| "素材库下载地址无效")?; - let request = backend.http.get(target).timeout(Duration::from_secs(900)); - let mut response = - if received == 0 { request } else { request.header(header::RANGE, format!("bytes={received}-")) }.send().map_err(|e| update_network_error(&e))?; + let request = backend.http.get(target).timeout(Duration::from_secs(90)); + let request = if received == 0 { request } else { request.header(header::RANGE, format!("bytes={received}-")) }; + let mut response = backend.http.read(request).map_err(|e| update_network_error(&e))?; match response.status() { StatusCode::OK => { output.set_len(0).map_err(io_error)?; @@ -170,7 +171,8 @@ fn download(backend: &Backend, root: &Path, latest: &Value, progress: impl Fn(u6 let mut buffer = [0; 64 * 1024]; let mut reported = Instant::now(); loop { - let count = response.read(&mut buffer).map_err(|_| "更新包下载中断,可重新下载续传")?; + let count = response.read(&mut buffer) + .map_err(|error| format!("{};可重新下载并续传", read_network_message(&error)))?; if count == 0 { break; } @@ -355,7 +357,7 @@ mod tests { run(backend, json!({"op":"check","request":1}), tx, egui::Context::default()); let Event::Json(_, Ok(receipt)) = rx.recv().unwrap() else { panic!("missing update status") }; assert_eq!(receipt["patch"]["status"], "error"); - assert!(receipt["patch"]["error"].as_str().unwrap().contains("无法连接")); + assert!(receipt["patch"]["error"].as_str().unwrap().contains("连不上服务器")); assert!(receipt["patch"]["checkedAt"].is_string()); } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs index 35c57e54..f7471153 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs @@ -626,7 +626,7 @@ impl Backend { fs::File::open(p).map_err(|_| "产品图无法读取")?.take(20 * 1024 * 1024 + 1).read_to_end(&mut bytes).map_err(|_| "产品图读取中断")?; out.push(image_copy(&dir, &bytes, p.file_name().and_then(|s| s.to_str()).unwrap_or("产品图"))?); } - Ok(json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"images":out})) + Ok(json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"images":out,"imageSlot":input["imageSlot"]})) } "creation-import-data" => { let images = input["images"].as_array().filter(|a| !a.is_empty() && a.len() <= 8).ok_or("每次最多8张图片")?; @@ -641,7 +641,7 @@ impl Backend { } out.push(image_copy(&dir, &bytes, image["name"].as_str().unwrap_or("产品图"))?); } - Ok(json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"images":out})) + Ok(json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"images":out,"imageSlot":input["imageSlot"]})) } "creation-import-library" => { self.validate()?; @@ -696,6 +696,7 @@ impl Backend { } } } + "creation-product-platform" => self.creation_product_platform(doc, &dir, input), "creation-product" => self.creation_product(input, tx, ctx), "creation-save" => self.save_creation_brief(doc, &dir, input, None), "creation-select" => { @@ -1165,6 +1166,105 @@ pub(super) fn reference_canvas_with_attachments(c: &Value, dir: &Path, doc: u64, } impl Backend { + pub(super) fn platform_previews(&self, receipt: &Value, events: &mpsc::Sender) { + let Some(doc) = receipt["doc"].as_u64() else { return }; + let Ok(dir) = self.project_dir(doc) else { return }; + let mut seen = std::collections::HashSet::new(); + for source in receipt["platformBrief"]["images"].as_array().into_iter().flatten() + .filter(|image| image["platformImage"] == true).filter_map(|image| image["source"].as_str()) { + if !seen.insert(source) { continue; } + if let Ok(file) = assets_file(&dir, source) && let Ok(bytes) = fs::read(file) + && let Ok(image) = reference_thumbnail(&bytes, REFERENCE_THUMBNAIL_EDGE) { + let reference = json!({"purpose":"creation-platform-preview","source":source, + "doc":doc,"accountId":receipt["accountId"],"origin":receipt["origin"]}); + let _ = events.send(Event::Preview(reference, image)); + } + } + } + + fn import_platform_images(&self, dir: &Path, data: &Value, images: &mut Vec) -> usize { + let common = data["mainImages"].as_array().into_iter().flatten().enumerate() + .map(|(position, image)| (position, image, None)); + let specific = data["barcodes"].as_array().into_iter().flatten().flat_map(|row| { + row["images"].as_array().into_iter().flatten().enumerate() + .map(|(position, image)| (position, image, row["barcode"].as_str())) + }); + let mut downloads: Vec<_> = common.chain(specific).collect(); + downloads.sort_by_key(|(position, _, _)| *position); + let mut skipped = 0; + for (index, (_, image, barcode)) in downloads.into_iter().enumerate() { + if index >= 8 || images.len() >= 8 { + skipped += 1; + continue; + } + let download = || -> R { + let url = reqwest::Url::parse(image["url"].as_str().ok_or("参考图缺少地址")?) + .map_err(|_| "参考图地址无效")?; + if !matches!(url.scheme(), "http" | "https") || !url.username().is_empty() || url.password().is_some() { + return Err("参考图地址无效".into()); + } + // Signed asset URLs authorize themselves. Never forward the desktop token. + let response = self.http.get(url).timeout(Duration::from_secs(5)).send() + .and_then(reqwest::blocking::Response::error_for_status).map_err(|_| "参考图无法下载")?; + let mut bytes = Vec::new(); + response.take(20 * 1024 * 1024 + 1).read_to_end(&mut bytes).map_err(|_| "参考图下载中断")?; + let name = barcode.map_or_else(|| format!("产品平台参考图 {}", index + 1), |code| format!("{code} 参考图")); + let mut row = image_copy(dir, &bytes, &name)?; + row["imageRole"] = json!("product"); + row["platformImage"] = json!(true); + if let Some(code) = barcode { row["barcode"] = json!(code); } + Ok(row) + }; + match download() { + Ok(row) => { + if !images.iter().any(|image| image["source"] == row["source"] && image["barcode"] == row["barcode"] + && image["fieldKey"].is_null()) { + images.push(row); + } + } + Err(_) => skipped += 1, + } + } + skipped + } + + fn creation_product_platform(&mut self, doc: u64, dir: &Path, input: &Value) -> R { + let spu = input["spu"].as_str().map(str::trim).filter(|spu| !spu.is_empty() && spu.chars().count() <= 200) + .ok_or("请输入有效的 SPU 型号")?; + let data = self.product_platform_spu(spu)?; + let mut brief = model::platform_brief(&input["brief"], &data)?; + let mut warning = Vec::new(); + if let Some(name) = data["brandName"].as_str().filter(|name| !name.is_empty()) { + match self.enterprise_template_request(json!({"action":"choices","kind":"brands"})) { + Ok(list) => { + if let Some(brand) = list["catalog"]["items"].as_array().into_iter().flatten() + .find(|brand| brand["name"] == name && brand["ready"] == true) { + brief["brandId"] = brand["id"].clone(); + brief["brandName"] = json!(name); + if let Some(category) = brand["categories"].as_array().into_iter().flatten() + .find(|category| category["name"].is_string() && category["name"] == data["categoryName"]) { + brief["categoryId"] = category["id"].clone(); + brief["categoryName"] = category["name"].clone(); + } + } + } + Err(_) => warning.push("品牌目录暂不可用,请手动选择品牌和品类".into()), + } + } + if brief["templateSelection"].is_object() && (brief["templateSelection"]["brandId"] != brief["brandId"] + || brief["templateSelection"]["categoryId"] != brief["categoryId"]) { + brief["templateSelection"] = Value::Null; + if let Some(fields) = brief.as_object_mut() { fields.remove("intake"); } + } + brief = model::brief(&brief)?; + if let Some(images) = brief["images"].as_array_mut() { + let skipped = self.import_platform_images(dir, &data, images); + if skipped > 0 { warning.push(format!("已跳过 {skipped} 张超出上限或暂不可用的参考图")); } + } + Ok(json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin, + "platformBrief":brief,"message":warning.join("。")})) + } + fn creation_product(&mut self, input: &Value, tx: &mpsc::Sender, ctx: &egui::Context) -> R { let doc = input["doc"].as_u64().ok_or("项目身份无效")?; let dir = self.project_dir(doc)?; @@ -1207,6 +1307,11 @@ impl Backend { return Err("此产品没有可用于分析的图片,请上传实拍或CAD导出图片".into()); } let before = c.clone(); + if c["brief"]["source"] == "product_platform" || c["brief"].get("platformFacts").is_some() { + if let Some(fields) = c["brief"].as_object_mut() { + for key in ["platformFacts", "barcodeBindings", "detailBarcode", "intake"] { fields.remove(key); } + } + } c["brief"]["source"] = json!("library"); c["brief"]["name"] = found.get("productModel").cloned().unwrap_or(json!(query)); c["brief"]["identifierType"] = json!(kind); @@ -1534,6 +1639,96 @@ mod tests { (dir, row, stored) } + #[test] + fn product_platform_spu_imports_all_barcodes_and_downloads_only_available_images() { + use std::io::{BufRead, BufReader, Write}; + use std::net::TcpListener; + let (fixture, _, png) = reference_fixture(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let data = json!({"source":"product_platform","spu":"00 α/+", "productName":"产品 A", + "brandName":null,"categoryName":null, + "shared":{"material":"棉","description":null,"dimensions":{"length":12,"width":null,"height":5,"unit":"cm"}}, + "mainImages":[{"url":format!("{origin}/main.png"),"kind":"main","signed":true}], + "barcodes":[{"barcode":"001;a-B","colorName":"灰色","dimensions":{"length":12,"width":8,"height":5,"unit":"cm"}, + "spec":"单人","attributes":{"面料":"绒布"},"images":[{"url":format!("{origin}/sku.png")}]}, + {"barcode":"000Cd","colorName":null,"images":[{"url":format!("{origin}/expired.png")}]}]}); + let routes = vec![ + ("/api/desktop/product-platform/spu?spu=missing",404,vec![]), + ("/api/desktop/product-platform/spu?spu=unconfigured",503,vec![]), + ("/api/desktop/product-platform/spu?spu=00+%CE%B1%2F%2B",200,data.to_string().into_bytes()), + ("/main.png",200,png.clone()), + ("/sku.png",200,png), + ("/expired.png",403,vec![]), + ]; + let (mut backend, dir) = platform_test_backend(&fixture.0, &origin); + let before = model::empty(); + let input = |spu: &str| json!({"doc":1,"spu":spu,"brief":before["brief"]}); + assert!(backend.creation_product_platform(1, &dir, &input("missing")).unwrap_err().contains("登录")); + backend.auth["access_token"] = json!("offline-test-token"); + let server = std::thread::spawn(move || { + for (path, status, bytes) in routes { + let (mut socket, _) = listener.accept().unwrap(); + socket.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); + let mut reader = BufReader::new(&mut socket); + let mut headers = String::new(); + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" { break; } + headers.push_str(&line); + } + assert!(headers.starts_with(&format!("GET {path} HTTP/1.1"))); + assert_eq!(headers.to_ascii_lowercase().contains("authorization: bearer offline-test-token"), + path.starts_with("/api/desktop/")); + write!(socket, "HTTP/1.1 {status} Test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", bytes.len()).unwrap(); + socket.write_all(&bytes).unwrap(); + } + }); + assert!(backend.creation_product_platform(1, &dir, &input("missing")).unwrap_err().contains("未找到")); + assert!(backend.creation_product_platform(1, &dir, &input("unconfigured")).unwrap_err().contains("未配置")); + let receipt = backend.creation_product_platform(1, &dir, &input("00 α/+")).unwrap(); + server.join().unwrap(); + let brief = model::brief(&receipt["platformBrief"]).unwrap(); + assert_eq!(brief["identifier"], "00 α/+"); + assert_eq!(brief["name"], "产品 A"); + assert_eq!(brief["barcodeBindings"]["default"], json!(["001;a-B","000Cd"])); + assert_eq!(brief["detailBarcode"], "001;a-B"); + assert_eq!(brief["platformFacts"]["shared"]["material"], "棉"); + assert!(brief["platformFacts"]["shared"].get("description").is_none()); + assert_eq!(brief["platformFacts"]["barcodes"]["001;a-B"]["dimensions"], json!({"length":12,"width":8,"height":5,"unit":"cm"})); + assert_eq!(brief["platformFacts"]["barcodes"]["001;a-B"]["colorName"], "灰色"); + assert!(brief["platformFacts"]["barcodes"]["000Cd"].get("colorName").is_none()); + assert_eq!(brief["dimensions"]["width"], ""); + assert_eq!(brief["images"].as_array().unwrap().len(), 2); + assert!(brief["images"][0]["barcode"].is_null()); + assert_eq!(brief["images"][1]["barcode"], "001;a-B"); + for image in brief["images"].as_array().unwrap() { + let path = assets_file(&dir, image["source"].as_str().unwrap()).unwrap(); + assert_eq!(reference_thumbnail(&fs::read(path).unwrap(), 320).unwrap().size, [320,160]); + } + assert!(receipt["message"].as_str().unwrap().contains("已跳过 1 张")); + assert!(!dir.join("creation.json").exists(), "lookup must leave the saved draft unchanged before UI applies it"); + } + + fn platform_test_backend(root: &Path, origin: &str) -> (Backend, PathBuf) { + let mut backend = Backend { + root: root.join("platform-profile"), + http: Client::builder().no_proxy().timeout(Duration::from_secs(3)).build().unwrap().into(), + origin: origin.into(), + auth: json!({"account":{"id":"offline-owner"}}), + access: Default::default(), + models: vec![], model: String::new(), + copy_models: vec![], copy_error: String::new(), image_models: vec![], image_error: String::new(), + owners: HashMap::new(), locations: HashMap::new(), last_saved: HashMap::new(), + draft_zip_writer: Default::default(), superseded_docs: Default::default(), + recovery_attempts: Default::default(), recovery_serial: Default::default(), + composer_store: Default::default(), exit_admission_closed: Default::default(), + }; + backend.bind_new(1); + let dir = backend.project_dir(1).unwrap(); + (backend, dir) + } + #[test] fn reference_thumbnails_read_only_canonical_common_or_variant_assets_and_preserve_the_original() { let (dir, row, original) = reference_fixture(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs index 8df3beee..6180c782 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs @@ -30,10 +30,18 @@ fn image_list(value: &Value) -> R { .as_str() .filter(|source| source.strip_prefix("local:").is_some_and(|id| id.len() == 64 && id.bytes().all(|byte| byte.is_ascii_hexdigit()))) .ok_or("产品图必须属于本机项目")?; - if !seen.insert(source) || !matches!(image["purpose"].as_str(), Some("product" | "scene")) { + if !seen.insert((source, image["fieldKey"].as_str(), image["barcode"].as_str())) + || !matches!(image["purpose"].as_str(), Some("product" | "scene")) { return Err("图片用途无效或图片重复".into()); } - clean.push(json!({"source":source,"purpose":image["purpose"],"name":string(&image["name"],200,"图片名称")?})); + let mut row = json!({"source":source,"purpose":image["purpose"],"name":string(&image["name"],200,"图片名称")?}); + for (key, limit) in [("imageRole",120),("fieldKey",120),("templateId",120),("barcode",200)] { + if let Some(value) = image.get(key) { + row[key] = json!(string(value, limit, "图片归属")?); + } + } + if image["platformImage"] == true { row["platformImage"] = json!(true); } + clean.push(row); } Ok(json!(clean)) } @@ -79,7 +87,7 @@ pub(in super::super) fn delivery_spu(brief: &Value) -> Option<&str> { value.as_str().map(str::trim).filter(|spu| !spu.is_empty()) } -fn intake(value: &Value) -> R { +fn intake(value: &Value, platform: bool) -> R { let template_id = string(&value["templateId"], 120, "模板编号")?; if template_id.trim().is_empty() { return Err("产品资料缺少模板编号".into()); } let schema = &value["schema"]; @@ -88,9 +96,9 @@ fn intake(value: &Value) -> R { for (index, name) in ["productFields", "barcodeFields"].iter().enumerate() { let fields = schema[*name].as_array().filter(|rows| rows.len() <= 100).ok_or("产品资料字段格式无效")?; for field in fields { - let id = string(&field["id"], 120, "资料字段编号")?; + let id = string(field.get("id").unwrap_or(&field["key"]), 120, "资料字段编号")?; let label = string(&field["label"], 200, "资料字段名称")?; - let kind = field["type"].as_str().filter(|kind| matches!(*kind, "text" | "number" | "select" | "boolean")) + let kind = field.get("type").unwrap_or(&field["kind"]).as_str().filter(|kind| matches!(*kind, "text" | "number" | "select" | "boolean" | "image")) .ok_or("资料字段类型无效")?; if id.trim().is_empty() || label.trim().is_empty() || kinds[index].insert(id, kind).is_some() { return Err("资料字段编号或名称无效".into()); @@ -98,7 +106,14 @@ fn intake(value: &Value) -> R { if field.get("required").is_some_and(|value| !value.is_boolean()) { return Err("资料字段的必填标记无效".into()); } - for optional in ["help", "unit"] { + if field.get("multiline").is_some_and(|value| !value.is_boolean()) { + return Err("资料字段的多行标记无效".into()); + } + if field.get("multiple").is_some_and(|value| !value.is_boolean()) { + return Err("资料字段的多图标记无效".into()); + } + if let Some(role) = field.get("imageRole") { string(role, 120, "资料图片角色")?; } + for optional in ["help", "unit", "placeholder"] { if let Some(value) = field.get(optional) { string(value, 500, "资料字段说明")?; } } if let Some(options) = field.get("options") { @@ -122,7 +137,7 @@ fn intake(value: &Value) -> R { Ok(()) }; validate_values(&value["productValues"], &kinds[0])?; - let barcode_values = value["barcodeValues"].as_object().filter(|rows| rows.len() <= 200).ok_or("条码资料格式无效")?; + let barcode_values = value["barcodeValues"].as_object().filter(|rows| platform || rows.len() <= 200).ok_or("条码资料格式无效")?; let mut clean = serde_json::Map::new(); for (barcode, fields) in barcode_values { let barcode = barcode.trim(); @@ -159,7 +174,7 @@ pub(super) fn brief(value: &Value) -> R { None => String::new(), }); } - if !matches!(value["source"].as_str(), Some("upload" | "library")) || !matches!(value["identifierType"].as_str(), Some("sku" | "spu" | "barcode")) { + if !matches!(value["source"].as_str(), Some("upload" | "library" | "product_platform")) || !matches!(value["identifierType"].as_str(), Some("sku" | "spu" | "barcode")) { return Err("资料来源或编号类型无效".into()); } out["source"] = value["source"].clone(); @@ -243,6 +258,7 @@ pub(super) fn brief(value: &Value) -> R { if out["identifierType"] != "spu" && let Some(spu) = value.get("deliverySpu") { out["deliverySpu"] = json!(string(spu, 120, "SPU 型号")?.trim()); } + let platform = value["platformFacts"].is_object(); if let Some(bindings) = value.get("barcodeBindings") { let rows = bindings.as_object().filter(|rows| rows.len() <= 65).ok_or("条码绑定格式无效")?; let mut clean = serde_json::Map::new(); @@ -276,7 +292,7 @@ pub(super) fn brief(value: &Value) -> R { return Err("同一花色的条码绑定重复".into()); } } - if owners.len() > 200 { return Err("最多填写 200 个条码".into()); } + if !platform && owners.len() > 200 { return Err("最多填写 200 个条码".into()); } out["barcodeBindings"] = Value::Object(clean); if let Some(selected) = value.get("detailBarcode").filter(|barcode| !barcode.is_null()) { let selected = selected.as_str().ok_or("详情主条码格式无效")?.trim(); @@ -306,8 +322,14 @@ pub(super) fn brief(value: &Value) -> R { } out["outputVariantIds"] = Value::Object(selected); } + if let Some(facts) = value.get("platformFacts") { + if !facts["shared"].is_object() || !facts["barcodes"].is_object() || facts.to_string().len() > 500_000 { + return Err("产品平台资料格式无效或超出大小限制".into()); + } + out["platformFacts"] = facts.clone(); + } if let Some(fields) = value.get("intake") { - out["intake"] = intake(fields)?; + out["intake"] = intake(fields, platform)?; } if let Some(selection) = value.get("templateSelection") { if selection.is_null() { @@ -355,6 +377,62 @@ pub(super) fn brief(value: &Value) -> R { Ok(out) } +pub(super) fn platform_brief(previous: &Value, data: &Value) -> R { + let spu = data["spu"].as_str().filter(|spu| !spu.is_empty()).ok_or("产品平台未返回 SPU")?; + let rows = data["barcodes"].as_array().ok_or("产品平台条码资料格式异常")?; + if data["source"] != "product_platform" || !data["shared"].is_object() { + return Err("产品平台资料格式异常".into()); + } + let mut brief = previous.clone(); + let fields = brief.as_object_mut().ok_or("请先打开产品资料")?; + for key in ["variants", "outputColors", "outputVariantIds", "skuBindings", "detailBarcode", "deliverySpu"] { + fields.remove(key); + } + let mut codes = Vec::new(); + let mut facts = serde_json::Map::new(); + for row in rows { + let code = row["barcode"].as_str().filter(|code| !code.trim().is_empty()) + .ok_or("产品平台返回了空条码")?; + if facts.contains_key(code) { return Err("产品平台返回了重复条码".into()); } + codes.push(code); + facts.insert(code.to_owned(), platform_fields(row, + &["skuCode","skuName","colorName","dimensions","spec","sizeText","attributes","sellingPoints","updatedAt"])); + } + brief["source"] = json!("product_platform"); + brief["name"] = json!(data["productName"].as_str().unwrap_or("")); + brief["identifierType"] = json!("spu"); + brief["identifier"] = json!(spu); + for field in ["brandId", "brandName", "categoryId", "categoryName", "variant", "colorMaterialId", "colorName"] { + brief[field] = json!(""); + } + brief["colorName"] = json!(rows.first().and_then(|row| row["colorName"].as_str()).unwrap_or("")); + brief["barcodeBindings"] = json!({"default":codes}); + if let Some(code) = codes.first() { brief["detailBarcode"] = json!(code); } + brief["platformFacts"] = json!({"spu":spu,"shared":platform_fields(&data["shared"], + &["dimensions","sizeText","material","description","attributes","sellingPoints"]),"barcodes":facts}); + brief["dimensions"] = empty()["brief"]["dimensions"].clone(); + let dimensions = &data["shared"]["dimensions"]; + if let Some(unit @ ("mm" | "cm" | "m")) = dimensions["unit"].as_str() { + brief["dimensions"]["unit"] = json!(unit); + for axis in ["length","width","height"] { + if let Some(n) = dimensions[axis].as_f64().filter(|n| *n > 0.0 && *n < 1_000_000.0 && *n == (*n * 1000.0).round() / 1000.0) { + brief["dimensions"][axis] = json!(n.to_string()); + } + } + } + if let Some(images) = brief["images"].as_array_mut() { + let same_product = previous["identifierType"] == "spu" && previous["identifier"] == spu; + images.retain(|image| image["platformImage"] != true && image["barcode"].as_str() + .is_none_or(|barcode| same_product && codes.contains(&barcode))); + } + Ok(brief) +} + +fn platform_fields(row: &Value, keys: &[&str]) -> Value { + Value::Object(keys.iter().filter_map(|&key| row.get(key).filter(|value| !value.is_null()) + .map(|value| (key.to_owned(), value.clone()))).collect()) +} + pub(super) fn facts_hash(c: &Value) -> String { hash(&json!({"brief":production_brief(&c["brief"]),"facts":c["facts"]}).to_string()) } @@ -703,6 +781,26 @@ mod tests { assert!(brief(&source).unwrap_err().contains("非空字符串")); } + #[test] + fn image_intake_preserves_schema_roles_and_exact_barcode_bindings() { + let mut original = empty()["brief"].clone(); + let asset = format!("local:{}", "a".repeat(64)); + original["barcodeBindings"] = json!({"default":["000xy"]}); + original["intake"] = json!({"templateId":"t","schema":{"version":1, + "productFields":[{"key":"hero","kind":"image","label":"产品图片","imageRole":"product","placeholder":"拖入产品图"}], + "barcodeFields":[{"key":"fabric","kind":"image","label":"材质图片","imageRole":"material","multiple":false}]}, + "productValues":{},"barcodeValues":{}}); + original["images"] = json!([ + {"source":asset,"name":"参考","purpose":"product","imageRole":"product","fieldKey":"hero","templateId":"t"}, + {"source":asset,"name":"参考","purpose":"scene","imageRole":"material","fieldKey":"fabric","templateId":"t","barcode":"000xy"} + ]); + let decoded = brief(&original).unwrap(); + assert_eq!(decoded["intake"], original["intake"]); + assert_eq!(decoded["images"], original["images"]); + original["intake"]["schema"]["barcodeFields"][0]["multiple"] = json!("false"); + assert!(brief(&original).is_err()); + } + #[test] fn template_intake_roundtrip_preserves_multiple_barcode_values_and_drafts() { let mut value = canvas_brief(); @@ -710,7 +808,7 @@ mod tests { "templateId":value["templateSelection"]["id"], "schema":{"version":1, "productFields":[{"id":"length","label":"长度","type":"number","unit":"cm"}], - "barcodeFields":[{"id":"size","label":"规格","type":"text"}]}, + "barcodeFields":[{"id":"size","label":"规格","type":"text","placeholder":"请输入规格","multiline":true}]}, "productValues":{"length":"1e"}, "barcodeValues":{"001 Foo, A/B;甲":{"size":"大号"},"CY001307N35V01":{"size":"小号"}} }); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_feedback.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_feedback.rs new file mode 100644 index 00000000..0240fc3a --- /dev/null +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_feedback.rs @@ -0,0 +1,92 @@ +use super::{Backend, R, Value}; +use std::time::Duration; + +pub(super) fn submit(backend: &Backend, input: &Value) -> R { + if input["origin"] != backend.origin || input["accountId"] != backend.auth["account"]["id"] { + return Err("账号已切换,请重新打开反馈".into()); + } + let token = backend.auth["access_token"].as_str().ok_or("请先登录素材库账号")?; + let payload = photocraft_ui_egui::jiansun::feedback_payload(&input["payload"])?; + backend.check_dispatch()?; + let response = backend + .http + .post(format!("{}/api/desktop/feedback", backend.origin)) + .bearer_auth(token) + .timeout(Duration::from_secs(15)) + .json(&payload) + .send() + .map_err(|_| "暂时无法确认反馈结果,请联网后用同一编号重试")?; + match response.status().as_u16() { + 200..=299 => {} + 401 | 403 => return Err("授权已失效或无权限,请检查素材库账号".into()), + 404 => return Err("当前素材库暂未开放客户端反馈".into()), + 409 => return Err("反馈编号不可用,请重新打开反馈".into()), + _ => return Err("反馈暂未提交,请稍后重试".into()), + } + let value: Value = response.json().map_err(|_| "反馈回执无法读取,请用同一编号重试")?; + if value["feedback"]["feedbackId"] != payload["feedbackId"] { + return Err("反馈回执无法确认,请用同一编号重试".into()); + } + Ok(value) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::jiansun_backend::json; + use std::io::{BufRead, BufReader, Read, Write}; + use std::net::TcpListener; + + #[test] + fn feedback_sends_a_screened_bearer_request_and_reuses_the_id_on_retry() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let id = uuid::Uuid::new_v4().to_string(); + let expected = id.clone(); + let server = std::thread::spawn(move || { + for status in ["503 Unavailable", "200 OK"] { + let (mut socket, _) = listener.accept().unwrap(); + socket.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut reader = BufReader::new(&mut socket); + let mut request = String::new(); + reader.read_line(&mut request).unwrap(); + assert_eq!(request, "POST /api/desktop/feedback HTTP/1.1\r\n"); + let mut authorization = false; + let mut length = 0; + loop { + let mut header = String::new(); + reader.read_line(&mut header).unwrap(); + if header.trim().is_empty() { + break; + } + let header = header.trim().to_ascii_lowercase(); + authorization |= header == "authorization: bearer local-fixture"; + if let Some(value) = header.strip_prefix("content-length: ") { + length = value.parse().unwrap(); + } + } + assert!(authorization); + let mut body = vec![0; length]; + reader.read_exact(&mut body).unwrap(); + let payload: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!( + payload, + json!({"feedbackId":expected,"summary":"无法打开项目", + "context":{"client":"XiaoYi","error":"[敏感信息已移除]"}}) + ); + let reply = json!({"feedback":{"feedbackId":expected,"detailPath":format!("/feedback/{expected}")}}).to_string(); + write!(socket, "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", reply.len()) + .unwrap(); + } + }); + let directory = tempfile::tempdir().unwrap(); + let mut backend = Backend::new(directory.path().join("jiansun")).unwrap(); + backend.origin = origin.clone(); + backend.auth = json!({"access_token":"local-fixture","account":{"id":"qa"}}); + let input = json!({"accountId":"qa","origin":origin,"payload":{"feedbackId":id,"summary":" 无法打开项目 ", + "context":{"client":"XiaoYi","error":"Cookie=fixture","screenshot":[12,13,14]}}}); + assert!(submit(&backend, &input).is_err()); + assert_eq!(submit(&backend, &input).unwrap()["feedback"]["feedbackId"], id); + server.join().unwrap(); + } +} diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs index 608e1dd2..efdf3d6a 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs @@ -851,12 +851,12 @@ impl Backend { } self.check_dispatch()?; let token = self.auth["access_token"].as_str().ok_or("请先在素材库登录")?; - let response = self + let request = self .http .get(format!("{}/api/desktop/session", self.origin)) .bearer_auth(token) - .timeout(recovery_timeout(deadline, Duration::from_secs(30))?) - .send(); + .timeout(recovery_timeout(deadline, Duration::from_secs(8))?); + let response = self.http.read_until(request, deadline); // 素材库暂时连不上或服务端出错时沿用本机登录,只有明确的授权撤销或换号才拦下。 let Ok(response) = response else { return self.check_dispatch(); }; if response.status().is_server_error() { @@ -1200,9 +1200,9 @@ impl Backend { request = request.header("Idempotency-Key", id); } check()?; - let response = request.send().map_err(|_| { + let response = self.http.read_until(request, deadline).map_err(|error| { wait.set(Some(RecoveryWait::Network)); - "原请求只读查询连接中断,保留待核查;不会重发" + format!("{};原请求保留待核查", network_message(&error)) })?; check()?; if let Some(last) = diagnostic["attempts"].as_array_mut().and_then(|a| a.last_mut()) { @@ -1279,7 +1279,7 @@ impl Backend { if self.exiting() { return Err("客户端正在退出,未提交生图请求".into()); } self.check_dispatch()?; progress("98k 正在生成图片…", true); - client.execute(request).map_err(|_| "生成连接中断,结果待核查;不会重发".into()) + client.execute(request).map_err(|error| stream::transport_error(&error)) })?; if let Some(seconds) = response.headers().get(reqwest::header::RETRY_AFTER).and_then(|value| value.to_str().ok()).and_then(|value| value.parse::().ok()) { t["retryAfterSeconds"] = json!(seconds); @@ -1310,14 +1310,14 @@ impl Backend { let uid = t["upstreamTaskId"].as_str().filter(|s| protocol::token(s)).ok_or("任务号无效")?; progress(if recover { "正在等待原任务结果…" } else { "正在生成图片…" }, false); check()?; - let response = self.http + let request = self.http .get(format!("{UPSTREAM}/extensions/v1/tasks/{uid}/result")) .bearer_auth(key) - .timeout(recovery_timeout(deadline, Duration::from_secs(30))?) - .send() - .map_err(|_| { + .timeout(recovery_timeout(deadline, Duration::from_secs(30))?); + let response = self.http.read_until(request, deadline) + .map_err(|error| { wait.set(Some(RecoveryWait::Network)); - "任务查询连接中断" + network_message(&error) })?; check()?; if response.status() == reqwest::StatusCode::GONE { @@ -1364,9 +1364,10 @@ impl Backend { } self.image_validate(deadline)?; check()?; - let response = self.http.get(url).timeout(recovery_timeout(deadline, Duration::from_secs(30))?).send().map_err(|_| { + let request = self.http.get(url).timeout(recovery_timeout(deadline, Duration::from_secs(30))?); + let response = self.http.read_until(request, deadline).map_err(|error| { wait.set(Some(RecoveryWait::Network)); - "图片下载连接中断,保留原结果后可重取" + format!("{};原结果已保留,可重新下载", network_message(&error)) })?; let code = response.status().as_u16(); if let Some(observed) = observed_wait("asset", code, &Value::Null) { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs index 716c6d8d..03832933 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs @@ -9,6 +9,7 @@ use std::{ net::{Ipv4Addr, SocketAddrV4, TcpListener, TcpStream}, process::Command, sync::{Arc, LazyLock, Mutex, OnceLock}, + sync::atomic::{AtomicU8, Ordering}, time::Duration, }; @@ -21,11 +22,15 @@ const XIAOYI_CURRENT: &str = "/api/xiaoyi/v1/templates/key-check/current"; const ORIGINS: &str = include_str!("../../../../detail-agent-pi/src/enterprise-knowledge-origins.json"); const INVALID: &str = "企业知识库请求边界无效"; const CREDENTIAL: &str = "企业知识库用户凭据未配置或不可读取"; -const NETWORK: &str = "企业知识库网络不可达"; +const NETWORK: &str = "连不上企业知识库服务器,请检查网络、VPN 或代理"; +const TIMEOUT: &str = "企业知识库请求超时,请检查网络后重试"; const RESPONSE: &str = "企业知识库响应无效"; const XIAOYI_ORIGIN_REQUIRED: &str = "请通过公司内网或 HTTPS 连接小壹制作知识库"; -const PORTAL_UNAVAILABLE: &str = "素材库暂时无法连接,请稍后重试"; +const PORTAL_UNAVAILABLE: &str = "连不上素材库服务器,请检查网络、VPN 或代理"; +const PORTAL_TIMEOUT: &str = "素材库换签请求超时,请检查网络后重试"; +const PORTAL_SERVER: &str = "素材库换签服务端异常,请稍后重试"; +const GATEWAY: &str = "小壹知识库服务端异常,请稍后重试"; const PORTAL_LOGIN: &str = "素材库授权已失效,请重新登录"; const PORTAL_FORBIDDEN: &str = "当前账户无权使用小壹知识库"; const AUTOMATIC_INVALID: &str = "小壹知识库自动授权无效,请联系管理员"; @@ -41,6 +46,7 @@ struct Account { access: super::AccountAccess, http: super::NetworkClient, cached: Arc>>, + channel: Arc, } static ACCOUNT: LazyLock>> = LazyLock::new(|| Mutex::new(None)); @@ -69,6 +75,7 @@ pub(super) fn set_account(backend: &super::Backend) { access: backend.access.clone(), http: backend.http.clone(), cached: Arc::new(Mutex::new(None)), + channel: Arc::new(AtomicU8::new(0)), }); } @@ -82,9 +89,8 @@ pub(super) fn clear_account(backend: &super::Backend) { } } -fn automatic_credential() -> R { - let account = ACCOUNT.lock().map_err(|_| PORTAL_UNAVAILABLE)?.clone().ok_or(PORTAL_LOGIN)?; - account_credential(&account) +fn current_account() -> R { + ACCOUNT.lock().map_err(|_| PORTAL_UNAVAILABLE)?.clone().ok_or_else(|| PORTAL_LOGIN.into()) } fn account_credential(account: &Account) -> R { @@ -94,19 +100,38 @@ fn account_credential(account: &Account) -> R { account.access.check().map_err(|_| PORTAL_LOGIN)?; return Ok(token.clone()); } - let response = account.http.get(format!("{}/api/desktop/knowledge/session", account.origin)) - .bearer_auth(&account.token).send().map_err(|_| PORTAL_UNAVAILABLE)?; + let request = account.http.get(format!("{}/api/desktop/knowledge/session", account.origin)) + .bearer_auth(&account.token).timeout(Duration::from_secs(8)); + let mut misconfigured = false; + let mut payload = Ok(Value::Null); + let response = account.http.read_with(request, None, |response| { + let status = response.status().as_u16(); + if status == 200 { + payload = super::response_json(response, super::MAX_JSON); + return matches!(payload, Err(super::JsonResponseError::Read(_))) && account.access.check().is_ok(); + } + if status == 503 { + misconfigured = super::response_json(response, 16 * 1024).is_ok_and(|value| + value["code"] == "knowledge_session_misconfigured"); + } + super::transient_status(status) && !misconfigured && account.access.check().is_ok() + }).map_err(|error| if error.is_timeout() { PORTAL_TIMEOUT } else { PORTAL_UNAVAILABLE })?; let status = response.status().as_u16(); account.access.check().map_err(|_| PORTAL_LOGIN)?; match status { 404 => return Err(SESSION_MISSING.into()), - 503 => return Err(SESSION_UNAVAILABLE.into()), + 503 if misconfigured => return Err(SESSION_UNAVAILABLE.into()), 401 => return Err(PORTAL_LOGIN.into()), 403 => return Err(PORTAL_FORBIDDEN.into()), 200 => {} - _ => return Err(PORTAL_UNAVAILABLE.into()), + 500..=599 => return Err(PORTAL_SERVER.into()), + _ => return Err(AUTOMATIC_INVALID.into()), } - let (_, value) = super::body(response, super::MAX_JSON).map_err(|_| AUTOMATIC_INVALID)?; + let value = payload.map_err(|error| match error { + super::JsonResponseError::Read(error) if super::read_timed_out(&error) => PORTAL_TIMEOUT, + super::JsonResponseError::Read(_) => PORTAL_UNAVAILABLE, + _ => AUTOMATIC_INVALID, + })?; account.access.check().map_err(|_| PORTAL_LOGIN)?; let token = value["token"].as_str().filter(|token| token.starts_with(TOKEN_PREFIX)) .ok_or(AUTOMATIC_INVALID)?; @@ -122,10 +147,16 @@ fn account_credential(account: &Account) -> R { Ok(token) } -fn verify_automatic_key(key: &str) -> Value { - let mut result = match origins() { - Ok(endpoints) => verify_xiaoyi_key(key, &endpoints, || Ok(false)), - Err(_) => json!({"status":null,"saved":false,"error":INVALID}), +fn verify_automatic_key() -> Value { + let response: R<_> = (|| { + let account = current_account()?; + let [origin, _] = origins()?; + let (response, _) = automatic_response(&account, &origin, XIAOYI_CURRENT, &json!({"headers":{}}))?; + Ok(response) + })(); + let mut result = match response { + Ok(response) => verified_key_response(response, || Ok(false)), + Err(error) => json!({"status":null,"saved":false,"error":error}), }; match result["status"].as_u64() { Some(401) => result["error"] = json!("知识库自动授权已失效,请重新登录素材库。"), @@ -136,13 +167,8 @@ fn verify_automatic_key(key: &str) -> Value { } pub(super) fn automatic_status() -> Value { - match automatic_credential() { - Ok(key) => { - let result = verify_automatic_key(&key); - json!({"mode":"automatic","error":result["error"].as_str().unwrap_or_default()}) - } - Err(error) => json!({"mode":"unavailable","error":error}), - } + let result = configure_for_account(&Value::Null); + json!({"mode":result["mode"],"error":result["error"].as_str().unwrap_or_default()}) } pub(super) fn configure_for_account(input: &Value) -> Value { @@ -151,14 +177,9 @@ pub(super) fn configure_for_account(input: &Value) -> Value { result["mode"] = json!("manual"); return result; } - match automatic_credential() { - Ok(key) => { - let mut result = verify_automatic_key(&key); - result["mode"] = json!("automatic"); - result - } - Err(error) => json!({"mode":"unavailable","status":null,"saved":false,"error":error}), - } + let mut result = verify_automatic_key(); + result["mode"] = if result["status"].is_null() { json!("unavailable") } else { json!("automatic") }; + result } @@ -219,15 +240,24 @@ pub(super) fn configure_xiaoyi(input: &Value) -> Value { } fn verify_xiaoyi_key(key: &str, origins: &[String], save: impl FnOnce() -> R) -> Value { - let Ok(client) = MCP_CLIENT.as_ref() else { - return json!({"status":null,"saved":false,"error":NETWORK}); - }; + let mut diagnosis = NETWORK; let response = origins.iter().filter(|origin| allows_xiaoyi_origin(origin)).find_map(|origin| { - client.get(format!("{origin}{XIAOYI_CURRENT}")).bearer_auth(key).send().ok() + let client = MCP_CLIENT.get(origin).ok()?; + match client.get(format!("{origin}{XIAOYI_CURRENT}")).bearer_auth(key).send() { + Ok(response) => Some(response), + Err(error) => { + diagnosis = if error.is_timeout() { TIMEOUT } else { NETWORK }; + None + } + } }); let Some(response) = response else { - return json!({"status":null,"saved":false,"error":NETWORK}); + return json!({"status":null,"saved":false,"error":diagnosis}); }; + verified_key_response(response, save) +} + +fn verified_key_response(response: reqwest::blocking::Response, save: impl FnOnce() -> R) -> Value { let status = response.status().as_u16(); let accepted = match status { 200 => response.json::().is_ok_and(|body| { @@ -303,10 +333,10 @@ impl Route { Ok(Self::Download) } (Some("GET"), path) - if input["body"].is_null() + if input["body"].is_null() && !path.contains('#') && regex::Regex::new( r"\A/api/xiaoyi/v1/(?:templates|templates/[A-Za-z0-9][A-Za-z0-9_.-]*/(?:current|releases/[A-Za-z0-9][A-Za-z0-9_.-]*/(?:manifest|bundle))|blobs/[a-f0-9]{64})\z" - ).map_err(|_| INVALID)?.is_match(path) => + ).map_err(|_| INVALID)?.is_match(path.split_once('?').map_or(path, |(route, _)| route)) => { if allows_xiaoyi_origin(origin) { Ok(Self::Xiaoyi) } else { Err(XIAOYI_ORIGIN_REQUIRED.into()) } } @@ -343,7 +373,10 @@ pub(super) fn exchange(input: &Value, mut emit: impl FnMut(Value) -> R<()>) -> R let token = std::env::var(BRIDGE_TOKEN).map_err(|_| INVALID)?; return relay_bridge(port.to_str().ok_or(INVALID)?.parse().map_err(|_| INVALID)?, &token, input, &mut emit); } - exchange_route(route, input, || Err(CREDENTIAL.into()), automatic_credential, &mut emit) + if route == Route::Xiaoyi { + return exchange_automatic(¤t_account()?, input, &mut emit); + } + exchange_route(route, input, || Err(CREDENTIAL.into()), || Err(INVALID.into()), &mut emit) })(); emit_error(result, &mut emit) } @@ -352,10 +385,14 @@ fn emit_error(result: R<()>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> { if let Err(error) = result { let (category, message) = match error.as_str() { NETWORK => ("network", NETWORK), + TIMEOUT => ("timeout", TIMEOUT), CREDENTIAL => ("credential", CREDENTIAL), - PORTAL_LOGIN => ("credential", PORTAL_LOGIN), - PORTAL_FORBIDDEN => ("credential", PORTAL_FORBIDDEN), - PORTAL_UNAVAILABLE => ("network", PORTAL_UNAVAILABLE), + PORTAL_LOGIN => ("session-login", PORTAL_LOGIN), + PORTAL_FORBIDDEN => ("session-forbidden", PORTAL_FORBIDDEN), + PORTAL_UNAVAILABLE => ("session-network", PORTAL_UNAVAILABLE), + PORTAL_TIMEOUT => ("session-timeout", PORTAL_TIMEOUT), + PORTAL_SERVER => ("server", PORTAL_SERVER), + GATEWAY => ("gateway", GATEWAY), SESSION_MISSING => ("session-missing", SESSION_MISSING), SESSION_UNAVAILABLE => ("session-unavailable", SESSION_UNAVAILABLE), AUTOMATIC_INVALID => ("credential", AUTOMATIC_INVALID), @@ -367,18 +404,111 @@ fn emit_error(result: R<()>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> { Ok(()) } -// reqwest blocking applies the client timeout to each response read. -static HEALTH_CLIENT: LazyLock> = LazyLock::new(|| client(2)); -static MCP_CLIENT: LazyLock> = LazyLock::new(|| client(15)); -static DOWNLOAD_CLIENT: LazyLock> = LazyLock::new(|| client(180)); +// The blocking timeout covers headers and each body read. Node bounds the complete exchange. +struct KnowledgeClients { + timeout_seconds: u64, + direct: OnceLock>, + https: OnceLock>, +} +impl KnowledgeClients { + const fn new(timeout_seconds: u64) -> Self { + Self { timeout_seconds, direct: OnceLock::new(), https: OnceLock::new() } + } + + fn get(&self, origin: &str) -> R<&Client> { + let https = url::Url::parse(origin).is_ok_and(|url| url.scheme() == "https" && !super::NetworkClient::is_loopback(&url)); + let cache = if https { &self.https } else { &self.direct }; + cache.get_or_init(|| { + let builder = super::network_builder(Duration::from_secs(self.timeout_seconds)).pool_max_idle_per_host(0); + if https { builder.build() } else { builder.no_proxy().connect_timeout(Duration::from_secs(2)).build() } + }).as_ref().map_err(|_| NETWORK.into()) + } +} +static HEALTH_CLIENT: KnowledgeClients = KnowledgeClients::new(2); +static MCP_CLIENT: KnowledgeClients = KnowledgeClients::new(15); +static METADATA_CLIENT: KnowledgeClients = KnowledgeClients::new(12); +static DOWNLOAD_CLIENT: KnowledgeClients = KnowledgeClients::new(180); + +#[cfg(test)] fn client(timeout_seconds: u64) -> reqwest::Result { - Client::builder() - .no_proxy() - .redirect(reqwest::redirect::Policy::none()) - .retry(reqwest::retry::never()) - .timeout(Duration::from_secs(timeout_seconds)) - .build() + super::network_builder(Duration::from_secs(timeout_seconds)).no_proxy().build() +} + +fn is_large(path: &str) -> bool { + let path = path.split_once('?').map_or(path, |(route, _)| route); + path.ends_with("/bundle") || path.starts_with("/api/xiaoyi/v1/blobs/") +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum KnowledgeChannel { Direct = 1, Portal = 2 } + +fn secure_portal(origin: &str) -> bool { + super::portal_origin(origin).is_ok_and(|canonical| canonical == origin) +} + +fn automatic_response( + account: &Account, origin: &str, path: &str, input: &Value, +) -> R<(reqwest::blocking::Response, String)> { + use KnowledgeChannel::{Direct, Portal}; + if !allows_xiaoyi_origin(origin) { return Err(XIAOYI_ORIGIN_REQUIRED.into()); } + let last = account.channel.load(Ordering::Relaxed); + let preferred = if last == Portal as u8 { [Portal, Direct] } else { [Direct, Portal] }; + let mut diagnosis = NETWORK; + for channel in preferred { + account.access.check().map_err(|_| PORTAL_LOGIN)?; + let clients = if is_large(path) { &DOWNLOAD_CLIENT } else { &METADATA_CLIENT }; + let (client, address, key) = match channel { + Direct => { + if last != Direct as u8 { + match HEALTH_CLIENT.get(origin)?.get(format!("{origin}/healthz")).send() { + Ok(response) if response.status().is_success() => {} + Err(error) if error.is_timeout() => { diagnosis = TIMEOUT; continue; } + _ => continue, + } + } + (clients.get(origin)?, format!("{origin}{path}"), account_credential(account)?) + } + Portal => { + if !secure_portal(&account.origin) { continue; } + let address = format!("{}/api/desktop/knowledge/proxy{path}", account.origin); + (account.http.client(&address), address, account.token.clone()) + } + }; + account.access.check().map_err(|_| PORTAL_LOGIN)?; + let result = Route::Xiaoyi.request(client, address, input)?.bearer_auth(&key) + .timeout(Duration::from_secs(clients.timeout_seconds)).send(); + let mut response = match result { + Ok(response) => response, + Err(error) => { + diagnosis = if error.is_timeout() { TIMEOUT } else { NETWORK }; + continue; + } + }; + account.access.check().map_err(|_| PORTAL_LOGIN)?; + let status = response.status().as_u16(); + if super::transient_status(status) { + if status == 503 && super::response_json(&mut response, 16 * 1024) + .is_ok_and(|value| value["code"] == "knowledge_session_misconfigured") { + return Err(SESSION_UNAVAILABLE.into()); + } + diagnosis = GATEWAY; + continue; + } + if response.status().is_success() || status == 404 { + account.channel.store(channel as u8, Ordering::Relaxed); + } + return Ok((response, key)); + } + // Probe both routes again on the next read if neither was reachable. + account.channel.store(0, Ordering::Relaxed); + Err(diagnosis.into()) +} + +fn exchange_automatic(account: &Account, input: &Value, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> { + let (response, key) = automatic_response(account, input["origin"].as_str().ok_or(INVALID)?, + input["path"].as_str().ok_or(INVALID)?, input)?; + emit_response(response, Some(&key), emit) } fn exchange_route( @@ -388,13 +518,15 @@ fn exchange_route( xiaoyi_key: impl FnOnce() -> R, emit: &mut impl FnMut(Value) -> R<()>, ) -> R<()> { - let url = format!("{}{}", input["origin"].as_str().ok_or(INVALID)?, input["path"].as_str().ok_or(INVALID)?); + let origin = input["origin"].as_str().ok_or(INVALID)?; + let path = input["path"].as_str().ok_or(INVALID)?; let client = match route { Route::Health => &HEALTH_CLIENT, Route::Mcp => &MCP_CLIENT, + Route::Xiaoyi if !is_large(path) => &METADATA_CLIENT, Route::Download | Route::Xiaoyi => &DOWNLOAD_CLIENT, - }.as_ref().map_err(|_| NETWORK)?; - let request = route.request(client, url, input)?; + }.get(origin)?; + let request = route.request(client, format!("{origin}{path}"), input)?; let key = match route { Route::Health => None, Route::Xiaoyi => Some(xiaoyi_key()?), @@ -451,6 +583,7 @@ fn serve_bridge( allowed_origins: impl FnOnce() -> R<[String; 2]>, ) -> R<()> { stream.set_read_timeout(Some(Duration::from_secs(5))).map_err(|_| NETWORK)?; + stream.set_write_timeout(Some(Duration::from_secs(15))).map_err(|_| NETWORK)?; let result = (|| { let Some(Ok(line)) = super::pi::bounded_line(&mut BufReader::new(&stream))? else { return Err(INVALID.into()); @@ -470,16 +603,23 @@ fn serve_bridge( if route != Route::Xiaoyi { return Err(INVALID.into()); } - exchange_route(route, input, || Err(INVALID.into()), || match key { - Some(key) => normalize_key(key.to_str().ok_or(CREDENTIAL)?), - None => automatic_credential(), - }, &mut |frame| writeln!(stream, "{frame}").map_err(|_| NETWORK.into())) + let emit = &mut |frame| writeln!(stream, "{frame}").map_err(|_| NETWORK.into()); + match key { + Some(key) => exchange_route(route, input, || Err(INVALID.into()), || + normalize_key(key.to_str().ok_or(CREDENTIAL)?), emit), + None => exchange_automatic(¤t_account()?, input, emit), + } })(); emit_error(result, &mut |frame| writeln!(stream, "{frame}").map_err(|_| NETWORK.into())) } fn relay_bridge(port: u16, token: &str, input: &Value, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> { - let mut stream = TcpStream::connect(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port)).map_err(|_| NETWORK)?; + // Raw loopback TCP never consults HTTP_PROXY or the Windows proxy settings. + let address = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port).into(); + let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(3)).map_err(|_| NETWORK)?; + let idle = if is_large(input["path"].as_str().ok_or(INVALID)?) { 210 } else { 45 }; + stream.set_read_timeout(Some(Duration::from_secs(idle))).map_err(|_| NETWORK)?; + stream.set_write_timeout(Some(Duration::from_secs(5))).map_err(|_| NETWORK)?; writeln!(stream, "{}", json!({"authorization":token,"request":input})).map_err(|_| NETWORK)?; let mut reader = BufReader::new(stream); while let Some(Ok(line)) = super::pi::bounded_line(&mut reader)? { @@ -495,7 +635,11 @@ fn relay_bridge(port: u16, token: &str, input: &Value, emit: &mut impl FnMut(Val fn send(request: RequestBuilder, key: Option<&str>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> { let request = if let Some(key) = key { request.bearer_auth(key) } else { request }; - let mut response = request.send().map_err(|_| NETWORK)?; + let response = request.send().map_err(|error| if error.is_timeout() { TIMEOUT } else { NETWORK })?; + emit_response(response, key, emit) +} + +fn emit_response(mut response: reqwest::blocking::Response, key: Option<&str>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> { let secret = key.map(|value| Finder::new(value.as_bytes())); let mut headers = serde_json::Map::new(); for name in ["content-type", "mcp-session-id", "mcp-protocol-version", "retry-after", "etag", "content-range", "content-length"] { @@ -518,7 +662,7 @@ fn stream_body(body: &mut impl Read, secret: Option<&Finder<'_>>, emit: &mut imp let mut pending = Vec::with_capacity(8192 + overlap); let mut chunk = [0; 8192]; loop { - let count = body.read(&mut chunk).map_err(|_| NETWORK)?; + let count = body.read(&mut chunk).map_err(|error| if super::read_timed_out(&error) { TIMEOUT } else { NETWORK })?; pending.extend_from_slice(&chunk[..count]); if secret.is_some_and(|needle| needle.find(&pending).is_some()) { return Err(RESPONSE.into()); @@ -578,6 +722,7 @@ mod tests { let account = Account { origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(), access: access.clone(), http: client.into(), cached: Arc::new(Mutex::new(None)), + channel: Arc::new(AtomicU8::new(0)), }; assert!(matches!(account_credential(&account), Ok(token) if token == TOKEN)); server.join().unwrap(); @@ -589,8 +734,10 @@ mod tests { #[test] fn jiansun_missing_knowledge_signer_returns_http_diagnostics() { for (status, body, code, message) in [ + (401, "{}", "session-login", PORTAL_LOGIN), + (403, "{}", "session-forbidden", PORTAL_FORBIDDEN), (404, r#"{"code":"not_found"}"#, "session-missing", SESSION_MISSING), - (503, r#"{"code":"knowledge_session_unavailable"}"#, "session-unavailable", SESSION_UNAVAILABLE), + (503, r#"{"code":"knowledge_session_misconfigured"}"#, "session-unavailable", SESSION_UNAVAILABLE), ] { let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); let origin = format!("http://{}", listener.local_addr().unwrap()); @@ -607,6 +754,7 @@ mod tests { origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(), access: super::super::AccountAccess::default(), http: client(5).unwrap().into(), cached: Arc::new(Mutex::new(None)), + channel: Arc::new(AtomicU8::new(0)), }; let error = account_credential(&account).unwrap_err(); assert_eq!(error, message); @@ -618,6 +766,109 @@ mod tests { } } + #[test] + fn jiansun_knowledge_signer_retries_reset_and_transient_503() { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = std::thread::spawn(move || { + listener.set_nonblocking(true).unwrap(); + let deadline = std::time::Instant::now() + Duration::from_secs(5); + for attempt in 0..3 { + let mut stream = loop { + match listener.accept() { + Ok((stream, _)) => break stream, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock && std::time::Instant::now() < deadline => + std::thread::sleep(Duration::from_millis(10)), + Err(error) => panic!("missing retry {attempt}: {error}"), + } + }; + stream.set_nonblocking(false).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let lines = BufReader::new(&mut stream).lines(); + assert!(lines.map(Result::unwrap).take_while(|line| !line.is_empty()) + .any(|line| line == "authorization: Bearer synthetic-desktop-session")); + if attempt == 0 { + stream.shutdown(std::net::Shutdown::Both).unwrap(); + continue; + } + let status = if attempt == 1 { 503 } else { 200 }; + let body = if attempt == 1 { "{}".into() } else { + json!({"token":"ekb_xiaoyi_session_retry-fixture", + "expiresAt":(chrono::Utc::now() + chrono::Duration::seconds(300)).to_rfc3339()}).to_string() + }; + write!(stream, "HTTP/1.1 {status} Fixture\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap(); + } + }); + let account = Account { + origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(), + access: super::super::AccountAccess::default(), http: super::super::NetworkClient::new(false).unwrap(), + cached: Arc::new(Mutex::new(None)), + channel: Arc::new(AtomicU8::new(0)), + }; + assert_eq!(account_credential(&account).unwrap(), "ekb_xiaoyi_session_retry-fixture"); + server.join().unwrap(); + } + + #[test] + fn jiansun_public_knowledge_uses_sticky_portal_for_check_manifest_and_stream() { + let closed = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); + let intranet_address = closed.local_addr().unwrap(); + let intranet = format!("http://{intranet_address}"); + drop(closed); + + let portal = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); + let account = Account { + origin: format!("http://{}", portal.local_addr().unwrap()), + token: "synthetic-desktop-portal-session".into(), account_id: "test-user".into(), + access: super::super::AccountAccess::default(), http: super::super::NetworkClient::new(false).unwrap(), + cached: Arc::new(Mutex::new(None)), channel: Arc::new(AtomicU8::new(0)), + }; + const MANIFEST: &str = "/api/xiaoyi/v1/templates/chair/releases/v1/manifest"; + const BUNDLE: &str = "/api/xiaoyi/v1/templates/chair/releases/v1/bundle"; + let bytes = vec![b'a'; 20_000]; + let expected = bytes.clone(); + let server = std::thread::spawn(move || { + for (path, body) in [ + (XIAOYI_CURRENT, br#"{"version":"v1"}"#.as_slice()), + (MANIFEST, br#"{"templateId":"chair"}"#.as_slice()), + (BUNDLE, bytes.as_slice()), + ] { + let (mut stream, _) = portal.accept().unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut lines = BufReader::new(&mut stream).lines(); + assert_eq!(lines.next().unwrap().unwrap(), format!("GET /api/desktop/knowledge/proxy{path} HTTP/1.1")); + let headers = lines.map(Result::unwrap).take_while(|line| !line.is_empty()).collect::>(); + assert!(headers.iter().any(|line| line == "authorization: Bearer synthetic-desktop-portal-session")); + if path == BUNDLE { assert!(headers.iter().any(|line| line == "range: bytes=5-")); } + let status = if path == BUNDLE { "206 Partial Content" } else { "200 OK" }; + write!(stream, "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).unwrap(); + for chunk in body.chunks(4096) { stream.write_all(chunk).unwrap(); } + } + }); + + let (response, _) = automatic_response(&account, &intranet, XIAOYI_CURRENT, &json!({"headers":{}})).unwrap(); + assert_eq!(verified_key_response(response, || Ok(false))["status"], 200); + assert_eq!(account.channel.load(Ordering::Relaxed), KnowledgeChannel::Portal as u8); + let recovered_intranet = TcpListener::bind(intranet_address).unwrap(); + recovered_intranet.set_nonblocking(true).unwrap(); + for (path, expected) in [(MANIFEST, br#"{"templateId":"chair"}"#.as_slice()), (BUNDLE, expected.as_slice())] { + let mut frames = Vec::new(); + let headers = if path == BUNDLE { json!({"range":"bytes=5-"}) } else { json!({}) }; + exchange_automatic(&account, &json!({"origin":intranet,"path":path,"headers":headers}), + &mut |frame| { frames.push(frame); Ok(()) }).unwrap(); + assert_eq!(frames[0]["status"], if path == BUNDLE { 206 } else { 200 }); + assert_eq!(frames.last().unwrap()["type"], "result"); + let streamed = frames.iter().filter_map(|frame| frame["data"].as_str()) + .flat_map(|chunk| STANDARD.decode(chunk).unwrap()).collect::>(); + assert_eq!(streamed, expected); + if path == BUNDLE { assert!(frames.len() > 3); } + } + assert_eq!(recovered_intranet.accept().unwrap_err().kind(), std::io::ErrorKind::WouldBlock); + assert_eq!(automatic_response(&account, "http://218.93.9.38:20009", MANIFEST, &json!({"headers":{}})) + .unwrap_err(), XIAOYI_ORIGIN_REQUIRED); + server.join().unwrap(); + } + #[test] fn jiansun_generic_key_has_no_configuration_or_import_entry() { let backend = include_str!("jiansun_backend.rs"); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs index b3c469cd..00d1c931 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs @@ -1,5 +1,5 @@ -use super::{Backend, R, Value, body, canvas_workspace, creation, json, project_file, read_json, write_json}; +use super::{Backend, R, Value, body, canvas_workspace, creation, json, network_message, project_file, read_json, write_json}; use std::{ collections::{BTreeMap, BTreeSet, HashMap, HashSet}, fs::{self, File}, @@ -519,9 +519,10 @@ impl Backend { let mut state = if state_file.exists() { read_json(&state_file)? } else { Value::Null }; let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?; self.check_dispatch()?; - let response = self.http.get(format!("{}/api/desktop/deliveries/{cloud_id}/detail", self.origin)) - .bearer_auth(token).timeout(Duration::from_secs(30)).send() - .map_err(|_| "素材库提交记录暂时无法核对,请重新点击完结")?; + let request = self.http.get(format!("{}/api/desktop/deliveries/{cloud_id}/detail", self.origin)) + .bearer_auth(token).timeout(Duration::from_secs(8)); + let response = self.http.read(request) + .map_err(|error| format!("{};暂时无法核对提交记录,请重新点击完结", network_message(&error)))?; self.check_cloud_authority(response.status().as_u16())?; let (status, existing) = body(response, 2 * 1024 * 1024)?; if status != 200 { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs index 2c2d712f..231170cd 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -346,8 +346,12 @@ fn evidence_images(value: &Value) -> Value { let reference = image["source"].as_str().and_then(|source| source.strip_prefix("local:")) .filter(|hash| hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit())) .map(|hash| format!("sha256:{}", hash.to_ascii_lowercase())); - json!({"ref":reference,"purpose":image["purpose"].as_str().filter(|purpose| matches!(*purpose,"product"|"scene")), - "name":evidence_safe_text(&image["name"],160),"description":evidence_safe_text(&image["description"],160)}) + let mut evidence = json!({"ref":reference,"purpose":image["purpose"].as_str().filter(|purpose| matches!(*purpose,"product"|"scene")), + "name":evidence_safe_text(&image["name"],160),"description":evidence_safe_text(&image["description"],160)}); + for key in ["imageRole","fieldKey","templateId","barcode"] { + if let Some(value) = image.get(key) { evidence[key] = value.clone(); } + } + evidence }).collect::>()) } fn evidence_output_colors(colors: &Value) -> Value { @@ -363,7 +367,7 @@ fn project_evidence(c: &Value, scope: &str, project: &str, doc: u64, current_var .filter_map(|key| c["brief"].get(key).map(|value| (key.to_owned(), value.clone()))) .collect(); let mut brief = brief; - for field in ["intake", "barcodeBindings", "deliverySpu"] { + for field in ["intake", "barcodeBindings", "deliverySpu", "platformFacts"] { if let Some(value) = c["brief"].get(field) { brief.insert(field.to_owned(), value.clone()); } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs index 405c010c..f3a9ab81 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs @@ -220,6 +220,12 @@ fn first_screen(doc: &Document) -> R { let w = (rect.width() as f32 * scale).round().max(1.0) as u32; let h = (rect.height() as f32 * scale).round().max(1.0) as u32; let image = photocraft_ui_egui::gpu_canvas::background_compose::render(doc, rect, w, h).to_rgba8(); + if let Some(first) = image.pixels.get(..4) + && (first == [255, 255, 255, 255] || first[3] == 0) + && image.pixels.chunks_exact(4).all(|pixel| pixel == first || (first[3] == 0 && pixel[3] == 0)) + { + return Err("尚无画布内容".into()); + } Ok(egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &image.pixels)) } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs index 499196a9..e6eabc5d 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs @@ -1,7 +1,8 @@ //! Account-scoped prompt drafts. Mutations have durable identities; after an //! uncertain delivery only the server's read-only receipt can resolve them. -use super::{json, Digest, R, Uuid, Value, Path, Read, fs, Backend, body, Sha256}; +use super::{json, Digest, R, Uuid, Value, Path, Read, fs, Backend, body, network_message, Sha256}; use serde::{Deserialize, Serialize}; +use std::time::Duration; const CACHE_LIMIT: u64 = 16 * 1024 * 1024; static IO: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -125,7 +126,9 @@ fn save(path: &Path, cache: &Cache) -> R<()> { fn read_remote(b: &Backend, path: &str) -> R<(u16, Value)> { let token = b.auth["access_token"].as_str().ok_or("请先登录素材库")?; - let response = b.http.get(format!("{}/api/desktop/{path}", b.origin)).bearer_auth(token).send().map_err(|_| "素材库连接不可用,本机提示词已保留")?; + let request = b.http.get(format!("{}/api/desktop/{path}", b.origin)).bearer_auth(token) + .timeout(Duration::from_secs(8)); + let response = b.http.read(request).map_err(|error| format!("{};本机提示词已保留", network_message(&error)))?; body(response, CACHE_LIMIT).map_err(|_| "素材库响应不可读取,本机提示词已保留".into()) } @@ -520,16 +523,16 @@ mod tests { let server = std::thread::spawn(move || { let mut newer = prompt(); newer.revision = 3; - for step in 0..4 { + for step in 0..6 { let (mut socket, _) = listener.accept().unwrap(); socket.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); let mut request = [0; 8192]; let n = socket.read(&mut request).unwrap(); let request = String::from_utf8_lossy(&request[..n]); - if step == 2 { continue; } // refresh lost, after definite conflict let (status, value) = match step { 0 => ("200 OK", json!({"prompts":[prompt()]})), 1 => { assert!(request.starts_with("PUT ")); ("409 Conflict", json!({"code":"revision_conflict"})) }, + 2..=4 => { assert!(request.starts_with("GET ")); ("503 Service Unavailable", json!({})) }, _ => ("200 OK", json!({"prompts":[newer]})), }; let body = value.to_string(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs index c0f110c3..6aaec261 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs @@ -611,12 +611,12 @@ impl Backend { } fn cloud_snapshot(&self, id: &str) -> R> { let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?; - let response = self + let request = self .http .get(format!("{}/api/desktop/projects/desktop/{id}", self.origin)) - .bearer_auth(token) - .send() - .map_err(|_| "云端状态暂时无法核对,本机草稿保留")?; + .bearer_auth(token).timeout(Duration::from_secs(8)); + let response = self.http.read(request) + .map_err(|error| format!("{};本机草稿已保留", network_message(&error)))?; self.check_cloud_authority(response.status().as_u16())?; let (code, value) = body(response, MAX_JSON)?; if code == 404 { @@ -707,9 +707,9 @@ impl Backend { let project = context["project"]["id"].as_str().and_then(|id| Uuid::parse_str(id).ok()) .ok_or("云项目身份无效")?; let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?; - let response = self.http.get(format!("{}/api/desktop/deliveries/{project}/detail", self.origin)) - .bearer_auth(token).timeout(Duration::from_secs(10)).send() - .map_err(|_| "素材库连接失败,请稍后重试")?; + let request = self.http.get(format!("{}/api/desktop/deliveries/{project}/detail", self.origin)) + .bearer_auth(token).timeout(Duration::from_secs(10)); + let response = self.http.read(request).map_err(|error| network_message(&error))?; self.check_cloud_authority(response.status().as_u16())?; let (status, value) = body(response, 16 * 1024)?; if status != 200 { @@ -970,13 +970,13 @@ impl Backend { return Err("云端工程文件身份无效".into()); } let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?; - let response = self + let request = self .http .get(format!("{}/api/desktop/projects/desktop/{id}/native/{source}", self.origin)) .bearer_auth(token) - .timeout(Duration::from_secs(300)) - .send() - .map_err(|_| "工程下载中断,本机项目保留")?; + .timeout(Duration::from_secs(90)); + let response = self.http.read(request) + .map_err(|error| format!("{};本机项目已保留", network_message(&error)))?; self.check_cloud_authority(response.status().as_u16())?; if response.status().as_u16() != 200 { return Err(request_error(response.status().as_u16())); diff --git a/apps/detail-photocraft/crates/ui-egui/Cargo.toml b/apps/detail-photocraft/crates/ui-egui/Cargo.toml index b9e56e74..c93bbd3b 100644 --- a/apps/detail-photocraft/crates/ui-egui/Cargo.toml +++ b/apps/detail-photocraft/crates/ui-egui/Cargo.toml @@ -56,6 +56,8 @@ rayon = { workspace = true } # Safe native UI-language APIs (Windows/macOS); no subprocess or web dependency. sys-locale = "=0.3.2" uuid = { version = "1", features = ["v4"] } +regex = "1" +percent-encoding = "2" # Installed RAM for the GPU memory budget (`gpu_canvas::physical_memory`) and the user's decimal # symbol (`i18n::decimal_separator`, a registry read): the safe binding the desktop app already diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index be0bf7bf..8f12b1ac 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -11,6 +11,7 @@ use std::{ }; mod account_dialog; +mod onboarding; mod client_update; mod client_update_ui; mod agent_image_cache; @@ -24,6 +25,8 @@ mod agent_stream; mod operation_error; mod template_preparation; mod workspace_navigation; +mod feedback; +pub use feedback::feedback_payload; mod agent_canvas_read; mod agent_native; mod agent_preview; @@ -959,6 +962,8 @@ impl RecoverySchedule { } pub struct Workspace { + feedback: feedback::Feedback, + workbench: workspace_navigation::Workbench, project_files: HashMap, tx: mpsc::Sender, rx: mpsc::Receiver, @@ -1034,6 +1039,7 @@ pub struct Workspace { observed_doc: Option, project_context: Value, startup_resume_checked: bool, + onboarding: onboarding::State, startup_interacted: bool, recovery_status: Value, image_recovery_schedules: HashMap, @@ -1517,6 +1523,8 @@ impl Workspace { account: Value::Null, prompt_library: prompt_library_ui::PromptLibraryUi::default(), library_status: String::new(), + feedback: Default::default(), + workbench: Default::default(), library_message: String::new(), library_http_status: None, library_authorization_enabled: None, @@ -1580,6 +1588,7 @@ impl Workspace { observed_doc: None, project_context: json!({}), startup_resume_checked: false, + onboarding: onboarding::State::default(), startup_interacted: false, recovery_status: Value::Null, image_recovery_schedules: HashMap::new(), @@ -2684,6 +2693,8 @@ impl Workspace { let scope_changed = self.account["id"] != v["account"]["id"] || v["origin"].as_str().is_some_and(|origin| origin != self.origin); if scope_changed { + self.feedback = feedback::Feedback::default(); + self.workbench = workspace_navigation::Workbench::default(); self.retain_creation_ui_draft(app); self.creation_ui_scope = None; self.creation_doc = None; @@ -2737,6 +2748,8 @@ impl Workspace { } if scope_changed { self.creation_reads_tick(app); + self.refresh_workbench_scope(); + if self.busy.is_none() && self.editing_product_brief() { self.apply_workbench_seed(app); } self.xiaoyi_knowledge_mode = "unavailable".into(); self.xiaoyi_key_check = None; } @@ -2762,7 +2775,9 @@ impl Workspace { } if method == "restore" && !self.startup_resume_checked { self.startup_resume_checked = true; + self.begin_onboarding(ctx); let quiet = !self.startup_interacted + && !self.onboarding.is_open() && app.session.documents().is_empty() && self.library && !self.material @@ -2976,6 +2991,12 @@ impl Workspace { } fn receive_json_event(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, method: String, mut result: Result) { + match method.as_str() { + "desktop-feedback" => { self.feedback_received(result); return; } + "workbench-knowledge" => { self.workbench_knowledge_received(result); return; } + _ => {} + } + if method == "client-update" { if let Ok(receipt) = result { self.client_update.receive(receipt); @@ -3206,22 +3227,28 @@ impl Workspace { if matches!(method, "creation-import" | "creation-import-data") { self.creation_reads.reference_import_error = e; self.creation_reads.reference_import_paths = None; + } else if method == "creation-product-platform" { + self.creation_reads.platform_message = e; } else if method == "configure-xiaoyi-knowledge" { self.xiaoyi_key_check = Some(Err(e)); } else if method == "project-delete" { self.delete_error = e; } else if matches!(method, "login" | "logout" | "connection-check" | "login-url") { - self.config = true; + if matches!(method, "logout" | "connection-check") && !self.onboarding.is_open() { + self.config = true; + } self.account_error = e; } else if self.set_library_issue(&e) { // A background rule refresh may discover expiry but should not // interrupt someone who is only opening a local project. - if method != "pi-rules" { self.open_library_login(); } + if method != "pi-rules" && !self.onboarding.is_open() { self.open_library_login(); } self.error.clear(); } else { if method == "configure" { - self.key_settings = true; - self.model_settings = true; + if !self.onboarding.is_open() { + self.key_settings = true; + self.model_settings = true; + } self.model_ready = false; self.image_ready = false; self.copy_ready = false; @@ -3282,7 +3309,6 @@ impl Workspace { && let Err(e) = open(url) { self.account_error = format!("无法打开授权网页:{e}"); - self.config = true; } } "restore" | "connection-check" | "login" | "logout" => self.receive_json_account(app, ctx, method, v), @@ -4110,7 +4136,7 @@ impl Workspace { self.project_open_saved(app, id, rev); } Event::Preview(reference, image) => { - if reference["purpose"] == "creation-material" { + if matches!(reference["purpose"].as_str(), Some("creation-material" | "creation-platform-preview")) { self.creation_thumbnail_received(app, ctx, &reference, image); return; } @@ -4215,13 +4241,11 @@ impl Workspace { .map(|ch| if ch.is_ascii() { 8.0 } else { 14.0 }) .sum::() + self.update_capsule_width(); if app.session.active().is_none() { - return account_width + 166.0 + 30.0; + return account_width + 166.0 + 110.0; } - let status_width = if self.navigation_sync_status(app).is_some() { 76.0 } else { 0.0 }; let save_width = if self.saving.is_some() || self.saved.is_some() { 26.0 } else { 0.0 }; let stop_width = if self.shows_stop_automation() { 116.0 } else { 0.0 }; - // Navigation segments, divider, sync controls, and right-edge spacing. - account_width + 246.0 + 24.0 + 270.0 + status_width + save_width + stop_width + 18.0 + account_width + 246.0 + 24.0 + 172.0 + save_width + stop_width + 18.0 } fn navigation_inner(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { if self.professional_child_active(app) { @@ -4243,12 +4267,15 @@ impl Workspace { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // Keep the rightmost hit box inside the clip after fractional pixel rounding. ui.add_space(1.0); + let compact = ui.clip_rect().width() < 540.0; let account_name = self.account["name"].as_str().unwrap_or("登录"); let account_label = self.navigation_account_label(); - // The bar keeps one light action (完结); the account is an entry, not an action. - if stitch_ui::action_button(ui, &account_label, stitch_ui::ButtonRole::Quiet, true).on_hover_text(account_name).clicked() { - self.config = true; + let account_text = if compact && !self.account.is_null() { "账户" } else { &account_label }; + let account = stitch_ui::action_button(ui, account_text, stitch_ui::ButtonRole::Quiet, true).on_hover_text(account_name); + if compact { + account.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &account_label)); } + if account.clicked() { self.config = true; } self.update_capsule(app, ui); let projects = self.library || (!document_open && !self.material); let options: Vec<(&str, bool)> = if document_open { vec![("我的项目", true), ("添加素材", true), ("当前画布", true)] } else { vec![("我的项目", true), ("添加素材", true)] }; @@ -4272,7 +4299,7 @@ impl Workspace { } if document_open { stitch_ui::divider(ui); - self.sync_controls(app, ui); + self.delivery_controls(app, ui); if self.saving.is_some() { let loader_id = ui.scope_id().with("loading"); stitch_ui::ai_loader(ui, loader_id, true, self.reduce_motion); @@ -4283,10 +4310,19 @@ impl Workspace { self.handover(); } } + let feedback = if compact { + let response = stitch_ui::icon_button(ui, "message-square", 24.0, false, "问题反馈"); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "问题反馈")); + response + } else { + stitch_ui::action_button(ui, "问题反馈", stitch_ui::ButtonRole::Quiet, true) + }; + if feedback.clicked() { self.open_feedback(app); } }); } fn header(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { self.template_progress_ui(app, ui.ctx()); + self.feedback_dialog(ui.ctx(), app.services.open_url.as_ref()); let t = Tokens::get(ui.ctx()); // The normal navigation lives in the tool-options row. Keep an escape hatch // only when the user has explicitly hidden that native toolbar. @@ -4303,7 +4339,11 @@ impl Workspace { }); }); } - self.account_dialog(ui); + if self.onboarding.is_open() { + self.onboarding_dialog(ui); + } else { + self.account_dialog(ui); + } let _ = app; } fn connection_received(&mut self, value: &Value) { @@ -4585,6 +4625,10 @@ pub(crate) fn begin_native_dock(app: &mut PhotocraftApp) { crate::panel_docking::sync_agent_tab(app); } +pub(crate) fn projects_agent_dock(app: &PhotocraftApp) -> bool { + app.jiansun.as_ref().is_some_and(|workspace| workspace.agent_page(app) == "projects") +} + pub(crate) fn agent_selected(app: &PhotocraftApp) -> bool { app.jiansun.is_some() && app.ui.dock.agent_available && app.ui.dock_tabs.color == 4 && !app.ui.dock.is_collapsed(crate::dock::Group::Color) } @@ -4738,7 +4782,7 @@ pub(crate) fn bind_workspace_rendering(app: &PhotocraftApp, ui: &Ui) { } pub fn prepare(app: &mut PhotocraftApp, ui: &mut Ui) { - let xiaoyi_open = agent_selected(app); + let xiaoyi_open = agent_selected(app) || projects_agent_dock(app); if let Some(mut w) = app.jiansun.take() { // Selecting 小壹 is also an explicit return from native editing. if w.professional_mode && w.professional_edit.is_none() && xiaoyi_open { @@ -5250,11 +5294,11 @@ fn action_impl(app: &mut PhotocraftApp, ctx: Option<&egui::Context>, method: &st "creation-attachment-import" | "creation-attachment-import-data" => Err("请使用授权的参考图导入入口".into()), name if name.starts_with("creation-") => w.creation_action(app, name, input), name if name.starts_with("slot-") => w.slot_action(app, name, input), + "project-sync" if input["status"] != "completed" => Err("工程保存在本机,请通过完结提交成品".into()), "project-sync" | "project-state" => { w.sync_action(app, method, input); Ok(Value::Null) } - "project-card-sync" => w.request_project_sync(app, &input), "agent" => { if let Some(text) = input["text"].as_str() { w.submit(app, text.to_owned()); @@ -5394,6 +5438,7 @@ mod tests { ("creation_reads", include_str!("jiansun/creation_reads.rs")), ("creation", include_str!("jiansun/creation.rs")), ("native_copy_warnings", include_str!("jiansun/native_copy_warnings.rs")), + ("onboarding", include_str!("jiansun/onboarding.rs")), ("pi_bridge", include_str!("jiansun/pi_bridge.rs")), ("professional_mode", include_str!("jiansun/professional_mode.rs")), ("project_browser", include_str!("jiansun/project_browser.rs")), @@ -5582,6 +5627,7 @@ mod tests { ("visual_preview_ui", include_str!("jiansun/visual_preview_ui.rs"), 10), ("template_slots", include_str!("jiansun/template_slots.rs"), 2), ("account_dialog", include_str!("jiansun/account_dialog.rs"), 5), + ("onboarding", include_str!("jiansun/onboarding.rs"), 0), ("copywriting", include_str!("jiansun/copywriting.rs"), 3), ]; for (name, source, ceiling) in baseline { @@ -5735,7 +5781,7 @@ mod tests { output.textures_delta.clear(); assert!(w.panel_geometry["composer"].is_null()); assert!(w.panel_geometry["subject"].is_null()); - assert!(w.panel_geometry["workspaceSearch"].is_null(), "the project page keeps one search, in the center; the dock only lists recent projects"); + assert!(w.panel_geometry["workspaceSearch"].is_array()); assert!(w.panel_geometry["workspaceReturn"].is_array(), "the dock still offers the way back to the open canvas"); assert!(requests.try_recv().is_err()); w.show_center(CenterView::Materials,true); @@ -5749,75 +5795,25 @@ mod tests { } #[test] - fn project_page_dock_lists_recent_projects_without_repeating_the_center() { - fn texts(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| texts(shape, out)), - egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), - _ => {} - } - } - let (mut w,mut app,requests,_)=slot_workspace(); - w.reduce_motion=true; - w.projects=vec![ - json!({"id":"local-old","source":"native","name":"本机旧项目","updatedAt":"2026-11-01T00:00:00Z"}), - json!({"id":"cloud-new","source":"desktop","name":"云端新项目","updatedAt":"2026-11-20T00:00:00Z"}), - json!({"id":"local-new","source":"native","name":"本机新项目","updatedAt":"2026-11-10T00:00:00Z"}), + fn workbench_finds_a_local_project_by_brand_and_omits_the_file_extension() { + use egui_kittest::{Harness, kittest::Queryable}; + let (mut w, app, requests, _) = slot_workspace(); + w.projects = vec![ + json!({"id":"local","source":"native","name":"卧室新品.pcraft","brandName":"示例品牌"}), + json!({"id":"remote","source":"desktop","name":"云端项目","brandName":"示例品牌"}), ]; - w.show_center(CenterView::Projects,true); - assert_eq!(w.agent_page(&app),"projects"); - let ctx=egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let mut seen=Vec::new(); - for _ in 0..3 { - let mut output=ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::pos2(0.0,0.0),egui::vec2(520.0,900.0))), ..Default::default() }, - |ui| w.workspace_panel(&mut app,ui)); - seen.clear(); - for clipped in &output.shapes { texts(&clipped.shape,&mut seen); } - output.textures_delta.clear(); - } - let position=|text:&str| seen.iter().position(|line| line==text); - assert!(position("最近的项目").is_some(),"{seen:?}"); - let (first,second,third)=(position("本机新项目"),position("本机旧项目"),position("云端新项目")); - assert!(matches!((first,second,third),(Some(a),Some(b),Some(c)) if a) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| texts(shape, out)), - egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), - _ => {} - } - } - let (mut w,mut app,requests,_)=slot_workspace(); - w.reduce_motion=true; - w.library_status="connected".into(); - w.projects=Vec::new(); - w.show_center(CenterView::Projects,true); - let ctx=egui::Context::default(); - PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let mut seen=Vec::new(); - for _ in 0..3 { - let mut output=ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::pos2(0.0,0.0),egui::vec2(250.0,900.0))), ..Default::default() }, - |ui| w.workspace_panel(&mut app,ui)); - seen.clear(); - for clipped in &output.shapes { texts(&clipped.shape,&mut seen); } - output.textures_delta.clear(); - } - // An empty dock beside the page reads as broken; it names the first step instead. - assert!(seen.iter().any(|line| line=="还没有项目"),"{seen:?}"); - assert!(seen.iter().any(|line| line.starts_with("从中间的「新建项目」开始")),"{seen:?}"); - assert!(!seen.iter().any(|line| line=="最近的项目" || line=="新建项目"),"no list to head, and the center keeps the button: {seen:?}"); - assert!(seen.iter().any(|line| line=="返回当前画布"),"{seen:?}"); + w.show_center(CenterView::Projects, true); + w.refresh_workbench_scope(); + w.workbench.input = "示例品牌".into(); + let mut harness = Harness::builder().with_size(egui::vec2(280.0, 600.0)) + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .build_ui_state(|ui, (w, app)| w.workspace_panel(app, ui), (w, app)); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); + harness.run_steps(4); + harness.get_by_label("发送").click(); + harness.run_steps(4); + harness.get_by_label("卧室新品 · 示例品牌"); + assert!(harness.query_by_label("云端项目 · 示例品牌").is_none()); assert!(requests.try_recv().is_err()); } @@ -6832,7 +6828,7 @@ mod tests { } #[test] - fn project_sync_controls_fit_inside_navigation_clip() { + fn project_actions_fit_inside_navigation_clip() { use egui_kittest::{Harness, kittest::Queryable}; for width in [960.0, 1100.0, 1280.0, 1400.0, 1440.0, 1920.0] { for name in ["222", "长账户名宽度验收"] { @@ -6850,7 +6846,7 @@ mod tests { let geometry = &harness.state().jiansun.as_ref().unwrap().navigation_geometry["clip"]; let point = |index: usize| geometry[index].as_f64().unwrap() as f32; let clip = egui::Rect::from_min_size(egui::pos2(point(0), point(1)), egui::vec2(point(2), point(3))); - for label in ["完结", "云同步", "同步对话", "我的项目", "添加素材", "当前画布", &format!("账户 · {name}")] { + for label in ["完结", "问题反馈", "我的项目", "添加素材", "当前画布", &format!("账户 · {name}")] { let rect = harness.get_by_label(label).rect(); assert!(clip.contains_rect(rect), "{label} at {width}pt, {scale}x: {rect:?} clipped by {clip:?}"); } @@ -6910,6 +6906,77 @@ mod tests { } } + #[test] + #[ignore = "offscreen GPU visual acceptance; writes only to PHOTOCRAFT_AGENT_QA_OUT"] + fn workbench_and_feedback_visual_acceptance() { + use egui_kittest::{Harness, kittest::Queryable}; + let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory")); + for width in [1440.0, 960.0] { + let (mut app, requests) = toolbar_fixture("验收账户"); + let workspace = app.jiansun.as_mut().unwrap(); + workspace.show_center(CenterView::Projects, true); + workspace.library_status = "connected".into(); + workspace.projects = vec![ + json!({"id":"local-1","source":"native","name":"栖木系列主卧详情页.pcraft","brandName":"栖木家居","productModel":"QIMU-301","updatedLabel":"2026-12-01 16:32","status":"draft"}), + json!({"id":"local-2","source":"native","name":"橡木餐椅.pcraft","brandName":"日常家居","productModel":"CHAIR-03","updatedLabel":"2026-11-29 10:45","status":"completed"}), + ]; + for local in ["local-1", "local-2"] { + workspace.cover_errors.insert(format!("native|{local}|null|null"), "尚无画布内容".into()); + } + let mut harness = Harness::builder() + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .with_size(egui::vec2(width, 800.0)).wgpu() + .build_ui_state(|ui, app| { + if !stitch_ui::ui_fonts_ready(ui) { return; } + crate::panels::options_bar(app, ui); + crate::panels::dock_area(app, ui); + if let Some(w) = app.jiansun.as_mut() { w.feedback_dialog(ui.ctx(), None); } + }, app); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium); + harness.run_steps(8); + harness.get_by_label("工作台总助"); + let geometry = &harness.state().jiansun.as_ref().unwrap().panel_geometry; + assert!(geometry["agentTab"].is_array()); + assert!(geometry["colorTab"].is_null()); + let workspace = harness.state().jiansun.as_ref().unwrap(); + let card = &workspace.project_geometry["tiles"][0]["card"]; + assert!(card[1].as_f64().unwrap() + card[3].as_f64().unwrap() < 800.0, "coverless card metadata fits the viewport"); + harness.render().unwrap().save(directory.join(format!("projects-{width}.png"))).unwrap(); + harness.get_by_label("问题反馈").click(); + harness.run_steps(6); + harness.get_by_label("提交反馈"); + harness.state_mut().jiansun.as_mut().unwrap().feedback.summary = "在我的项目打开本机作品后,首屏封面仍显示加载中。".into(); + harness.get_by_label("查看脱敏诊断").click(); + harness.run_steps(6); + harness.render().unwrap().save(directory.join(format!("feedback-{width}.png"))).unwrap(); + harness.get_by_label("提交反馈").click(); + harness.run_steps(5); + let sent = requests.try_iter().find_map(|request| match request { + Request::Action(method, input) if method == "desktop-feedback" => Some(input), + _ => None, + }).expect("feedback submits through the native host"); + let mut receipt = json!({"readId":sent["readId"],"accountId":sent["accountId"],"origin":sent["origin"],"error":"暂时无法确认反馈结果,请联网后用同一编号重试"}); + harness.state_mut().jiansun.as_mut().unwrap().feedback_received(Ok(receipt.clone())); + harness.run_steps(5); + harness.get_by_label("重试").click(); + harness.run_steps(5); + assert!(requests.try_iter().any(|request| matches!(request, Request::Action(method, input) if method == "desktop-feedback" && input == sent))); + receipt.as_object_mut().unwrap().remove("error"); + receipt["feedback"] = json!({"feedbackId":sent["readId"]}); + harness.state_mut().jiansun.as_mut().unwrap().feedback_received(Ok(receipt)); + harness.run_steps(5); + harness.get_by_label("查看反馈"); + harness.render().unwrap().save(directory.join(format!("feedback-receipt-{width}.png"))).unwrap(); + harness.get_by_label("关闭").click(); + harness.state_mut().jiansun.as_mut().unwrap().show_center(CenterView::Canvas, true); + harness.run_steps(6); + let geometry = &harness.state().jiansun.as_ref().unwrap().panel_geometry; + for tab in ["agentTab", "colorTab", "swatchesTab", "gradientsTab", "patternsTab"] { + assert!(geometry[tab].is_array(), "canvas tab {tab} should be visible"); + } + } + } + #[test] fn saved_receipt_refreshes_only_the_loaded_active_project_state() { let context = json!({"cloudLink":{"id":"cloud","source":"desktop","revision":3},"syncedRevision":8,"status":"completed","document":"preserved"}); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/account_dialog.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/account_dialog.rs index f8f26f74..99611d0c 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/account_dialog.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/account_dialog.rs @@ -3,6 +3,19 @@ use egui::{Id, RichText, Ui}; use serde_json::json; impl Workspace { + pub(super) fn library_login_enabled(&self) -> bool { + self.busy.is_none() + && ((self.library_status != "disabled" && self.library_authorization_enabled != Some(false)) + || self.login_origin.as_deref().is_some_and(|origin| origin != self.origin)) + } + + pub(super) fn authorize_library(&mut self, ctx: &egui::Context) { + if self.flush_account_drafts(ctx) { + self.account_error.clear(); + self.send("login", json!({"origin":self.login_origin.as_deref().unwrap_or(&self.origin)})); + } + } + pub(super) fn account_dialog(&mut self, ui: &mut Ui) { let mut close = false; let reduced = self.reduce_motion; @@ -52,11 +65,11 @@ impl Workspace { } ui.label(RichText::new("通过浏览器授权,客户端不获取登录密码。").size(12.0).color(t.text_dim)); ui.add_space(4.0); - let enabled = self.busy.is_none() && ((self.library_status != "disabled" && self.library_authorization_enabled != Some(false)) || self.login_origin.as_deref() != Some(self.origin.as_str())); + let enabled = self.library_login_enabled(); ui.horizontal_wrapped(|ui| { let label = if self.library_status == "connected" { "重新授权" } else { "在浏览器中登录" }; - if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Primary, enabled).clicked() && self.flush_account_drafts(ui.ctx()) { - self.send("login", json!({"origin":self.login_origin})); + if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Primary, enabled).clicked() { + self.authorize_library(ui.ctx()); } if !self.account.is_null() { let logout = stitch_ui::action_button(ui, "退出账户", stitch_ui::ButtonRole::QuietDanger, self.busy.is_none()); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs index db89cc9c..7432e3fe 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs @@ -3541,11 +3541,68 @@ impl Workspace { self.model_ready = false; self.copy_ready = false; self.image_ready = false; - self.key_settings = true; - self.model_settings = true; + if !self.onboarding.is_open() { + self.key_settings = true; + self.model_settings = true; + } } } + pub(super) fn onboarding_model_options(&mut self, ui: &mut Ui) { + use crate::theme::agent_scale::Type; + let roles = [(ModelRole::Chat, "对话模型", !self.models.is_empty()), + (ModelRole::Copy, "文案模型", !self.copy_models.is_empty()), + (ModelRole::Image, "生图模型", !self.image_models.is_empty())]; + let available = roles.into_iter().filter(|(_, _, available)| *available); + let count = available.clone().count(); + if count == 0 { + ui.horizontal_wrapped(|ui| { + super::stitch_ui::status_label(ui, "模型目录未加载", super::stitch_ui::StatusTone::Warning); + if super::stitch_ui::action_button(ui, "重试", super::stitch_ui::ButtonRole::Quiet, self.busy.is_none()).clicked() { + self.send("restore", json!({})); + } + }); + return; + } + ui.label(RichText::new("至少选择一个模型").font(Type::Meta.font_id()).color(Tokens::get(ui.ctx()).agent().text_dim)); + ui.horizontal_top(|ui| { + let width = (ui.available_width() - (count - 1) as f32 * ui.spacing().item_spacing.x) / count as f32; + for (role, label, _) in available { + ui.vertical(|ui| { + ui.set_width(width); + ui.label(label); + self.model_picker(ui, role, width, true); + }); + } + }); + } + + pub(super) fn model_key_editor(&mut self, ui: &mut Ui, open: bool, focus: bool) { + let enabled = open && self.busy.is_none() && !self.account.is_null(); + ui.add_enabled_ui(enabled, |ui| { + let key_id = ui.make_persistent_id(("personal-key", &self.origin, self.account["id"].as_str().unwrap_or_default())); + let input = super::stitch_ui::halo_field(ui, key_id.with("field"), None, self.reduce_motion, |ui| ui.add( + super::stitch_ui::text_input( + &mut self.api_key, + if self.key_saved { "输入新的个人 Key" } else { "输入个人 Key" }, + false, + ) + .id(key_id).password(true).desired_width(f32::INFINITY).frame(Frame::NONE), + ).accessible_name("模型 API Key")); + if focus && enabled { input.request_focus(); } + input.on_hover_text("只保存在本机系统凭据库"); + if super::stitch_ui::action_button(ui, "保存连接", super::stitch_ui::ButtonRole::Primary, + !self.api_key.trim().is_empty() && (!self.model.is_empty() || !self.copy_model.is_empty() || !self.image_model.is_empty())) + .clicked() + { + self.model_ready = false; + self.image_ready = false; + self.copy_ready = false; + self.send("configure", json!({"key":self.api_key,"model":self.model,"copyModel":self.copy_model,"imageModel":self.image_model})); + } + }); + } + pub(super) fn receive_model_preference(&mut self, value: &Value) { if value["field"] == "thinkingLevel" { self.thinking_by_model = value["thinkingByModel"].clone(); @@ -3744,29 +3801,7 @@ impl Workspace { } }); super::stitch_ui::morph_surface(ui, ui.scope_id().with("key-reveal"), self.key_settings, self.reduce_motion, |ui| { - ui.add_enabled_ui(self.key_settings && self.busy.is_none() && !self.account.is_null(), |ui| { - let key_id = ui.make_persistent_id(("personal-key", &self.origin, self.account["id"].as_str().unwrap_or_default())); - super::stitch_ui::halo_field(ui, key_id.with("field"), None, self.reduce_motion, |ui| ui.add( - super::stitch_ui::text_input( - &mut self.api_key, - if self.key_saved { "输入新的个人 Key" } else { "输入个人 Key" }, - false, - ) - .id(key_id) - .password(true) - .desired_width(f32::INFINITY).frame(Frame::NONE), - )) - .on_hover_text("只保存在本机系统凭据库"); - if super::stitch_ui::action_button(ui, "保存连接", super::stitch_ui::ButtonRole::Primary, - !self.api_key.trim().is_empty() && (!self.model.is_empty() || !self.copy_model.is_empty() || !self.image_model.is_empty())) - .clicked() - { - self.model_ready = false; - self.image_ready = false; - self.copy_ready = false; - self.send("configure", json!({"key":self.api_key,"model":self.model,"copyModel":self.copy_model,"imageModel":self.image_model})); - } - }); + self.model_key_editor(ui, self.key_settings, false); }); super::stitch_ui::divider(ui); self.knowledge_settings(ui); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs index fd16c537..3685f17a 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs @@ -124,23 +124,31 @@ impl PhotocraftApp { } let Some(w) = self.jiansun.as_ref() else { return false }; let Some(doc) = self.session.active().map(|state| state.doc.id.0) else { return false }; - let target = &w.creation_view_geometry["referenceDrop"]; - let on_reference = target["doc"].as_u64() == Some(doc) && target["accountId"] == w.account["id"] - && target["origin"] == w.origin && drop_contains(&target["rect"], at) - && ctx.layer_id_at(at).is_none_or(|layer| layer.order == egui::Order::Background); - if !on_reference { + let target = std::iter::once(&w.creation_view_geometry["referenceDrop"]) + .chain(w.creation_view_geometry["imageSlots"].as_object().into_iter().flat_map(|slots| slots.values())) + .find(|target| target["doc"].as_u64() == Some(doc) && target["accountId"] == w.account["id"] + && target["origin"] == w.origin && drop_contains(&target["rect"], at) + && ctx.layer_id_at(at).is_none_or(|layer| layer.order == egui::Order::Background)); + let Some(target) = target else { if drop_contains(&w.creation_view_geometry["product-form-viewport"], at) && files.iter().any(|file| reference_image_path(file.path())) { - if let Some(w) = self.jiansun.as_mut() { w.creation_reads.reference_import_error = "请将图片拖到「产品参考图」区域".into(); } + if let Some(w) = self.jiansun.as_mut() { + w.creation_reads.reference_import_error = if uses_template_images(&w.creation_brief) { + "请将图片拖到图片框内" + } else { "请将图片拖到「产品参考图」区域" }.into(); + } return true; } return false; - } + }; + let slot = target["slot"].clone(); let reject = if w.creation_doc != Some(doc) || w.busy.is_some() { Some("请等待当前操作完成,再添加参考图") } else if w.unknown { Some("原请求结果待核查,请先核查后再添加参考图") + } else if slot["multiple"] == false && files.len() != 1 { + Some("此图片框一次只能添加一张图片") } else if files.is_empty() || files.len() > 8 { Some("每次请选择 1 至 8 张参考图片") } else { @@ -159,16 +167,19 @@ impl PhotocraftApp { if let Some(w) = self.jiansun.as_mut() { w.creation_reads.reference_import_error = "请选择 PNG、JPG 或 WebP 格式的本机图片".into(); } return true; }; - if let Err(error) = self.import_reference_paths(paths) + if let Err(error) = self.import_reference_paths(paths, slot) && let Some(w) = self.jiansun.as_mut() { w.creation_reads.reference_import_error = error; } true } - fn import_reference_paths(&mut self, paths: Vec) -> Result { + fn import_reference_paths(&mut self, paths: Vec, slot: Value) -> Result { let native = self.session.authorize.is_none(); - let result = super::action(self, "creation-import", json!({"paths": paths}))?; + if slot.is_object() && self.jiansun.as_ref().is_none_or(|w| !current_image_slot(&w.creation_brief, &slot)) { + return Err("图片框已变化,请重新选择".into()); + } + let result = super::action(self, "creation-import", json!({"paths":paths,"imageSlot":slot}))?; if let Some(w) = self.jiansun.as_mut() { w.creation_reads.reference_import_error.clear(); if native && result["submitted"] == true { @@ -410,7 +421,8 @@ fn canvas_entry_missing(brief: &Value, template: &Value) -> Vec<&'static str> { (filled("categoryId"), "品类"), (template_identity(template), "模板"), (filled("name"), "产品名称"), - (image_rows(brief).iter().any(|(image, _)| image["purpose"] == "product"), "产品图"), + (image_rows(brief).iter().any(|(image, _)| image["purpose"] == "product" + && (image["barcode"].is_null() || image["barcode"] == brief["detailBarcode"])), "产品图"), (project_barcodes(brief).next().is_none() || filled(spu_field(brief)), "SPU 型号"), (project_barcodes(brief).nth(1).is_none() || brief["detailBarcode"].as_str().is_some_and(|selected| project_barcodes(brief).any(|code| code == selected)), "详情页出图条码"), @@ -487,32 +499,80 @@ fn intake_columns(width: f32) -> usize { if width >= 420.0 { 3 } else if width >= 152.0 { 2 } else { 1 } } -fn intake_fields(ui: &mut Ui, scope: egui::Id, width: f32, schema: &Value, values: &mut Value, reduced: bool) -> bool { - let Some(fields) = schema.as_array() else { return false }; - let columns = intake_columns(width); - let column_width = (width - 8.0 * (columns - 1) as f32) / columns as f32; - let compact = |field: &Value| matches!(field["type"].as_str(), Some("number" | "select" | "boolean")); +fn product_intake_columns(width: f32) -> usize { + if width >= 560.0 { 2 } else { 1 } +} + +fn is_product_name_field(field: &Value) -> bool { + field["type"] == "text" + && field["label"].as_str().is_some_and(|label| { + matches!(label.trim().trim_end_matches(['*', '*']).trim(), "产品名称" | "产品名" | "商品名称" | "商品名") + }) +} + +fn intake_multiline(field: &Value) -> bool { + field["type"] == "text" && field["multiline"].as_bool().unwrap_or_else(|| { + matches!(field["label"].as_str().map(str::trim), + Some("核心卖点" | "产品卖点" | "卖点描述" | "注意事项" | "产品描述" | "产品介绍" | "使用说明")) + }) +} + +fn intake_help(field: &Value) -> Option<&str> { + field["help"].as_str().map(str::trim).filter(|help| !help.is_empty()) +} + +fn intake_hint<'a>(field: &'a Value, group: &[&Value]) -> &'a str { + field["placeholder"].as_str().map(str::trim).filter(|hint| !hint.is_empty()) + .or_else(|| intake_help(field).filter(|help| { + *help != "按本款确认资料填写;尺寸注明单位,暂无资料可留空。" + && group.iter().filter(|row| intake_help(row) == Some(*help)).take(2).count() < 2 + })) + .unwrap_or(match field["type"].as_str() { + Some("number") => "数字", + Some("select") => "请选择", + _ => "", + }) +} + +#[derive(Clone, Copy)] +enum IntakeScope { + Product, + Barcode, +} + +fn intake_fields(ui: &mut Ui, scope: egui::Id, width: f32, fields: &[&Value], kind: IntakeScope, values: &mut Value, reduced: bool) -> bool { + let (columns, gap) = match kind { + IntakeScope::Product => (product_intake_columns(width), 14.0), + IntakeScope::Barcode => (intake_columns(width), 8.0), + }; + let spans_row = |field: &Value| match kind { + IntakeScope::Product => intake_multiline(field), + IntakeScope::Barcode => !matches!(field["type"].as_str(), Some("number" | "select" | "boolean")), + }; + let column_width = (width - gap * (columns - 1) as f32) / columns as f32; let mut changed = false; - let mut remaining = fields.as_slice(); - while let Some((first, rest)) = remaining.split_first() { - if !compact(first) { - changed |= intake_field(ui, scope, width, 0.0, first, values, reduced); - remaining = rest; - } else { - let count = remaining.iter().take(columns).take_while(|field| compact(field)).count(); + ui.scope(|ui| { + ui.spacing_mut().item_spacing.y = 14.0; + let mut remaining = fields; + while let Some((first, _)) = remaining.split_first() { + let full_width = spans_row(first); + let count = if full_width { 1 } else { + remaining.iter().take(columns).take_while(|field| !spans_row(field)).count() + }; let (row, rest) = remaining.split_at(count); + let field_width = if full_width { width } else { column_width }; ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = 8.0; + ui.spacing_mut().item_spacing.x = gap; let label_height = row.iter().map(|field| ui.painter().layout( - intake_label(field), crate::theme::agent_scale::Type::Title.font_id(), egui::Color32::WHITE, column_width, + intake_label(field), crate::theme::agent_scale::Type::Title.font_id(), egui::Color32::WHITE, field_width, ).size().y).fold(0.0_f32, f32::max); for field in row { - changed |= intake_field(ui, scope, column_width, label_height, field, values, reduced); + changed |= intake_field(ui, scope, field_width, label_height, field, intake_hint(field, fields), values, reduced); } }); remaining = rest; } - } + }); changed } @@ -523,7 +583,7 @@ fn intake_label(field: &Value) -> String { if field["required"] == true { " *" } else { "" }) } -fn intake_field(ui: &mut Ui, scope: egui::Id, width: f32, label_height: f32, field: &Value, values: &mut Value, reduced: bool) -> bool { +fn intake_field(ui: &mut Ui, scope: egui::Id, width: f32, label_height: f32, field: &Value, hint: &str, values: &mut Value, reduced: bool) -> bool { let label = intake_label(field); let Some(id) = field["id"].as_str().filter(|id| !id.trim().is_empty()) else { stitch_ui::status_label(ui, &format!("{label}缺少字段编号"), stitch_ui::StatusTone::Warning); @@ -540,12 +600,15 @@ fn intake_field(ui: &mut Ui, scope: egui::Id, width: f32, label_height: f32, fie }); match field["type"].as_str() { Some("text" | "number") => { - let hint = if field["type"] == "number" { "输入数字" } else { "输入内容" }; - changed |= edit_named(ui, scope.with(id), &mut values[id], width, false, hint, &label); + let mut value = values[id].clone(); + if edit_named(ui, scope.with(id), &mut value, width, intake_multiline(field), hint, &label) { + values[id] = value; + changed = true; + } } Some("select") => { - let selected = values[id].as_str().unwrap_or("请选择").to_owned(); - let response = stitch_ui::halo_select(ui, scope.with(id), width, &selected, reduced, |ui| { + let selected = values[id].as_str().filter(|value| !value.is_empty()).map(str::to_owned); + let response = stitch_ui::halo_select_hint(ui, scope.with(id), width, selected.as_deref(), hint, reduced, |ui| { for option in field["options"].as_array().into_iter().flatten().filter_map(Value::as_str) { if stitch_ui::select_option_sized(ui, option, values[id] == option, true, vec2(ui.available_width(), 28.0)).clicked() { values[id] = json!(option); @@ -554,7 +617,7 @@ fn intake_field(ui: &mut Ui, scope: egui::Id, width: f32, label_height: f32, fie } } }); - response.response.on_hover_text(&label); + response.response.accessible_name(&label); } Some("boolean") => { let value = values[id] == true; @@ -568,9 +631,6 @@ fn intake_field(ui: &mut Ui, scope: egui::Id, width: f32, label_height: f32, fie stitch_ui::status_label(ui, &format!("暂不支持此字段类型({kind})"), stitch_ui::StatusTone::Warning); } } - if let Some(help) = field["help"].as_str().filter(|help| !help.is_empty()) { - ui.weak(help); - } }); changed } @@ -579,6 +639,156 @@ fn spu_field(brief: &Value) -> &'static str { if brief["identifierType"] == "spu" { "identifier" } else { "deliverySpu" } } +fn field_kind(field: &Value) -> &Value { field.get("type").unwrap_or(&field["kind"]) } + +fn field_key(field: &Value) -> &Value { field.get("id").unwrap_or(&field["key"]) } + +fn image_slot(template: &Value, field: &Value, barcode: Option<&str>) -> Value { + json!({"templateId":template,"fieldKey":field_key(field),"barcode":barcode, + "imageRole":field["imageRole"].as_str().or_else(|| field_key(field).as_str()), + "multiple":field["multiple"] != false, + "purpose":if field["imageRole"].as_str().is_none_or(|role| matches!(role, "product" | "detail")) { "product" } else { "scene" }}) +} + +fn current_image_slot(brief: &Value, slot: &Value) -> bool { + let intake = &brief["intake"]; + let barcode = slot["barcode"].as_str(); + let scope = if barcode.is_some() { "barcodeFields" } else { "productFields" }; + barcode.is_none_or(|barcode| project_barcodes(brief).any(|code| code == barcode)) + && intake["schema"][scope].as_array().into_iter().flatten().any(|field| + field_kind(field) == "image" && image_slot(&intake["templateId"], field, barcode) == *slot) +} + +fn in_image_slot(image: &Value, slot: &Value) -> bool { + image["fieldKey"] == slot["fieldKey"] && image["templateId"] == slot["templateId"] + && image["barcode"] == slot["barcode"] +} + +fn uses_template_images(brief: &Value) -> bool { + ["productFields", "barcodeFields"].into_iter().any(|scope| + brief["intake"]["schema"][scope].as_array().into_iter().flatten().any(|field| field_kind(field) == "image")) +} + +fn assign_platform_images(brief: &mut Value) { + let intake = brief["intake"].clone(); + if let Some(images) = brief["images"].as_array_mut() { + for image in images.iter_mut().filter(|image| image["platformImage"] == true) { + let scope = if image["barcode"].is_string() { "barcodeFields" } else { "productFields" }; + if let Some(field) = intake["schema"][scope].as_array().into_iter().flatten().find(|field| + field_kind(field) == "image" && field["imageRole"] == "product" && field["multiple"] != false) { + image["fieldKey"] = field_key(field).clone(); + image["templateId"] = intake["templateId"].clone(); + } else if let Some(row) = image.as_object_mut() { + row.remove("fieldKey"); + row.remove("templateId"); + } + } + } +} + +fn add_slot_images(brief: &mut Value, slot: &Value, images: &[Value]) -> Result<(), String> { + if !current_image_slot(brief, slot) { + return Err("图片框已变化,请重新选择".into()); + } + let mut current = brief["images"].as_array().cloned().unwrap_or_default(); + if slot["multiple"] == false { + current.retain(|image| !in_image_slot(image, slot)); + } + for mut image in images.iter().take(if slot["multiple"] == false { 1 } else { 8 }).cloned() { + if current.iter().any(|row| in_image_slot(row, slot) && row["source"] == image["source"]) { continue; } + for key in ["fieldKey","templateId","imageRole","barcode"] { + if !slot[key].is_null() { image[key] = slot[key].clone(); } + } + image["purpose"] = slot["purpose"].clone(); + current.push(image); + } + if current.len() > 8 { return Err("共用及条码图片最多 8 张,请先删除不用的图片".into()); } + brief["images"] = json!(current); + Ok(()) +} + +fn field_fact(field: &Value, facts: &Value) -> Option { + let lookup = |name: &str| -> Option { + let alias = match name { + "颜色" | "花色" | "color" => "colorName", + "商品名" | "产品名称" | "name" => "productName", + "条码" | "商品条码" => "barcode", + "SKU 编号" | "SKU编码" => "skuCode", + "规格" | "规格型号" => "spec", + "尺寸" | "产品尺寸" | "size" => "sizeText", + "材质" | "主要材质" => "material", + "说明" | "产品说明" | "产品描述" | "描述" => "description", + "卖点" | "产品卖点" => "sellingPoints", + "长" | "长度" => "length", + "宽" | "宽度" => "width", + "高" | "高度" => "height", + _ => name, + }; + if matches!(alias, "length" | "width" | "height") { + let dimension = &facts["dimensions"]; + let value = dimension.get(alias).filter(|value| value.is_number())?; + if !field["unit"].is_string() || dimension["unit"] == field["unit"] { + return Some(value.clone()); + } + let millimetres = |unit: &Value| match unit.as_str()? { + "mm" => Some(1.0), "cm" => Some(10.0), "m" => Some(1000.0), _ => None, + }; + let converted = value.as_f64()? * millimetres(&dimension["unit"])? / millimetres(&field["unit"])?; + return converted.is_finite().then(|| json!(converted)); + } + facts.get(alias).or_else(|| facts["attributes"].get(name)) + .or_else(|| match alias { + "sizeText" => facts.get("spec").or_else(|| facts.get("dimensions")), + "spec" => facts.get("sizeText"), + _ => None, + }).filter(|value| !value.is_null()).cloned() + }; + let key = field_key(field).as_str()?; + let label = field["label"].as_str().unwrap_or(key); + let value = lookup(key).or_else(|| lookup(label))?; + match field_kind(field).as_str()? { + "text" if value.is_number() => Some(json!(value.to_string())), + "text" if value.is_string() => Some(value), + "text" if value.is_array() => Some(json!(value.as_array()?.iter().filter_map(Value::as_str).collect::>().join("\n"))), + "text" if value.is_object() => dimension_text(&value).map(Value::String), + "number" if value.is_number() || value.as_str().is_some_and(|s| s.parse::().is_ok_and(f64::is_finite)) => Some(value), + "select" if field["options"].as_array().is_some_and(|options| options.contains(&value)) => Some(value), + "boolean" if value.is_boolean() => Some(value), + _ => None, + } +} + +fn dimension_text(dimensions: &Value) -> Option { + let axes = [("length", "长"), ("width", "宽"), ("height", "高")].into_iter() + .filter_map(|(axis, label)| dimensions[axis].as_number().map(|value| format!("{label} {value}"))) + .collect::>(); + (!axes.is_empty()).then(|| match dimensions["unit"].as_str() { + Some(unit) => format!("{} {unit}", axes.join(" × ")), + None => axes.join(" × "), + }) +} + +fn fill_platform_intake(brief: &mut Value) { + if brief["intake"]["schema"]["version"] != 1 || brief["platformFacts"]["spu"] != brief["identifier"] { return; } + let mut shared = brief["platformFacts"]["shared"].clone(); + if !shared.is_object() { return; } + shared["productName"] = brief["name"].clone(); + let fill = |fields: &Value, facts: &Value| -> Value { + Value::Object(fields.as_array().into_iter().flatten().filter_map(|field| + Some((field_key(field).as_str()?.to_owned(), field_fact(field, facts)?))).collect()) + }; + let mut barcodes = serde_json::Map::new(); + if let Some(rows) = brief["platformFacts"]["barcodes"].as_object() { + for (code, row) in rows { + let mut facts = row.clone(); + facts["barcode"] = json!(code); + barcodes.insert(code.clone(), fill(&brief["intake"]["schema"]["barcodeFields"], &facts)); + } + } + brief["intake"]["productValues"] = fill(&brief["intake"]["schema"]["productFields"], &shared); + brief["intake"]["barcodeValues"] = Value::Object(barcodes); +} + fn set_intake(brief: &mut Value, template_id: &Value, schema: &Value) { if schema["version"] != 1 { if let Some(fields) = brief.as_object_mut() { @@ -586,6 +796,8 @@ fn set_intake(brief: &mut Value, template_id: &Value, schema: &Value) { } } else if brief["intake"]["templateId"] != *template_id { brief["intake"] = json!({"templateId":template_id,"schema":schema,"productValues":{},"barcodeValues":{}}); + fill_platform_intake(brief); + assign_platform_images(brief); } } @@ -655,6 +867,18 @@ fn replace_barcode(brief: &mut Value, old: &str, replacement: Option<&str>) { fields.remove("detailBarcode"); } } + if let Some(images) = brief["images"].as_array_mut() { + if let Some(barcode) = replacement { + for image in images.iter_mut().filter(|image| image["barcode"] == old) { image["barcode"] = json!(barcode); } + } else { + images.retain(|image| image["barcode"] != old); + } + } + if let Some(values) = brief.get_mut("platformFacts").and_then(|facts| facts["barcodes"].as_object_mut()) + && let Some(value) = values.remove(old) && let Some(code) = replacement + { + values.insert(code.to_owned(), value); + } if let Some(values) = brief.get_mut("intake").and_then(|intake| intake.get_mut("barcodeValues")) .and_then(Value::as_object_mut) && let Some(value) = values.remove(old) @@ -771,10 +995,31 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val w.creation_progress = value["text"].as_str().unwrap_or("").chars().take(4000).collect(); return; } + if method == "creation-product-platform" && value["platformBrief"].is_object() { + w.creation_read_scope(app); + w.creation_brief = value["platformBrief"].clone(); + fill_platform_intake(&mut w.creation_brief); + assign_platform_images(&mut w.creation_brief); + w.creation_dirty = true; + w.sync_dirty = true; + w.draft_changed = true; + w.creation_reads.platform_message = value["message"].as_str().unwrap_or("").into(); + return; + } if let Some(images) = value["images"].as_array() { if method == "creation-import" { w.match_imported_reference_paths(app, images); } + if value["imageSlot"].is_object() { + match add_slot_images(&mut w.creation_brief, &value["imageSlot"], images) { + Ok(()) => { + w.creation_dirty = true; + w.sync_dirty = true; + } + Err(error) => w.creation_reads.reference_import_error = error, + } + return; + } let mut current = w.creation_brief["images"].as_array().cloned().unwrap_or_default(); let references = image_rows(&w.creation_brief); for image in images { @@ -886,7 +1131,7 @@ pub(super) fn sync_received(w: &mut Workspace, app: &PhotocraftApp, value: &Valu } w.project_refresh_requested = true; w.creation_progress = if value["materialDelivery"]["materialId"].is_string() { - "成品已提交素材库;项目可另行云同步" + "成品已提交素材库" } else if w.sync_dirty { "云端已保存该版本,当前仍有新修改" } else { "已同步" }.into(); } pub(super) fn listing_status_received(w: &mut Workspace, app: &PhotocraftApp, value: &Value) { @@ -936,11 +1181,6 @@ fn reference_import_activity(busy: Option<&str>) -> Option<&'static str> { } } -fn sync_status(changed: bool, busy: Option<&str>) -> Option<&'static str> { - if busy == Some("project-sync") { Some("正在同步") } - else if !changed { Some("已同步") } - else { None } -} impl Workspace { fn creation_escape(&mut self, app: &PhotocraftApp, ui: &mut Ui) { @@ -1047,13 +1287,6 @@ impl Workspace { json!({"composer":self.composer,"messages":self.messages,"creation":self.creation,"draft":self.creation_draft(),"templateWorkflow":self.template_workflow}).to_string() } pub(super) fn sync_action(&mut self, app: &PhotocraftApp, method: &str, mut input: Value) { - if method == "project-sync" && input["status"] != "completed" { - if let Err(error) = self.request_current_sync(app, input["syncChatHistory"] == true) { - self.error = error.clone(); - self.project_list_error = error; - } - return; - } if self.busy.is_some() || self.saving.is_some() || self.project_operation_pending() { self.error = "请等待当前操作完成".into(); return; @@ -1078,66 +1311,15 @@ impl Workspace { self.saving = Some((st.doc.id.0, st.revision)); self.send(method, input); } - pub(super) fn has_sync_changes(&self, app: &PhotocraftApp) -> bool { - self.sync_dirty || app.session.active().is_some_and(|s| self.project_context["syncedRevision"].as_u64() != Some(s.revision)) - } - pub(super) fn navigation_sync_status(&self, app: &PhotocraftApp) -> Option<&'static str> { - sync_status(self.has_sync_changes(app), self.busy.as_deref()) - } - pub(super) fn sync_controls(&mut self, app: &PhotocraftApp, ui: &mut Ui) { - let changed = self.has_sync_changes(app); - let visible_width = ui.available_rect_before_wrap().intersect(ui.clip_rect()).width().max(1.0); - let compact = visible_width < 220.0; + pub(super) fn delivery_controls(&mut self, app: &PhotocraftApp, ui: &mut Ui) { let idle = self.busy.is_none() && self.saving.is_none() && !self.project_operation_pending(); - let sync_failed = self.project_operation["phase"] == "failed" && self.project_operation["kind"] == "sync" - && self.project_operation["accountId"] == self.account["id"] && self.project_operation["origin"] == self.origin - && self.current_sync_item(app).is_some_and(|item| item["id"] == self.project_operation["projectId"]); - let status = self.navigation_sync_status(app); - let label = if compact && status == Some("正在同步") {"正在同步"} else if self.project_operation_pending() {"正在处理…"} - else if sync_failed {"同步失败"} else if changed {"云同步"} else {"已同步"}; - let chat_option = ui.scope_id().with(("cloud-chat-history", self.origin.as_str(), - self.account["id"].as_str(), app.session.active().map(|state| state.doc.id.0))); - let mut chat = ui.ctx().data(|data| data.get_temp::(chat_option)).unwrap_or(false); - let hint = if sync_failed { self.project_operation["message"].as_str().unwrap_or("同步未完成,请查看我的项目") } else { "备份工程和资料到当前素材库账户" }; - let chat_control = |ui: &mut Ui, chat: &mut bool| { - if ui.add_enabled(idle && changed, egui::Checkbox::new(chat, "同步对话")).changed() { - ui.ctx().data_mut(|data| data.insert_temp(chat_option, *chat)); - } - }; let delivered = self.project_context["materialDelivery"]["materialId"].is_string() && self.project_context["status"] == "completed"; - let actions = |ui: &mut Ui, height| { - let sync = stitch_ui::action_button_height(ui, label, stitch_ui::ButtonRole::Secondary, idle && changed && !self.creation_dirty, height) - .on_hover_text(hint).on_disabled_hover_text(hint).clicked(); - let (finish_label, finish_role) = if delivered { - ("上架状态", stitch_ui::ButtonRole::Secondary) - } else { - ("完结", stitch_ui::ButtonRole::Primary) - }; - let finish = stitch_ui::action_button_height(ui, finish_label, finish_role, - delivered || (idle && !self.unknown && !self.creation_dirty), height); - (sync, finish.clicked(), finish.rect) - }; - let (sync, finish, finish_rect) = if compact { - ui.allocate_ui_with_layout(egui::vec2(visible_width, 38.0), egui::Layout::top_down(egui::Align::Max), |ui| { - ui.spacing_mut().item_spacing = egui::vec2(4.0, 0.0); - ui.spacing_mut().button_padding = egui::vec2(4.0, 1.0); - ui.spacing_mut().interact_size.y = 18.0; - let buttons = ui.horizontal(|ui| actions(ui, 18.0)).inner; - chat_control(ui, &mut chat); - buttons - }).inner - } else { - if let Some(status) = status { - stitch_ui::status_label(ui, status, stitch_ui::StatusTone::Neutral); - } - chat_control(ui, &mut chat); - actions(ui, crate::theme::agent_scale::control::DEFAULT) - }; - self.navigation_geometry["delivery"] = rect_value(finish_rect); - if sync { - self.sync_action(app, "project-sync", json!({"status":"draft","syncChatHistory":chat})); - } + let (label, role) = if delivered { ("上架状态", stitch_ui::ButtonRole::Secondary) } + else { ("完结", stitch_ui::ButtonRole::Primary) }; + let button = stitch_ui::action_button(ui, label, role, delivered || (idle && !self.unknown && !self.creation_dirty)); + self.navigation_geometry["delivery"] = rect_value(button.rect); + let finish = button.clicked(); if finish { self.sync_confirm = true; self.listing_read_at = None; @@ -1159,7 +1341,7 @@ impl Workspace { let closed = stitch_ui::dialog(ui, egui::Id::unique("xiaoyi-finish-project"), title, self.sync_confirm, self.reduce_motion, 360.0, |ui| { if !delivered { - ui.label("将已完成的详情、主图和 SKU 成品提交到素材库?项目备份可另行云同步。"); + ui.label("将已完成的详情、主图和 SKU 成品提交到素材库?"); } let receipt = &self.project_context["materialDelivery"]; if let Some(id) = receipt["materialId"].as_str() { @@ -1190,7 +1372,7 @@ impl Workspace { } if !delivered && stitch_ui::action_button(ui, "完结并提交", stitch_ui::ButtonRole::Primary, idle).clicked() { self.sync_confirm = false; - self.sync_action(app, "project-sync", json!({"status":"completed","syncChatHistory":chat})); + self.sync_action(app, "project-sync", json!({"status":"completed"})); } }); }); @@ -1230,6 +1412,9 @@ impl Workspace { if self.busy.is_some() { return Err("请等待当前操作完成".into()); } + if method == "creation-product-platform" && !self.account["id"].is_string() { + return Err("请先登录素材库账号".into()); + } if self.unknown && !matches!(method, "creation-recover" | "creation-read" | "creation-load") && !(method == "creation-save" && self.scoped_production_pending()) { @@ -1505,7 +1690,7 @@ impl Workspace { ui.add_space(8.0); if width >= 600.0 { ui.horizontal(|ui| { - ui.allocate_ui_with_layout(vec2(320.0, 32.0), egui::Layout::left_to_right(egui::Align::Center), |ui| self.source_picker(ui)); + ui.allocate_ui_with_layout(vec2(380.0, 32.0), egui::Layout::left_to_right(egui::Align::Center), |ui| self.source_picker(ui)); if self.creation_brief["source"] == "library" { ui.add_space((ui.available_width() - 160.0).max(0.0)); self.product_search_button(app, ui); @@ -1520,15 +1705,19 @@ impl Workspace { } if self.creation_brief["source"] == "library" { self.product_select_results(app, ui); + } else if self.creation_brief["source"] == "product_platform" { + self.platform_spu_ui(app, ui, field_scope, width); } ui.add_space(10.0); let dynamic = self.creation_brief["intake"]["schema"]["version"] == 1; let columns = brief_columns(width).min(2); let field_width = ((width - 14.0 * (columns - 1) as f32) / columns as f32).max(130.0); + let platform = self.creation_brief["source"] == "product_platform"; let labels = ["产品名称 *", "产品尺寸(长 × 宽 × 高)", "SPU 型号", "画幅导出规格"]; egui::Grid::new("creation-brief").num_columns(columns).spacing(vec2(14.0, 12.0)).show(ui, |ui| { for (position, (index, label)) in labels.iter().enumerate() - .filter(|(index, _)| !dynamic || matches!(index, 0 | 2)).enumerate() { + .filter(|(index, _)| (!dynamic || matches!(index, 0 | 2)) + && (*index != 2 || !platform)).enumerate() { field_group(ui, field_width, label, |ui| match index { 0 => { let name = ui.scope(|ui| edit(ui, (field_scope, "name"), &mut self.creation_brief["name"], field_width, false, "产品名称")); @@ -1608,17 +1797,25 @@ impl Workspace { }); ui.add_space(8.0); let product_fields = self.creation_brief["intake"]["schema"]["productFields"].clone(); - if product_fields.as_array().is_some_and(|fields| !fields.is_empty()) { + self.poll_imported_reference_previews(app, ui.ctx()); + let image_fields = product_fields.as_array().into_iter().flatten() + .filter(|field| field_kind(field) == "image").collect::>(); + let product_fields = product_fields.as_array().into_iter().flatten() + .filter(|field| field_kind(field) != "image" && !is_product_name_field(field)).collect::>(); + if !product_fields.is_empty() { section_heading(ui, "共用属性", ""); let mut values = self.creation_brief["intake"]["productValues"].clone(); if !values.is_object() { values = json!({}); } - if intake_fields(ui, field_scope.with("intake-product"), width, &product_fields, &mut values, self.reduce_motion) { + if intake_fields(ui, field_scope.with("intake-product"), width, &product_fields, IntakeScope::Product, &mut values, self.reduce_motion) { self.creation_brief["intake"]["productValues"] = values; self.creation_dirty = true; } } + for field in image_fields { + self.image_slot_ui(app, ui, width, field, None); + } brief_section_break(ui); - if !dynamic { + if !dynamic && !platform { if width >= 600.0 { ui.horizontal_top(|ui| { // The trigger and popup share a width in `picker`: keep room @@ -1640,7 +1837,7 @@ impl Workspace { ui.add_space(12.0); self.sku_colors(ui, width, field_scope); } - let barcode_pending = self.barcode_cards_ui(ui, width, field_scope); + let barcode_pending = self.barcode_cards_ui(app, ui, width, field_scope); if self.creation_brief.get("barcodeBindings").is_none() { stitch_ui::disclosure(ui, field_scope.with("legacy-sku-bindings"), "旧项目商品编号", false, self.reduce_motion, |ui| { let mut variants = brief_variants(&self.creation_brief); @@ -1679,7 +1876,7 @@ impl Workspace { self.control_geometry("special-requirements", response.rect); } - fn barcode_cards_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id) -> bool { + fn barcode_cards_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, scope: egui::Id) -> bool { let variants = brief_variants(&self.creation_brief); let mut groups: Vec<(&str, &str)> = variants.iter().filter_map(|variant| { Some((variant["id"].as_str()?, variant["name"].as_str().unwrap_or("条码"))) @@ -1688,6 +1885,8 @@ impl Workspace { groups.insert(0, ("default", "条码")); } let fields = self.creation_brief["intake"]["schema"]["barcodeFields"].clone(); + let images = fields.as_array().into_iter().flatten().filter(|field| field_kind(field) == "image").collect::>(); + let fields = fields.as_array().into_iter().flatten().filter(|field| field_kind(field) != "image").collect::>(); let mut ordinal = 0; let mut pending = false; for (id, label) in groups { @@ -1747,10 +1946,18 @@ impl Workspace { }); let mut values = self.creation_brief["intake"]["barcodeValues"][code.as_str()].clone(); if !values.is_object() { values = json!({}); } - if intake_fields(ui, card_scope, width, &fields, &mut values, self.reduce_motion) { + if intake_fields(ui, card_scope, width, &fields, IntakeScope::Barcode, &mut values, self.reduce_motion) { self.creation_brief["intake"]["barcodeValues"][code.as_str()] = values; self.creation_dirty = true; } + for field in &images { self.image_slot_ui(app, ui, width, field, Some(code)); } + if fields.is_empty() { + let facts = &self.creation_brief["platformFacts"]["barcodes"][code.as_str()]; + for key in ["colorName","sizeText","spec"] { + if let Some(value) = facts[key].as_str().filter(|value| !value.is_empty()) { ui.label(value); } + } + if let Some(dimensions) = dimension_text(&facts["dimensions"]) { ui.label(dimensions); } + } }); self.control_geometry(&format!("barcode-card-{id}-{index}"), card.response.rect); } @@ -1781,6 +1988,9 @@ impl Workspace { self.control_geometry(&format!("detail-barcode-option-{index}"), option.rect); if option.clicked() { self.creation_brief["detailBarcode"] = json!(code); + if self.creation_brief["source"] == "product_platform" { + self.creation_brief["colorName"] = json!(self.creation_brief["platformFacts"]["barcodes"][code.as_str()]["colorName"].as_str().unwrap_or("")); + } self.creation_dirty = true; ui.close(); } @@ -2105,6 +2315,12 @@ impl Workspace { } fn add_reference_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) -> egui::Rect { + self.reference_picker(app, ui, width, egui::Id::unique("creation-reference-drop"), None, Value::Null) + } + + fn reference_picker(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, + id: egui::Id, labels: Option<(&str, &str)>, slot: Value, + ) -> egui::Rect { let supported = ui.input(|input| { let files = &input.raw.hovered_files; !files.is_empty() && files.len() <= 8 && files.iter().all(|file| { @@ -2117,16 +2333,20 @@ impl Workspace { }); let enabled = self.busy.is_none() && !self.unknown; let drop_pointer = if supported && enabled { app.services.cursor_pos.as_mut().and_then(|cursor| cursor(ui.ctx())) } else { None }; - let add_reference = stitch_ui::file_drop_zone(ui, egui::Id::unique("creation-reference-drop"), width, drop_pointer, enabled, self.reduce_motion) + let add_reference = if let Some((label, placeholder)) = labels { + stitch_ui::labeled_file_drop_zone(ui, id, width, drop_pointer, enabled, self.reduce_motion, label, Some(placeholder)) + } else { + stitch_ui::file_drop_zone(ui, id, width, drop_pointer, enabled, self.reduce_motion) + } .on_hover_text("支持 PNG、JPG、WebP;每次最多 8 张,单张不超过 20 MB"); - self.control_geometry("reference-add", add_reference.rect); + if slot.is_null() { self.control_geometry("reference-add", add_reference.rect); } if enabled && add_reference.clicked() { let id = app.session.active().map(|s| s.doc.id.0); let account = self.account["id"].clone(); let origin = self.origin.clone(); let result = app.ask_file( crate::FileDialogRequest::Open { - multiple: true, + multiple: slot["multiple"] != false, initial_dir: None, extensions: Some(vec!["png".into(), "jpg".into(), "jpeg".into(), "webp".into()]), }, @@ -2138,7 +2358,7 @@ impl Workspace { } match answer { crate::FileDialogAnswer::Paths(paths) => { - if let Err(error) = app.import_reference_paths(paths) + if let Err(error) = app.import_reference_paths(paths, slot) && let Some(w) = app.jiansun.as_mut() { w.creation_reads.reference_import_error = error; @@ -2178,16 +2398,76 @@ impl Workspace { } } + fn platform_spu_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32) { + let query_id = scope.with("platform-spu-query"); + let seed = if self.creation_brief["identifierType"] == "spu" { &self.creation_brief["identifier"] } + else { &self.creation_brief["deliverySpu"] }; + let mut query = ui.data(|data| data.get_temp::(query_id)).unwrap_or_else(|| seed.clone()); + let loading = self.busy.as_deref() == Some("creation-product-platform"); + let logged_in = self.account["id"].is_string(); + ui.horizontal_wrapped(|ui| { + let editor = ui.scope(|ui| edit_named(ui, query_id, &mut query, + (width - 144.0).max(100.0), false, "输入 SPU 型号", "SPU 型号")); + self.control_geometry("identifier", editor.response.rect); + let spu = query.as_str().unwrap_or("").trim(); + let fetch = stitch_ui::action_button(ui, if loading { "正在拉取…" } else { "拉取条码资料" }, + stitch_ui::ButtonRole::Secondary, logged_in && form_editable(self.busy.as_deref(), self.unknown) && !spu.is_empty()); + self.control_geometry("platform-fetch", fetch.rect); + if fetch.clicked() { + self.creation_reads.platform_message.clear(); + if let Err(error) = self.creation_action(app, "creation-product-platform", json!({"spu":spu})) { + self.creation_reads.platform_message = error; + } + } + }); + ui.data_mut(|data| data.insert_temp(query_id, query)); + let message = if logged_in { self.creation_reads.platform_message.as_str() } else { "请先登录素材库账号" }; + if !message.is_empty() { stitch_ui::status_label(ui, message, stitch_ui::StatusTone::Warning); } + } + + fn image_slot_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, field: &Value, barcode: Option<&str>) { + let slot = image_slot(&self.creation_brief["intake"]["templateId"], field, barcode); + let label = intake_label(field); + ui.label(&label); + let key = self.creation_field_scope(app).with(("reference-image-slot", slot.to_string())); + let placeholder = field["placeholder"].as_str().unwrap_or("拖放图片或点击选择"); + let drop = self.reference_picker(app, ui, width, key, Some((&label, placeholder)), slot.clone()); + self.creation_view_geometry["imageSlots"][key.value().to_string()] = json!({ + "doc":self.creation_doc,"accountId":self.account["id"],"origin":self.origin, + "rect":rect_value(drop.intersect(ui.clip_rect())),"slot":slot,"label":label,"placeholder":placeholder + }); + let rows = self.creation_brief["images"].as_array().cloned().unwrap_or_default(); + let mut remove = None; + for (index, image) in rows.iter().enumerate().filter(|(_, image)| in_image_slot(image, &slot)) { + let Some(source) = image["source"].as_str() else { continue }; + self.queue_creation_reference(app, source); + let preview_key = super::creation_reads::reference_key(source); + ui.horizontal(|ui| { + material_thumbnail(ui, self.creation_thumbs.get(&preview_key), self.creation_thumbnail_loading(&preview_key), + self.creation_thumbnail_error(&preview_key).is_some()); + let response = stitch_ui::icon_button(ui, "trash", 28.0, false, "删除图片"); + if response.clicked() { remove = Some(index); } + let name = image["name"].as_str().unwrap_or("图片"); + ui.add(egui::Label::new(name).truncate()).on_hover_text(name); + }); + } + if let Some(index) = remove { + self.creation_brief["images"] = json!(rows.into_iter().enumerate() + .filter_map(|(position, image)| (position != index).then_some(image)).collect::>()); + self.creation_dirty = true; + } + } + fn source_picker(&mut self, ui: &mut Ui) { let t = Tokens::get(ui.ctx()).agent(); let mut choices = Vec::new(); let label = egui::RichText::new("资料来源").size(12.0).color(t.text_dim); - let narrow = ui.available_width() < 240.0; + let narrow = ui.available_width() < 360.0; if narrow { ui.label(label.clone()); } let source = ui.horizontal_wrapped(|ui| { if !narrow { ui.label(label); } - let option_width = if narrow { (ui.available_width() - ui.spacing().item_spacing.x) / 2.0 } else { 92.0 }; - for (value, label) in [("upload", "手工录入"), ("library", "素材库产品")] { + let option_width = if narrow { (ui.available_width() - 2.0 * ui.spacing().item_spacing.x) / 3.0 } else { 92.0 }; + for (value, label) in [("upload", "手工录入"), ("product_platform", "产品平台"), ("library", "素材库产品")] { let selected = self.creation_brief["source"] == value; let response = stitch_ui::segmented_option_sized(ui, label, selected, true, vec2(option_width, 28.0)); self.control_geometry(&format!("source-{value}"), response.rect); @@ -2216,15 +2496,27 @@ impl Workspace { let mut changed = false; let mut remove = None; let mut errors = Vec::new(); - let title = ui.label(egui::RichText::new("产品参考图 *").size(13.0).color(t.text_dim)); - if !rows.is_empty() && !rows.iter().any(|(image, _)| image["purpose"] == "product") { + let explicit = uses_template_images(&self.creation_brief); + let hidden: Vec<_> = rows.iter().map(|(image, _)| explicit && image["fieldKey"].is_string() + && ["productFields", "barcodeFields"].into_iter().any(|scope| { + let intake = &self.creation_brief["intake"]; + (scope == "barcodeFields") == image["barcode"].is_string() + && intake["schema"][scope].as_array().into_iter().flatten().any(|field| + field_kind(field) == "image" && in_image_slot(image, + &image_slot(&intake["templateId"], field, image["barcode"].as_str()))) + })).collect(); + let has_visible = hidden.iter().any(|&hidden| !hidden); + let title = (!explicit || has_visible).then(|| ui.label(egui::RichText::new( + if explicit { "其他参考图" } else { "产品参考图 *" }).size(13.0).color(t.text_dim))); + if !explicit && !rows.is_empty() && !rows.iter().any(|(image, _)| image["purpose"] == "product") { stitch_ui::status_label(ui, "请将至少一张参考图的用途设为「产品图」。", stitch_ui::StatusTone::Warning); } // Keep real purpose and ownership controls visible alongside each image. let columns = if width >= 780.0 { 3 } else if width >= 600.0 { 2 } else { 1 }; let card_width = (width - 12.0 * (columns - 1) as f32) / columns as f32; let grid = egui::Grid::new("creation-references").num_columns(columns).spacing(vec2(12.0, 12.0)).show(ui, |ui| { - for (index, (image, owner)) in rows.iter_mut().enumerate() { + for (position, (index, (image, owner))) in rows.iter_mut().enumerate() + .filter(|(index, _)| hidden.get(*index) == Some(&false)).enumerate() { let source = image["source"].as_str().unwrap_or("").to_owned(); let preview_key = super::creation_reads::reference_key(&source); let frame = stitch_ui::material_frame(ui, stitch_ui::surface_frame(ui.ctx(), stitch_ui::SurfaceRole::Input).corner_radius(12).inner_margin(12), |ui| { @@ -2348,20 +2640,22 @@ impl Workspace { }); }); self.control_geometry(&format!("reference-{index}"), frame.response.rect); - if (index + 1) % columns == 0 { + if (position + 1) % columns == 0 { ui.end_row(); } } }); - let drop_rect = self.add_reference_button(app, ui, width); - if rows.is_empty() { - self.control_geometry("reference-empty", drop_rect); + if !explicit && let Some(title) = title { + let drop_rect = self.add_reference_button(app, ui, width); + if rows.is_empty() { + self.control_geometry("reference-empty", drop_rect); + } + let target = title.rect.union(drop_rect); + let visible = if rows.is_empty() { target } else { target.union(grid.response.rect) }.intersect(ui.clip_rect()); + self.creation_view_geometry["referenceDrop"] = json!({ + "doc":app.session.active().map(|state| state.doc.id.0),"accountId":self.account["id"],"origin":self.origin,"rect":rect_value(visible) + }); } - let target = title.rect.union(drop_rect); - let visible = if rows.is_empty() { target } else { target.union(grid.response.rect) }.intersect(ui.clip_rect()); - self.creation_view_geometry["referenceDrop"] = json!({ - "doc":app.session.active().map(|state| state.doc.id.0),"accountId":self.account["id"],"origin":self.origin,"rect":rect_value(visible) - }); for error in errors { stitch_ui::status_label(ui, &error, stitch_ui::StatusTone::Error); } @@ -3510,21 +3804,6 @@ mod tests { } } - #[test] - fn reference_import_and_sync_activity_only_reflect_actual_operations() { - for busy in ["creation-import", "creation-import-data"] { - assert_eq!(reference_import_activity(Some(busy)), Some("正在导入参考图")); - } - assert_eq!(reference_import_activity(Some("creation-import-library")), Some("正在读取素材库参考图")); - for busy in [None, Some("creation-read"), Some("agent"), Some("project-sync")] { - assert_eq!(reference_import_activity(busy), None); - } - assert_eq!(sync_status(false, Some("project-sync")), Some("正在同步")); - assert_eq!(sync_status(true, Some("project-sync")), Some("正在同步")); - assert_eq!(sync_status(false, None), Some("已同步")); - assert_eq!(sync_status(true, None), None); - } - #[test] fn reference_import_progress_is_visible_only_while_import_is_in_flight() { let (mut w, mut app) = setup(); @@ -3909,6 +4188,104 @@ mod tests { (w, app, requests) } + #[test] + fn platform_facts_fill_template_fields_and_keep_missing_fields_empty() { + let (mut w, mut app, requests) = barcode_fixture(); + let mut brief = w.creation_brief.clone(); + brief["source"] = json!("product_platform"); + brief["identifierType"] = json!("spu"); + brief["identifier"] = json!("00-Model"); + brief["barcodeBindings"] = json!({"default":["00-a,01","00-B"]}); + brief["detailBarcode"] = json!("00-a,01"); + brief["platformFacts"] = json!({"spu":"00-Model","shared":{"material":"织物"},"barcodes":{ + "00-a,01":{"colorName":"灰色","dimensions":{"unit":"mm","length":1800,"width":900,"height":700}}, + "00-B":{"colorName":"米色","dimensions":{"unit":"mm","width":880}} + }}); + brief["intake"]["schema"]["productFields"].as_array_mut().unwrap() + .push(json!({"id":"material","label":"材质","type":"text"})); + let doc = app.session.active().unwrap().doc.id.0; + let receipt = json!({"doc":doc,"origin":w.origin,"accountId":w.account["id"],"platformBrief":brief}); + received(&mut w, &app, "creation-product-platform", &receipt); + assert_eq!(w.creation_brief["intake"]["productValues"], json!({"material":"织物"})); + assert_eq!(w.creation_brief["intake"]["barcodeValues"]["00-a,01"], json!({"color":"灰色","length":1800,"width":900,"height":700})); + assert_eq!(w.creation_brief["intake"]["barcodeValues"]["00-B"], json!({"color":"米色","width":880})); + assert_eq!(field_fact(&json!({"id":"length","type":"number","unit":"cm"}), + &w.creation_brief["platformFacts"]["barcodes"]["00-a,01"]), Some(json!(180.0))); + let ctx = egui::Context::default(); + w.account = Value::Null; + let before = w.creation_brief.clone(); + brief_frame(&mut w, &mut app, &ctx, 380.0, vec![]); + assert!(!w.creation_view_geometry["controls"]["platform-fetch"].is_null()); + assert!(w.creation_action(&mut app, "creation-product-platform", json!({"spu":"00-Model"})).unwrap_err().contains("登录")); + assert_eq!(w.creation_brief, before); + assert!(!requests.try_iter().any(|request| matches!(request, Request::Action(method, _) if method == "creation-product-platform"))); + } + + #[test] + fn template_image_slots_use_drop_and_picker_with_exact_roles_and_barcode() { + let (mut w, mut app, requests) = barcode_fixture(); + w.creation_open = true; + w.library = false; + let schema = json!({"version":1,"productFields":[ + {"key":"hero","kind":"image","label":"产品图片","imageRole":"product","placeholder":"拖入产品图"}], + "barcodeFields":[{"key":"fabric","kind":"image","label":"材质图片","imageRole":"material","multiple":false,"placeholder":"拖入材质图"}]}); + set_intake(&mut w.creation_brief, &json!("image-template"), &schema); + let (picker, asked) = crate::file_dialog::fake(vec![Some(crate::FileDialogAnswer::Paths(vec!["D:\\photos\\fabric.png".into()]))]); + app.services.file_dialog = Some(picker); + let ctx = egui::Context::default(); + for width in [380.0, 850.0] { + brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let bounds = brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let slots = w.creation_view_geometry["imageSlots"].as_object().unwrap(); + assert_eq!(slots.len(), 3); + assert!(slots.values().all(|target| { + let rect = &target["rect"]; + rect[0].as_f64().unwrap_or_default() >= f64::from(bounds.left()) && + rect[0].as_f64().unwrap_or_default() + rect[2].as_f64().unwrap_or_default() <= f64::from(bounds.right()) + })); + assert!(w.creation_view_geometry["controls"]["reference-add"].is_null()); + } + let slots = w.creation_view_geometry["imageSlots"].as_object().unwrap(); + let product = slots.values().find(|row| row["label"] == "产品图片").unwrap().clone(); + let fabric = slots.values().find(|row| row["label"] == "材质图片" + && row["slot"]["barcode"] == "DNZ030516N717V01").unwrap().clone(); + let center = |rect: &Value| egui::pos2((rect[0].as_f64().unwrap()+rect[2].as_f64().unwrap()/2.0) as f32, + (rect[1].as_f64().unwrap()+rect[3].as_f64().unwrap()/2.0) as f32); + assert_eq!(product["placeholder"], "拖入产品图"); + assert_eq!(fabric["placeholder"], "拖入材质图"); + app.jiansun = Some(w); + app.open_dropped(&ctx, vec![reference_drop("D:\\photos\\product.png")], Some(center(&product["rect"]))); + let Some(Request::Action(_, input)) = requests.try_iter() + .find(|request| matches!(request, Request::Action(method, _) if method == "creation-import")) + else { panic!("expected import"); }; + assert_eq!(input["imageSlot"]["imageRole"], "product"); + let mut w = app.jiansun.take().unwrap(); + w.busy = None; + let pixels = json!([{"source":format!("local:{}", "d".repeat(64)),"purpose":"product","name":"样品"}]); + let draft = w.creation_brief.clone(); + let doc = app.session.active().unwrap().doc.id.0; + let import = |slot: &Value| json!({"doc":doc,"origin":product["origin"],"accountId":product["accountId"],"images":pixels,"imageSlot":slot}); + received(&mut w, &app, "creation-import", &import(&input["imageSlot"])); + brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); + let slot = w.creation_view_geometry["imageSlots"].as_object().unwrap().values() + .find(|row| row["slot"] == fabric["slot"]).unwrap(); + let click = center(&slot["rect"]); + brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(click)); + app.jiansun = Some(w); + app.poll_file_dialog(&ctx, None); + assert!(matches!(asked.borrow().first(), Some(crate::FileDialogRequest::Open { multiple:false, .. }))); + let Some(Request::Action(_, input)) = requests.try_iter() + .find(|request| matches!(request, Request::Action(method, _) if method == "creation-import")) + else { panic!("expected import"); }; + assert_eq!(input["imageSlot"], fabric["slot"]); + let mut w = app.jiansun.take().unwrap(); + received(&mut w, &app, "creation-import", &import(&input["imageSlot"])); + assert_eq!(w.creation_brief["images"][0]["imageRole"], "product"); + assert_eq!(w.creation_brief["images"][1]["imageRole"], "material"); + assert_eq!(w.creation_brief["images"][1]["barcode"], "DNZ030516N717V01"); + assert_eq!(w.creation_brief["intake"], draft["intake"]); + } + #[test] fn barcode_bindings_read_legacy_lists_and_deduplicate_the_complete_trimmed_values() { let legacy = json!(" DNZ030516N717V01,;CY001307N35V01、\r\nDNZ030516N717V01 "); @@ -3964,6 +4341,68 @@ mod tests { assert_eq!(w.creation_brief["detailBarcode"], "CY001307N35V01"); } + #[test] + fn dynamic_intake_reads_optional_hints_and_multiline_without_requiring_schema_changes() { + let explicit = json!({"id":"copy","type":"text","placeholder":" 如:收拢深度 35 cm ","help":"旧说明","multiline":true}); + let legacy_long = json!({"id":"notes","type":"text","label":"注意事项","help":"如:远离火源"}); + let legacy_short = json!({"id":"material","type":"text","label":"材质"}); + let a = json!({"id":"length","type":"number","help":"按本款确认资料填写;尺寸注明单位,暂无资料可留空。"}); + let b = json!({"id":"wood","type":"select","help":"请按确认资料填写。"}); + let c = json!({"id":"finish","type":"text","help":" 请按确认资料填写。 "}); + let group = [&explicit, &legacy_long, &legacy_short, &a, &b, &c]; + assert_eq!(intake_hint(&explicit, &group), "如:收拢深度 35 cm"); + assert_eq!(intake_hint(&legacy_long, &group), "如:远离火源"); + assert_eq!(intake_hint(&legacy_short, &group), ""); + assert_eq!(intake_hint(&a, &group), "数字"); + assert_eq!(intake_hint(&b, &group), "请选择"); + assert_eq!(intake_hint(&c, &group), ""); + assert!(intake_multiline(&explicit)); + assert!(intake_multiline(&legacy_long)); + assert!(!intake_multiline(&legacy_short)); + assert!(!intake_multiline(&json!({"type":"text","label":"注意事项","multiline":false}))); + assert!(is_product_name_field(&json!({"id":"name","label":"产品名称","type":"text"}))); + assert!(is_product_name_field(&json!({"id":"title","label":"商品名 * ","type":"text"}))); + assert!(!is_product_name_field(&json!({"id":"english","label":"英文产品名称","type":"text"}))); + } + + #[test] + fn dynamic_product_intake_reflows_short_fields_and_spans_long_text() { + use egui_kittest::{Harness, kittest::Queryable}; + assert_eq!(product_intake_columns(559.0), 1); + assert_eq!(product_intake_columns(560.0), 2); + for width in [420.0, 640.0] { + let mut harness = Harness::builder().with_size(vec2(width + 40.0, 460.0)) + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests) + .build_ui_state(|ui, values: &mut Value| { + let fields = [ + json!({"id":"a","label":"材质","type":"text","placeholder":"如:橡木"}), + json!({"id":"b","label":"产地","type":"text","help":"如:江苏"}), + json!({"id":"c","label":"核心卖点","type":"text","multiline":true}), + ]; + let fields = fields.iter().collect::>(); + intake_fields(ui, egui::Id::unique("product-intake-test"), width, &fields, + IntakeScope::Product, values, true); + }, json!({})); + harness.run_steps(2); + let a = harness.get_by_role_and_label(egui::accesskit::Role::TextInput, "材质").rect(); + let b = harness.get_by_role_and_label(egui::accesskit::Role::TextInput, "产地").rect(); + let c = harness.get_by_role_and_label(egui::accesskit::Role::MultilineTextInput, "核心卖点").rect(); + if width >= 560.0 { + assert!((a.top() - b.top()).abs() < 1.0 && a.right() < b.left()); + assert!(c.width() > a.width() * 1.9); + } else { + assert!(b.top() > a.bottom() && (a.left() - b.left()).abs() < 1.0); + assert!((c.width() - a.width()).abs() < 1.0); + } + assert!(c.top() > b.bottom() && c.height() > a.height()); + harness.get_by_role_and_label(egui::accesskit::Role::TextInput, "材质").click(); + harness.run_steps(2); + harness.event(egui::Event::Text("橡木".to_owned())); + harness.run_steps(2); + assert_eq!(harness.state(), &json!({"a":"橡木"})); + } + } + #[test] fn dynamic_barcode_form_keeps_cards_and_controls_within_wide_and_narrow_bounds() { assert_eq!(intake_columns(178.0), 2); @@ -4034,8 +4473,9 @@ mod tests { assert_eq!(w.creation_brief["note"], "已保存的特殊制作要求"); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let field = json!({"id":"unexpected","label":"扩展字段","type":"future-kind"}); intake_fields(ui, egui::Id::unique("unknown-field-test"), 360.0, - &json!([{"id":"unexpected","label":"扩展字段","type":"future-kind"}]), &mut json!({}), true); + &[&field], IntakeScope::Product, &mut json!({}), true); }); let text = out.shapes.iter().filter_map(|shape| match &shape.shape { egui::Shape::Text(text) => Some(text.galley.text()), @@ -4049,13 +4489,22 @@ mod tests { #[ignore = "offscreen GPU visual evidence; requires PHOTOCRAFT_AGENT_QA_OUT"] fn barcode_form_visual_acceptance() { let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); - for (width, height) in [(248.0, 2100.0), (900.0, 1600.0)] { + for (width, height) in [(248.0, 2100.0), (760.0, 1760.0), (900.0, 1600.0)] { let (mut w, app, _) = barcode_fixture(); w.creation_brief["name"] = json!("轻量可调工作台"); + w.creation_brief["intake"]["schema"]["productFields"] = json!([ + {"id":"name","label":"产品名称","type":"text","required":true}, + {"id":"species","label":"主要材质","type":"text","placeholder":"如:白橡木"}, + {"id":"load","label":"承重","type":"number","unit":"kg","help":"如:60"}, + {"id":"finish","label":"表面处理","type":"select","options":["木蜡油","水性漆"],"placeholder":"选择表面处理"}, + {"id":"origin","label":"产地","type":"text","help":"如:江苏"}, + {"id":"copy","label":"核心卖点","type":"text","multiline":true,"placeholder":"如:台面高度可调。折叠后靠墙收纳。"}, + ]); w.creation_brief["identifier"] = json!("QA-DESK-001"); w.creation_brief["detailBarcode"] = json!("CY001307N35V01"); w.reduce_motion = true; - let mut h = egui_kittest::Harness::builder().with_size(vec2(width, height)).wgpu().build_ui_state( + let mut h = egui_kittest::Harness::builder().with_size(vec2(width, height)) + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests).wgpu().build_ui_state( |ui, state: &mut (Workspace, PhotocraftApp)| { if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { stitch_ui::scope(ui, |ui| state.0.brief_ui(&mut state.1, ui)); @@ -4067,6 +4516,33 @@ mod tests { } } + #[test] + #[ignore = "offscreen GPU image-slot acceptance; requires PHOTOCRAFT_AGENT_QA_OUT"] + fn template_image_slots_visual_acceptance() { + let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + for width in [380.0, 850.0] { + let (mut w, app, _) = barcode_fixture(); + w.creation_brief["source"] = json!("product_platform"); + w.creation_brief["identifierType"] = json!("spu"); + w.creation_brief["identifier"] = json!("SPU-001"); + w.creation_brief["name"] = json!("可调工作台"); + set_intake(&mut w.creation_brief, &json!("visual-template"), &json!({"version":1, + "productFields":[{"key":"product","kind":"image","label":"产品图片","placeholder":"拖入产品图或点击选择","imageRole":"product"}], + "barcodeFields":[{"key":"material","kind":"image","label":"材质图片","placeholder":"拖入材质图或点击选择","imageRole":"material"}]})); + w.reduce_motion = true; + let mut h = egui_kittest::Harness::builder().with_size(vec2(width, 1600.0)) + .with_context_setup(crate::cjk_fonts::install_system_provider_for_tests).wgpu().build_ui_state( + |ui, state: &mut (Workspace, PhotocraftApp)| { + if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { + stitch_ui::scope(ui, |ui| state.0.brief_ui(&mut state.1, ui)); + } + }, (w, app)); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join(format!("track-h-form-{width}.png"))).unwrap(); + } + } + #[test] fn resumed_project_shows_continue_after_the_originals_settle() { let (mut w, mut app, _) = brief_fixture(); @@ -4792,7 +5268,7 @@ mod tests { expected["source"] = json!("library"); assert_eq!(w.creation_brief, expected, "switching source must preserve names, images, variants and template identity"); assert_eq!(w.creation_view_geometry["sourceChoices"][0]["selected"], false); - assert_eq!(w.creation_view_geometry["sourceChoices"][1]["selected"], true); + assert_eq!(w.creation_view_geometry["sourceChoices"][2]["selected"], true); assert!(w.creation_dirty); brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); let upload = control_rect(&w, "source-upload").center(); @@ -4842,9 +5318,13 @@ mod tests { frame(&mut w, key_events(egui::Key::Tab)); frame(&mut w, key_events(egui::Key::Tab)); frame(&mut w, key_events(egui::Key::Enter)); + expected["source"] = json!("product_platform"); + assert_eq!(w.creation_brief, expected, "keyboard can select the product platform without changing the draft"); + frame(&mut w, key_events(egui::Key::Tab)); + frame(&mut w, key_events(egui::Key::Enter)); expected["source"] = json!("library"); - assert_eq!(w.creation_brief, expected, "Tab, Tab, Enter selects the library without changing the draft"); - assert_eq!(w.creation_view_geometry["sourceChoices"][1]["selected"], true); + assert_eq!(w.creation_brief, expected, "keyboard can select the library without changing the draft"); + assert_eq!(w.creation_view_geometry["sourceChoices"][2]["selected"], true); assert!(requests.try_recv().is_err()); } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs index ef1c71f6..0f25c30b 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs @@ -39,6 +39,7 @@ pub(super) struct UiState { cache_order: VecDeque, pub(super) reference_previews: HashMap, pub(super) reference_import_error: String, + pub(super) platform_message: String, pub(super) reference_import_paths: Option>, imported_reference_files: Vec<(String, String)>, #[cfg(not(target_arch = "wasm32"))] @@ -106,6 +107,7 @@ impl Workspace { self.creation_reads.thumbnail_errors.clear(); self.creation_reads.reference_import_error.clear(); self.creation_reads.reference_import_paths = None; + self.creation_reads.platform_message.clear(); self.creation_reads.imported_reference_files.clear(); #[cfg(not(target_arch = "wasm32"))] self.creation_reads.imported_reference_previews.clear(); @@ -418,6 +420,20 @@ impl Workspace { true } pub(super) fn creation_thumbnail_received(&mut self, app: &PhotocraftApp, ctx: &egui::Context, reference: &Value, image: egui::ColorImage) -> bool { + if reference["purpose"] == "creation-platform-preview" { + self.creation_read_scope(app); + if reference["accountId"] == self.account["id"] && reference["origin"] == self.origin + && reference["doc"].as_u64() == self.creation_doc + && self.creation_doc == app.session.active().map(|state| state.doc.id.0) + && let Some(source) = reference["source"].as_str() + && brief_reference(&self.creation_brief, source) + { + let key = reference_key(source); + let texture = ctx.load_texture(&key, image, egui::TextureOptions::LINEAR); + self.store_creation_thumbnail(key, texture); + } + return true; + } if reference["purpose"] != "creation-material" { return false; } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/feedback.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/feedback.rs new file mode 100644 index 00000000..8ed4c2d2 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/feedback.rs @@ -0,0 +1,324 @@ +use super::{PhotocraftApp, Request, Workspace, stitch_ui}; +use egui::{Context, Id, RichText}; +use percent_encoding::percent_decode_str; +use serde_json::{Value, json}; +use std::sync::LazyLock; + +const MAX_SUMMARY: usize = 2000; +const FIELDS: &[&str] = &[ + "client", + "clientVersion", + "appVersion", + "version", + "platform", + "os", + "arch", + "capturedAt", + "online", + "project", + "projectId", + "projectName", + "task", + "taskId", + "request", + "requestId", + "id", + "name", + "title", + "kind", + "type", + "status", + "stage", + "model", + "timestamp", + "createdAt", + "durationMs", + "code", + "errorCode", + "error", + "errors", + "message", + "diagnostics", + "events", +]; + +static SENSITIVE: LazyLock = LazyLock::new(|| { + #[allow(clippy::expect_used)] + regex::Regex::new(concat!( + r#"(?i)\bdata\s*:|[A-Za-z0-9+/_=-]{40,}|\beyJ[\w-]+\.[\w-]+\.[\w-]+"#, + r#"|\b(?:authorization|(?:set[-_ ]?)?cookie|[\w-]*(?:api|access|auth|private)[-_ ]?key(?:[-_ ]?id)?|[\w-]*token|[\w-]*secret|[\w-]*pass(?:word|wd|phrase)?|credentials?|[\w-]*session(?:[-_ ]?id)?|sid(?:\.sig)?|[\w-]*signature)["']?\s*[:=]"#, + r#"|--(?:api[-_]?key|token|password|secret)\s+|\bcookie\s+\S+=|\b(?:bearer|basic)\s+\S|-----BEGIN [^-]+-----"#, + r#"|\b[a-z][a-z\d+.-]{0,24}://|\b[\w.%-]{1,64}:[^\s@]{1,256}@\S"#, + r#"|\b(?:dcs_|dca_|sk[-_]|rk[-_]|gh[pousr]_|github_pat_|xox[baprs]-|AKIA|ASIA)[\w-]+"#, + )).expect("constant feedback redaction pattern") +}); + +fn clean_text(text: &str, limit: usize) -> String { + let text: String = text.chars().filter(|c| !c.is_control() || matches!(c, '\n' | '\r' | '\t')).collect(); + let text = text.trim(); + let folded: String = text + .chars() + .map(|c| match c { + '\u{3000}' => ' ', + '\u{ff01}'..='\u{ff5e}' => char::from_u32(u32::from(c) - 0xfee0).unwrap_or(c), + _ => c, + }) + .collect(); + let scan = percent_decode_str(&folded).decode_utf8_lossy(); + if SENSITIVE.is_match(&scan) || scan.len() > 12_288 { + return "[敏感信息已移除]".into(); + } + text.chars().take(limit).collect() +} + +fn diagnostic(value: &Value, depth: usize) -> Option { + match value { + Value::String(text) => Some(json!(clean_text(text, 1000))), + Value::Bool(_) | Value::Number(_) => Some(value.clone()), + Value::Array(values) if depth > 0 => Some(Value::Array( + values + .iter() + .take(12) + .filter(|value| value.is_string() || value.is_object() || value.is_array()) + .filter_map(|value| diagnostic(value, depth - 1)) + .collect(), + )), + Value::Object(fields) if depth > 0 => Some(Value::Object( + fields + .iter() + .filter(|(key, _)| FIELDS.contains(&key.as_str())) + .filter_map(|(key, value)| diagnostic(value, depth - 1).map(|value| (key.clone(), value))) + .take(16) + .collect(), + )), + _ => None, + } +} + +/// Build the same screened payload for preview and the native HTTP boundary. +pub fn feedback_payload(input: &Value) -> Result { + let id = input["feedbackId"].as_str().ok_or("反馈编号无效")?; + let uuid = uuid::Uuid::parse_str(id).map_err(|_| "反馈编号无效")?; + if uuid.get_version_num() != 4 || uuid.get_variant() != uuid::Variant::RFC4122 || uuid.to_string() != id { + return Err("反馈编号无效".into()); + } + let summary = + input["summary"].as_str().map(str::trim).filter(|text| (1..=MAX_SUMMARY).contains(&text.chars().count())).ok_or("请填写 2000 字以内的问题说明")?; + let summary = clean_text(summary, MAX_SUMMARY); + if summary.is_empty() { + return Err("请填写问题说明".into()); + } + let context = input["context"].as_object().and_then(|_| diagnostic(&input["context"], 4)); + let mut value = json!({"feedbackId":id,"summary":summary,"context":context.unwrap_or_else(|| json!({}))}); + for field in ["projectId", "taskId", "requestId"] { + if let Some(text) = input[field].as_str().map(|text| clean_text(text, 180)).filter(|text| !text.is_empty() && text != "[敏感信息已移除]") { + value[field] = json!(text); + } + } + Ok(value) +} + +#[derive(Default)] +pub(super) struct Feedback { + open: bool, + id: String, + scope: Value, + pub(super) summary: String, + project: Value, + task: Value, + context: Value, + include_project: bool, + include_task: bool, + pending: bool, + submitted: Option, + receipt: bool, + error: String, +} + +impl Feedback { + fn input(&self) -> Value { + let mut context = self.context.clone(); + let mut value = json!({"feedbackId":self.id,"summary":self.summary}); + if self.include_project { + value["projectId"] = self.project["id"].clone(); + context["project"] = self.project.clone(); + } + if self.include_task { + value["taskId"] = self.task["taskId"].clone(); + value["requestId"] = self.task["requestId"].clone(); + context["task"] = self.task.clone(); + } + value["context"] = context; + value + } +} + +impl Workspace { + pub(super) fn open_feedback(&mut self, app: &PhotocraftApp) { + let scope = json!({"accountId":self.account["id"],"origin":self.origin}); + if self.feedback.id.is_empty() || self.feedback.scope != scope || self.feedback.receipt { + let active = app.session.active().filter(|state| self.loaded_draft == Some(state.doc.id.0)); + let project = active + .map(|state| { + json!({ + "id":self.project_context["cloudLink"]["id"].as_str().or(self.project_context["localId"].as_str()), + "name":state.doc.name,"status":self.project_context["status"] + }) + }) + .unwrap_or_default(); + let task_row = active + .and_then(|_| self.pending_image.as_ref().or_else(|| self.creation_pending.as_ref().map(|(_, task)| task))) + .filter(|task| task["taskId"].is_string() || task["requestId"].is_string()); + let task = task_row + .map(|row| json!({"taskId":row["taskId"],"requestId":row["requestId"],"stage":row["stage"],"status":row["status"]})) + .or_else(|| active.and(self.pi_run.as_ref()).map(|run| json!({"taskId":run,"kind":"chat"}))) + .or_else(|| active.and(self.unknown_image_task.as_ref()).map(|id| json!({"taskId":id,"status":"unknown"}))) + .unwrap_or_default(); + let context = json!({"client":"XiaoYi","clientVersion":self.client_update.version["version"], + "os":std::env::consts::OS,"arch":std::env::consts::ARCH,"online":self.library_status == "connected", + "diagnostics":{"status":self.library_status,"code":self.library_http_status}, + "capturedAt":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok().map(|time| time.as_secs())}); + self.feedback = Feedback { id: uuid::Uuid::new_v4().to_string(), scope, project, task, context, ..Default::default() }; + } + self.feedback.open = true; + } + + pub(super) fn feedback_received(&mut self, result: Result) { + let Ok(value) = result else { return }; + if value["accountId"] != self.account["id"] || value["origin"] != self.origin || value["readId"] != self.feedback.id || !self.feedback.pending { + return; + } + self.feedback.pending = false; + self.feedback.receipt = value["feedback"]["feedbackId"] == self.feedback.id; + self.feedback.error = value["error"].as_str().unwrap_or("").into(); + } + + pub(super) fn feedback_dialog(&mut self, ctx: &Context, open_url: Option<&crate::services::OpenUrlFn>) { + if !self.feedback.id.is_empty() && (self.feedback.scope["accountId"] != self.account["id"] || self.feedback.scope["origin"] != self.origin) { + self.feedback = Feedback::default(); + } + if !self.feedback.open { + return; + } + let signed_in = self.account["id"].is_string() && !self.library_blocked(); + let offline = self.library_status == "unavailable"; + let feedback = &mut self.feedback; + let id = Id::unique("xiaoyi-feedback-modal"); + let visual = stitch_ui::overlay_transition(ctx, id.with("transition"), true, true); + let mut close = false; + let response = stitch_ui::modal(ctx, id, visual, true, |ui| { + ui.set_width(460.0_f32.min((ctx.content_rect().width() - 72.0).max(180.0))); + close = stitch_ui::dialog_heading(ui, "问题反馈"); + ui.add_space(8.0); + if feedback.receipt { + ui.label(RichText::new("反馈已收到").strong()); + ui.label(format!("反馈编号 {}", feedback.id)); + ui.label("在浏览器登录同一素材库账号即可查看详情。"); + if stitch_ui::action_button(ui, "查看反馈", stitch_ui::ButtonRole::Primary, true).clicked() + && let Some(origin) = feedback.scope["origin"].as_str() + { + let url = format!("{origin}/feedback/{}", feedback.id); + if let Some(open) = open_url { + if open(&url).is_err() { + feedback.error = "无法打开浏览器,可凭反馈编号查询。".into(); + } + } else { + ctx.open_url(egui::OpenUrl::new_tab(url)); + } + } + if !feedback.error.is_empty() { + stitch_ui::status_label(ui, &feedback.error, stitch_ui::StatusTone::Error); + } + return; + } + let t = crate::theme::Tokens::get(ctx).agent(); + ui.add_enabled_ui(feedback.submitted.is_none(), |ui| { + let description = ui.label("问题说明"); + let editor = stitch_ui::text_input(&mut feedback.summary, "描述你遇到的问题和操作步骤", true) + .desired_rows(5) + .desired_width(f32::INFINITY) + .char_limit(MAX_SUMMARY); + egui::ScrollArea::vertical().id_salt("feedback-summary").max_height(136.0).show(ui, |ui| ui.add(editor).labelled_by(description.id)); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(RichText::new(format!("{} / {MAX_SUMMARY}", feedback.summary.chars().count())).color(t.text_dim)); + }); + }); + if feedback.project["name"].is_string() { + ui.checkbox(&mut feedback.include_project, "关联当前项目"); + } + if feedback.task["taskId"].is_string() || feedback.task["requestId"].is_string() { + ui.checkbox(&mut feedback.include_task, "关联当前任务"); + } + }); + ui.collapsing("查看脱敏诊断", |ui| { + let input = feedback.input(); + let snapshot = diagnostic(&input["context"], 4).unwrap_or_else(|| json!({})); + egui::ScrollArea::vertical().max_height(122.0).show(ui, |ui| { + ui.add(egui::Label::new(serde_json::to_string_pretty(&snapshot).unwrap_or_default()).wrap().selectable(true)); + }); + }); + if !signed_in { + stitch_ui::status_label(ui, "登录素材库后可以提交反馈。", stitch_ui::StatusTone::Neutral); + } else if !feedback.error.is_empty() { + stitch_ui::status_label(ui, &feedback.error, stitch_ui::StatusTone::Error); + } else if offline { + stitch_ui::status_label(ui, "素材库暂时离线,联网后可提交。", stitch_ui::StatusTone::Warning); + } + let enabled = signed_in && !feedback.pending && !feedback.summary.trim().is_empty(); + let label = if feedback.pending { + "提交中…" + } else if !feedback.error.is_empty() { + "重试" + } else { + "提交反馈" + }; + if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Primary, enabled).clicked() { + let payload = feedback.submitted.clone().map_or_else(|| feedback_payload(&feedback.input()), Ok); + match payload { + Ok(payload) => { + feedback.pending = self + .tx + .send(Request::Action( + "desktop-feedback".into(), + json!({ + "payload":&payload,"accountId":feedback.scope["accountId"],"origin":feedback.scope["origin"],"readId":feedback.id + }), + )) + .is_ok(); + if feedback.pending { + feedback.submitted = Some(payload); + feedback.error.clear(); + } else { + feedback.error = "本机服务已停止,请重启后提交。".into(); + } + } + Err(error) => feedback.error = error, + } + } + }); + if close || response.is_some_and(|response| response.should_close()) { + feedback.open = false; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn feedback_payload_screens_summary_and_nested_diagnostics() { + let mut input = json!({"feedbackId":uuid::Uuid::new_v4().to_string(),"summary":" 图片加载失败 ", + "context":{"events":vec![json!({"message":"data%3Aimage/png;base64,abc","image":[1,2,3], + "error":"https://me:password@private","detail":"hidden","code":503});13], + "project":{"name":"Token: abc"},"client":"XiaoYi"}}); + let payload = feedback_payload(&input).unwrap(); + assert_eq!(payload["summary"], "图片加载失败"); + assert_eq!(payload["context"]["events"].as_array().unwrap().len(), 12); + assert_eq!(payload["context"]["events"][0], json!({"message":"[敏感信息已移除]","error":"[敏感信息已移除]","code":503})); + assert_eq!(payload["context"]["project"]["name"], "[敏感信息已移除]"); + input["summary"] = json!("图".repeat(2001)); + assert!(feedback_payload(&input).is_err()); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/onboarding.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/onboarding.rs new file mode 100644 index 00000000..387c7bdf --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/onboarding.rs @@ -0,0 +1,231 @@ +use super::{Tokens, Workspace, stitch_ui}; +use crate::theme::{AGENT_SEMANTIC, agent_scale::{Type, control}}; +use egui::{Context, Id, RichText, Ui}; + +#[derive(Default, Debug, PartialEq, Eq)] +pub(super) enum State { + #[default] + WaitingForRestore, + Open { focus_key: bool }, + Dismissed, +} + +impl State { + pub(super) fn is_open(&self) -> bool { + matches!(self, Self::Open { .. }) + } +} + +fn preference_id() -> Id { + Id::unique("xiaoyi-first-run-dismissed") +} + +impl Workspace { + fn onboarding_signed_in(&self) -> bool { + !self.account.is_null() && self.library_status != "sign_in_required" + } + + pub(super) fn begin_onboarding(&mut self, ctx: &Context) { + if self.onboarding != State::WaitingForRestore { + return; + } + if ctx.data_mut(|data| data.get_persisted::(preference_id())).unwrap_or(false) + || self.onboarding_signed_in() && self.key_saved + { + self.dismiss_onboarding(ctx); + } else { + self.onboarding = State::Open { focus_key: true }; + } + } + + fn dismiss_onboarding(&mut self, ctx: &Context) { + self.onboarding = State::Dismissed; + self.api_key.clear(); + ctx.data_mut(|data| data.insert_persisted(preference_id(), true)); + } + + pub(super) fn onboarding_dialog(&mut self, ui: &mut Ui) { + let ctx = ui.ctx(); + let signed_in = self.onboarding_signed_in(); + let key_saved = self.key_saved; + let visual = stitch_ui::OverlayVisual { render: true, interactive: true, opacity: 1.0 }; + let screen = ctx.content_rect(); + let body_height = (screen.height() - 64.0).max(1.0); + stitch_ui::modal(ctx, Id::unique("xiaoyi-first-run"), visual, self.reduce_motion, |ui| { + ui.set_width(424.0_f32.min((screen.width() - 64.0).max(1.0))); + egui::ScrollArea::vertical().max_height(body_height).min_scrolled_height(body_height).show(ui, |ui| { + let t = Tokens::get(ui.ctx()).agent(); + ui.spacing_mut().item_spacing.y = 8.0; + ui.heading(RichText::new("小壹首次设置").font(Type::TitleLg.semibold()).color(t.text)); + ui.add_space(8.0); + step_heading(ui, "1. 登录素材库", signed_in, "已登录"); + ui.add(egui::Label::new(RichText::new("登录后自动连接企业知识库,成品可一键入库。").color(t.text_dim)).wrap()); + if !signed_in { + if self.busy.as_deref() == Some("login") { + stitch_ui::status_label(ui, "等待浏览器授权…", stitch_ui::StatusTone::Neutral); + } else if stitch_ui::action_button(ui, "在浏览器中登录", stitch_ui::ButtonRole::Primary, self.library_login_enabled()).clicked() { + self.authorize_library(ui.ctx()); + } + let message = if self.account_error.is_empty() { &self.library_message } else { &self.account_error }; + if !message.is_empty() { + stitch_ui::status_label(ui, message, stitch_ui::StatusTone::Warning); + } + } + ui.add_space(6.0); + stitch_ui::divider(ui); + ui.add_space(6.0); + step_heading(ui, "2. 配置模型 API Key", key_saved, "已保存"); + ui.add(egui::Label::new(RichText::new("配置后可使用所选模型作图和生成详情。").color(t.text_dim)).wrap()); + if !key_saved && signed_in { + self.onboarding_model_options(ui); + let focus = if self.busy.is_none() && let State::Open { focus_key } = &mut self.onboarding { + std::mem::take(focus_key) + } else { + false + }; + self.model_key_editor(ui, true, focus); + if self.busy.as_deref() == Some("configure") { + stitch_ui::status_label(ui, "正在校验 Key…", stitch_ui::StatusTone::Neutral); + } + } else if !key_saved { + stitch_ui::status_label(ui, "登录后可配置", stitch_ui::StatusTone::Neutral); + } + if !self.error.is_empty() { + stitch_ui::status_label(ui, &self.error, stitch_ui::StatusTone::Error); + } + ui.add_space(8.0); + let complete = signed_in && key_saved; + let footer = egui::vec2(ui.available_width(), control::DEFAULT); + ui.allocate_ui_with_layout(footer, egui::Layout::right_to_left(egui::Align::Center), |ui| { + let (label, role) = if complete { + ("开始使用小壹", stitch_ui::ButtonRole::Primary) + } else { + ("稍后在设置里配置", stitch_ui::ButtonRole::Quiet) + }; + let enabled = self.busy.as_deref() != Some("configure"); + if stitch_ui::action_button(ui, label, role, enabled).clicked() { + self.dismiss_onboarding(ui.ctx()); + } + }); + }); + }); + } +} + +fn step_heading(ui: &mut Ui, label: &str, done: bool, status: &str) { + ui.horizontal_wrapped(|ui| { + let t = Tokens::get(ui.ctx()).agent(); + ui.label(RichText::new(label).font(Type::Subheading.semibold()).color(t.text)); + if done { + ui.label(RichText::new(status).font(Type::Meta.font_id()).color(AGENT_SEMANTIC.success)); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::PhotocraftApp; + use super::super::Request; + use egui_kittest::{Harness, kittest::Queryable}; + use serde_json::{Value, json}; + use std::sync::mpsc; + + fn setup_context(ctx: &Context) { + crate::cjk_fonts::install_system_provider_for_tests(ctx); + PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); + } + + #[test] + fn first_restore_opens_guide_only_when_setup_is_incomplete() { + for (account, key_saved, expected) in [ + (Value::Null, false, true), + (json!({"id":"test"}), false, true), + (Value::Null, true, true), + (json!({"id":"test"}), true, false), + ] { + let ctx = Context::default(); + let mut workspace = Workspace::new(mpsc::channel().0, mpsc::channel().1); + workspace.account = account; + workspace.key_saved = key_saved; + assert!(!workspace.onboarding.is_open()); + workspace.begin_onboarding(&ctx); + assert_eq!(workspace.onboarding.is_open(), expected); + } + } + + #[test] + fn later_dismisses_the_guide_and_new_workspace_reads_the_preference() { + let (tx, requests) = mpsc::channel(); + let mut workspace = Workspace::new(tx, mpsc::channel().1); + let _ = requests.try_recv(); + workspace.busy = None; + workspace.api_key = "unfinished-draft".into(); + let mut harness = Harness::builder().with_size(egui::vec2(760.0, 560.0)) + .with_context_setup(setup_context) + .build_ui_state(|ui, workspace: &mut Workspace| { + workspace.begin_onboarding(ui.ctx()); + if workspace.onboarding.is_open() { workspace.onboarding_dialog(ui); } + }, workspace); + harness.run_steps(3); + harness.get_by_label("在浏览器中登录").click(); + harness.run_steps(2); + assert!(matches!(requests.try_recv(), Ok(Request::Action(method, _)) if method == "login")); + harness.get_by_label("稍后在设置里配置").click(); + harness.run_steps(2); + assert!(!harness.state().onboarding.is_open()); + assert!(harness.state().api_key.is_empty()); + let mut reopened = Workspace::new(mpsc::channel().0, mpsc::channel().1); + reopened.begin_onboarding(&harness.ctx); + assert!(!reopened.onboarding.is_open()); + } + + #[test] + fn login_focuses_the_shared_key_editor_and_saved_key_finishes_the_guide() { + let evidence = std::env::var_os("PHOTOCRAFT_ONBOARDING_QA_OUT"); + for width in [760.0, 1180.0] { + let (tx, requests) = mpsc::channel(); + let mut workspace = Workspace::new(tx, mpsc::channel().1); + let _ = requests.try_recv(); + workspace.busy = None; + workspace.reduce_motion = true; + let builder = Harness::builder().with_size(egui::vec2(width, 620.0)) + .with_context_setup(setup_context); + let builder = if evidence.is_some() { builder.wgpu() } else { builder }; + let mut harness = builder.build_ui_state(|ui, workspace: &mut Workspace| { + workspace.begin_onboarding(ui.ctx()); + if workspace.onboarding.is_open() { workspace.onboarding_dialog(ui); } + }, workspace); + harness.run_steps(3); + if let Some(directory) = &evidence { + harness.render().unwrap().save(std::path::Path::new(directory).join(format!("onboarding-login-{width}.png"))).unwrap(); + } + let workspace = harness.state_mut(); + workspace.account = json!({"id":"test"}); + workspace.models = vec![json!({"id":"test-model","key":"test-model"})]; + workspace.model = "test-model".into(); + harness.run_steps(3); + assert!(harness.ctx.memory(|memory| memory.focused().is_some())); + let key = harness.get_by_label("模型 API Key").rect(); + assert!(key.width() >= 360.0 && key.right() < width); + if let Some(directory) = &evidence { + harness.render().unwrap().save(std::path::Path::new(directory).join(format!("onboarding-key-{width}.png"))).unwrap(); + } + harness.state_mut().api_key = "offline-test-key".into(); + harness.run_steps(1); + harness.get_by_label("保存连接").click(); + harness.run_steps(2); + assert!(matches!(requests.try_recv(), Ok(Request::Action(method, value)) + if method == "configure" && value["key"] == "offline-test-key" && value["model"] == "test-model")); + let workspace = harness.state_mut(); + workspace.busy = None; + workspace.key_saved = true; + harness.run_steps(3); + harness.get_by_label("已登录"); + harness.get_by_label("已保存"); + harness.get_by_label("开始使用小壹").click(); + harness.run_steps(2); + assert!(!harness.state().onboarding.is_open()); + } + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs index 6c2b8963..a639de89 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs @@ -1,7 +1,7 @@ //! One native home for account projects and local drafts. Covers are requested only for //! visible rows; destructive actions always name their scope and require confirmation. use super::{json, Value, Tokens, Workspace, PhotocraftApp, Ui, stitch_ui, agent_panel, CenterView, RichText, agent_motion, Duration, Request}; -use crate::{icons, widgets}; +use crate::{icons, theme::agent_scale::Type, widgets}; use egui::{Align, Frame, Layout, Sense, Stroke, pos2, vec2}; fn key(item: &Value) -> String { @@ -16,14 +16,6 @@ fn cloud_present(item: &Value) -> bool { matches!(item["source"].as_str(), Some("web" | "desktop")) || item["cloudPresent"] == true } -fn sync_choice(item: &Value) -> (&'static str, Option<&'static str>) { - if item["source"] != "native" { return ("同步", Some("pull")); } - if !cloud_present(item) { return ("同步到云端", Some("sync")); } - if item["syncDirty"] != false || item["syncedRevision"] != item["revision"] { return ("同步", Some("sync")); } - if item["cloudUpdateAvailable"] == true { return ("同步", Some("pull")); } - ("已同步", None) -} - #[derive(Clone)] struct DeleteDialogContent { item: Value, @@ -48,7 +40,7 @@ fn cloud_update_block_reason(item: &Value, open: bool) -> Option<&'static str> { } else if item["localPending"] == true || item["cloudUpdateBlocked"] == "pending_request" || item["deleteBlocked"] == true { Some("原任务尚待处理,本机工程已保留") } else if item["syncDirty"] != false || item["cloudUpdateBlocked"] == "unsynced_draft" { - Some("本机还有未同步修改,暂不替换工程") + Some("本机工程有修改,暂不替换") } else if item["cloudUpdateAvailable"] != true { Some("请刷新项目后核对云端版本") } else { @@ -77,9 +69,24 @@ fn project_status(item: &Value) -> Option { } } +pub(super) fn project_title(item: &Value) -> &str { + let name = item["name"].as_str().unwrap_or("未命名项目"); + if let Some((stem, extension)) = name.rsplit_once('.') + && extension.eq_ignore_ascii_case("pcraft") && !stem.is_empty() + { + return stem; + } + name +} + +pub(super) fn project_matches_query(item: &Value, query: &str) -> bool { + [item["name"].as_str(), item["brandName"].as_str(), item["productModel"].as_str()] + .into_iter().flatten().any(|value| value.to_lowercase().contains(query)) +} + fn matches_project(item: &Value, filter: ProjectFilter, query: &str) -> bool { let status_matches = filter == ProjectFilter::All || project_status(item) == Some(filter); - status_matches && (query.is_empty() || item["name"].as_str().unwrap_or("").to_lowercase().contains(query)) + status_matches && (query.is_empty() || project_matches_query(item, query)) } fn badge(item: &Value, t: &Tokens) -> (&'static str, egui::Color32, egui::Color32) { @@ -97,32 +104,6 @@ impl Workspace { self.project_operation["phase"] == "running" && self.project_operation["accountId"] == self.account["id"] && self.project_operation["origin"] == self.origin } - fn project_sync_item(&self, app: &PhotocraftApp, item: &Value) -> Value { - let mut item = item.clone(); - if item["source"] == "native" { - let identity = self.local_identity(item["id"].as_str().unwrap_or("")); - if let Some(state) = app.session.documents().iter().find(|state| self.open_projects.get(&state.doc.id.0) == Some(&identity)) { - item["revision"] = json!(state.revision); - if self.loaded_draft == Some(state.doc.id.0) && self.sync_dirty { item["syncDirty"] = json!(true); } - } - } - item - } - - pub(super) fn current_sync_item(&self, app: &PhotocraftApp) -> Option { - let state = app.session.active()?; - let identity = self.open_projects.get(&state.doc.id.0)?; - let local = identity.rsplit('|').next()?; - let item = self.projects.iter().find(|item| item["source"] == "native" && item["id"] == local).cloned().unwrap_or_else(|| - json!({"source":"native","id":local,"revision":state.revision,"cloudPresent":self.project_context["cloudLink"]["id"].is_string(),"syncedRevision":self.project_context["syncedRevision"],"syncDirty":self.sync_dirty})); - Some(self.project_sync_item(app, &item)) - } - - pub(super) fn request_current_sync(&mut self, app: &PhotocraftApp, chat: bool) -> Result { - let item = self.current_sync_item(app).ok_or("请先保存并打开项目")?; - self.request_project_sync_with_policy(app, &item, chat) - } - fn project_action_block(&self, app: &PhotocraftApp, item: &Value) -> Option<&'static str> { if self.project_operation_pending() { return Some("项目操作正在进行,请稍候"); } let identity = self.local_identity(item["id"].as_str().unwrap_or("")); @@ -134,11 +115,11 @@ impl Workspace { None } - fn begin_project_operation(&mut self, kind: &str, item: &Value, mut input: Value) -> Result { + fn begin_project_delete(&mut self, item: &Value, mut input: Value) -> Result { if self.project_operation_pending() { return Err("项目操作正在进行,请稍候".into()); } self.project_operation_serial = self.project_operation_serial.wrapping_add(1); - self.project_operation = json!({"id":self.project_operation_serial,"kind":kind,"projectId":item["id"],"source":item["source"],"accountId":self.account["id"],"origin":self.origin,"phase":"running", - "message":match kind {"delete"=>"正在删除项目…","pull"=>"正在同步到本机…",_=>"正在同步到云端…"}}); + self.project_operation = json!({"id":self.project_operation_serial,"kind":"delete","projectId":item["id"],"source":item["source"],"accountId":self.account["id"],"origin":self.origin,"phase":"running", + "message":"正在删除项目…"}); input["operation"] = self.project_operation.clone(); if self.tx.send(Request::Action("project-operation".into(), input)).is_err() { self.project_operation["phase"] = json!("failed"); @@ -148,68 +129,22 @@ impl Workspace { Ok(json!({"submitted":true})) } - pub(super) fn request_project_sync(&mut self, app: &PhotocraftApp, item: &Value) -> Result { - self.request_project_sync_with_policy(app, item, false) - } - - fn request_project_sync_with_policy(&mut self, app: &PhotocraftApp, item: &Value, chat: bool) -> Result { - if let Some(reason) = self.project_action_block(app, item) { return Err(reason.into()); } - let item = self.project_sync_item(app, item); - let (_, action) = sync_choice(&item); - let Some(kind) = action else { return Ok(json!({"synced":true,"submitted":false})); }; - let mut input = item.clone(); - input["accountId"] = self.account["id"].clone(); - input["origin"] = json!(self.origin); - if kind == "pull" && item["source"] == "native" { - let open = self.open_project_index(app, item["id"].as_str().unwrap_or("")).is_some(); - if let Some(reason) = cloud_update_block_reason(&item, open) { return Err(reason.into()); } - input = item["cloudUpdateRef"].clone(); - } else if kind == "sync" { - input["localId"] = item["id"].clone(); - input["syncChatHistory"] = json!(chat); - input["status"] = json!("draft"); - let identity = self.local_identity(item["id"].as_str().ok_or("项目编号无效")?); - if let Some(state) = app.session.documents().iter().find(|state| self.open_projects.get(&state.doc.id.0) == Some(&identity)) { - let current = self.loaded_draft == Some(state.doc.id.0); - let meta = if current { - self.sync_request_meta = self.sync_signature(); - json!({"composer":self.composer,"messages":self.messages,"project":self.project_context,"syncDirty":self.sync_dirty,"creationDraft":self.creation_draft()}) - } else { json!({}) }; - self.tx.send(Request::Save(state.doc.clone(), state.revision, meta)).map_err(|_| "本机服务已停止,未同步")?; - if current { self.saving = Some((state.doc.id.0, state.revision)); } - input["doc"] = json!(state.doc.id.0); - input["revision"] = json!(state.revision); - } else { input.as_object_mut().ok_or("项目同步参数无效")?.remove("doc"); } - } - self.begin_project_operation(kind, &item, input) - } - pub(super) fn project_operation_received(&mut self, app: &mut PhotocraftApp, result: Result) { let Ok(reply) = result else { return }; let operation = &reply["operation"]; if !self.project_operation_pending() || operation["id"] != self.project_operation["id"] || operation["accountId"] != self.account["id"] || operation["origin"] != self.origin { return; } - let kind = operation["kind"].as_str().unwrap_or(""); if let Some(error) = reply["error"].as_str() { self.project_operation["phase"] = json!("failed"); self.project_operation["message"] = json!(error); - if kind == "delete" { self.delete_error = error.into(); } + self.delete_error = error.into(); return; } let value = &reply["value"]; self.project_read = None; self.project_refresh_requested = true; - if kind == "delete" { self.project_deleted(app, value); } - else { - if let Some(items) = value["projects"].as_array() { self.merge_project_receipt(app, items); } - if kind == "sync" { super::creation::sync_received(self, app, value); } - } + self.project_deleted(app, value); self.project_operation["phase"] = json!("done"); - self.project_operation["message"] = json!(match kind { - "delete" => "项目已删除", - "pull" => "已同步到本机", - _ if value["syncDirty"] == true => "云端已保存该版本,当前仍有新修改", - _ => "已同步到云端", - }); + self.project_operation["message"] = json!("项目已删除"); } pub(super) fn local_identity(&self, local: &str) -> String { @@ -502,26 +437,28 @@ impl Workspace { let k = key(item); let native = item["source"] == "native"; let cloud = cloud_present(item); - let preview_height = width * 1.6; - let (shell, _) = ui.allocate_exact_size(vec2(width, preview_height + 62.0), Sense::hover()); + let has_screen = native || item["screenCount"].as_u64().unwrap_or(0) > 0; + let unavailable = !self.project_covers.contains_key(&k) && (!has_screen || self.cover_errors.contains_key(&k)); + let preview_height = width * if unavailable { 0.85 } else { 1.6 }; + let (shell, _) = ui.allocate_exact_size(vec2(width, preview_height + 82.0), Sense::hover()); let rect = egui::Rect::from_min_size(shell.min, vec2(width, preview_height)); let response = ui.interact(shell, ui.scope_id().with("project-open"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); let enabled = self.busy.is_none(); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button,enabled,"打开项目")); let hover = stitch_ui::morph_value(ui.ctx(),ui.scope_id().with("project-hover"),enabled && (response.hovered() || response.has_focus()),self.reduce_motion); let stroke_width = if cloud { 2.0 / ui.ctx().pixels_per_point() } else { 1.0 / ui.ctx().pixels_per_point() }; - stitch_ui::material(ui,ui.scope_id().with("project-material"),shell,16.0,hover*0.58,background); + stitch_ui::material_over(ui, ui.scope_id().with("project-material"), shell, 16.0, hover * 0.35, background, t.card, t.card_border); if let Some(texture) = self.project_covers.get(&k) { let size = texture.size_vec2(); let factor = (rect.width()/size.x).max(rect.height()/size.y); let uv = egui::Rect::from_center_size(pos2(0.5,0.5),rect.size()/(size*factor)); egui::Image::new(texture).uv(uv).corner_radius(egui::CornerRadius {nw:16,ne:16,sw:0,se:0}).paint_at(ui,rect); } else { - let has_screen = native || item["screenCount"].as_u64().unwrap_or(0) > 0; + ui.painter().rect_filled(rect, egui::CornerRadius { nw: 16, ne: 16, sw: 0, se: 0 }, t.field); let error = self.cover_errors.get(&k); let empty = error.is_some_and(|s|s=="尚无画布内容" || s=="尚未生成页面"); let text = if self.cover_loading.contains(&k) {"加载封面…"} else if empty {"待生成"} else if error.is_some() {"封面暂不可用"} else if has_screen {"首屏预览"} else {"待生成"}; - ui.painter().text(rect.center(),egui::Align2::CENTER_CENTER,text,egui::FontId::proportional(12.0),t.text_dim); + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, text, Type::Meta.font_id(), t.text_dim); if let Some(error) = error { response.clone().on_hover_text(error); } if has_screen && error.is_none() && !self.cover_loading.contains(&k) && self.cover_loading.len() < 2 && ui.is_rect_visible(rect) { self.cover_loading.insert(k); @@ -555,20 +492,8 @@ impl Workspace { let mut delete_rect = None; let blocked = delete_block_reason(item).or_else(|| self.project_action_block(app, item)); let delete_enabled = blocked.is_none(); - let sync_item = self.project_sync_item(app, item); - let (sync_label, sync_kind) = sync_choice(&sync_item); - let open_local = self.open_project_index(app, item["id"].as_str().unwrap_or("")).is_some(); - let sync_blocked = self.project_action_block(app, item).or_else(|| - if sync_kind == Some("pull") && native { cloud_update_block_reason(item, open_local) } else { None }); - let sync_enabled = sync_kind.is_some() && sync_blocked.is_none(); - let mut syncing = false; - let mut sync_rect = None; stitch_ui::select_popup(ui,&menu,176.0,self.reduce_motion,|ui| { menu_open = stitch_ui::menu_item(ui,"打开项目",enabled).clicked(); - let sync = stitch_ui::menu_item(ui, sync_label, sync_enabled); - sync_rect = Some(sync.rect); - syncing = sync.clicked(); - if let Some(reason) = sync_blocked { sync.on_disabled_hover_text(reason); } stitch_ui::divider(ui); let delete = stitch_ui::menu_item(ui,"删除项目",delete_enabled); delete_rect = Some(delete.rect); @@ -578,32 +503,36 @@ impl Workspace { ui.add(egui::Label::new(RichText::new(reason).size(11.5).color(t.text_dim)).wrap()); } }); - if syncing { - egui::Popup::close_id(ui.ctx(),menu.id.with("popup")); - if let Err(error) = self.request_project_sync(app, item) { self.project_list_error = error; } - } if deleting { egui::Popup::close_id(ui.ctx(),menu.id.with("popup")); self.delete_error.clear();self.delete_confirm=Some(item.clone()); } - let name = item["name"].as_str().unwrap_or("未命名项目"); + let name = project_title(item); let name_rect = egui::Rect::from_min_size(pos2(rect.left()+12.0,rect.bottom()+10.0),vec2(width-24.0,22.0)); let mut label_ui = ui.new_child(egui::UiBuilder::new().id_salt("project-title").max_rect(name_rect).layout(Layout::left_to_right(Align::Center))); widgets::elided_label(&mut label_ui,name,name_rect.width()).on_hover_text(name); - let status = if item["cloudDeleted"]==true {if item["retainedReason"]=="pending_request" {"云端已删除 · 任务待核查"} else {"云端已删除 · 本机保留"}} else if native && cloud {if item["syncDirty"]==true {"本机 · 尚有未同步修改"} else {"本机 · 云端"}} else if native {"仅本机 · 未同步"} else {"云端"}; - let status_rect = egui::Rect::from_min_size(pos2(rect.left()+12.0,rect.bottom()+36.0),vec2(width-24.0,18.0)); - let status_galley = ui.painter().layout_no_wrap(status.to_owned(),egui::FontId::proportional(11.5),t.text_dim); - ui.painter_at(status_rect).galley(status_rect.min,status_galley,t.text_dim); + let brand = item["brandName"].as_str().filter(|value| !value.is_empty()).unwrap_or("品牌未填写"); + let model = item["productModel"].as_str().filter(|value| !value.is_empty()).unwrap_or("型号未填写"); + let status = if item["retainedReason"] == "pending_request" { "任务待核查" } + else if native { "本机" } else { "云端" }; + let updated = item["updatedLabel"].as_str().or_else(|| item["updatedAt"].as_str()?.get(..10)) + .unwrap_or("更新时间未知"); + for (offset, text) in [(36.0, format!("{brand} · {model}")), (56.0, format!("{updated} · {status}"))] { + let line = egui::Rect::from_min_size(pos2(rect.left() + 12.0, rect.bottom() + offset), vec2(width - 24.0, 18.0)); + let mut row = ui.new_child(egui::UiBuilder::new().id_salt(("project-meta", offset as u32)) + .max_rect(line).layout(Layout::left_to_right(Align::Center))); + row.add(egui::Label::new(RichText::new(&text).size(Type::Meta.size()).color(t.text_dim)).truncate()).on_hover_text(text); + } let on_menu = ui.input(|i|i.pointer.interact_pos().is_some_and(|p|menu_rect.contains(p))); let opening = menu_open || (response.clicked() && !on_menu && !egui::Popup::is_any_open(ui.ctx())); if update.as_ref().is_some_and(|button|button.clicked()) { if let Err(error)=self.request_cloud_update(app,item) {self.project_list_error=error;} - } else if opening && enabled && !deleting && !syncing { + } else if opening && enabled && !deleting { egui::Popup::close_id(ui.ctx(),menu.id.with("popup")); self.handover();if let Err(error)=self.request_project_open(app,item.clone()) {self.project_list_error=error;} } if let Some(tiles)=self.project_geometry["tiles"].as_array_mut() { - tiles.push(json!({"id":item["id"],"source":item["source"],"open":agent_panel::rect_value(rect),"card":agent_panel::rect_value(shell),"hover":hover,"menu":agent_panel::rect_value(menu.rect),"sync":sync_rect.map(agent_panel::rect_value),"syncLabel":sync_label,"syncEnabled":sync_enabled,"syncBlockedReason":sync_blocked,"delete":delete_rect.map(agent_panel::rect_value),"deleteEnabled":delete_enabled,"deleteBlockedReason":blocked,"hasCover":self.project_covers.contains_key(&key(item)),"cloud":cloud,"borderPhysicalPixels":if cloud {2.0} else {1.0},"state":state,"badge":agent_panel::rect_value(badge_rect),"cloudUpdate":update.as_ref().map(|b|agent_panel::rect_value(b.rect)),"cloudUpdateEnabled":update.as_ref().is_some_and(|b|b.enabled())})); + tiles.push(json!({"id":item["id"],"source":item["source"],"open":agent_panel::rect_value(rect),"card":agent_panel::rect_value(shell),"hover":hover,"menu":agent_panel::rect_value(menu.rect),"delete":delete_rect.map(agent_panel::rect_value),"deleteEnabled":delete_enabled,"deleteBlockedReason":blocked,"hasCover":self.project_covers.contains_key(&key(item)),"cloud":cloud,"borderPhysicalPixels":if cloud {2.0} else {1.0},"state":state,"badge":agent_panel::rect_value(badge_rect),"cloudUpdate":update.as_ref().map(|b|agent_panel::rect_value(b.rect)),"cloudUpdateEnabled":update.as_ref().is_some_and(|b|b.enabled())})); } } @@ -711,7 +640,7 @@ impl Workspace { .collect::>() ); self.delete_confirm = Some(request.clone()); - if let Err(error) = self.begin_project_operation("delete", &item, request) { self.delete_error = error; } + if let Err(error) = self.begin_project_delete(&item, request) { self.delete_error = error; } } }); }); @@ -728,79 +657,6 @@ mod tests { use crate::jiansun::Event; use super::*; - #[test] - fn card_sync_uses_presence_and_saved_content_to_choose_upload_download_or_disabled() { - assert_eq!(sync_choice(&json!({"source":"web","id":"remote"})), ("同步", Some("pull"))); - assert_eq!(sync_choice(&json!({"source":"native","id":"local","revision":2})), ("同步到云端", Some("sync"))); - let mut local = json!({"source":"native","id":"local","cloudPresent":true,"revision":2,"syncedRevision":2,"syncDirty":false}); - assert_eq!(sync_choice(&local), ("已同步", None)); - local["revision"] = json!(3); - assert_eq!(sync_choice(&local), ("同步", Some("sync"))); - local["syncedRevision"] = json!(3); - local["syncDirty"] = json!(true); - assert_eq!(sync_choice(&local), ("同步", Some("sync"))); - local["syncDirty"] = json!(false); - local["cloudUpdateAvailable"] = json!(true); - assert_eq!(sync_choice(&local), ("同步", Some("pull"))); - } - - #[test] - fn card_sync_targets_the_chosen_project_without_opening_or_stopping_another_agent() { - let (tx, requests) = mpsc::channel(); - let (_events, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - let _ = requests.try_iter().collect::>(); - w.account = json!({"id":"owner"}); - w.busy = Some("agent".into()); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"name":"当前项目","width":1440,"height":400})).unwrap(); - let active = app.session.active().unwrap().doc.id.0; - w.loaded_draft = Some(active); - w.open_projects.insert(active, w.local_identity("current")); - w.project_context = json!({"localId":"current"}); - let item = json!({"source":"native","id":"00000000-0000-4000-8000-000000000001","revision":7,"syncDirty":true}); - assert_eq!(w.request_project_sync(&app, &item).unwrap()["submitted"], true); - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected the project operation"); }; - assert_eq!(method, "project-operation"); - assert_eq!(input["localId"], item["id"]); - assert_eq!(input["operation"]["kind"], "sync"); - assert_eq!(input["revision"], 7); - assert!(input["doc"].is_null()); - assert_eq!(w.busy.as_deref(), Some("agent")); - assert_eq!(w.project_context["localId"], "current"); - assert_eq!(app.session.active().unwrap().doc.id.0, active); - assert!(requests.try_recv().is_err()); - } - - #[test] - fn unsaved_canvas_edits_reenable_card_sync_and_save_the_exact_document_first() { - let (tx, requests) = mpsc::channel(); - let (_events, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - let _ = requests.try_iter().collect::>(); - w.account = json!({"id":"owner"}); - w.busy = None; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width":1440,"height":400})).unwrap(); - let st = app.session.active().unwrap(); - let id = st.doc.id.0; - let revision = st.revision; - w.loaded_draft = Some(id); - w.sync_dirty = false; - w.open_projects.insert(id, w.local_identity("local")); - let item = json!({"source":"native","id":"local","revision":revision,"syncedRevision":revision,"syncDirty":false,"cloudPresent":true}); - assert_eq!(w.request_project_sync(&app, &item).unwrap()["submitted"], false); - app.session.execute("image.imageSize", json!({"width":1440,"height":800})).unwrap(); - let changed = app.session.active().unwrap().revision; - assert_eq!(w.request_project_sync(&app, &item).unwrap()["submitted"], true); - let Request::Save(doc, saved_revision, _) = requests.try_recv().unwrap() else { panic!("save must precede upload"); }; - assert_eq!(doc.id.0, id); - assert_eq!(saved_revision, changed); - let Request::Action(_, input) = requests.try_recv().unwrap() else { panic!("expected upload"); }; - assert_eq!(input["doc"], id); - assert_eq!(input["revision"], changed); - } - #[test] fn project_operation_errors_are_visible_and_late_other_account_receipts_are_ignored() { let (tx, requests) = mpsc::channel(); @@ -812,7 +668,7 @@ mod tests { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); let item = json!({"source":"desktop","id":"remote","revision":2}); assert!(w.project_action_block(&app, &item).is_none()); - w.begin_project_operation("delete", &item, item.clone()).unwrap(); + w.begin_project_delete(&item, item.clone()).unwrap(); let operation = w.project_operation.clone(); let mut other = operation.clone(); other["accountId"] = json!("another"); @@ -1007,37 +863,32 @@ mod tests { } #[test] fn closing_the_native_tab_reenables_cloud_download_even_when_its_binding_is_retained() { - for via_sync_menu in [false, true] { - let (tx, requests) = mpsc::channel(); - let (_events, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - w.busy = None; - w.account = json!({"id":"a"}); - let _ = requests.try_iter().collect::>(); - let mut item = cloud_update_item(&w.origin); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width":1440,"height":400})).unwrap(); - let doc = app.session.active().unwrap().doc.id.0; - let revision = app.session.active().unwrap().revision; - item["revision"] = json!(revision); - item["syncedRevision"] = json!(revision); - item["cloudUpdateRef"]["localRevision"] = json!(revision); - w.open_projects.insert(doc, w.local_identity(item["id"].as_str().unwrap())); - if via_sync_menu { assert!(w.request_project_sync(&app, &item).is_err()); } - else { assert!(w.request_cloud_update(&mut app, &item).is_err()); } - assert!(requests.try_recv().is_err()); - app.session.close(0).unwrap(); - assert!(w.open_projects.contains_key(&doc)); - if via_sync_menu { assert_eq!(w.request_project_sync(&app, &item).unwrap()["submitted"], true); } - else { w.request_cloud_update(&mut app, &item).unwrap(); } - let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected the existing cloud update path"); }; - assert_eq!(method, if via_sync_menu { "project-operation" } else { "open" }); - assert_eq!(input["id"], item["cloudUpdateRef"]["id"]); - assert_eq!(input["revision"], 4); - assert_eq!(input["localRevision"], revision); - assert_eq!(input["updateExisting"], true); - if via_sync_menu { assert_eq!(input["operation"]["kind"], "pull"); } - } + let (tx, requests) = mpsc::channel(); + let (_events, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + w.busy = None; + w.account = json!({"id":"a"}); + let _ = requests.try_iter().collect::>(); + let mut item = cloud_update_item(&w.origin); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width":1440,"height":400})).unwrap(); + let doc = app.session.active().unwrap().doc.id.0; + let revision = app.session.active().unwrap().revision; + item["revision"] = json!(revision); + item["syncedRevision"] = json!(revision); + item["cloudUpdateRef"]["localRevision"] = json!(revision); + w.open_projects.insert(doc, w.local_identity(item["id"].as_str().unwrap())); + assert!(w.request_cloud_update(&mut app, &item).is_err()); + assert!(requests.try_recv().is_err()); + app.session.close(0).unwrap(); + assert!(w.open_projects.contains_key(&doc)); + w.request_cloud_update(&mut app, &item).unwrap(); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected the existing cloud update path"); }; + assert_eq!(method, "open"); + assert_eq!(input["id"], item["cloudUpdateRef"]["id"]); + assert_eq!(input["revision"], 4); + assert_eq!(input["localRevision"], revision); + assert_eq!(input["updateExisting"], true); } #[test] fn deletion_block_state_is_explicit_and_never_inferred_from_names_or_age() { @@ -1235,7 +1086,7 @@ mod tests { let mut w = Workspace::new(tx, rx); w.busy = None; w.projects = vec![ - json!({"id":"one","source":"web","name":"很长的中文项目名称用于验证首屏预览与删除按钮不会互相挤压","revision":1,"hasDraft":true,"screenCount":0}), + json!({"id":"one","source":"web","name":"很长的中文项目名称用于验证首屏预览与删除按钮不会互相挤压","revision":1,"hasDraft":true,"screenCount":1}), json!({"id":"two","source":"web","name":"第二个项目","revision":1,"hasDraft":true,"screenCount":0}), json!({"id":"three","source":"web","name":"第三个项目","revision":1,"hasDraft":true,"screenCount":0}), ]; @@ -1254,7 +1105,12 @@ mod tests { } for tile in w.project_geometry["tiles"].as_array().unwrap() { let preview = tile["open"].as_array().unwrap(); - assert!(preview[3].as_f64().unwrap() > preview[2].as_f64().unwrap() * 1.5, "preview stays portrait"); + let aspect = preview[3].as_f64().unwrap() / preview[2].as_f64().unwrap(); + if tile["id"] == "one" { + assert!(aspect > 1.5, "leave room for the portrait cover"); + } else { + assert!(aspect < 1.0, "keep coverless project details near the top"); + } for action in ["open", "menu"] { let r = tile[action].as_array().unwrap(); let x = r[0].as_f64().unwrap(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs index 0de230ca..6a319672 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs @@ -104,14 +104,23 @@ pub(super) fn halo_select(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::D halo_select_with_behavior(ui, id, width, selected, reduced, egui::PopupCloseBehavior::CloseOnClick, contents) } -pub(super) fn halo_select_with_behavior(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, width: f32, selected: &str, reduced: bool, close_behavior: egui::PopupCloseBehavior, contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse> { +pub(super) fn halo_select_hint(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, width: f32, selected: Option<&str>, hint: &str, reduced: bool, contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse> { + let label = selected.map_or_else( + || RichText::new(hint).color(Tokens::get(ui.ctx()).agent().text_dim), + RichText::new, + ); + halo_select_with_behavior(ui, id, width, label, reduced, egui::PopupCloseBehavior::CloseOnClick, contents) +} + +pub(super) fn halo_select_with_behavior(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, width: f32, selected: impl Into, reduced: bool, close_behavior: egui::PopupCloseBehavior, contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse> { let t = Tokens::get(ui.ctx()).agent(); let background = super::agent_motion::reserve_background(ui); - let response = ui.push_id(id, |ui| ui.add(egui::Button::new(RichText::new(selected).size(Type::Title.size())) + let selected = selected.into().size(Type::Title.size()); + let response = ui.push_id(id, |ui| ui.add(egui::Button::new(selected.clone()) .right_text(crate::icons::image("chevron-down", 12.0, t.text_dim)).gap(2.0) .fill(Color32::TRANSPARENT).stroke(Stroke::NONE) .min_size(vec2(width, control::DEFAULT)).corner_radius(radius::CHIP).truncate())).inner; - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), selected)); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), selected.text())); control_material(ui, &response, 12.0, reduced, egui::Popup::is_id_open(ui.ctx(), response.id.with("popup")), background); let limit = (ui.ctx().content_rect().width() - 32.0).max(140.0); let inner = select_popup_with_behavior(ui, &response, width.clamp(140.0, limit), reduced, close_behavior, contents) @@ -2066,10 +2075,16 @@ pub(super) fn paint_drop_halo(ui: &Ui, rect: egui::Rect, radius: f32, reduced: b /// Draw the real reference-image drop target. The caller supplies a pointer /// only while the platform reports hovered files and owns all file handling. pub(super) fn file_drop_zone(ui: &mut Ui, id: egui::Id, width: f32, drop_pointer: Option, enabled: bool, reduced: bool) -> Response { + labeled_file_drop_zone(ui, id, width, drop_pointer, enabled, reduced, "添加参考图", None) +} + +pub(super) fn labeled_file_drop_zone(ui: &mut Ui, id: egui::Id, width: f32, drop_pointer: Option, + enabled: bool, reduced: bool, label: &str, placeholder: Option<&str>, +) -> Response { let t = Tokens::get(ui.ctx()).agent(); let enabled = enabled && ui.is_enabled(); let (rect, response) = ui.add_enabled_ui(enabled, |ui| ui.allocate_exact_size(vec2(width.max(100.0), 72.0), egui::Sense::click())).inner; - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, "添加参考图")); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label)); let visible = rect.intersect(ui.clip_rect()); if !visible.is_positive() { return response; } let active = enabled && drop_pointer.is_some_and(|point| visible.contains(point)); @@ -2082,9 +2097,11 @@ pub(super) fn file_drop_zone(ui: &mut Ui, id: egui::Id, width: f32, drop_pointer let gain = 0.52 * strength; material_over(ui, id, rect, 12.0, gain, background, material_fallback(gain), Color32::TRANSPARENT); let color = drop_halo_outline(ui, id.with("rim"), rect, 12.0, active, reduced); - let title = if active { "释放以上传图片" } else if rect.width() < 230.0 { "添加参考图" } else { "拖放图片,或点击添加参考图" }; - let foreground = if enabled { t.text } else { t.text_faint }; - let galley = painter.layout_no_wrap(title.to_owned(), Type::Meta.font_id(), foreground); + let title = if active { "释放以上传图片" } else { placeholder.unwrap_or(if rect.width() < 230.0 { + "添加参考图" + } else { "拖放图片,或点击添加参考图" }) }; + let foreground = if !enabled { t.text_faint } else if !active && placeholder.is_some() { t.text_dim } else { t.text }; + let galley = painter.layout(title.to_owned(), Type::Meta.font_id(), foreground, (rect.width() - 36.0).max(1.0)); let icon_size = if active && !reduced { 15.0 * (0.92 + 0.08 * pulse) } else { 15.0 }; let left = rect.center().x - (galley.size().x + 23.0) * 0.5; crate::icons::paint(ui, egui::Rect::from_center_size(egui::pos2(left + 7.5, rect.center().y), vec2(icon_size, icon_size)), "image", icon_size, if active { color } else if enabled { t.text_dim } else { t.text_faint }); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workspace_navigation.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workspace_navigation.rs index b2915c2a..b4914b37 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workspace_navigation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workspace_navigation.rs @@ -1,11 +1,30 @@ -use super::{CenterView, Workspace, agent_panel, stitch_ui}; -use crate::{PhotocraftApp, theme::Tokens}; +use super::{CenterView, Request, Workspace, agent_panel, project_browser, stitch_ui}; +use crate::{ + PhotocraftApp, + theme::{Tokens, agent_scale::Type}, +}; use egui::{Id, RichText, Ui}; use serde_json::{Value, json}; -/// How many of the center grid's first rows the project page repeats as a -/// quick jump from the dock. -const RECENT_PROJECTS: usize = 6; +#[derive(Clone, Copy, Default, PartialEq, Eq)] +enum Intent { + #[default] + Find, + Spu, + Brief, + Knowledge, +} + +#[derive(Default)] +pub(super) struct Workbench { + scope: Value, + intent: Intent, + pub(super) input: String, + turns: Vec<(String, String)>, + matches: Vec, + pending: Option, + seed: Option<(u64, Intent, String)>, +} impl Workspace { pub(super) fn agent_page(&self, app: &PhotocraftApp) -> &'static str { @@ -26,62 +45,219 @@ impl Workspace { !self.library && !self.material && self.creation_open && self.creation_step < 3 } - /// The right-hand companion of a center destination. On the project page - /// the center owns the title, filters, search and "新建项目"; this panel - /// adds only what helps beside it, so nothing on screen exists twice. + fn workbench_scope(&self) -> Value { + json!({"accountId":self.account["id"],"origin":self.origin}) + } + + pub(super) fn refresh_workbench_scope(&mut self) { + let scope = self.workbench_scope(); + if self.workbench.scope != scope { + self.workbench = Workbench { scope, ..Default::default() }; + } + } + + pub(super) fn apply_workbench_seed(&mut self, app: &mut PhotocraftApp) { + let Some((doc, intent, text)) = self.workbench.seed.take() else { return }; + if app.session.active().map(|state| state.doc.id.0) != Some(doc) || self.creation_doc != Some(doc) { + self.workbench.seed = Some((doc, intent, text)); + return; + } + if intent == Intent::Spu { + self.creation_brief["identifierType"] = json!("spu"); + self.creation_brief["identifier"] = json!(text); + self.creation_dirty = true; + if let Err(error) = self.creation_action(app, "creation-product-platform", json!({"spu":text})) { + self.error = error; + } + } else { + self.creation_brief["note"] = json!(text); + self.creation_dirty = true; + } + } + + fn submit_workbench(&mut self, app: &mut PhotocraftApp) { + let query = self.workbench.input.trim().to_owned(); + let intent = self.workbench.intent; + self.workbench.matches.clear(); + let result = match intent { + Intent::Find => { + let query = query.to_lowercase(); + self.workbench.matches = self + .projects + .iter() + .filter(|item| item["source"] == "native" && project_browser::project_matches_query(item, &query)) + .take(12) + .cloned() + .collect(); + if self.workbench.matches.is_empty() { + "本机没有匹配的项目。".into() + } else { + "点击下方匹配的本机项目即可打开。".into() + } + } + Intent::Spu | Intent::Brief => { + if intent == Intent::Spu && !self.account["id"].is_string() { + "登录素材库后可以按 SPU 导入商品资料。".into() + } else { + match self.creation_action(app, "creation-new", Value::Null) { + Ok(_) => { + if let Some(doc) = app.session.active() { + self.workbench.seed = Some((doc.doc.id.0, intent, query.clone())); + } + "已打开新项目的产品资料页。".into() + } + Err(error) => error, + } + } + } + Intent::Knowledge => { + let id = uuid::Uuid::new_v4().to_string(); + if !self.account["id"].is_string() { + "登录素材库后可以查询企业知识库。".into() + } else if self + .tx + .send(Request::Action( + "workbench-knowledge".into(), + json!({ + "accountId":self.account["id"],"origin":self.origin,"readId":id,"query":query + }), + )) + .is_ok() + { + self.workbench.pending = Some(id); + "正在查阅企业知识库…".into() + } else { + "知识库读取服务暂不可用,请稍后重试。".into() + } + } + }; + self.workbench.input.clear(); + if self.workbench.turns.len() >= 12 { + self.workbench.turns.remove(0); + } + self.workbench.turns.push((query, result)); + } + + pub(super) fn workbench_knowledge_received(&mut self, result: Result) { + let Ok(value) = result else { return }; + if self.workbench.scope != self.workbench_scope() + || value["accountId"] != self.account["id"] + || value["origin"] != self.origin + || value["readId"].as_str() != self.workbench.pending.as_deref() + || self.workbench.pending.is_none() + { + return; + } + self.workbench.pending = None; + if let Some((_, reply)) = self.workbench.turns.last_mut() { + *reply = if let Some(error) = value["error"].as_str() { + error.to_owned() + } else { + let excerpts = value["sources"] + .as_array() + .into_iter() + .flatten() + .filter_map(|source| Some(format!("{}\n来源:{}", source["text"].as_str()?, source["path"].as_str()?))) + .collect::>(); + if excerpts.is_empty() { + "知识库没有返回相关规范,可补充品牌、品类或模板名称再问。".into() + } else { + excerpts.join("\n\n") + } + }; + } + } + + fn workbench_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + self.refresh_workbench_scope(); + let t = Tokens::get(ui.ctx()).agent(); + ui.label(RichText::new("工作台总助").size(Type::TitleLg.size()).strong().color(t.text)); + ui.add_space(6.0); + if self.workbench.turns.is_empty() { + ui.label(RichText::new("查找本机项目、用商品资料新建项目,或查询企业模板和规范。").color(t.text_dim)); + } + ui.add_space(10.0); + egui::ScrollArea::vertical().id_salt("workbench-turns").max_height((ui.available_height() - 220.0).max(60.0)).stick_to_bottom(true).show(ui, |ui| { + for (index, (query, answer)) in self.workbench.turns.iter().enumerate() { + ui.label(RichText::new(query).strong().color(t.text)); + stitch_ui::streaming_reply(ui, ui.scope_id().with(index), answer, false, self.reduce_motion); + ui.add_space(8.0); + } + for item in self.workbench.matches.clone() { + let name = project_browser::project_title(&item); + let label = item["brandName"].as_str().filter(|name| !name.is_empty()).map_or_else(|| name.to_owned(), |brand| format!("{name} · {brand}")); + if stitch_ui::menu_item(ui, &label, self.busy.is_none()).on_hover_text(&label).clicked() + && let Err(error) = self.request_project_open(app, item) + { + self.project_list_error = error; + } + } + }); + let modes = [(Intent::Find, "找项目"), (Intent::Spu, "按 SPU 新建"), (Intent::Brief, "用资料新建"), (Intent::Knowledge, "问规范")]; + ui.horizontal_wrapped(|ui| { + for (intent, label) in modes { + if ui.add_enabled_ui(self.workbench.pending.is_none(), |ui| ui.selectable_label(self.workbench.intent == intent, label)).inner.clicked() { + self.workbench.intent = intent; + } + } + }); + let (hint, limit, minimum) = match self.workbench.intent { + Intent::Find => ("输入项目名称、品牌或型号", 200, 1), + Intent::Spu => ("粘贴商品 SPU", 200, 1), + Intent::Brief => ("粘贴商品资料或制作要求", 2000, 1), + Intent::Knowledge => ("例如:这个品牌的详情页首屏有什么要求?", 500, 2), + }; + let pending = self.workbench.pending.is_some(); + let response = egui::ScrollArea::vertical() + .id_salt("workbench-input") + .max_height(88.0) + .show(ui, |ui| { + ui.add_enabled( + !pending, + stitch_ui::text_input(&mut self.workbench.input, hint, true).desired_width(f32::INFINITY).desired_rows(2).char_limit(limit), + ) + }) + .inner; + self.panel_geometry["workspaceSearch"] = agent_panel::rect_value(response.rect); + let count = self.workbench.input.trim().chars().count(); + let enabled = !pending && (minimum..=limit).contains(&count); + if stitch_ui::action_button(ui, if pending { "查阅中…" } else { "发送" }, stitch_ui::ButtonRole::Primary, enabled).clicked() { + self.submit_workbench(app); + } + } + pub(super) fn workspace_panel(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { - let page = self.agent_page(app); - let projects = page == "projects"; + let projects = self.agent_page(app) == "projects"; let t = Tokens::get(ui.ctx()).agent(); ui.memory_mut(|memory| memory.surrender_focus(super::composer_input_id())); self.focus_composer = false; - for key in ["composer", "input", "subject", "references", "send", "conversationClip", "copywritingFields", "copywritingOptions", - "workspaceSearch", "workspaceReturn"] { - self.panel_geometry[key] = serde_json::Value::Null; + for key in [ + "composer", + "input", + "subject", + "references", + "send", + "conversationClip", + "copywritingFields", + "copywritingOptions", + "workspaceSearch", + "workspaceReturn", + ] { + self.panel_geometry[key] = Value::Null; } - if projects { - ui.add_space(6.0); - } else { - ui.add_space(18.0); + ui.add_space(if projects { 6.0 } else { 18.0 }); + if !projects { ui.horizontal(|ui| { ui.add_space(16.0); ui.add(crate::icons::image("image", 20.0, t.text_dim)); - ui.label(RichText::new("素材库").size(18.0).color(t.text)); + ui.label(RichText::new("素材库").size(Type::TitleLg.size()).color(t.text)); }); ui.add_space(20.0); } egui::Frame::NONE.inner_margin(16).show(ui, |ui| { ui.set_width(ui.available_width()); if projects { - if let Some(recent) = self.recent_projects() { - ui.label(RichText::new("最近的项目").size(12.0).color(t.text_dim)); - ui.add_space(8.0); - ui.scope(|ui| { - ui.spacing_mut().item_spacing.y = 2.0; - for item in recent { - // A list row, not a pill: names of any length share - // one left edge and one width. - let name = item["name"].as_str().unwrap_or("未命名项目"); - let response = stitch_ui::menu_item(ui, name, self.busy.is_none()); - if response.clicked() - && let Err(error) = self.request_project_open(app, item) - { - self.project_list_error = error; - } - } - }); - } else { - // Nothing to jump to yet. Say where a project starts, - // rather than leaving a blank column beside the page. - let (title, line) = if self.needs_library_login() || self.library_blocked() { - ("还没有可用的项目", "连接素材库后,这里会列出你最近的项目。") - } else { - ("还没有项目", "从中间的「新建项目」开始:填好产品资料、选好模板,就能进入画布和小壹一起制作。") - }; - ui.label(RichText::new(title).size(14.0).strong().color(t.text)); - ui.add_space(6.0); - ui.add(egui::Label::new(RichText::new(line).size(12.0).color(t.text_dim)).wrap()); - } + self.workbench_ui(app, ui); } else { ui.label(RichText::new("选择素材,预览后置入画布").color(t.text_dim)); let search = stitch_ui::search_field(ui, Id::unique("workspace-material-search"), &mut self.query, "输入产品编号"); @@ -101,7 +277,7 @@ impl Workspace { } } if let Some(state) = app.session.active() { - ui.add_space(24.0); + ui.add_space(16.0); stitch_ui::divider(ui); let label = if self.pending() { "返回当前任务" } else { "返回当前画布" }; let document = state.doc.id.0; @@ -113,22 +289,46 @@ impl Workspace { } self.panel_geometry["backgroundDocument"] = json!(document); } - // The project page shows its library notice in the center. if !projects && (self.needs_library_login() || self.library_blocked()) { ui.add_space(16.0); self.library_notice(ui); } }); } +} - /// The first rows of the center grid, in its own order: local projects - /// first, then the most recently updated. - fn recent_projects(&self) -> Option> { - let mut order: Vec<_> = self.projects.iter().enumerate() - .map(|(index, item)| (item["source"] == "native", item["updatedAt"].as_str(), index)) - .collect(); - order.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.cmp(&a.1))); - let recent: Vec = order.into_iter().take(RECENT_PROJECTS).map(|(_, _, index)| self.projects[index].clone()).collect(); - (!recent.is_empty()).then_some(recent) +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + + #[test] + fn workbench_spu_import_is_bound_to_the_new_project() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"name":"已有项目","width":800,"height":800})).unwrap(); + let previous = app.session.active().unwrap().doc.id.0; + let (tx, requests) = mpsc::channel(); + let (_events, receiver) = mpsc::channel(); + let mut workspace = Workspace::new(tx, receiver); + let _ = requests.try_iter().count(); + workspace.busy = None; + workspace.account = json!({"id":"qa"}); + workspace.workbench.intent = Intent::Spu; + workspace.workbench.input = "0003-A".into(); + workspace.creation_doc = Some(previous); + workspace.submit_workbench(&mut app); + let current = app.session.active().unwrap().doc.id.0; + assert_ne!(previous, current); + workspace.apply_workbench_seed(&mut app); + assert!(requests.try_recv().is_err(), "wait for the new document's product brief"); + workspace.creation_doc = Some(current); + workspace.apply_workbench_seed(&mut app); + let Request::Action(method, input) = requests.try_recv().unwrap() else { + panic!("expected a product lookup"); + }; + assert_eq!(method, "creation-product-platform"); + assert_eq!(input["doc"], current); + assert_eq!(input["spu"], "0003-A"); + assert!(requests.try_recv().is_err()); } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/panels/panel_docking.rs b/apps/detail-photocraft/crates/ui-egui/src/panels/panel_docking.rs index 0148a860..1bfd929a 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/panels/panel_docking.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/panels/panel_docking.rs @@ -629,14 +629,20 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { None => legacy(app), }; #[cfg(not(target_arch = "wasm32"))] - let agent_projection = crate::jiansun::agent_selected(app); + let projects_projection = crate::jiansun::projects_agent_dock(app); + #[cfg(not(target_arch = "wasm32"))] + let agent_projection = projects_projection || crate::jiansun::agent_selected(app); #[cfg(target_arch = "wasm32")] let agent_projection = false; #[cfg(not(target_arch = "wasm32"))] let layout = if agent_projection { let pro = app.ui.theme.is_pro(); - let panels: Vec = app.ui.dock.visible_tabs(Group::Color, pro).iter() - .filter_map(|(_, label)| normalize(label).map(str::to_owned)).collect(); + let panels: Vec = if projects_projection { + vec!["xiaoyi".into()] + } else { + app.ui.dock.visible_tabs(Group::Color, pro).iter() + .filter_map(|(_, label)| normalize(label).map(str::to_owned)).collect() + }; if let Some(active) = panels.iter().position(|id| id == "xiaoyi") { let range = agent_width_range(app, ui.available_width().min(ui.ctx().content_rect().width())); let width = ui.ctx().data_mut(|data| data.get_persisted::(agent_width_id())).unwrap_or(520.0).clamp(*range.start(), *range.end()); @@ -739,7 +745,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.ctx().data_mut(|data| data.insert_persisted(agent_width_id(), width.clamp(*range.start(), *range.end()))); continue; } - if !matches!(action, Action::Activate { .. }) { continue; } + if projects_projection || !matches!(action, Action::Activate { .. }) { continue; } } let result = match action { // A dock group minimizes as PhotoCraft's collapsed group, which the native dock's