fix(detail-client): separate material loading and bind project templates
This commit is contained in:
parent
8b982ff3b8
commit
7a6dde5ac4
@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
|
||||
import { requireDesktop } from '@/lib/desktop-client/service'
|
||||
import { DesktopClientError } from '@/lib/desktop-client/contract.mjs'
|
||||
import { desktopAgentRules } from '@/lib/desktop-client/agent-rules'
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
export const dynamic = 'force-dynamic'
|
||||
@ -9,7 +10,12 @@ const headers = { 'Cache-Control': 'private, no-store', 'X-Content-Type-Options'
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
await requireDesktop(request)
|
||||
return NextResponse.json(desktopAgentRules(new URL(request.url).searchParams.get('binding')), { headers })
|
||||
const value = desktopAgentRules(new URL(request.url).searchParams.get('binding'))
|
||||
const etag = `"${createHash('sha256').update(JSON.stringify(value)).digest('hex')}"`
|
||||
// Authorization is always evaluated before a conditional response. Browser
|
||||
// caching stays disabled; the native client maintains its own scoped cache.
|
||||
if (request.headers.get('if-none-match') === etag) return new NextResponse(null, { status: 304, headers: { ...headers, ETag: etag } })
|
||||
return NextResponse.json(value, { headers: { ...headers, ETag: etag } })
|
||||
} catch (error) {
|
||||
const known = error instanceof DesktopClientError
|
||||
return NextResponse.json({ error: known ? error.message : '规则暂时无法读取', code: known ? error.code : 'internal_error' }, { status: known ? error.status : 500, headers })
|
||||
|
||||
@ -37,6 +37,8 @@ mod sync;
|
||||
mod creation;
|
||||
#[path = "jiansun_recovery.rs"]
|
||||
mod recovery;
|
||||
#[path = "jiansun_reads.rs"]
|
||||
mod reads;
|
||||
|
||||
/// Opt-in, local SDK transport. The personal Key never leaves this native process.
|
||||
pub fn pi_stdio() -> R<()> {
|
||||
@ -115,6 +117,11 @@ fn read_json(path: &Path) -> R<Value> {
|
||||
}
|
||||
serde_json::from_slice(&bytes).map_err(|_| "本机记录格式无效".into())
|
||||
}
|
||||
fn bound_material_read(result: R<Value>, reference: &Value) -> Value {
|
||||
let mut value = match result { Ok(value) => value, Err(error) => json!({"error":error}) };
|
||||
for key in ["readId", "accountId", "origin", "doc"] { value[key] = reference[key].clone(); }
|
||||
value
|
||||
}
|
||||
fn write_json(path: &Path, v: &Value) -> R<()> {
|
||||
if let Some(p) = path.parent() {
|
||||
fs::create_dir_all(p).map_err(|_| "无法创建本机项目目录")?;
|
||||
@ -477,6 +484,35 @@ impl Backend {
|
||||
}
|
||||
Ok(b)
|
||||
}
|
||||
fn material_asset(&mut self, method: &str, input: &Value, events: &mpsc::Sender<Event>) -> R<Value> {
|
||||
let id = input["doc"].as_u64().ok_or("请先打开项目")?;
|
||||
self.ensure_owner(id)?;
|
||||
let material = identifier(input["materialId"].as_str().ok_or("素材编号无效")?)?;
|
||||
let asset = &input["asset"];
|
||||
let kind = identifier(asset["kind"].as_str().ok_or("素材种类无效")?)?;
|
||||
let aid = identifier(asset["id"].as_str().ok_or("图片编号无效")?)?;
|
||||
// This GET checks the current session and the exact asset's ACL; no cached grant.
|
||||
let bytes = self.bytes(&format!("catalog/products/{material}/{kind}/{aid}"))?;
|
||||
let mut reference = input.clone();
|
||||
reference["accountId"] = self.auth["account"]["id"].clone();
|
||||
reference["origin"] = json!(self.origin);
|
||||
if method == "preview" {
|
||||
use photocraft_codecs::{ChannelLayout, SampleType};
|
||||
let decoded = photocraft_codecs::decode_with(&bytes, &photocraft_codecs::DecodeOptions {
|
||||
limits: photocraft_codecs::Limits { max_width: 16384, max_height: 16384, max_pixels: 24_000_000, max_alloc: 128 * 1024 * 1024 },
|
||||
..Default::default()
|
||||
}).map_err(|_| "此文件不能作为图片预览")?.convert(ChannelLayout::Rgba, SampleType::U8);
|
||||
let image = egui::ColorImage::from_rgba_unmultiplied([decoded.width() as usize, decoded.height() as usize], decoded.data());
|
||||
events.send(Event::Preview(reference.clone(), image)).map_err(|_| "工作台已关闭")?;
|
||||
// Preview is read-only. Placing later uses a fresh authorized GET, and is serialized.
|
||||
return Ok(reference);
|
||||
}
|
||||
let dir = self.project_dir(id)?;
|
||||
fs::create_dir_all(&dir).map_err(|_| "图片目录无法创建")?;
|
||||
let path = dir.join(format!("material-{}.png", hash(&format!("{material}|{kind}|{aid}"))));
|
||||
photocraft_format::atomic_write(&path, &bytes).map_err(|_| "图片保存失败")?;
|
||||
Ok(json!({"doc":id,"path":path.to_string_lossy(),"reference":reference}))
|
||||
}
|
||||
fn save(&mut self, doc: Arc<Document>, revision: u64, meta: Value) -> R<Value> {
|
||||
let _guard = sync::context_guard();
|
||||
if !meta["creationDraft"].is_null() && (!meta["creationDraft"].is_object() || meta["creationDraft"].to_string().len()>100_000) {
|
||||
@ -758,13 +794,16 @@ impl Backend {
|
||||
"image-applied" => self.image_applied(input),
|
||||
"image-use" => self.image_use(input),
|
||||
"materials" => {
|
||||
self.validate()?;
|
||||
// The catalogue GET validates the live session and material ACL itself.
|
||||
let kind = input["identifierType"].as_str().filter(|s| ["sku", "spu", "barcode"].contains(s)).ok_or("查询类型无效")?;
|
||||
let q = input["identifier"].as_str().filter(|s| !s.is_empty() && s.len() <= 100).ok_or("请输入产品编号")?;
|
||||
self.json(&format!(
|
||||
let mut value = self.json(&format!(
|
||||
"catalog/products?{}",
|
||||
url::form_urlencoded::Serializer::new(String::new()).append_pair("identifierType", kind).append_pair("identifier", q).finish()
|
||||
))
|
||||
))?;
|
||||
value["accountId"] = self.auth["account"]["id"].clone();
|
||||
value["origin"] = json!(self.origin);
|
||||
Ok(value)
|
||||
}
|
||||
_ => Err("未开放的本机业务操作".into()),
|
||||
}
|
||||
@ -853,6 +892,8 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
}
|
||||
};
|
||||
let model_busy = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let catalog_reads = reads::ReadPool::catalog();
|
||||
let image_reads = reads::ReadPool::images();
|
||||
let mut recovery_scope = String::new();
|
||||
if !backend.auth.is_null() {
|
||||
recovery_scope = backend.scope();
|
||||
@ -901,6 +942,37 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
let _ = events.send(event);
|
||||
}
|
||||
Request::Action(method, input) => {
|
||||
if matches!(method.as_str(), "materials" | "creation-catalog" | "creation-thumbnail" | "preview") {
|
||||
if method.starts_with("creation-") {
|
||||
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();
|
||||
let reference = json!({"readId":input["readId"],"doc":input["doc"],"accountId":backend.auth["account"]["id"],"origin":backend.origin});
|
||||
let task_reference = reference.clone();
|
||||
let pool = if matches!(method.as_str(), "preview" | "creation-thumbnail") { &image_reads } else { &catalog_reads };
|
||||
if let Err(error) = pool.submit(move || {
|
||||
let result = if task_method == "preview" {
|
||||
reader.material_asset(&task_method, &input, &task_events)
|
||||
} else if task_method.starts_with("creation-") {
|
||||
reader.creation_action(&task_method, &input, None, &task_events, &task_ctx)
|
||||
} else {
|
||||
reader.action(&task_method, &input, &task_events, &task_ctx)
|
||||
};
|
||||
if task_method != "preview" || result.is_err() {
|
||||
let result = if matches!(task_method.as_str(), "materials" | "preview") { Ok(bound_material_read(result, &task_reference)) } else { result };
|
||||
let _ = task_events.send(Event::Json(task_method, result));
|
||||
}
|
||||
task_ctx.request_repaint();
|
||||
}) {
|
||||
let result = if matches!(method.as_str(), "materials" | "preview") { Ok(bound_material_read(Err(error.into()), &reference)) } else { Err(error.into()) };
|
||||
let _ = events.send(Event::Json(method, result));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if matches!(method.as_str(), "project-sync" | "project-state" | "project-delete") && model_busy.load(std::sync::atomic::Ordering::Acquire) {
|
||||
let _ = events.send(Event::Json(method, Err("任务仍在运行,请等待完成或接手后再保存云端状态".into())));
|
||||
ctx.request_repaint();
|
||||
@ -986,38 +1058,9 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
});
|
||||
ctx.request_repaint();Request::OpenedResult{binding,result}
|
||||
});
|
||||
} else if method == "place" || method == "preview" {
|
||||
let result = (|| -> R<Value> {
|
||||
backend.validate()?;
|
||||
let id = input["doc"].as_u64().ok_or("请先打开项目")?;
|
||||
backend.ensure_owner(id)?;
|
||||
let material = identifier(input["materialId"].as_str().ok_or("素材编号无效")?)?;
|
||||
let asset = &input["asset"];
|
||||
let kind = identifier(asset["kind"].as_str().ok_or("素材种类无效")?)?;
|
||||
let aid = identifier(asset["id"].as_str().ok_or("图片编号无效")?)?;
|
||||
let bytes = backend.bytes(&format!("catalog/products/{material}/{kind}/{aid}"))?;
|
||||
let dir = backend.project_dir(id)?;
|
||||
fs::create_dir_all(&dir).map_err(|_| "图片目录无法创建")?;
|
||||
let path = dir.join(format!("material-{}.png", hash(&format!("{material}|{kind}|{aid}"))));
|
||||
photocraft_format::atomic_write(&path, &bytes).map_err(|_| "图片保存失败")?;
|
||||
let mut reference = input.clone();
|
||||
reference["accountId"] = backend.auth["account"]["id"].clone();
|
||||
reference["origin"] = json!(backend.origin);
|
||||
if method == "preview" {
|
||||
use photocraft_codecs::{ChannelLayout, SampleType};
|
||||
let decoded =
|
||||
photocraft_codecs::decode(&bytes).map_err(|_| "此文件不能作为图片预览")?.convert(ChannelLayout::Rgba, SampleType::U8);
|
||||
if u64::from(decoded.width()) * u64::from(decoded.height()) > 24_000_000 {
|
||||
return Err("图片过大,请先使用缩略图".into());
|
||||
}
|
||||
let image = egui::ColorImage::from_rgba_unmultiplied([decoded.width() as usize, decoded.height() as usize], decoded.data());
|
||||
let _ = events.send(Event::Preview(reference.clone(), image));
|
||||
}
|
||||
Ok(json!({"doc":id,"path":path.to_string_lossy(),"reference":reference}))
|
||||
})();
|
||||
if method != "preview" || result.is_err() {
|
||||
let _ = events.send(Event::Json(method, result));
|
||||
}
|
||||
} else if method == "place" {
|
||||
let result = backend.material_asset(&method, &input, &events);
|
||||
let _ = events.send(Event::Json(method, result));
|
||||
} else {
|
||||
let result = backend.action(&method, &input, &events, &ctx);
|
||||
let _ = events.send(Event::Json(method, result));
|
||||
@ -1039,6 +1082,35 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn catalog_search_authorizes_each_get_once_and_does_not_cache_a_previous_grant() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let server = std::thread::spawn(move || {
|
||||
for status in [200, 403] {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let mut request = [0; 8192];
|
||||
let size = stream.read(&mut request).unwrap();
|
||||
let request = String::from_utf8_lossy(&request[..size]);
|
||||
assert!(request.starts_with("GET /api/desktop/catalog/products?identifierType=spu&identifier=TEST-001 "));
|
||||
assert!(request.to_ascii_lowercase().contains("authorization: bearer local-test-only"));
|
||||
let body = if status == 200 { r#"{"items":[]}"# } else { r#"{"error":"denied"}"# };
|
||||
write!(stream, "HTTP/1.1 {status} Test\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();
|
||||
}
|
||||
});
|
||||
let mut backend = Backend::new(std::env::temp_dir().join(format!("catalog-readonly-{}", Uuid::new_v4()))).unwrap();
|
||||
backend.origin = origin.clone();
|
||||
backend.auth = json!({"access_token":"local-test-only","account":{"id":"local-account"}});
|
||||
backend.http = Client::builder().no_proxy().redirect(reqwest::redirect::Policy::none()).timeout(Duration::from_secs(3)).build().unwrap();
|
||||
let (events, _) = mpsc::channel();
|
||||
let input = json!({"identifierType":"spu","identifier":"TEST-001"});
|
||||
let result = backend.action("materials", &input, &events, &egui::Context::default()).unwrap();
|
||||
assert_eq!(result["accountId"], "local-account");
|
||||
assert_eq!(result["origin"], origin);
|
||||
assert!(backend.action("materials", &input, &events, &egui::Context::default()).is_err());
|
||||
server.join().unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn a_gated_open_leaves_the_receive_queue_free_for_another_project_save() {
|
||||
enum Message {SaveB,Opened(Value)}
|
||||
let root=std::env::temp_dir().join(format!("native-open-queue-{}",Uuid::new_v4()));
|
||||
|
||||
@ -28,6 +28,20 @@ pub(super) fn save(dir: &Path, c: &mut Value) -> R<()> {
|
||||
c["revision"] = json!(n);
|
||||
write_json(&dir.join("creation.json"), c)
|
||||
}
|
||||
/// Attach only a verified fixed rule package, after transport has completed.
|
||||
/// Ordinary product saves remain entirely local, including unsupported categories.
|
||||
pub(super) fn attach_agent_rules(dir: &Path, saved: &Value) -> R<()> {
|
||||
let mut c = load(dir)?;
|
||||
let shop = saved["catalog"]["shops"].as_array().and_then(|a|a.first()).ok_or("项目模板品牌缺失")?;
|
||||
let category = saved["catalog"]["categories"].as_array().and_then(|a|a.first()).ok_or("项目模板品类缺失")?;
|
||||
if shop["id"] != c["brief"]["brandId"] || category["id"] != c["brief"]["categoryId"] { return Err("项目资料已切换,未载入旧模板".into()); }
|
||||
if c["designSnapshot"].is_null() { return Err("请先保存项目品牌资料".into()); }
|
||||
if c["designSnapshot"]["rules"] == *saved { return Ok(()); }
|
||||
let before = c.clone();
|
||||
c["designSnapshot"]["rules"] = saved.clone();
|
||||
model::invalidate(&mut c,&before);
|
||||
save(dir,&mut c)
|
||||
}
|
||||
/// Reserve the screen/task association before a paid dispatch. The immutable
|
||||
/// native baseline makes automatic recovery conditional on *unchanged* editing.
|
||||
pub(super) fn bind_image_dispatch(dir: &Path, task: &mut Value) -> R<()> {
|
||||
@ -125,6 +139,15 @@ fn clear_product_brand(c: &mut Value, name: &str) {
|
||||
c["brief"]["brandName"] = json!(name);
|
||||
c["designSnapshot"] = Value::Null;
|
||||
}
|
||||
fn copy_product_category(c: &mut Value, product: &Value) -> R<()> {
|
||||
c["brief"]["categoryId"] = json!(""); c["brief"]["categoryName"] = json!("");
|
||||
let id = product["categoryId"].as_str().unwrap_or("");
|
||||
let name = product["categoryName"].as_str().unwrap_or("");
|
||||
if id.is_empty() && name.is_empty() { return Ok(()); }
|
||||
if Uuid::parse_str(id).is_err() || name.is_empty() || name.chars().count() > 120 { return Err("素材库产品品类资料无效,未沿用旧品类".into()); }
|
||||
c["brief"]["categoryId"] = json!(id); c["brief"]["categoryName"] = json!(name);
|
||||
Ok(())
|
||||
}
|
||||
fn task_public(t: &Value) -> Value {
|
||||
json!({"id":t["id"],"stage":t["stage"],"phase":t["phase"],"requestId":t["requestId"],"idempotencyKey":t["id"],"model":t["model"]["id"],"message":t["message"],"canRecover":matches!(t["phase"].as_str(),Some("unknown"|"received")),"createdAt":t["createdAt"]})
|
||||
}
|
||||
@ -240,7 +263,7 @@ impl Backend {
|
||||
match method {
|
||||
"creation-read" => self.creation_result(doc, &dir),
|
||||
"creation-catalog" => {
|
||||
self.validate()?;
|
||||
// The authenticated catalogue GET rechecks the live account and ACL.
|
||||
let kind = input["kind"].as_str().filter(|s| matches!(*s, "brands" | "materials" | "products")).ok_or("资料目录类型无效")?;
|
||||
let mut query = url::form_urlencoded::Serializer::new(String::new());
|
||||
for key in ["query", "page", "identifierType", "identifier"] {
|
||||
@ -292,7 +315,7 @@ impl Backend {
|
||||
let mut reference =
|
||||
json!({"purpose":"creation-material","id":input["id"],"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin});
|
||||
let outcome = (|| -> R<Value> {
|
||||
self.validate()?;
|
||||
// The thumbnail GET performs its own live permission check.
|
||||
let id = identifier(input["id"].as_str().ok_or("材质编号无效")?)?;
|
||||
let bytes = self.bytes(&format!("catalog/materials/{id}/thumbnail"))?;
|
||||
let decoded = photocraft_codecs::decode_with(
|
||||
@ -901,6 +924,7 @@ impl Backend {
|
||||
}
|
||||
let brand_name = found["brandName"].as_str().unwrap_or("");
|
||||
clear_product_brand(&mut c, brand_name);
|
||||
copy_product_category(&mut c, found)?;
|
||||
if !brand_name.is_empty() {
|
||||
let p = url::form_urlencoded::Serializer::new(String::new()).append_pair("query", brand_name).finish();
|
||||
let list = self.json(&format!("catalog/brands?{p}"))?;
|
||||
@ -1215,6 +1239,16 @@ mod tests {
|
||||
assert!(model::prompt("facts", &c).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn library_product_only_uses_an_explicit_official_category_and_never_reuses_the_previous_one() {
|
||||
let mut c = model::empty();
|
||||
c["brief"]["categoryId"] = json!("old-category"); c["brief"]["categoryName"] = json!("电脑桌");
|
||||
copy_product_category(&mut c,&json!({"productModel":"电脑桌样例不能据此猜品类"})).unwrap();
|
||||
assert_eq!(c["brief"]["categoryId"],""); assert_eq!(c["brief"]["categoryName"],"");
|
||||
copy_product_category(&mut c,&json!({"categoryId":"53333bd0-9cc9-440b-80db-dd04280f0295","categoryName":"化妆台"})).unwrap();
|
||||
assert_eq!(c["brief"]["categoryId"],"53333bd0-9cc9-440b-80db-dd04280f0295");
|
||||
assert!(copy_product_category(&mut c,&json!({"categoryId":"../../../","categoryName":"电脑桌"})).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn generated_images_use_real_landscape_portrait_and_square_aspects_and_old_rows_reflow_read_only() {
|
||||
let dir = std::env::temp_dir().join(format!("native-creation-aspect-{}", Uuid::new_v4()));
|
||||
let mut c = model::empty();
|
||||
|
||||
@ -5,7 +5,7 @@ const FACTUAL_RULES: &str = "仅将已核对的事实用于卖点、标题和画
|
||||
const CONSUMER_COPY: &str = "sellingPoints、title和body必须是可直接用于产品详情页的简洁消费者成稿。先从事实提炼清楚、具体的产品表达,不要复制资料分析报告,也不要向消费者讲述取证或验收过程。不要把‘模板’‘验收’‘只说明看得到的组成’‘不能推断’‘不能据此判断’‘不表示性能’‘待确认’‘证据’或免责声明写入这些成稿字段。缺失信息只写在warnings;事实不足时省略对应句子或模块,不能用免责声明填满页面,也不能凭空补出性能、认证或体验承诺。例如已核实四条支腿可提炼为‘四腿支撑结构’,不能扩写为稳固、承重或耐用。保留事实的边界,成稿要讲产品本身。";
|
||||
|
||||
pub(super) fn empty() -> Value {
|
||||
json!({"version":1,"revision":0,"width":1440,"screenCount":5,"brief":{"source":"upload","name":"","brandId":"","brandName":"","identifierType":"sku","identifier":"","variant":"","colorMaterialId":"","colorName":"","dimensions":{"length":"","width":"","height":"","unit":"mm"},"images":[],"note":""},"facts":{"status":"idle","items":[],"missing":[]},"sellingPoints":{"batches":[],"selected":[],"direction":"","stale":false},"plan":{"status":"idle","screens":[],"invalidReason":"","confirmedAt":null,"confirmedInput":null},"designSnapshot":null,"generation":null})
|
||||
json!({"version":1,"revision":0,"width":1440,"screenCount":5,"brief":{"source":"upload","name":"","brandId":"","brandName":"","categoryId":"","categoryName":"","identifierType":"sku","identifier":"","variant":"","colorMaterialId":"","colorName":"","dimensions":{"length":"","width":"","height":"","unit":"mm"},"images":[],"note":""},"facts":{"status":"idle","items":[],"missing":[]},"sellingPoints":{"batches":[],"selected":[],"direction":"","stale":false},"plan":{"status":"idle","screens":[],"invalidReason":"","confirmedAt":null,"confirmedInput":null},"designSnapshot":null,"generation":null})
|
||||
}
|
||||
|
||||
fn string(value: &Value, max: usize, label: &str) -> R<String> {
|
||||
@ -26,6 +26,9 @@ pub(super) fn brief(value: &Value) -> R<Value> {
|
||||
] {
|
||||
out[field] = json!(string(&value[field], max, field)?);
|
||||
}
|
||||
for (field, max) in [("categoryId", 150), ("categoryName", 120)] {
|
||||
out[field] = json!(match value.get(field) { Some(value) => string(value, max, field)?, None => String::new() });
|
||||
}
|
||||
if !matches!(value["source"].as_str(), Some("upload" | "library")) || !matches!(value["identifierType"].as_str(), Some("sku" | "spu" | "barcode")) {
|
||||
return Err("资料来源或编号类型无效".into());
|
||||
}
|
||||
@ -128,12 +131,13 @@ pub(super) fn prompt(stage: &str, c: &Value) -> R<String> {
|
||||
if stage != "plan" {
|
||||
return Err("创作阶段无效".into());
|
||||
}
|
||||
let template = plan_template(c)?;
|
||||
let points = selected(c)?;
|
||||
if points.is_empty() || points.iter().any(|p| p["factsHash"] != facts_hash(c)) {
|
||||
return Err("请从当前产品事实的批次挑选卖点".into());
|
||||
}
|
||||
Ok(format!(
|
||||
"{FACTUAL_RULES}\n{CONSUMER_COPY}\n基于已选卖点策划恰好{}屏,最多12屏。只返回JSON:{{\"screens\":[{{\"title\":\"标题\",\"body\":\"正文\",\"imagePrompt\":\"无字画面要求\"}}],\"warnings\":[\"待确认\"]}}。标题1至120字、正文最多600字,imagePrompt最多3000字。统一Noto Sans SC中文字体、品牌色、布光和摄影风格。每屏只表达一个重点;缺少尺寸、检测或设备依据的模块省略,不虚构、不在成稿写待补说明。此步只能策划,不声称已生图。\n产品:{product}\n已核对事实:{}\n已选卖点:{}\n品牌快照:{knowledge}\n画布宽度:{},总高最多30000px。",
|
||||
"{FACTUAL_RULES}\n{CONSUMER_COPY}\n基于已选卖点策划恰好{}屏,最多12屏。只返回JSON:{{\"screens\":[{{\"title\":\"标题\",\"body\":\"正文\",\"imagePrompt\":\"无字画面要求\"}}],\"warnings\":[\"待确认\"]}}。标题1至120字、正文最多600字,imagePrompt最多3000字。统一Noto Sans SC中文字体、品牌色、布光和摄影风格。每屏只表达一个重点;缺少尺寸、检测或设备依据的模块省略,不虚构、不在成稿写待补说明。此步只能策划,不声称已生图。\n产品:{product}\n已核对事实:{}\n已选卖点:{}\n品牌快照:{knowledge}\n固定模板模块候选(仅结构,不是本款产品事实;不继承示例参数或品牌背书):{template}\n画布宽度:{},总高最多30000px。",
|
||||
c["screenCount"].as_u64().unwrap_or(5),
|
||||
c["facts"],
|
||||
json!(points),
|
||||
@ -141,6 +145,17 @@ pub(super) fn prompt(stage: &str, c: &Value) -> R<String> {
|
||||
))
|
||||
}
|
||||
|
||||
fn plan_template(c: &Value) -> R<Value> {
|
||||
let saved = &c["designSnapshot"]["rules"];
|
||||
let catalog = &saved["catalog"];
|
||||
let binding = catalog["bindings"].as_array().filter(|a|a.len()==1).and_then(|a|a.first()).ok_or("请先在产品资料中选择已配置模板的品牌和品类")?;
|
||||
let shop = catalog["shops"].as_array().filter(|a|a.len()==1).and_then(|a|a.first()).ok_or("项目模板品牌缺失")?;
|
||||
if shop["id"] != c["brief"]["brandId"] || binding["categoryId"] != c["brief"]["categoryId"] || binding["state"] != "ready" { return Err("项目模板与品牌、品类不匹配,请核对产品资料".into()); }
|
||||
let screens:Vec<_> = binding["template"]["screens"].as_array().ok_or("项目模板模块缺失")?.iter().filter(|s|s["role"]=="content").take(12).map(|s|json!({"id":s["id"],"title":s["title"]})).collect();
|
||||
if screens.is_empty() { return Err("此品类模板尚未配置内容模块".into()); }
|
||||
Ok(json!({"id":saved["id"],"revision":saved["contentHash"],"modules":screens}))
|
||||
}
|
||||
|
||||
fn entries(v: &Value, limit: usize, max: usize, min: usize) -> R<Vec<String>> {
|
||||
let a = v.as_array().filter(|a| (min..=limit).contains(&a.len())).ok_or("模型条目数量无效")?;
|
||||
let mut out = Vec::new();
|
||||
@ -280,6 +295,7 @@ mod tests {
|
||||
let mut c = empty();
|
||||
c["brief"]["name"] = json!("产品");
|
||||
c["brief"]["brandId"] = json!("brand");
|
||||
c["brief"]["categoryId"] = json!("category");
|
||||
c["brief"]["images"] = json!([{"source":format!("local:{}","a".repeat(64)),"purpose":"product","name":"实拍"}]);
|
||||
c["designSnapshot"] = json!({"brand":{"id":"brand","profile":{"tone":"简洁"}}});
|
||||
c["facts"] = json!({"status":"ready","items":[{"text":"四条支腿","source":"实拍"}],"missing":["承重待确认"]});
|
||||
@ -289,10 +305,26 @@ mod tests {
|
||||
assert!(points.contains("不能扩写为稳固、承重或耐用"));
|
||||
c["sellingPoints"]["batches"] = json!([{"id":"batch","items":["四腿支撑结构"],"factsHash":facts_hash(&c)}]);
|
||||
c["sellingPoints"]["selected"] = json!(["batch:0"]);
|
||||
assert!(prompt("plan", &c).unwrap_err().contains("选择已配置模板"));
|
||||
c["designSnapshot"]["rules"] = json!({"id":"qa-template","contentHash":"a".repeat(64),"catalog":{"shops":[{"id":"brand"}],"bindings":[{"categoryId":"category","state":"ready","template":{"screens":[{"id":"first","title":"首屏","role":"content"}]}}]}});
|
||||
let plan = prompt("plan", &c).unwrap();
|
||||
assert!(plan.contains("不要复制资料分析报告"));
|
||||
assert!(plan.contains("不在成稿写待补说明"));
|
||||
assert!(plan.contains("qa-template"));
|
||||
assert!(!points.contains("qa-template"));
|
||||
// Tone is guidance for the model, not a regex rejection of an otherwise complete response.
|
||||
assert!(parse("plan", r#"{"screens":[{"title":"结构","body":"用户仍可编辑的完整文案","imagePrompt":"产品近景"}],"warnings":[]}"#, &c).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn category_is_optional_for_old_briefs_and_fixed_template_metadata_is_bounded() {
|
||||
let mut b = empty()["brief"].clone();
|
||||
b.as_object_mut().unwrap().remove("categoryId"); b.as_object_mut().unwrap().remove("categoryName");
|
||||
let clean = brief(&b).unwrap(); assert_eq!(clean["categoryId"], ""); assert_eq!(clean["categoryName"], "");
|
||||
b["categoryId"] = json!(false); assert!(brief(&b).is_err());
|
||||
let mut c = empty(); c["brief"]["brandId"] = json!("brand"); c["brief"]["categoryId"] = json!("category");
|
||||
c["designSnapshot"] = json!({"rules":{"id":"template","contentHash":"a".repeat(64),"catalog":{"shops":[{"id":"brand"}],"bindings":[{"state":"ready","categoryId":"category","rules":["do not inject this whole original file"],"template":{"screens":(0..22).map(|i|json!({"id":format!("S{i}"),"title":"模块","role":"content","purpose":"a".repeat(2000)})).collect::<Vec<_>>()}}]}}});
|
||||
let template = plan_template(&c).unwrap(); assert_eq!(template["modules"].as_array().unwrap().len(),12);
|
||||
assert!(template.to_string().len()<2000); assert!(!template.to_string().contains("purpose"));
|
||||
c["brief"]["categoryId"] = json!("other"); assert!(plan_template(&c).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,6 +2,83 @@
|
||||
use super::*;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::process::{Command, Stdio};
|
||||
#[path = "jiansun_rule_cache.rs"]
|
||||
mod rule_cache;
|
||||
|
||||
fn cache_root(b: &Backend) -> PathBuf { b.dir().join("rule-cache") }
|
||||
fn refresh_cache(b: &Backend, wanted: Option<&str>) -> R<Value> {
|
||||
let index = b.json("agent-rules")?;
|
||||
rule_cache::store_index(&cache_root(b), &index, now())?;
|
||||
if let Some(item) = wanted.and_then(|id| index["items"].as_array()?.iter().find(|item| item["id"] == id)) {
|
||||
let _ = cached_package(b, item)?;
|
||||
}
|
||||
Ok(index)
|
||||
}
|
||||
fn background_refresh(b: &Backend, wanted: Option<String>) {
|
||||
let root = cache_root(b);
|
||||
if fs::create_dir_all(&root).is_err() { return; }
|
||||
let lock = root.join("refresh.lock");
|
||||
// A process exit can leave a marker, but never a permanently locked cache.
|
||||
if fs::metadata(&lock).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > Duration::from_secs(120)) { let _ = fs::remove_file(&lock); }
|
||||
let Ok(marker) = fs::OpenOptions::new().write(true).create_new(true).open(&lock) else { return; };
|
||||
let backend = b.clone();
|
||||
std::thread::spawn(move || {
|
||||
let result = refresh_cache(&backend, wanted.as_deref());
|
||||
let status = match result { Ok(_) => json!({"checkedAt":now(),"state":"ready"}), Err(error) => json!({"checkedAt":now(),"state":"failed","error":error}) };
|
||||
let _ = write_json(&root.join("refresh-state.json"), &status);
|
||||
drop(marker); let _ = fs::remove_file(lock);
|
||||
});
|
||||
}
|
||||
fn cached_index(b: &Backend, wanted: Option<String>) -> R<Value> {
|
||||
if let Some((index, at)) = rule_cache::read_index(&cache_root(b))? {
|
||||
if now().saturating_sub(at) >= rule_cache::CHECK_SECONDS { background_refresh(b, wanted); }
|
||||
return Ok(index);
|
||||
}
|
||||
refresh_cache(b, wanted.as_deref())
|
||||
}
|
||||
fn cached_package(b: &Backend, item: &Value) -> R<Value> {
|
||||
if let Some(saved) = rule_cache::read_package(&cache_root(b), item)? { return Ok(saved); }
|
||||
let id = item["id"].as_str().ok_or("规则编号无效")?;
|
||||
let value = b.json(&format!("agent-rules?binding={id}"))?;
|
||||
let saved = rule_cache::package(id, &value, Some(item))?;
|
||||
rule_cache::store_package(&cache_root(b), &saved)?;
|
||||
Ok(saved)
|
||||
}
|
||||
fn original_rule(dir: &Path) -> R<Option<Value>> {
|
||||
let file = dir.join("agent-binding.json");
|
||||
if !file.exists() { return Ok(None); }
|
||||
let old = read_json(&file)?;
|
||||
Ok(Some(rule_cache::package(old["id"].as_str().ok_or("项目规则编号无效")?, &old, None)?))
|
||||
}
|
||||
fn can_change_rule(b: &Backend, doc: u64, dir: &Path) -> R<()> {
|
||||
let project = b.locations.get(&doc).ok_or("项目身份尚未绑定")?;
|
||||
if !super::pi::unresolved(&b.dir().join("pi-validation").join(project).join("requests"))?.is_empty() || super::creation::unresolved(dir)? || super::images::pending(dir)? || !super::projects::creation_barriers(dir)?.is_empty() {
|
||||
return Err("有原请求待核查,不能切换规则绕过".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn automatic_rule(b: &Backend, doc: u64, index: &Value) -> R<(Option<Value>, Value)> {
|
||||
let dir = b.project_dir(doc)?;
|
||||
let creation = super::creation::load(&dir)?;
|
||||
let brand = creation["brief"]["brandId"].as_str().unwrap_or("");
|
||||
let category = creation["brief"]["categoryId"].as_str().unwrap_or("");
|
||||
if brand.is_empty() || category.is_empty() { return Ok((None, json!({"state":"needs-category","reason":"请在产品资料中选择品牌和品类"}))); }
|
||||
let item = rule_cache::matching(index, brand, category)?;
|
||||
if let Some(saved) = original_rule(&dir)?.filter(|saved| rule_cache::matches_project(saved, brand, category)) {
|
||||
// A catalogue update never rewrites an existing project's fixed snapshot.
|
||||
if creation["designSnapshot"]["rules"] != saved { can_change_rule(b,doc,&dir)?; super::creation::attach_agent_rules(&dir, &saved)?; }
|
||||
return Ok((Some(saved.clone()), json!({"state":"ready","updateAvailable":rule_cache::update_available(&saved,item),"templateId":saved["id"],"contentHash":saved["contentHash"]})));
|
||||
}
|
||||
let Some(item) = item else { return Ok((None, json!({"state":"unavailable","reason":"此品牌与品类的模板待配置"}))); };
|
||||
can_change_rule(b, doc, &dir)?;
|
||||
let saved = cached_package(b, item)?;
|
||||
// Download outside the project write lock; re-read the actual project before
|
||||
// attaching so a late response cannot replace a newly selected product.
|
||||
can_change_rule(b, doc, &dir)?;
|
||||
super::creation::attach_agent_rules(&dir, &saved)?;
|
||||
write_json(&dir.join("agent-binding.json"), &saved)?;
|
||||
Ok((Some(saved.clone()), json!({"state":"ready","updateAvailable":false,"templateId":saved["id"],"contentHash":saved["contentHash"]})))
|
||||
}
|
||||
|
||||
fn invocation_from(catalog: &Value, model: &Value) -> R<Value> {
|
||||
let sections = catalog["data"]["sections"].as_array().or_else(|| catalog["sections"].as_array()).ok_or("98k公开模型目录格式已改变")?;
|
||||
@ -28,7 +105,12 @@ pub(super) fn invocation(b: &Backend, model: &Value) -> R<Value> {
|
||||
pub(super) fn rules(b: &mut Backend, input: &Value) -> R<Value> {
|
||||
let doc = input["doc"].as_u64().ok_or("请先打开项目")?;
|
||||
b.bind_new(doc); b.ensure_owner(doc)?; b.validate()?;
|
||||
let mut result = b.json("agent-rules")?;
|
||||
let dir = b.project_dir(doc)?;
|
||||
let wanted = original_rule(&dir)?.and_then(|s|s["id"].as_str().map(str::to_owned));
|
||||
let mut result = cached_index(b, wanted)?;
|
||||
let (rule, state) = automatic_rule(b, doc, &result)?;
|
||||
result["rule"] = rule.unwrap_or(Value::Null); result["ruleState"] = state;
|
||||
result["creation"] = super::creation::load(&dir)?;
|
||||
result["doc"] = json!(doc); result["accountId"] = b.auth["account"]["id"].clone(); result["origin"] = json!(b.origin);
|
||||
Ok(result)
|
||||
}
|
||||
@ -37,14 +119,18 @@ pub(super) fn select(b: &mut Backend, input: &Value) -> R<Value> {
|
||||
b.bind_new(doc); b.ensure_owner(doc)?; b.validate()?;
|
||||
let id = input["id"].as_str().filter(|s| !s.is_empty() && s.len() <= 100 && s.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_'))).ok_or("规则编号无效")?;
|
||||
let dir = b.project_dir(doc)?;
|
||||
let project = b.locations.get(&doc).ok_or("项目身份尚未绑定")?;
|
||||
if !super::pi::unresolved(&b.dir().join("pi-validation").join(project).join("requests"))?.is_empty() { return Err("有原请求待核查,不能切换规则绕过".into()); }
|
||||
can_change_rule(b, doc, &dir)?;
|
||||
let file = dir.join("agent-binding.json");
|
||||
if file.exists() { let old = read_json(&file)?; if old["id"] == id { return Ok(json!({"doc":doc,"rule":old})); } }
|
||||
let value = b.json(&format!("agent-rules?binding={id}"))?;
|
||||
let saved = json!({"id":id,"catalog":value["catalog"],"revision":value["revision"]});
|
||||
let index = cached_index(b, Some(id.into()))?;
|
||||
let c = super::creation::load(&dir)?;
|
||||
let item = rule_cache::matching(&index, c["brief"]["brandId"].as_str().unwrap_or(""), c["brief"]["categoryId"].as_str().unwrap_or(""))?.filter(|item| item["id"] == id).ok_or("此模板不属于当前项目的品牌和品类")?;
|
||||
if let Some(old) = original_rule(&dir)?.filter(|old| old["id"] == id)
|
||||
&& input["adoptUpdate"] != true { return Ok(json!({"doc":doc,"rule":old,"updateAvailable":rule_cache::update_available(&old,Some(item))})); }
|
||||
let saved = cached_package(b, item)?;
|
||||
can_change_rule(b, doc, &dir)?;
|
||||
super::creation::attach_agent_rules(&dir, &saved)?;
|
||||
write_json(&file, &saved)?;
|
||||
Ok(json!({"doc":doc,"rule":saved}))
|
||||
Ok(json!({"doc":doc,"rule":saved,"creation":super::creation::load(&dir)?}))
|
||||
}
|
||||
fn runtime() -> R<(PathBuf, PathBuf)> {
|
||||
let exe = std::env::current_exe().map_err(|_| "客户端位置不可用")?;
|
||||
@ -76,7 +162,14 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
|
||||
b.ensure_owner(doc)?; b.validate()?;
|
||||
let project = b.locations.get(&doc).ok_or("项目身份尚未绑定")?.clone();
|
||||
let dir = b.project_dir(doc)?;
|
||||
let saved = read_json(&dir.join("agent-binding.json")).map_err(|_| "请在对话栏选择项目的品牌和品类规则")?;
|
||||
let saved = if matches!(method,"pi-recover"|"pi-review") {
|
||||
original_rule(&dir)?.ok_or("原项目规则快照缺失,请保留原请求")?
|
||||
} else {
|
||||
let wanted = original_rule(&dir)?.and_then(|s|s["id"].as_str().map(str::to_owned));
|
||||
let index = cached_index(b,wanted)?;
|
||||
let (saved,state) = automatic_rule(b,doc,&index)?;
|
||||
saved.ok_or_else(||state["reason"].as_str().unwrap_or("项目模板尚未配置").to_string())?
|
||||
};
|
||||
let (node, script) = runtime()?;
|
||||
let binary = std::env::current_exe().map_err(|_| "客户端位置不可用")?;
|
||||
let profile = b.root.parent().ok_or("配置位置无效")?;
|
||||
|
||||
@ -87,6 +87,22 @@ fn cloud_matches(local: &Value, remote: &Value) -> bool {
|
||||
|| (link["source"] == "web" && link["id"] == remote["sourceWebId"]))
|
||||
}
|
||||
|
||||
/// A version conflict needs a fresh confirmation; an unresolved request needs
|
||||
/// read-only recovery. Refreshing cannot resolve an unknown model result.
|
||||
fn delete_error(status: u16, value: &Value) -> String {
|
||||
match status {
|
||||
401 | 403 => "授权已失效,未删除项目;请重新登录".into(),
|
||||
404 => "项目不存在或无权访问,请刷新列表".into(),
|
||||
409 => match value["code"].as_str() {
|
||||
Some("revision_conflict") => "项目已有新版本,未删除;请刷新列表后重新确认".into(),
|
||||
Some("project_busy") => "此项目有正在执行的任务,未删除;请等待原任务结束".into(),
|
||||
Some("task_busy") => "此项目有未结束或结果待核查的原请求,未删除;请先核查原请求,刷新列表不能解除此保护".into(),
|
||||
_ => "删除发生冲突,结果未确认;请刷新核对,不会自动重试".into(),
|
||||
},
|
||||
_ => format!("删除结果尚未确认(HTTP {status}),请刷新核对;未重试"),
|
||||
}
|
||||
}
|
||||
|
||||
fn trash_local(account: &Path, id: &str) -> R<()> {
|
||||
let _guard = sync::context_guard();
|
||||
let dir = local_path(&account.join("projects"), id)?;
|
||||
@ -168,6 +184,8 @@ impl Backend {
|
||||
} else if let Some(remote) = cloud.iter().find(|r| cloud_matches(&local, r)) {
|
||||
local["cloudPresent"] = json!(true);
|
||||
local["cloudRef"] = json!({"id":remote["id"],"source":remote["source"],"revision":remote["revision"]});
|
||||
local["deleteBlocked"] = json!(remote["deleteBlocked"] == true);
|
||||
local["deleteBlockedReason"] = remote["deleteBlockedReason"].clone();
|
||||
represented.insert(format!("{}:{}", remote["source"], remote["id"]));
|
||||
}
|
||||
out.push(local);
|
||||
@ -268,12 +286,7 @@ impl Backend {
|
||||
.map_err(|_| "删除结果尚未确认,请刷新项目列表核对;未重试")?;
|
||||
let (status, value) = body(response, MAX_JSON)?;
|
||||
if status != 200 || value["deleted"] != true {
|
||||
return Err(match status {
|
||||
401 | 403 => "授权已失效,未删除项目;请重新登录".into(),
|
||||
404 => "项目不存在或无权访问,请刷新列表".into(),
|
||||
409 => "项目已更新,或有运行中/待核查任务;请刷新后核对".into(),
|
||||
_ => format!("删除结果尚未确认(HTTP {status}),请刷新核对;未重试"),
|
||||
});
|
||||
return Err(delete_error(status, &value));
|
||||
}
|
||||
deleted_projects = value["deletedProjects"].as_array().cloned().unwrap_or_else(|| vec![remote.clone()]);
|
||||
if deleted_projects.is_empty() { deleted_projects.push(remote.clone()); }
|
||||
@ -288,6 +301,19 @@ impl Backend {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn deletion_conflicts_keep_the_authoritative_reason_and_do_not_echo_untrusted_details() {
|
||||
assert!(delete_error(409, &json!({"code":"revision_conflict"})).contains("新版本"));
|
||||
assert!(delete_error(409, &json!({"code":"project_busy"})).contains("正在执行"));
|
||||
let unknown = delete_error(409, &json!({"code":"task_busy"}));
|
||||
assert!(unknown.contains("原请求") && unknown.contains("刷新列表不能解除"));
|
||||
assert!(!unknown.contains("新版本"));
|
||||
let detail = "arbitrary internal error or secret";
|
||||
for status in [200, 401, 403, 404, 409, 503] {
|
||||
assert!(!delete_error(status, &json!({"code":"unrecognized", "error":detail})).contains(detail));
|
||||
}
|
||||
assert!(delete_error(409, &json!({"error":"revision_conflict"})).contains("不会自动重试"), "an untyped conflict must not be guessed to be a stale revision");
|
||||
}
|
||||
fn creation_barrier_fixture() -> (PathBuf, PathBuf, Value, Value) {
|
||||
let account = std::env::temp_dir().join(format!("creation-lifecycle-{}", Uuid::new_v4()));
|
||||
let dir = account.join("projects").join(Uuid::new_v4().to_string());
|
||||
@ -368,12 +394,13 @@ mod tests {
|
||||
#[test]
|
||||
fn linked_projects_merge_only_after_cloud_confirmation_and_tombstones_preserve_unknown_tasks() {
|
||||
let mut b=fixture(); let (doc,mut local)=create(&mut b);
|
||||
let remote=json!({"id":Uuid::new_v4().to_string(),"source":"web","revision":3});
|
||||
let remote=json!({"id":Uuid::new_v4().to_string(),"source":"web","revision":3,"deleteBlocked":true,"deleteBlockedReason":"pending_request"});
|
||||
let dir=b.project_dir(doc.id.0).unwrap();
|
||||
let mut context=read_json(&dir.join("context.json")).unwrap(); context["project"]=remote.clone(); write_json(&dir.join("context.json"),&context).unwrap();
|
||||
local["cloudLink"]=remote.clone();
|
||||
let merged=b.reconcile_projects(vec![local.clone()],vec![remote.clone()],&[]).unwrap();
|
||||
assert_eq!(merged.len(),1); assert_eq!(merged[0]["cloudPresent"],true);
|
||||
assert_eq!(merged[0]["deleteBlocked"],true); assert_eq!(merged[0]["deleteBlockedReason"],"pending_request");
|
||||
assert_eq!(b.reconcile_projects(vec![local.clone()],vec![],&[]).unwrap()[0]["cloudPresent"],false);
|
||||
assert!(b.delete_project(&local).unwrap_err().contains("尚未核对"));
|
||||
write_json(&dir.join("task.json"),&json!({"phase":"unknown","requestId":"original"})).unwrap();
|
||||
@ -446,7 +473,7 @@ mod tests {
|
||||
let expected_id = id.clone();
|
||||
let server = std::thread::spawn(move || {
|
||||
let mut requests = Vec::new();
|
||||
for (status, response) in [(200, json!({"account":{"id":"local-fixture"}})), (409, json!({"error":"revision_conflict"}))] {
|
||||
for (status, response) in [(200, json!({"account":{"id":"local-fixture"}})), (409, json!({"error":"项目已有新版本", "code":"revision_conflict"}))] {
|
||||
let (mut socket, _) = listener.accept().unwrap();
|
||||
socket.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let mut raw = Vec::new();
|
||||
@ -480,7 +507,7 @@ mod tests {
|
||||
let mut b = fixture();
|
||||
b.origin = format!("http://{address}");
|
||||
b.auth["access_token"] = json!("fixture-token");
|
||||
assert!(b.delete_project(&json!({"source":"web","id":id,"revision":7})).unwrap_err().contains("已更新"));
|
||||
assert!(b.delete_project(&json!({"source":"web","id":id,"revision":7})).unwrap_err().contains("新版本"));
|
||||
server.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
105
apps/detail-photocraft/apps/photocraft/src/jiansun_reads.rs
Normal file
105
apps/detail-photocraft/apps/photocraft/src/jiansun_reads.rs
Normal file
@ -0,0 +1,105 @@
|
||||
//! Bounded workers for authenticated catalogue/image GETs. Never run model tasks here.
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
|
||||
type Task = Box<dyn FnOnce() + Send + 'static>;
|
||||
|
||||
pub(super) struct ReadPool {
|
||||
queue: mpsc::SyncSender<Task>,
|
||||
}
|
||||
|
||||
impl ReadPool {
|
||||
pub(super) fn catalog() -> Self {
|
||||
Self::with_limits(1, 4)
|
||||
}
|
||||
|
||||
pub(super) fn images() -> Self {
|
||||
Self::with_limits(2, 4)
|
||||
}
|
||||
|
||||
fn with_limits(workers: usize, pending: usize) -> Self {
|
||||
let (queue, receive) = mpsc::sync_channel::<Task>(pending);
|
||||
let receive = Arc::new(Mutex::new(receive));
|
||||
for _ in 0..workers {
|
||||
let receive = receive.clone();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
let task = match receive.lock() {
|
||||
Ok(receiver) => receiver.recv(),
|
||||
Err(_) => return,
|
||||
};
|
||||
match task {
|
||||
Ok(task) => task(),
|
||||
Err(_) => return,
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Self { queue }
|
||||
}
|
||||
|
||||
/// Main receive/save processing must never wait for an image download.
|
||||
pub(super) fn submit(&self, task: impl FnOnce() + Send + 'static) -> Result<(), &'static str> {
|
||||
self.queue.try_send(Box::new(task)).map_err(|error| match error {
|
||||
mpsc::TrySendError::Full(_) => "素材正在加载,请稍后再试",
|
||||
mpsc::TrySendError::Disconnected(_) => "素材加载服务已停止,请保留作品后重启",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[test]
|
||||
fn two_slow_images_do_not_block_save_dispatch_or_catalog_search() {
|
||||
let pool = ReadPool::images();
|
||||
let catalog = ReadPool::catalog();
|
||||
let (started, running) = mpsc::channel();
|
||||
let mut releases = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let (release, gate) = mpsc::channel();
|
||||
releases.push(release);
|
||||
let started = started.clone();
|
||||
pool.submit(move || {
|
||||
started.send(()).unwrap();
|
||||
gate.recv().unwrap();
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
for _ in 0..2 {
|
||||
running.recv_timeout(Duration::from_secs(2)).unwrap();
|
||||
}
|
||||
let (finished, result) = mpsc::channel();
|
||||
catalog
|
||||
.submit(move || {
|
||||
finished.send("search").unwrap();
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(result.recv_timeout(Duration::from_secs(2)).unwrap(), "search");
|
||||
let (save, saved) = mpsc::channel();
|
||||
save.send("local-save").unwrap();
|
||||
assert_eq!(saved.try_recv().unwrap(), "local-save");
|
||||
for release in releases {
|
||||
release.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_image_queue_rejects_immediately_instead_of_growing_or_blocking() {
|
||||
let pool = ReadPool::with_limits(1, 1);
|
||||
let (started, running) = mpsc::channel();
|
||||
let (release, gate) = mpsc::channel();
|
||||
pool.submit(move || {
|
||||
started.send(()).unwrap();
|
||||
gate.recv().unwrap();
|
||||
})
|
||||
.unwrap();
|
||||
running.recv_timeout(Duration::from_secs(2)).unwrap();
|
||||
pool.submit(|| {}).unwrap();
|
||||
let before = Instant::now();
|
||||
assert_eq!(pool.submit(|| {}), Err("素材正在加载,请稍后再试"));
|
||||
assert!(before.elapsed() < Duration::from_millis(100));
|
||||
release.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
181
apps/detail-photocraft/apps/photocraft/src/jiansun_rule_cache.rs
Normal file
181
apps/detail-photocraft/apps/photocraft/src/jiansun_rule_cache.rs
Normal file
@ -0,0 +1,181 @@
|
||||
//! Account-scoped, content-addressed copies of the production rule metadata.
|
||||
//! These are rule/screen manifests, not complete PSD or reference-image packs.
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{fs, path::{Path, PathBuf}};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
const LIMIT: u64 = 2 * 1024 * 1024;
|
||||
pub(super) const CHECK_SECONDS: u64 = 300;
|
||||
|
||||
fn digest(value: &Value) -> R<String> {
|
||||
let bytes = serde_json::to_vec(value).map_err(|_| "规则内容无法校验")?;
|
||||
Ok(format!("{:x}", Sha256::digest(bytes)))
|
||||
}
|
||||
fn id(value: &Value) -> R<&str> {
|
||||
value.as_str().filter(|s| !s.is_empty() && s.len() <= 100 && s.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_'))).ok_or("规则编号无效".into())
|
||||
}
|
||||
fn sha(value: &Value) -> R<&str> {
|
||||
value.as_str().filter(|s| s.len() == 64 && s.bytes().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())).ok_or("规则内容校验值无效".into())
|
||||
}
|
||||
fn read(file: &Path) -> R<Value> {
|
||||
if fs::metadata(file).map_err(|_| "规则缓存无法读取")?.len() > LIMIT { return Err("规则缓存超过限制".into()); }
|
||||
serde_json::from_slice(&fs::read(file).map_err(|_| "规则缓存无法读取")?).map_err(|_| "规则缓存格式无效".into())
|
||||
}
|
||||
fn write(file: &Path, value: &Value) -> R<()> {
|
||||
let bytes = serde_json::to_vec(value).map_err(|_| "规则缓存无法保存")?;
|
||||
if bytes.len() as u64 > LIMIT { return Err("规则缓存超过限制".into()); }
|
||||
let parent = file.parent().ok_or("规则缓存位置无效")?;
|
||||
fs::create_dir_all(parent).map_err(|_| "规则缓存目录无法创建")?;
|
||||
let temp = parent.join(format!(".rules-{}.tmp", uuid::Uuid::new_v4()));
|
||||
fs::write(&temp, bytes).map_err(|_| "规则缓存无法保存")?;
|
||||
if fs::rename(&temp, file).is_err() { let _ = fs::remove_file(&temp); return Err("规则缓存无法提交".into()); }
|
||||
Ok(())
|
||||
}
|
||||
fn only<'a>(value: &'a Value, field: &str) -> R<&'a Value> {
|
||||
value[field].as_array().filter(|a| a.len() == 1).and_then(|a| a.first()).ok_or("规则必须属于唯一品牌和品类".into())
|
||||
}
|
||||
pub(super) fn project_brand(item: &Value) -> &Value { item.get("projectBrandId").unwrap_or(&item["shopId"]) }
|
||||
|
||||
pub(super) fn validate_index(value: &Value) -> R<()> {
|
||||
sha(&value["revision"])?;
|
||||
let items = value["items"].as_array().filter(|a| a.len() <= 1000).ok_or("规则目录格式无效")?;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for item in items {
|
||||
if !seen.insert(id(&item["id"])?) { return Err("规则目录包含重复编号".into()); }
|
||||
for field in ["shopId", "categoryId"] { uuid::Uuid::parse_str(item[field].as_str().ok_or("规则身份无效")?).map_err(|_| "规则身份无效")?; }
|
||||
if project_brand(item) != &item["shopId"] || item["brandId"] != format!("enterprise:{}", item["shopId"].as_str().ok_or("品牌身份无效")?) { return Err("规则品牌身份不一致".into()); }
|
||||
sha(&item["version"])?;
|
||||
if !item["contentHash"].is_null() { sha(&item["contentHash"])?; }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn store_index(root: &Path, value: &Value, at: u64) -> R<()> {
|
||||
validate_index(value)?;
|
||||
write(&root.join("index.json"), &json!({"index":value,"sha256":digest(value)?,"checkedAt":at}))
|
||||
}
|
||||
pub(super) fn read_index(root: &Path) -> R<Option<(Value, u64)>> {
|
||||
let file = root.join("index.json");
|
||||
if !file.exists() { return Ok(None); }
|
||||
let value = read(&file)?;
|
||||
if value["sha256"] != digest(&value["index"])? { return Err("规则目录缓存已损坏,未使用".into()); }
|
||||
validate_index(&value["index"])?;
|
||||
Ok(Some((value["index"].clone(), value["checkedAt"].as_u64().ok_or("规则检查时间无效")?)))
|
||||
}
|
||||
pub(super) fn matching<'a>(index: &'a Value, brand: &str, category: &str) -> R<Option<&'a Value>> {
|
||||
if brand.is_empty() || category.is_empty() { return Ok(None); }
|
||||
let mut matches = index["items"].as_array().ok_or("规则目录格式无效")?.iter().filter(|item| project_brand(item) == brand && item["categoryId"] == category);
|
||||
let found = matches.next();
|
||||
if matches.next().is_some() { return Err("此品牌与品类存在多个模板,需先明确项目模板,未自动替选".into()); }
|
||||
Ok(found)
|
||||
}
|
||||
pub(super) fn package(id_value: &str, value: &Value, item: Option<&Value>) -> R<Value> {
|
||||
id(&json!(id_value))?;
|
||||
let catalog = &value["catalog"];
|
||||
let binding = only(catalog, "bindings")?;
|
||||
let shop = only(catalog, "shops")?;
|
||||
let brand = only(catalog, "brands")?;
|
||||
let category = only(catalog, "categories")?;
|
||||
if binding["id"] != id_value || binding["state"] != "ready" || binding["shopId"] != shop["id"] || binding["categoryId"] != category["id"] || shop["brandId"] != brand["id"] || brand["id"] != format!("enterprise:{}", shop["id"].as_str().ok_or("品牌身份无效")?) { return Err("规则快照的品牌、品类或模板身份不一致".into()); }
|
||||
sha(&binding["revision"])?;
|
||||
sha(&value["revision"])?;
|
||||
let hash = digest(catalog)?;
|
||||
if value.get("contentHash").is_some_and(|v| v != &hash) { return Err("规则内容校验失败,未写入缓存".into()); }
|
||||
if let Some(item) = item
|
||||
&& (item["id"] != id_value || item["shopId"] != shop["id"] || item["categoryId"] != category["id"] || item["brandId"] != brand["id"] || item["version"] != binding["revision"] || item.get("contentHash").is_some_and(|v| v != &hash)) { return Err("模板版本已更新,请重新读取目录,未替换项目快照".into()); }
|
||||
Ok(json!({"schemaVersion":1,"id":id_value,"catalog":catalog,"revision":value["revision"],"contentHash":hash}))
|
||||
}
|
||||
pub(super) fn matches_project(saved: &Value, brand: &str, category: &str) -> bool {
|
||||
saved["catalog"]["shops"].as_array().and_then(|a| a.first()).is_some_and(|s| s["id"] == brand)
|
||||
&& saved["catalog"]["categories"].as_array().and_then(|a| a.first()).is_some_and(|s| s["id"] == category)
|
||||
}
|
||||
fn pointer(root: &Path, id_value: &str) -> R<PathBuf> { id(&json!(id_value))?; Ok(root.join("bindings").join(format!("{id_value}.json"))) }
|
||||
pub(super) fn store_package(root: &Path, saved: &Value) -> R<()> {
|
||||
let normalized = package(id(&saved["id"])?, saved, None)?;
|
||||
let hash = sha(&normalized["contentHash"])?;
|
||||
write(&root.join("objects").join(format!("{hash}.json")), &normalized)?;
|
||||
write(&pointer(root, id(&saved["id"])?)?, &json!({"contentHash":hash}))
|
||||
}
|
||||
pub(super) fn read_package(root: &Path, item: &Value) -> R<Option<Value>> {
|
||||
let p = pointer(root, id(&item["id"])?)?;
|
||||
if !p.exists() { return Ok(None); }
|
||||
let ptr = read(&p)?;
|
||||
let hash = sha(&ptr["contentHash"])?;
|
||||
if item.get("contentHash").is_some_and(|expected| expected != hash) { return Ok(None); }
|
||||
let saved = read(&root.join("objects").join(format!("{hash}.json")))?;
|
||||
let normalized = package(id(&item["id"])?, &saved, Some(item))?;
|
||||
if normalized["contentHash"] != hash { return Err("规则包缓存已损坏,未使用".into()); }
|
||||
Ok(Some(normalized))
|
||||
}
|
||||
pub(super) fn update_available(saved: &Value, item: Option<&Value>) -> bool {
|
||||
item.is_some_and(|item| item["id"] == saved["id"] && item.get("contentHash").map_or_else(|| item["version"] != saved["catalog"]["bindings"][0]["revision"], |hash| hash != &saved["contentHash"]))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn fixture() -> (Value, Value) {
|
||||
let shop = "42bb46b2-89cd-47cf-9ad8-f2e95b8c5a3a";
|
||||
let category = "78f8044c-62d3-49fa-9b25-3e011bc0a0cf";
|
||||
let binding = json!({"id":"REAL-DESK","shopId":shop,"categoryId":category,"revision":"a".repeat(64),"state":"ready","rules":["test rule metadata only"]});
|
||||
let catalog = json!({"brands":[{"id":format!("enterprise:{shop}")}],"shops":[{"id":shop,"brandId":format!("enterprise:{shop}")}],"categories":[{"id":category}],"bindings":[binding]});
|
||||
let package = json!({"revision":"b".repeat(64),"catalog":catalog,"contentHash":digest(&catalog).unwrap()});
|
||||
let index = json!({"revision":"b".repeat(64),"items":[{"id":"REAL-DESK","shopId":shop,"projectBrandId":shop,"brandId":format!("enterprise:{shop}"),"categoryId":category,"version":"a".repeat(64),"contentHash":package["contentHash"]}]});
|
||||
(index, package)
|
||||
}
|
||||
fn temp() -> PathBuf {
|
||||
let root = std::env::var_os("JIANSUN_RULE_TEST_ROOT").expect("test output root is required");
|
||||
let path = PathBuf::from(root).join(format!("case-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir_all(&path).unwrap(); path
|
||||
}
|
||||
#[test]
|
||||
fn identity_is_exact_and_missing_or_ambiguous_category_never_borrows_another_template() {
|
||||
let (mut index, _) = fixture(); validate_index(&index).unwrap();
|
||||
let item = &index["items"][0]; let brand = item["shopId"].as_str().unwrap().to_owned(); let category = item["categoryId"].as_str().unwrap().to_owned();
|
||||
assert!(matching(&index, &brand, "").unwrap().is_none());
|
||||
assert!(matching(&index, &brand, "化妆台").unwrap().is_none());
|
||||
assert!(matching(&index, "顾家", &category).unwrap().is_none());
|
||||
assert!(matching(&index, &brand, &category).unwrap().is_some());
|
||||
let duplicate = index["items"][0].clone(); index["items"].as_array_mut().unwrap().push(duplicate);
|
||||
assert!(matching(&index, &brand, &category).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn local_cache_round_trip_and_tampered_content_fail_closed() {
|
||||
let root = temp(); let (index, value) = fixture(); let item = &index["items"][0];
|
||||
store_index(&root, &index, 123).unwrap(); assert_eq!(read_index(&root).unwrap().unwrap(), (index.clone(),123));
|
||||
let saved = package("REAL-DESK", &value, Some(item)).unwrap(); store_package(&root, &saved).unwrap();
|
||||
assert_eq!(read_package(&root, item).unwrap().unwrap(), saved);
|
||||
let mut altered = saved.clone(); altered["catalog"]["bindings"][0]["rules"] = json!(["changed"]);
|
||||
assert!(package("REAL-DESK", &altered, Some(item)).is_err());
|
||||
assert!(package("../other", &saved, None).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn downloaded_update_never_rewrites_the_projects_fixed_snapshot() {
|
||||
let root = temp(); let (mut index, mut value) = fixture();
|
||||
let old = package("REAL-DESK", &value, Some(&index["items"][0])).unwrap();
|
||||
let project = root.join("project-agent-binding.json"); write(&project, &old).unwrap(); store_package(&root, &old).unwrap();
|
||||
value["catalog"]["bindings"][0]["revision"] = json!("c".repeat(64)); value["contentHash"] = json!(digest(&value["catalog"]).unwrap());
|
||||
index["items"][0]["version"] = json!("c".repeat(64)); index["items"][0]["contentHash"] = value["contentHash"].clone();
|
||||
assert!(read_package(&root, &index["items"][0]).unwrap().is_none());
|
||||
assert!(update_available(&old, Some(&index["items"][0])));
|
||||
let new = package("REAL-DESK", &value, Some(&index["items"][0])).unwrap(); store_package(&root, &new).unwrap();
|
||||
assert_eq!(read(&project).unwrap(), old); assert_ne!(read_package(&root, &index["items"][0]).unwrap().unwrap(), old);
|
||||
}
|
||||
#[test]
|
||||
fn mismatched_scope_and_changed_package_revisions_are_rejected() {
|
||||
let (index, mut value) = fixture(); let item = &index["items"][0];
|
||||
value["catalog"]["categories"][0]["id"] = json!("other"); value.as_object_mut().unwrap().remove("contentHash");
|
||||
assert!(package("REAL-DESK", &value, Some(item)).is_err());
|
||||
let (_, mut value) = fixture(); value["catalog"]["bindings"][0]["revision"] = json!("c".repeat(64)); value.as_object_mut().unwrap().remove("contentHash");
|
||||
assert!(package("REAL-DESK", &value, Some(item)).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn real_server_catalog_uses_the_same_canonical_hash_and_only_documented_coverage() {
|
||||
let file = std::env::var_os("JIANSUN_REAL_RULE_FIXTURE").expect("real rule fixture path is required");
|
||||
let value = read(Path::new(&file)).unwrap();
|
||||
let saved = package("GJ-DESK-DNZ0385", &value, None).unwrap();
|
||||
assert_eq!(saved["contentHash"],value["contentHash"]);
|
||||
assert_eq!(saved["catalog"]["bindings"].as_array().unwrap().len(),1);
|
||||
assert_eq!(saved["catalog"]["shops"][0]["name"],"顾家");
|
||||
}
|
||||
}
|
||||
@ -237,6 +237,10 @@ pub struct Workspace {
|
||||
projects: Vec<Value>,
|
||||
models: Vec<Value>,
|
||||
material_rows: Vec<Value>,
|
||||
material_search_pending: Option<u64>,
|
||||
material_preview_pending: Option<u64>,
|
||||
material_read_sequence: u64,
|
||||
material_error: String,
|
||||
origin: String,
|
||||
model: String,
|
||||
model_ready: bool,
|
||||
@ -290,6 +294,7 @@ pub struct Workspace {
|
||||
cover_errors: std::collections::HashMap<String, String>,
|
||||
project_query: String,
|
||||
delete_confirm: Option<Value>,
|
||||
delete_error: String,
|
||||
open_projects: std::collections::HashMap<u64, String>,
|
||||
project_geometry: Value,
|
||||
project_refresh: Instant,
|
||||
@ -297,7 +302,9 @@ pub struct Workspace {
|
||||
pi_touched: Instant,
|
||||
pi_binding: Value,
|
||||
agent_rule: Value,
|
||||
agent_rule_state: Value,
|
||||
agent_rules: Vec<Value>,
|
||||
agent_categories: Vec<Value>,
|
||||
pi_unknown: bool,
|
||||
pi_review: bool,
|
||||
pi_usage: Value,
|
||||
@ -343,6 +350,10 @@ impl Workspace {
|
||||
projects: vec![],
|
||||
models: vec![],
|
||||
material_rows: vec![],
|
||||
material_search_pending: None,
|
||||
material_preview_pending: None,
|
||||
material_read_sequence: 0,
|
||||
material_error: String::new(),
|
||||
origin: "https://sc.jiansun.vip".into(),
|
||||
model: String::new(),
|
||||
model_ready: false,
|
||||
@ -396,6 +407,7 @@ impl Workspace {
|
||||
cover_errors: std::collections::HashMap::new(),
|
||||
project_query: String::new(),
|
||||
delete_confirm: None,
|
||||
delete_error: String::new(),
|
||||
open_projects: std::collections::HashMap::new(),
|
||||
project_geometry: json!({}),
|
||||
project_refresh: Instant::now(),
|
||||
@ -403,7 +415,9 @@ impl Workspace {
|
||||
pi_touched: Instant::now(),
|
||||
pi_binding: Value::Null,
|
||||
agent_rule: Value::Null,
|
||||
agent_rule_state: Value::Null,
|
||||
agent_rules: vec![],
|
||||
agent_categories: vec![],
|
||||
pi_unknown: false,
|
||||
pi_review: false,
|
||||
pi_usage: Value::Null,
|
||||
@ -441,22 +455,65 @@ impl Workspace {
|
||||
out
|
||||
}
|
||||
fn send(&mut self, method: &str, input: Value) {
|
||||
if self.busy.is_some() {
|
||||
if matches!(method, "materials" | "preview") {
|
||||
self.send_material_read(method, input);
|
||||
return;
|
||||
}
|
||||
self.error.clear();
|
||||
if self.busy.is_some() || (method == "place" && self.material_preview_pending.is_some()) {
|
||||
return;
|
||||
}
|
||||
if method == "project-delete" {
|
||||
self.delete_error.clear();
|
||||
} else {
|
||||
self.error.clear();
|
||||
}
|
||||
self.busy = Some(if method == "open" && input["autoResume"] == true { "startup-open" } else { method }.into());
|
||||
if self.tx.send(Request::Action(method.into(), input)).is_err() {
|
||||
self.busy = None;
|
||||
self.error = "本机服务已停止,请保留作品后重启".into();
|
||||
if method == "project-delete" {
|
||||
self.delete_error = "本机服务已停止,请保留作品后重启".into();
|
||||
} else {
|
||||
self.error = "本机服务已停止,请保留作品后重启".into();
|
||||
}
|
||||
}
|
||||
}
|
||||
fn send_material_read(&mut self, method: &str, mut input: Value) {
|
||||
if !input.is_object() {
|
||||
self.material_error = "素材查询参数无效".into();
|
||||
return;
|
||||
}
|
||||
let pending = if method == "materials" { &mut self.material_search_pending } else { &mut self.material_preview_pending };
|
||||
if pending.is_some() { return; }
|
||||
self.material_read_sequence = self.material_read_sequence.wrapping_add(1);
|
||||
let read_id = self.material_read_sequence;
|
||||
*pending = Some(read_id);
|
||||
input["readId"] = json!(read_id);
|
||||
self.material_error.clear();
|
||||
if self.tx.send(Request::Action(method.into(), input)).is_err() {
|
||||
*pending = None;
|
||||
self.material_error = "本机服务已停止,请保留作品后重启".into();
|
||||
}
|
||||
}
|
||||
fn finish_material_read(&mut self, method: &str, value: &Value, active_doc: Option<u64>) -> bool {
|
||||
let pending = if method == "materials" { &mut self.material_search_pending } else { &mut self.material_preview_pending };
|
||||
if pending.is_none() || value["readId"].as_u64() != *pending { return false; }
|
||||
*pending = None;
|
||||
value["accountId"] == self.account["id"] && value["origin"] == self.origin
|
||||
&& (method != "preview" || value["doc"].as_u64() == active_doc)
|
||||
}
|
||||
pub fn state(&self) -> Value {
|
||||
let mut state = self.base_state();
|
||||
state["pi"] = json!({"run":self.pi_run,"allowed":self.allow_apply,"revision":self.expected_revision});
|
||||
state["agentEngine"] = json!("pi");
|
||||
state["agentRule"] = json!({"id":self.agent_rule["id"],"revision":self.agent_rule["revision"]});
|
||||
state["agentRuleState"] = self.agent_rule_state.clone();
|
||||
state["agentRules"] = json!(self.agent_rules);
|
||||
state["agentCategories"] = json!(self.agent_categories);
|
||||
state["deleteError"] = json!(self.delete_error);
|
||||
state["materialLoading"] = json!({"search":self.material_search_pending.is_some(),"preview":self.material_preview_pending.is_some()});
|
||||
state["materialError"] = json!(self.material_error);
|
||||
state["materialRows"] = json!(self.material_rows);
|
||||
state["materialPreview"] = self.preview.as_ref().map(|(reference, texture)| json!({"reference":reference,"size":texture.size()})).unwrap_or(Value::Null);
|
||||
state["piReview"] = json!(self.pi_review);
|
||||
state["piUsage"] = self.pi_usage.clone();
|
||||
state["creation"] = self.creation.clone();
|
||||
@ -663,6 +720,17 @@ impl Workspace {
|
||||
}
|
||||
Event::CreationCanvas(doc, meta) => creation::canvas_received(self, app, doc, meta),
|
||||
Event::Json(method, result) => {
|
||||
if matches!(method.as_str(), "materials" | "preview") {
|
||||
if let Ok(value) = result
|
||||
&& self.finish_material_read(&method, &value, app.session.active().map(|s| s.doc.id.0)) {
|
||||
if let Some(error) = value["error"].as_str() {
|
||||
self.material_error = error.into();
|
||||
} else if method == "materials" {
|
||||
self.material_rows = value["items"].as_array().cloned().unwrap_or_default();
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if method == "startup-open" && (self.startup_interacted || !app.session.documents().is_empty()) {
|
||||
finish_open_busy(&mut self.busy, true);
|
||||
continue;
|
||||
@ -684,7 +752,9 @@ impl Workspace {
|
||||
if method == "creation-thumbnail" {
|
||||
self.creation_thumb_failed.extend(self.creation_thumb_loading.drain());
|
||||
}
|
||||
if method == "login" || method == "logout" {
|
||||
if method == "project-delete" {
|
||||
self.delete_error = e;
|
||||
} else if method == "login" || method == "logout" {
|
||||
self.account_error = e;
|
||||
} else {
|
||||
if method == "configure" {
|
||||
@ -712,6 +782,10 @@ impl Workspace {
|
||||
if self.account["id"] != v["account"]["id"] {
|
||||
self.api_key.clear();
|
||||
self.preview = None;
|
||||
self.material_rows.clear();
|
||||
self.material_search_pending = None;
|
||||
self.material_preview_pending = None;
|
||||
self.material_error.clear();
|
||||
self.agent_images.clear();
|
||||
self.requested_previews.clear();
|
||||
self.stream_reply.clear();
|
||||
@ -721,6 +795,7 @@ impl Workspace {
|
||||
self.cover_loading.clear();
|
||||
self.cover_errors.clear();
|
||||
self.delete_confirm = None;
|
||||
self.delete_error.clear();
|
||||
}
|
||||
self.account = v["account"].clone();
|
||||
if let Some(origin) = v["origin"].as_str() {
|
||||
@ -763,7 +838,6 @@ impl Workspace {
|
||||
}
|
||||
"project-cover" => self.cover_failed(&v),
|
||||
"project-delete" => self.project_deleted(app, &v),
|
||||
"materials" => self.material_rows = v["items"].as_array().cloned().unwrap_or_default(),
|
||||
"configure" => {
|
||||
self.connection_received(&v);
|
||||
self.api_key.clear();
|
||||
@ -840,6 +914,12 @@ impl Workspace {
|
||||
&& v["doc"].as_u64() == app.session.active().map(|s| s.doc.id.0)
|
||||
{
|
||||
self.agent_rules = v["items"].as_array().cloned().unwrap_or_default();
|
||||
self.agent_categories = v["categories"].as_array().cloned().unwrap_or_default();
|
||||
self.agent_rule = v["rule"].clone();
|
||||
self.agent_rule_state = v["ruleState"].clone();
|
||||
if v["creation"].is_object() && v["creation"]["revision"] != self.creation["revision"] {
|
||||
creation::received(self, app, "creation-rules", &v);
|
||||
}
|
||||
}
|
||||
}
|
||||
"pi-select" => {
|
||||
@ -1026,10 +1106,7 @@ impl Workspace {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if self.busy.as_deref() == Some("preview") {
|
||||
self.busy = None;
|
||||
}
|
||||
if reference["accountId"] == self.account["id"] && reference["origin"] == self.origin {
|
||||
if self.finish_material_read("preview", &reference, app.session.active().map(|s| s.doc.id.0)) {
|
||||
self.preview = Some((reference, ui.ctx().load_texture("material-preview", image, egui::TextureOptions::LINEAR)));
|
||||
}
|
||||
}
|
||||
@ -1065,6 +1142,8 @@ impl Workspace {
|
||||
}
|
||||
if self.observed_doc != current.map(|v| v.0) {
|
||||
self.handover();
|
||||
self.preview = None;
|
||||
self.material_preview_pending = None;
|
||||
self.observed_doc = current.map(|v| v.0);
|
||||
self.loaded_draft = None;
|
||||
self.messages.clear();
|
||||
@ -1089,6 +1168,8 @@ impl Workspace {
|
||||
self.creation_run = None;
|
||||
self.creation_progress.clear();
|
||||
self.agent_rule = Value::Null;
|
||||
self.agent_rule_state = Value::Null;
|
||||
self.agent_categories.clear();
|
||||
self.pi_unknown = false;
|
||||
self.pi_review = false;
|
||||
self.pi_usage = Value::Null;
|
||||
@ -1173,50 +1254,54 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
}
|
||||
fn navigation(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
let document_open = app.session.active().is_some();
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let account_name = self.account["name"].as_str().unwrap_or("登录");
|
||||
let short_name =
|
||||
if account_name.chars().count() > 8 { format!("{}…", account_name.chars().take(8).collect::<String>()) } else { account_name.to_owned() };
|
||||
let account_label = if self.account.is_null() { short_name } else { format!("账户 · {short_name}") };
|
||||
if ui.button(account_label).on_hover_text(account_name).clicked() {
|
||||
self.config = true;
|
||||
}
|
||||
let projects = self.library || (!document_open && !self.material);
|
||||
if document_open && ui.selectable_label(self.creation_open && !self.library && !self.material, "产品资料").clicked() {
|
||||
self.creation_open = !self.creation_open;
|
||||
self.library = false;
|
||||
self.material = false;
|
||||
self.creation_step = 0;
|
||||
}
|
||||
if ui.selectable_label(self.material, "添加素材").on_hover_text("从素材库取图,置入当前画布").clicked() {
|
||||
self.show_center(if self.material { CenterView::Canvas } else { CenterView::Materials }, document_open);
|
||||
}
|
||||
if ui.selectable_label(projects, "我的项目").on_hover_text(if projects && document_open { "返回当前画布" } else { "查看项目与本机草稿" }).clicked()
|
||||
{
|
||||
self.show_center(if projects && !self.material && document_open { CenterView::Canvas } else { CenterView::Projects }, document_open);
|
||||
}
|
||||
if document_open {
|
||||
ui.separator();
|
||||
self.sync_controls(app, ui);
|
||||
if self.saving.is_some() {
|
||||
ui.spinner();
|
||||
} else if self.saved.is_some() {
|
||||
ui.add(crate::icons::image("check", 14.0, Tokens::get(ui.ctx()).text_dim)).on_hover_text("已存本机");
|
||||
}
|
||||
if (!self.queue.is_empty() || self.busy.as_deref() == Some("creation-generate")) && ui.button("接手").clicked() {
|
||||
self.handover();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
fn header(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let document_open = app.session.active().is_some();
|
||||
egui::Panel::top("jiansun-navigation").exact_size(34.0).frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(10, 4))).show(
|
||||
ui,
|
||||
|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let projects = self.library || (!document_open && !self.material);
|
||||
if ui
|
||||
.selectable_label(projects, "我的项目")
|
||||
.on_hover_text(if projects && document_open { "返回当前画布" } else { "查看项目与本机草稿" })
|
||||
.clicked()
|
||||
{
|
||||
self.show_center(if projects && !self.material && document_open { CenterView::Canvas } else { CenterView::Projects }, document_open);
|
||||
}
|
||||
if ui.selectable_label(self.material, "添加素材").on_hover_text("从素材库取图,置入当前画布").clicked() {
|
||||
self.show_center(if self.material { CenterView::Canvas } else { CenterView::Materials }, document_open);
|
||||
}
|
||||
if document_open && ui.selectable_label(self.creation_open && !self.library && !self.material, "产品资料").clicked() {
|
||||
self.creation_open = !self.creation_open;
|
||||
self.library = false;
|
||||
self.material = false;
|
||||
self.creation_step = 0;
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let account_label = self.account["name"].as_str().map(|name| format!("账户 · {name}")).unwrap_or_else(|| "登录".into());
|
||||
if ui.button(account_label).clicked() {
|
||||
self.config = true;
|
||||
}
|
||||
if self.saving.is_some() {
|
||||
ui.spinner();
|
||||
} else if self.saved.is_some() {
|
||||
ui.weak("已存本机");
|
||||
}
|
||||
if document_open {
|
||||
self.sync_controls(app, ui);
|
||||
}
|
||||
if (!self.queue.is_empty() || self.busy.as_deref() == Some("creation-generate")) && ui.button("接手").clicked() {
|
||||
self.handover();
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
// The normal navigation lives in the tool-options row. Keep an escape hatch
|
||||
// only when the user has explicitly hidden that native toolbar.
|
||||
if !app.ui.panels.options_bar {
|
||||
egui::Panel::top("jiansun-navigation")
|
||||
.exact_size(30.0)
|
||||
.frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(10, 0)))
|
||||
.show(ui, |ui| self.navigation(app, ui));
|
||||
}
|
||||
if self.config {
|
||||
let mut open = true;
|
||||
egui::Window::new("素材库账户").open(&mut open).collapsible(false).resizable(false).default_width(380.0).show(ui.ctx(), |ui| {
|
||||
@ -1273,7 +1358,7 @@ impl Workspace {
|
||||
}
|
||||
});
|
||||
text_edit(ui, egui::TextEdit::singleline(&mut self.query).hint_text("输入产品编号"));
|
||||
if ui.add_enabled(self.busy.is_none() && !self.query.trim().is_empty(), egui::Button::new("搜索")).clicked() {
|
||||
if ui.add_enabled(self.material_search_pending.is_none() && !self.query.trim().is_empty(), egui::Button::new("搜索")).clicked() {
|
||||
self.send("materials", json!({"identifierType":self.identifier_type,"identifier":self.query}));
|
||||
}
|
||||
if ui.button("返回画布").clicked() {
|
||||
@ -1284,7 +1369,7 @@ impl Workspace {
|
||||
if let Some((reference, texture)) = &self.preview {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::Image::new(texture).max_size(egui::vec2(280.0, 240.0)));
|
||||
if ui.add_enabled(self.busy.is_none() && app.session.active().is_some(), egui::Button::new("置入画布")).clicked() {
|
||||
if ui.add_enabled(self.busy.is_none() && self.material_preview_pending.is_none() && app.session.active().is_some(), egui::Button::new("置入画布")).clicked() {
|
||||
chosen = Some(("place", reference.clone()));
|
||||
}
|
||||
});
|
||||
@ -1295,7 +1380,7 @@ impl Workspace {
|
||||
ui.label(item["productModel"].as_str().or_else(|| item["name"].as_str()).unwrap_or("产品资料"));
|
||||
if let Some(assets) = item["assets"].as_array() {
|
||||
for asset in assets {
|
||||
if ui.add_enabled(self.busy.is_none(), egui::Button::new(asset["name"].as_str().unwrap_or("置入图片"))).clicked() {
|
||||
if ui.add_enabled(self.material_preview_pending.is_none(), egui::Button::new(asset["name"].as_str().unwrap_or("置入图片"))).clicked() {
|
||||
chosen = Some(("preview",json!({"materialId":item["materialId"],"productModel":item["productModel"],"skuCode":item["skuCode"],"variant":item["variant"],"asset":asset,"doc":app.session.active().map(|s|s.doc.id.0)})));
|
||||
}
|
||||
}
|
||||
@ -1306,7 +1391,10 @@ impl Workspace {
|
||||
if let Some((method, value)) = chosen {
|
||||
self.send(method, value);
|
||||
}
|
||||
if self.busy.is_some() {
|
||||
if !self.material_error.is_empty() {
|
||||
ui.colored_label(ui.visuals().error_fg_color, &self.material_error);
|
||||
}
|
||||
if self.busy.is_some() || self.material_search_pending.is_some() || self.material_preview_pending.is_some() {
|
||||
ui.spinner();
|
||||
}
|
||||
}
|
||||
@ -1320,6 +1408,22 @@ pub fn prepare(app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
app.jiansun = Some(w);
|
||||
}
|
||||
}
|
||||
/// Reserved, non-scrolling right edge of the native tool-options row.
|
||||
pub(crate) fn navigation_width(app: &PhotocraftApp) -> f32 {
|
||||
if app.jiansun.is_none() {
|
||||
0.0
|
||||
} else if app.session.active().is_some() {
|
||||
540.0
|
||||
} else {
|
||||
256.0
|
||||
}
|
||||
}
|
||||
pub(crate) fn navigation(app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
if let Some(mut workspace) = app.jiansun.take() {
|
||||
workspace.navigation(app, ui);
|
||||
app.jiansun = Some(workspace);
|
||||
}
|
||||
}
|
||||
pub fn center(app: &mut PhotocraftApp, ui: &mut Ui) -> bool {
|
||||
let Some(mut w) = app.jiansun.take() else {
|
||||
return false;
|
||||
@ -1427,6 +1531,96 @@ pub fn action(app: &mut PhotocraftApp, method: &str, input: Value) -> Result<Val
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn material_search_dispatches_during_preview_and_never_clears_a_model_task() {
|
||||
let (tx, requests) = mpsc::channel();
|
||||
let (events, rx) = mpsc::channel();
|
||||
let mut workspace = Workspace::new(tx, rx);
|
||||
let _ = requests.try_recv();
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"width":1440,"height":1800})).unwrap();
|
||||
let mut app = PhotocraftApp::new(session, crate::Services::default());
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
workspace.account = json!({"id":"account-a"});
|
||||
workspace.observed_doc = Some(doc);
|
||||
workspace.loaded_draft = Some(doc);
|
||||
workspace.busy = Some("image".into());
|
||||
workspace.unknown = true;
|
||||
workspace.error = "原模型结果未知".into();
|
||||
workspace.send("preview", json!({"doc":doc,"materialId":"material-a","asset":{"kind":"asset","id":"image-a"}}));
|
||||
let Request::Action(method, preview) = requests.try_recv().unwrap() else { panic!("expected preview read") };
|
||||
assert_eq!(method, "preview");
|
||||
workspace.send("materials", json!({"identifierType":"spu","identifier":"PRODUCT-A"}));
|
||||
let Request::Action(method, search) = requests.try_recv().unwrap() else { panic!("expected independent catalogue read") };
|
||||
assert_eq!(method, "materials");
|
||||
workspace.send("preview", json!({"doc":doc}));
|
||||
workspace.send("materials", json!({"identifierType":"spu","identifier":"PRODUCT-A"}));
|
||||
assert!(requests.try_recv().is_err(), "only one preview and one catalogue read may be pending");
|
||||
workspace.send("place", json!({"doc":doc}));
|
||||
assert!(requests.try_recv().is_err(), "placing still respects the model/write busy gate");
|
||||
events.send(Event::Json("materials".into(), Ok(json!({"readId":search["readId"],"accountId":"account-a","origin":workspace.origin,"items":[{"materialId":"found"}]})))).unwrap();
|
||||
events.send(Event::Json("preview".into(), Ok(json!({"readId":preview["readId"],"accountId":"account-a","origin":workspace.origin,"doc":doc,"error":"素材正在加载,请稍后再试"})))).unwrap();
|
||||
let context = egui::Context::default();
|
||||
let mut output = context.run_ui(egui::RawInput::default(), |ui| workspace.tick(&mut app, ui));
|
||||
output.textures_delta.clear();
|
||||
assert_eq!(workspace.material_rows[0]["materialId"], "found");
|
||||
assert!(workspace.material_search_pending.is_none());
|
||||
assert!(workspace.material_preview_pending.is_none());
|
||||
assert_eq!(workspace.material_error, "素材正在加载,请稍后再试");
|
||||
assert_eq!(workspace.busy.as_deref(), Some("image"));
|
||||
assert!(workspace.unknown);
|
||||
assert_eq!(workspace.error, "原模型结果未知");
|
||||
}
|
||||
#[test]
|
||||
fn stale_read_ids_or_accounts_cannot_release_another_read_or_apply_its_result() {
|
||||
let (tx, requests) = mpsc::channel();
|
||||
let (_events, rx) = mpsc::channel();
|
||||
let mut workspace = Workspace::new(tx, rx);
|
||||
let _ = requests.try_recv();
|
||||
workspace.account = json!({"id":"account-b"});
|
||||
workspace.send("materials", json!({"identifierType":"spu","identifier":"PRODUCT-B"}));
|
||||
let read_id = workspace.material_search_pending.unwrap();
|
||||
assert!(!workspace.finish_material_read("materials", &json!({"readId":read_id+1,"accountId":"account-b","origin":workspace.origin}), None));
|
||||
assert_eq!(workspace.material_search_pending, Some(read_id));
|
||||
assert!(!workspace.finish_material_read("materials", &json!({"readId":read_id,"accountId":"old-account","origin":workspace.origin}), None));
|
||||
assert!(workspace.material_search_pending.is_none());
|
||||
workspace.send("preview", json!({"doc":1}));
|
||||
let read_id = workspace.material_preview_pending.unwrap();
|
||||
assert!(!workspace.finish_material_read("preview", &json!({"readId":read_id,"accountId":"account-b","origin":workspace.origin,"doc":1}), Some(2)));
|
||||
assert!(workspace.material_preview_pending.is_none());
|
||||
assert_eq!(workspace.busy.as_deref(), Some("restore"));
|
||||
}
|
||||
#[test]
|
||||
fn project_navigation_shares_the_options_row_and_stays_on_its_right_edge() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
for width in [960.0, 1100.0, 1440.0, 1920.0] {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"width":1440,"height":1800})).unwrap();
|
||||
let mut app = PhotocraftApp::new(session, crate::Services::default());
|
||||
let (tx, _requests) = mpsc::channel();
|
||||
let (_events, rx) = mpsc::channel();
|
||||
let mut workspace = Workspace::new(tx, rx);
|
||||
workspace.account = json!({"id":"qa","name":"很长的账户姓名也不能挤出控件"});
|
||||
app.jiansun = Some(workspace);
|
||||
let mut harness = Harness::builder().with_size(egui::vec2(width, 120.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
|
||||
crate::panels::options_bar(app, ui);
|
||||
}
|
||||
},
|
||||
app,
|
||||
);
|
||||
PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ProMedium);
|
||||
harness.run_steps(4);
|
||||
let projects = harness.get_by_label("我的项目").rect();
|
||||
let materials = harness.get_by_label("添加素材").rect();
|
||||
let brief = harness.get_by_label("产品资料").rect();
|
||||
assert!((projects.center().y - materials.center().y).abs() < 1.0);
|
||||
assert!((projects.center().y - brief.center().y).abs() < 1.0);
|
||||
assert!(projects.left() > width - navigation_width(harness.state()) - 1.0, "navigation remains at right, width={width}");
|
||||
assert!(brief.right() <= width, "no overflow at width={width}");
|
||||
}
|
||||
}
|
||||
#[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"});
|
||||
let saved = json!({"cloudLink":{"id":"cloud","source":"desktop","revision":3},"syncedRevision":8,"status":"draft","syncDirty":true});
|
||||
|
||||
@ -112,9 +112,15 @@ impl Workspace {
|
||||
Frame::NONE.inner_margin(8).show(ui, |ui| crate::panels::layers(app, ui));
|
||||
return;
|
||||
}
|
||||
let composer_min_height = self.composer_min_height(app, ui);
|
||||
egui::Panel::bottom("jiansun-composer")
|
||||
.resizable(false)
|
||||
.frame(Frame::NONE.fill(t.dock).inner_margin(12))
|
||||
// Reserve the capped input + action/model rows from the first
|
||||
// frame. The input ScrollArea must not size itself against a
|
||||
// shorter previous panel and grow the model row below the dock.
|
||||
.default_size(composer_min_height)
|
||||
.min_size(composer_min_height)
|
||||
.frame(Frame::NONE.fill(t.dock).inner_margin(10))
|
||||
.show(ui, |ui| self.composer_ui(app, ui));
|
||||
egui::ScrollArea::vertical().id_salt("jiansun-conversation").stick_to_bottom(true).auto_shrink([false, false]).show(ui, |ui| {
|
||||
Frame::NONE.inner_margin(egui::Margin { left: 16, right: 16, top: 18, bottom: 16 }).show(ui, |ui| {
|
||||
@ -318,6 +324,37 @@ impl Workspace {
|
||||
|| self.pending_image.is_some()
|
||||
}
|
||||
|
||||
fn composer_min_height(&self, app: &PhotocraftApp, ui: &Ui) -> f32 {
|
||||
// At the native UI scale the bounded input and both model choices need
|
||||
// 179 points; include both 10-point panel margins, without a third row.
|
||||
let mut height = 200.0;
|
||||
if app.session.active().is_some_and(|st| !st.selected_layers().is_empty()) {
|
||||
height += 24.0;
|
||||
}
|
||||
if self.image_mode != "chat" && (self.image_mode == "regenerate" || app.session.active().is_some_and(|st| !st.selected_layers().is_empty())) {
|
||||
// Space for the replace-image checkbox when a real image is selected.
|
||||
height += 24.0;
|
||||
}
|
||||
if self.pi_review && self.busy.is_none() {
|
||||
height += 50.0;
|
||||
}
|
||||
if self.unknown || self.pending() || self.ready_image.is_some() {
|
||||
height += 50.0;
|
||||
}
|
||||
if !self.error.is_empty() {
|
||||
let width = (ui.available_width() - 40.0).max(80.0);
|
||||
let color = Tokens::get(ui.ctx()).danger;
|
||||
height += ui.fonts_mut(|f| f.layout(self.error.clone(), egui::FontId::proportional(12.0), color, width).size().y).max(18.0) + 6.0;
|
||||
}
|
||||
if self.busy.as_deref() == Some("configure") {
|
||||
height += 26.0;
|
||||
}
|
||||
if self.account.is_null() || !self.key_saved {
|
||||
height += 26.0;
|
||||
}
|
||||
height
|
||||
}
|
||||
|
||||
fn can_send(&self, app: &PhotocraftApp) -> bool {
|
||||
app.session.active().is_some()
|
||||
&& self.busy.is_none()
|
||||
@ -348,7 +385,7 @@ impl Workspace {
|
||||
|
||||
fn composer_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
ui.spacing_mut().item_spacing = vec2(6.0, 8.0);
|
||||
ui.spacing_mut().item_spacing = vec2(6.0, 6.0);
|
||||
if self.pi_review && self.busy.is_none() {
|
||||
self.status_row(ui, "info", "原建议未执行", t.warning, |this, ui| {
|
||||
if ui.button("放弃原建议").on_hover_text("保留原响应和已完成的修改;不重新运行模型或工具").clicked() {
|
||||
@ -403,22 +440,103 @@ impl Workspace {
|
||||
ui.add(egui::Label::new(RichText::new(&error).size(12.0).color(t.danger)).wrap().selectable(true));
|
||||
});
|
||||
}
|
||||
let frame = Frame::NONE.fill(t.field).stroke(Stroke::new(1.0, t.field_border)).corner_radius(t.radius).inner_margin(10).show(ui, |ui| {
|
||||
let frame = Frame::NONE.show(ui, |ui| {
|
||||
ui.set_min_width(ui.available_width());
|
||||
self.selection_context(app, ui);
|
||||
let selected_image = app.session.active().is_some_and(|st| {
|
||||
let mut images = Vec::new();
|
||||
for id in st.selected_layers() {
|
||||
match st.doc.layer(id).map(|l| &l.content) {
|
||||
Some(LayerContent::Smart(_)) => images.push(id),
|
||||
Some(LayerContent::Group(group)) => {
|
||||
images.extend(group.children.iter().filter(|l| matches!(l.content, LayerContent::Smart(_))).map(|l| l.id))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
images.sort_unstable_by_key(|id| id.0);
|
||||
images.dedup();
|
||||
images.len() == 1
|
||||
});
|
||||
if self.image_mode != "chat" && (selected_image || self.image_mode == "regenerate") {
|
||||
let mut replace = self.image_mode == "regenerate";
|
||||
if ui
|
||||
.add_enabled(!self.pending() && !self.unknown && selected_image, egui::Checkbox::new(&mut replace, "替换选中图"))
|
||||
.on_hover_text("选中一张产品图片后,只替换该图片;文字和其他图层保持可编辑")
|
||||
.changed()
|
||||
{
|
||||
self.image_mode = if replace { "regenerate" } else { "generate" }.into();
|
||||
self.draft_changed = true;
|
||||
}
|
||||
}
|
||||
let hint = match self.image_mode.as_str() {
|
||||
"generate" => "描述想生成的产品场景…",
|
||||
"regenerate" => "告诉我这一屏哪里需要调整…",
|
||||
_ => "告诉我想怎么改…",
|
||||
};
|
||||
let input = Frame::NONE.fill(t.field).stroke(Stroke::new(1.0, t.field_border)).corner_radius(t.radius_sm).inner_margin(10).show(ui, |ui| {
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("agent-input-scroll")
|
||||
.max_height(72.0)
|
||||
.min_scrolled_height(48.0)
|
||||
.content_margin(egui::Margin::ZERO)
|
||||
.auto_shrink([false, true])
|
||||
.show(ui, |ui| {
|
||||
text_edit(
|
||||
ui,
|
||||
egui::TextEdit::multiline(&mut self.composer)
|
||||
.id_salt("jiansun-composer-input")
|
||||
.font(egui::FontId::proportional(13.0))
|
||||
.desired_rows(3)
|
||||
.desired_width(f32::INFINITY)
|
||||
.frame(Frame::NONE)
|
||||
.hint_text(hint),
|
||||
)
|
||||
})
|
||||
.inner
|
||||
});
|
||||
let response = input.inner;
|
||||
self.panel_geometry["input"] = rect_value(input.response.rect);
|
||||
if response.has_focus() {
|
||||
ui.painter().rect_stroke(input.response.rect, t.radius_sm, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
if self.focus_composer {
|
||||
response.request_focus();
|
||||
self.focus_composer = false;
|
||||
}
|
||||
if response.changed() {
|
||||
self.draft_changed = true;
|
||||
self.touched = Instant::now();
|
||||
}
|
||||
let shortcut = response.has_focus() && ui.input_mut(|i| i.consume_key(egui::Modifiers::CTRL, egui::Key::Enter));
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_enabled_ui(!self.pending() && !self.unknown, |ui| {
|
||||
egui::ComboBox::from_id_salt("agent-purpose")
|
||||
.width(122.0)
|
||||
.selected_text(mode_label(&self.image_mode))
|
||||
.show_ui(ui, |ui| {
|
||||
for (mode, label) in [("chat", "编辑画布"), ("generate", "生成图片"), ("regenerate", "重做当前屏")] {
|
||||
ui.selectable_value(&mut self.image_mode, mode.into(), label);
|
||||
}
|
||||
})
|
||||
.response
|
||||
.on_hover_text("选择本次任务");
|
||||
for (image, label) in [(false, "对话"), (true, "生图")] {
|
||||
let selected = (self.image_mode != "chat") == image;
|
||||
let button = ui.add(egui::Button::new(RichText::new(label).size(12.0)).selected(selected).min_size(vec2(46.0, 28.0)));
|
||||
self.panel_geometry[if image { "imageMode" } else { "chatMode" }] = rect_value(button.rect);
|
||||
if button.on_hover_text(if image { "使用生图模型" } else { "分析、文案与画布编辑" }).clicked() && !selected {
|
||||
self.image_mode = if image { "generate" } else { "chat" }.into();
|
||||
self.draft_changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
let can = self.can_send(app);
|
||||
let response =
|
||||
ui.add_enabled_ui(can, |ui| send_button(ui, t, self.reduce_motion)).inner.on_hover_text("发送 · Ctrl+Enter").on_disabled_hover_text(
|
||||
if self.unknown {
|
||||
"先核查原请求结果"
|
||||
} else if self.image_mode == "chat" && !self.agent_rule["id"].is_string() {
|
||||
"先在产品资料中选择品牌与品类"
|
||||
} else {
|
||||
"打开项目、连接模型并输入要求后发送"
|
||||
},
|
||||
);
|
||||
self.panel_geometry["send"] = rect_value(response.rect);
|
||||
if response.clicked() || (shortcut && can) {
|
||||
self.send_composer(app);
|
||||
}
|
||||
let response = icons::button(ui, "sliders-horizontal", 28.0, self.model_settings, "个人 Key 与连接设置");
|
||||
self.panel_geometry["settings"] = rect_value(response.rect);
|
||||
if response.clicked() {
|
||||
@ -431,73 +549,24 @@ impl Workspace {
|
||||
self.settings_popup(ui, &response);
|
||||
});
|
||||
});
|
||||
self.selection_context(app, ui);
|
||||
let hint = match self.image_mode.as_str() {
|
||||
"generate" => "描述想生成的产品场景…",
|
||||
"regenerate" => "告诉我这一屏哪里需要调整…",
|
||||
_ => "告诉我想怎么改…",
|
||||
};
|
||||
let response = text_edit(
|
||||
ui,
|
||||
egui::TextEdit::multiline(&mut self.composer)
|
||||
.id_salt("jiansun-composer-input")
|
||||
.font(egui::FontId::proportional(13.0))
|
||||
.desired_rows(3)
|
||||
.desired_width(f32::INFINITY)
|
||||
.frame(Frame::NONE)
|
||||
.margin(egui::Margin::symmetric(0, 7))
|
||||
.hint_text(hint),
|
||||
);
|
||||
self.panel_geometry["input"] = rect_value(response.rect);
|
||||
if self.focus_composer {
|
||||
response.request_focus();
|
||||
self.focus_composer = false;
|
||||
}
|
||||
if response.changed() {
|
||||
self.draft_changed = true;
|
||||
self.touched = Instant::now();
|
||||
}
|
||||
let shortcut = response.has_focus() && ui.input_mut(|i| i.consume_key(egui::Modifiers::CTRL, egui::Key::Enter));
|
||||
for (image, label) in [(false, "对话"), (true, "生图")] {
|
||||
ui.columns(2, |columns| {
|
||||
for (image, label) in [(false, "对话模型"), (true, "生图模型")] {
|
||||
let column = &mut columns[usize::from(image)];
|
||||
// egui columns inherit a justified layout. A ComboBox adds its
|
||||
// own frame padding; do not justify that frame past the column.
|
||||
column.with_layout(Layout::top_down(Align::Min), |ui| {
|
||||
ui.label(RichText::new(label).size(11.0).color(t.text_dim));
|
||||
let width = (ui.available_width() - 8.0).max(76.0);
|
||||
self.model_picker(ui, image, width, true);
|
||||
});
|
||||
}
|
||||
});
|
||||
if self.busy.as_deref() == Some("configure") {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_sized(vec2(30.0, 24.0), egui::Label::new(RichText::new(label).size(11.5).color(t.text_dim)));
|
||||
self.model_picker(ui, image, (ui.available_width() - 8.0).max(100.0), true);
|
||||
});
|
||||
}
|
||||
if app.session.active().is_some() {
|
||||
let current = self.agent_rule["id"].as_str().unwrap_or("").to_owned();
|
||||
let catalog = &self.agent_rule["catalog"];
|
||||
let combo = catalog["bindings"].as_array().and_then(|a|a.iter().find(|b| b["id"] == current));
|
||||
let saved_label = combo.and_then(|b|catalog["shops"].as_array().and_then(|a|a.iter().find(|s|s["id"]==b["shopId"])).and_then(|s|s["name"].as_str()).zip(catalog["categories"].as_array().and_then(|a|a.iter().find(|c|c["id"]==b["categoryId"])).and_then(|c|c["name"].as_str()))).map(|(shop,category)|format!("{shop} · {category}"));
|
||||
let title = self.agent_rules.iter().find(|r| r["id"] == current).and_then(|r| r["label"].as_str()).map(str::to_owned).or(saved_label).unwrap_or_else(||"选择品牌与品类".into());
|
||||
let mut selected = current.clone();
|
||||
let mut refresh = false;
|
||||
let response = ui.add_enabled_ui(self.busy.is_none() && !self.unknown, |ui| {
|
||||
egui::ComboBox::from_id_salt("agent-project-rules").selected_text(title).width(ui.available_width() - 8.0).show_ui(ui, |ui| {
|
||||
if self.agent_rules.is_empty() && ui.button("刷新规则").clicked() { refresh = true; }
|
||||
for choice in &self.agent_rules {
|
||||
if let (Some(id), Some(label)) = (choice["id"].as_str(), choice["label"].as_str()) { ui.selectable_value(&mut selected, id.to_owned(), label); }
|
||||
}
|
||||
}).response.on_hover_text("使用此项目的规则快照;切换组合会保留旧会话并打开独立会话")
|
||||
}).inner;
|
||||
self.panel_geometry["rules"] = rect_value(response.rect);
|
||||
if selected != current { self.send("pi-select", json!({"doc":app.session.active().map(|s|s.doc.id.0),"id":selected})); }
|
||||
else if refresh { self.send("pi-rules", json!({"doc":app.session.active().map(|s|s.doc.id.0)})); }
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if self.busy.as_deref() == Some("configure") {
|
||||
ui.spinner();
|
||||
ui.label(RichText::new("正在校验模型…").size(11.0).color(t.text_dim));
|
||||
}
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
let can = self.can_send(app);
|
||||
let response = ui.add_enabled_ui(can, |ui| send_button(ui, t, self.reduce_motion)).inner.on_hover_text("发送 · Ctrl+Enter");
|
||||
self.panel_geometry["send"] = rect_value(response.rect);
|
||||
if response.clicked() || (shortcut && can) {
|
||||
self.send_composer(app);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
self.panel_geometry["composer"] = rect_value(frame.response.rect);
|
||||
if self.account.is_null() {
|
||||
@ -680,14 +749,6 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
|
||||
fn mode_label(mode: &str) -> &'static str {
|
||||
match mode {
|
||||
"generate" => "生成图片",
|
||||
"regenerate" => "重做当前屏",
|
||||
_ => "编辑画布",
|
||||
}
|
||||
}
|
||||
|
||||
fn send_button(ui: &mut Ui, t: Tokens, reduce_motion: bool) -> Response {
|
||||
let (rect, response) = ui.allocate_exact_size(Vec2::splat(30.0), Sense::click());
|
||||
let hover = ui.ctx().animate_bool_with_time_and_easing(response.id.with("hover"), response.hovered(), if reduce_motion { 0.0 } else { 0.12 }, cubic_out);
|
||||
@ -783,6 +844,7 @@ mod tests {
|
||||
w.busy = None;
|
||||
w.account = json!({"id":"a"});
|
||||
w.key_saved = true;
|
||||
w.composer = "很长的产品要求也只在输入区域内部滚动。\n".repeat(40);
|
||||
w.messages = vec![json!({"role":"user","text":"用户要求"}), json!({"role":"assistant","kind":"reply","text":"这是答复"})];
|
||||
for _ in 0..2 {
|
||||
let mut output = ctx
|
||||
@ -800,10 +862,13 @@ mod tests {
|
||||
};
|
||||
let panel = value("panel");
|
||||
let composer = value("composer");
|
||||
assert!(panel.contains_rect(composer), "{width}x{height}");
|
||||
for key in ["input", "send", "model", "settings", "chatModel", "imageModel"] {
|
||||
assert!(panel.contains_rect(composer), "{width}x{height}: panel={panel:?}, composer={composer:?}, geometry={}", w.panel_geometry);
|
||||
for key in ["input", "send", "model", "settings", "chatModel", "imageModel", "chatMode", "imageMode"] {
|
||||
assert!(composer.contains_rect(value(key)), "{key} at {width}x{height}");
|
||||
}
|
||||
assert!(composer.height() <= 190.0, "compact input at {width}x{height}: {}", composer.height());
|
||||
assert!((value("chatModel").top() - value("imageModel").top()).abs() < 1.0, "both model choices share one row");
|
||||
assert!(w.panel_geometry.get("rules").is_none(), "project rules do not become a second composer selector");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@ use super::*;
|
||||
use egui::{Align, Layout, vec2};
|
||||
|
||||
pub(super) fn empty_brief() -> Value {
|
||||
json!({"source":"upload","name":"","brandId":"","brandName":"","identifierType":"sku","identifier":"","variant":"","colorMaterialId":"","colorName":"","dimensions":{"length":"","width":"","height":"","unit":"mm"},"images":[],"note":""})
|
||||
json!({"source":"upload","name":"","brandId":"","brandName":"","categoryId":"","categoryName":"","identifierType":"sku","identifier":"","variant":"","colorMaterialId":"","colorName":"","dimensions":{"length":"","width":"","height":"","unit":"mm"},"images":[],"note":""})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@ -83,6 +83,38 @@ mod tests {
|
||||
sync_received(&mut w, &app, &value);
|
||||
assert!(!w.sync_dirty);
|
||||
}
|
||||
#[test]
|
||||
fn delayed_rules_refresh_updates_canonical_revision_without_overwriting_the_users_draft() {
|
||||
let (mut w, app) = setup();
|
||||
w.creation = json!({"revision":2,"brief":empty_brief(),"sellingPoints":{"selected":["old:0"],"direction":"原方向"},"plan":{"status":"confirmed","screens":[{"id":"one","title":"原方案"}]},"width":1440,"screenCount":3,"designSnapshot":{"rules":{"id":"old-rule"}}});
|
||||
w.creation_brief = w.creation["brief"].clone();
|
||||
w.creation_brief["name"] = json!("刚输入的产品名称");
|
||||
w.creation_brief["dimensions"]["length"] = json!("1800");
|
||||
w.creation_selected = vec!["new:1".into()];
|
||||
w.creation_direction = "刚输入的表达方向".into();
|
||||
w.creation_plan = json!([{"id":"one","title":"尚未保存的标题"}]);
|
||||
w.creation_width = 750;
|
||||
w.creation_count = 6;
|
||||
w.creation_dirty = true;
|
||||
let draft = w.creation_draft();
|
||||
let mut value = reference(&w);
|
||||
value["creation"] = w.creation.clone();
|
||||
value["creation"]["revision"] = json!(3);
|
||||
value["creation"]["designSnapshot"]["rules"] = json!({"id":"fixed-rule","contentHash":"a".repeat(64)});
|
||||
value["creation"]["plan"]["status"] = json!("stale");
|
||||
received(&mut w,&app,"creation-rules",&value);
|
||||
assert_eq!(w.creation_draft()["brief"],draft["brief"]);
|
||||
for field in ["screens","direction","selected","width","screenCount"] { assert_eq!(w.creation_draft()[field],draft[field]); }
|
||||
assert!(w.creation_dirty);
|
||||
assert_eq!(w.creation["revision"],3);
|
||||
assert_eq!(w.creation["designSnapshot"]["rules"]["id"],"fixed-rule");
|
||||
assert_eq!(w.creation["plan"]["status"],"stale");
|
||||
// With no local edits, the normal canonical plan state remains visible.
|
||||
w.creation_dirty = false;
|
||||
received(&mut w,&app,"creation-rules",&value);
|
||||
assert_eq!(w.creation_plan,value["creation"]["plan"]["screens"]);
|
||||
assert!(!w.creation_dirty);
|
||||
}
|
||||
}
|
||||
fn edit(ui: &mut Ui, value: &mut Value, width: f32, multiline: bool) -> bool {
|
||||
let mut text = value.as_str().unwrap_or("").to_owned();
|
||||
@ -193,7 +225,7 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val
|
||||
w.creation = value["creation"].clone();
|
||||
w.creation_doc = value["doc"].as_u64();
|
||||
w.creation_read_failed = false;
|
||||
if !w.creation_dirty || !matches!(method, "creation-read" | "creation-import") {
|
||||
if !w.creation_dirty || !matches!(method, "creation-read" | "creation-import" | "creation-rules") {
|
||||
w.creation_brief = w.creation["brief"].clone();
|
||||
w.creation_dirty = false;
|
||||
w.creation_selected =
|
||||
@ -249,6 +281,9 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val
|
||||
if method != "creation-read" {
|
||||
w.sync_dirty = true;
|
||||
}
|
||||
if method == "creation-save" {
|
||||
let _ = w.tx.send(Request::Action("pi-rules".into(), json!({"doc":value["doc"]})));
|
||||
}
|
||||
}
|
||||
pub(super) fn thumbnail_received(w: &mut Workspace, ui: &Ui, value: &Value, image: egui::ColorImage) {
|
||||
if value["accountId"] != w.account["id"] || value["origin"] != w.origin {
|
||||
@ -547,6 +582,9 @@ impl Workspace {
|
||||
ui.label("品牌 *");
|
||||
self.brand_select(app, ui, width);
|
||||
ui.end_row();
|
||||
ui.label("品类 *");
|
||||
self.category_select(app, ui, width);
|
||||
ui.end_row();
|
||||
ui.label("颜色");
|
||||
self.material_select(app, ui, width);
|
||||
ui.end_row();
|
||||
@ -589,6 +627,10 @@ impl Workspace {
|
||||
self.creation_dirty |= edit(ui, &mut self.creation_brief["note"], width, true);
|
||||
ui.end_row();
|
||||
});
|
||||
if self.agent_rule_state["updateAvailable"] == true {
|
||||
ui.add_space(6.0);
|
||||
ui.label(egui::RichText::new("模板有新版本,当前项目保留原版本").small().color(Tokens::get(ui.ctx()).text_dim));
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
if self.creation_brief["source"] == "library" {
|
||||
self.product_select(app, ui);
|
||||
@ -677,12 +719,57 @@ impl Workspace {
|
||||
if ui.add_enabled(ready, egui::Button::selectable(self.creation_brief["brandId"] == row["id"], label)).clicked() {
|
||||
self.creation_brief["brandId"] = row["id"].clone();
|
||||
self.creation_brief["brandName"] = row["name"].clone();
|
||||
self.creation_brief["categoryId"] = json!("");
|
||||
self.creation_brief["categoryName"] = json!("");
|
||||
self.agent_rule = Value::Null;
|
||||
self.agent_rule_state = Value::Null;
|
||||
self.creation_dirty = true;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
fn category_select(&mut self, app: &PhotocraftApp, ui: &mut Ui, width: f32) {
|
||||
let brand = self.creation_brief["brandId"].as_str().unwrap_or("");
|
||||
let rows = self.agent_categories.clone();
|
||||
let ready_categories: Vec<String> =
|
||||
self.agent_rules.iter().filter(|r| r["shopId"] == brand).filter_map(|r| r["categoryId"].as_str().map(str::to_owned)).collect();
|
||||
let mut refresh = false;
|
||||
egui::ComboBox::from_id_salt("creation-category")
|
||||
.width(width)
|
||||
.selected_text(self.creation_brief["categoryName"].as_str().filter(|s| !s.is_empty()).unwrap_or(if brand.is_empty() {
|
||||
"先选择品牌"
|
||||
} else {
|
||||
"选择品类"
|
||||
}))
|
||||
.show_ui(ui, |ui| {
|
||||
if rows.is_empty() {
|
||||
if ui.button("读取品类").clicked() {
|
||||
refresh = true;
|
||||
}
|
||||
}
|
||||
for row in rows {
|
||||
let ready = row["id"].as_str().is_some_and(|id| ready_categories.iter().any(|s| s == id));
|
||||
let name = row["name"].as_str().unwrap_or("");
|
||||
let label = if ready { name.to_owned() } else { format!("{name} · 待配置") };
|
||||
if ui
|
||||
.add_enabled(ready, egui::Button::selectable(self.creation_brief["categoryId"] == row["id"], label))
|
||||
.on_hover_text(if ready { "使用该品牌与品类的项目模板" } else { "此品牌尚未配置该品类模板" })
|
||||
.clicked()
|
||||
{
|
||||
self.creation_brief["categoryId"] = row["id"].clone();
|
||||
self.creation_brief["categoryName"] = row["name"].clone();
|
||||
self.agent_rule = Value::Null;
|
||||
self.agent_rule_state = Value::Null;
|
||||
self.creation_dirty = true;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
if refresh {
|
||||
let _ = self.tx.send(Request::Action("pi-rules".into(), json!({"doc":app.session.active().map(|s| s.doc.id.0)})));
|
||||
}
|
||||
}
|
||||
fn material_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) {
|
||||
let rows = self.creation_catalog.get("materials").cloned().unwrap_or_default();
|
||||
egui::ComboBox::from_id_salt("creation-material")
|
||||
@ -709,7 +796,7 @@ impl Workspace {
|
||||
ui.horizontal(|ui| {
|
||||
if let Some(image) = self.creation_thumbs.get(&id) {
|
||||
ui.image((image.id(), vec2(30.0, 30.0)));
|
||||
} else if self.creation_thumb_loading.is_empty() && !self.creation_thumb_failed.contains(&id) {
|
||||
} else if self.creation_thumb_loading.len() < 2 && !self.creation_thumb_loading.contains(&id) && !self.creation_thumb_failed.contains(&id) {
|
||||
self.creation_thumb_loading.insert(id.clone());
|
||||
let _ = self.tx.send(Request::Action(
|
||||
"creation-thumbnail".into(),
|
||||
|
||||
@ -16,6 +16,16 @@ fn cloud_present(item: &Value) -> bool {
|
||||
matches!(item["source"].as_str(), Some("web" | "desktop")) || item["cloudPresent"] == true
|
||||
}
|
||||
|
||||
fn delete_block_reason(item: &Value) -> Option<&'static str> {
|
||||
if item["deleteBlocked"] != true {
|
||||
None
|
||||
} else if item["deleteBlockedReason"] == "task_running" {
|
||||
Some("任务执行中,暂不能删除")
|
||||
} else {
|
||||
Some("原请求待核查,暂不能删除")
|
||||
}
|
||||
}
|
||||
|
||||
fn badge(item: &Value) -> (&'static str, egui::Color32, egui::Color32) {
|
||||
if item["status"] == "completed" && item["hasDraft"] != true {
|
||||
("完结", egui::Color32::from_rgb(183, 232, 206), egui::Color32::from_rgb(21, 67, 43))
|
||||
@ -59,6 +69,7 @@ impl Workspace {
|
||||
return;
|
||||
}
|
||||
let pending = self.delete_confirm.take();
|
||||
self.delete_error.clear();
|
||||
let local_ids = value["localIds"].as_array().cloned().unwrap_or_else(|| if value["source"] == "native" { vec![value["id"].clone()] } else { vec![] });
|
||||
let remotes = value["deletedProjects"].as_array().cloned().unwrap_or_default();
|
||||
self.projects.retain(|p| !same(p, value) && !(p["source"] == "native" && local_ids.contains(&p["id"])) && !remotes.iter().any(|r| same(p, r)));
|
||||
@ -72,7 +83,7 @@ impl Workspace {
|
||||
if expected.is_some_and(|d| d["revision"] == st.revision) {
|
||||
close.push(index);
|
||||
} else {
|
||||
self.error = "项目已移到本机回收区;当前画布的新修改仍保留,请另存文件".into();
|
||||
self.delete_error = "项目已移到本机回收区;当前画布的新修改仍保留,请另存文件".into();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -101,7 +112,7 @@ impl Workspace {
|
||||
if Some(st.revision) == item["revision"].as_u64() {
|
||||
close.push(index);
|
||||
} else {
|
||||
self.error = "项目已在云端删除;当前新修改仍保留,请另存为新项目".into();
|
||||
self.delete_error = "项目已在云端删除;当前新修改仍保留,请另存为新项目".into();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -159,6 +170,10 @@ impl Workspace {
|
||||
ui.colored_label(t.danger, &self.error);
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
if self.delete_confirm.is_none() && !self.delete_error.is_empty() {
|
||||
ui.colored_label(t.danger, &self.delete_error);
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
let query = self.project_query.trim().to_lowercase();
|
||||
let mut items: Vec<Value> =
|
||||
self.projects.iter().filter(|p| query.is_empty() || p["name"].as_str().unwrap_or("").to_lowercase().contains(&query)).cloned().collect();
|
||||
@ -242,10 +257,12 @@ impl Workspace {
|
||||
ui.label(RichText::new(if item["cloudDeleted"]==true {"云端已删除 · 任务待核查"} else if native && cloud {"本机 · 云端"} else if native {"仅本机"} else {"云端"}).size(11.0).color(t.text_dim))
|
||||
.on_hover_text(if native && cloud {"云端有原项目;当前本机修改尚不代表已备份"} else if cloud {"账户中的项目"} else {"尚未同步至云端"});
|
||||
ui.with_layout(Layout::right_to_left(Align::Center),|ui| {
|
||||
let response = ui.add_enabled_ui(self.busy.is_none() && self.saving.is_none(),|ui|icons::button(ui,"trash",28.0,false,"删除项目")).inner;
|
||||
if response.clicked() { self.handover(); self.error.clear(); self.delete_confirm=Some(item.clone()); }
|
||||
let blocked = delete_block_reason(item);
|
||||
let response = ui.add_enabled_ui(self.busy.is_none() && self.saving.is_none() && blocked.is_none(),|ui|icons::button(ui,"trash",28.0,false,"删除项目")).inner;
|
||||
let response = if let Some(reason) = blocked { response.on_disabled_hover_text(reason) } else { response };
|
||||
if response.clicked() { self.handover(); self.delete_error.clear(); self.delete_confirm=Some(item.clone()); }
|
||||
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),"delete":agent_panel::rect_value(response.rect),"hasCover":self.project_covers.contains_key(&key(item)),"cloud":cloud,"borderPhysicalPixels":if cloud {2.0} else {ui.ctx().pixels_per_point()},"state":state,"badge":agent_panel::rect_value(badge_rect)}));
|
||||
tiles.push(json!({"id":item["id"],"source":item["source"],"open":agent_panel::rect_value(rect),"delete":agent_panel::rect_value(response.rect),"deleteEnabled":response.enabled(),"deleteBlockedReason":blocked,"hasCover":self.project_covers.contains_key(&key(item)),"cloud":cloud,"borderPhysicalPixels":if cloud {2.0} else {ui.ctx().pixels_per_point()},"state":state,"badge":agent_panel::rect_value(badge_rect)}));
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -277,8 +294,8 @@ impl Workspace {
|
||||
} else {
|
||||
"仅移除本机副本,云端项目保留。"
|
||||
});
|
||||
if !self.error.is_empty() {
|
||||
ui.colored_label(Tokens::get(ui.ctx()).danger, &self.error);
|
||||
if !self.delete_error.is_empty() {
|
||||
ui.colored_label(Tokens::get(ui.ctx()).danger, &self.delete_error);
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
ui.horizontal(|ui| {
|
||||
@ -291,6 +308,7 @@ impl Workspace {
|
||||
self.project_geometry["confirm"] = agent_panel::rect_value(confirm.rect);
|
||||
if cancel.clicked() {
|
||||
self.delete_confirm = None;
|
||||
self.delete_error.clear();
|
||||
}
|
||||
if confirm.clicked() {
|
||||
let mut request = item.clone();
|
||||
@ -317,6 +335,28 @@ impl Workspace {
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn deletion_block_state_is_explicit_and_never_inferred_from_names_or_age() {
|
||||
assert_eq!(delete_block_reason(&json!({"name":"old test","updatedAt":"2020-01-01"})), None);
|
||||
assert_eq!(delete_block_reason(&json!({"deleteBlocked":true,"deleteBlockedReason":"pending_request"})), Some("原请求待核查,暂不能删除"));
|
||||
assert_eq!(delete_block_reason(&json!({"deleteBlocked":true,"deleteBlockedReason":"task_running"})), Some("任务执行中,暂不能删除"));
|
||||
}
|
||||
#[test]
|
||||
fn delete_failures_do_not_replace_an_agent_error_or_repeat_in_the_composer() {
|
||||
let (tx, _requests) = mpsc::channel();
|
||||
let (events, rx) = mpsc::channel();
|
||||
let mut workspace = Workspace::new(tx, rx);
|
||||
workspace.error = "真实模型连接错误".into();
|
||||
workspace.busy = Some("project-delete".into());
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
events.send(Event::Json("project-delete".into(), Err("原请求待核查,未删除".into()))).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| workspace.tick(&mut app, ui));
|
||||
output.textures_delta.clear();
|
||||
assert_eq!(workspace.error, "真实模型连接错误");
|
||||
assert_eq!(workspace.delete_error, "原请求待核查,未删除");
|
||||
assert!(workspace.busy.is_none());
|
||||
}
|
||||
#[test]
|
||||
fn cloud_outline_and_completion_are_truthful_and_not_inferred_from_approval() {
|
||||
assert!(!cloud_present(&json!({"source":"native","cloudLink":{"id":"old"},"cloudPresent":false})));
|
||||
assert!(cloud_present(&json!({"source":"desktop"})));
|
||||
@ -359,7 +399,8 @@ mod tests {
|
||||
w.project_deleted(&mut app, &result);
|
||||
assert!(w.projects.is_empty());
|
||||
assert!(app.session.active().is_some());
|
||||
assert!(w.error.contains("新修改仍保留"));
|
||||
assert!(w.delete_error.contains("新修改仍保留"));
|
||||
assert!(w.error.is_empty(), "project deletion notices must not leak into Agent errors");
|
||||
}
|
||||
#[test]
|
||||
fn unchanged_open_local_project_closes_only_after_successful_deletion() {
|
||||
|
||||
@ -927,6 +927,14 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
.exact_size(options_bar_height(t.pro, narrow))
|
||||
.frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(10, 0)))
|
||||
.show(ui, |ui| {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let navigation_width = crate::jiansun::navigation_width(app);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let navigation_width = 0.0;
|
||||
let row = ui.max_rect();
|
||||
let options_right = if navigation_width > 0.0 { row.right() - navigation_width - 12.0 } else { row.right() };
|
||||
let mut options_ui = ui.new_child(egui::UiBuilder::new().max_rect(Rect::from_min_max(row.min, pos2(options_right.max(row.left() + 80.0), row.bottom()))));
|
||||
let ui = &mut options_ui;
|
||||
ui.style_mut().spacing.scroll = egui::style::ScrollStyle { bar_width: 4.0, ..egui::style::ScrollStyle::floating() };
|
||||
egui::ScrollArea::horizontal().id_salt("tool-options").auto_shrink([false, false]).show(ui, |ui| {
|
||||
// Font ink can extend beyond its advance width at fractional positions.
|
||||
@ -1526,6 +1534,13 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
reveal_focused_control(ui);
|
||||
});
|
||||
});
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if navigation_width > 0.0 {
|
||||
let nav_rect = Rect::from_min_max(pos2(options_right + 12.0, row.top()), row.max);
|
||||
let mut navigation_ui = options_ui.new_child(egui::UiBuilder::new().id_salt("jiansun-options-navigation").max_rect(nav_rect).layout(egui::Layout::right_to_left(egui::Align::Center)));
|
||||
navigation_ui.set_clip_rect(nav_rect);
|
||||
crate::jiansun::navigation(app, &mut navigation_ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
# 详情页原生客户端设计标准
|
||||
|
||||
更新:2026-10-21。适用于 `apps/detail-photocraft` 的二次开发;不替换线上素材库、旧 Electron 客户端或品牌中心的设计规范。
|
||||
更新:2026-10-23。适用于 `apps/detail-photocraft` 的二次开发;不替换线上素材库、旧 Electron 客户端或品牌中心的设计规范。
|
||||
|
||||
## 定位与依据
|
||||
|
||||
@ -13,15 +13,16 @@
|
||||
## 工作区布局
|
||||
|
||||
```text
|
||||
┌ Logo 我的项目 添加素材 原生菜单 / 当前工具选项 账户 ┐
|
||||
┌ Logo 原生菜单 ┐
|
||||
├ 当前工具选项 我的项目 添加素材 产品资料 同步 账户 ┤
|
||||
├ 工具条 ┬ 文档标签 / 画布 ┬ Agent / 图层 ┤
|
||||
│ │ │ 对话与操作记录 │
|
||||
│ │ 可编辑作品 │ │
|
||||
│ │ │ │
|
||||
│ │ ├───────────────┤
|
||||
│ │ │ 用途 / 选中内容 │
|
||||
│ │ │ 对话 / 生图 │
|
||||
│ │ │ 要求输入 / 设置 │
|
||||
│ │ │ 对话 / 生图模型 │
|
||||
│ │ │ 双模型同一行 │
|
||||
│ │ │ 发送 │
|
||||
├────────┴ 缩放、尺寸、保存状态 ┴───────────────┤
|
||||
```
|
||||
@ -31,11 +32,11 @@
|
||||
- 左侧沿用 PhotoCraft 工具分组、快捷键、鼠标与键盘语义;不另造一套操作方式。
|
||||
- 右侧固定协作面板,默认 Agent,可切换图层;调节宽度后记住。图层、属性、历史沿用原生编辑器。
|
||||
- 右侧对话区独立滚动,用户气泡靠右、段落仍左对齐,Agent 回复与产出靠左;每轮只显示一个 Agent 标识。操作记录默认收起为摘要,点击展开该轮原始历史。
|
||||
- 底部统一输入区包括用途、选中图层上下文、草稿,以及始终可见的“对话/生图”两行独立模型选择与发送。滑杆图标打开个人 Key 和连接设置;账户弹窗只负责素材库网页登录授权。保存与校验有加载、失败和成功反馈,不把已保存的 Key 回显到界面。
|
||||
- 底部统一输入区使用独立边框、内边距和焦点反馈,输入文字超过三行后在框内滚动。对话与生图模型放在同一行的两个独立选单;选中内容仅以紧凑上下文显示。滑杆图标打开个人 Key 和连接设置;账户弹窗只负责素材库网页登录授权。保存与校验有加载、失败和成功反馈,不把已保存的 Key 回显到界面。
|
||||
- 没有文档时直接进入“我的项目”,不另设欢迎页或草稿入口。项目以真实首屏缩略图、名称、草稿角标与本机/账户来源呈现,按更新时间排序;没有页面时显示待生成。可见行才请求封面,后台渲染并限制并发与缓存。
|
||||
- 项目垃圾桶入口保持可见,确认时明确删除本机还是账户项目。本机移入所属账户回收区,账户删除复用现有鉴权、版本和任务保护;网络或版本错误显示实际原因,不乐观移除。存在待核查任务时保留项目和请求记录。
|
||||
- 项目垃圾桶入口保持可见,确认时明确删除本机还是账户项目。本机移入所属账户回收区,账户删除复用现有鉴权、版本和任务保护;网络、版本冲突、正在执行和结果待核查分别显示原因。列表已知受保护时禁用删除并给出悬停原因;最终提交仍实时核对,不乐观移除。存在待核查任务时保留项目和请求记录。删除错误只出现在项目和确认区,不混入 Agent 对话。
|
||||
- “我的项目/添加素材/画布”是互斥的中央目的地,切换不重建或清空原文档。返回画布时关闭浏览层;没有文档时回到我的项目。
|
||||
- 顶部“添加素材”支持 SKU / SPU / 条码从素材库查询,图片预览后置入当前画布。私有图片保持鉴权下载。
|
||||
- “我的项目/添加素材”等入口放在原生工具选项行右侧,不额外占用一整行;左侧工具参数可横向滚动。隐藏工具选项时保留最小可达入口。“添加素材”支持 SKU / SPU / 条码从素材库查询,图片预览后置入当前画布。目录与图片采用独立有界只读队列;缩略图最多两张在途。私有图片每次 GET 保持实时鉴权,预览不生成临时图片,置入及画布修改仍串行。
|
||||
- 默认窗口 1440×900,验收 1280×800、1440×900、1920×1080 与 125% / 150% 缩放。最低 1100×720;窄窗口收起辅助面板,不把桌面客户端伪装成移动网页。
|
||||
|
||||
## 视觉与文案
|
||||
@ -68,7 +69,9 @@
|
||||
- 正式验收前联网功能继续仅有效超级管理员使用;每次调用前重验账户、权限和模型开放政策,不信任界面缓存。
|
||||
- 不读取 98k 的源码、数据库或服务器。每个素材库账户使用自己的 98k Key,只存本机操作系统凭据库;不打包或分发公司共用 Key。更换素材库账户后不共享模型连接。对话与生图分别保存选择,保留原有个人 Key 时切换模型不用重填。
|
||||
- 模型选项复用线上现有的只读目录,对话用 `agent-models`、生图用 `models.modelOptions.image`。保存前与个人 Key 的公开 `/v1/models` 核对,不根据模型名称猜测用途;选择配置与原生生图执行分开验收。
|
||||
- 输入区以“编辑画布/生成图片/重做当前屏”选择任务,不增加常驻参数面板。原生生图使用选中产品图片与当前模型;单屏重生成只替换所选图片,保持原图框和独立文字层。生成过程用单行状态,接手后的结果待明确应用,进入同一份撤销历史。
|
||||
- 输入区保留紧凑的“对话/生图”,不展示三个含糊任务的下拉选单。只有真实选中可替换图片时出现“替换选中图”;沿用原生生图与单屏替换能力,保持图框和独立文字层。没有自动模型路由实现时不声称已由 Agent 自动判断生图。生成过程用单行状态,接手后的结果待明确应用,进入同一份撤销历史。
|
||||
- 品牌、品类在产品资料中一次选择,Agent 不重复询问。素材联动仅精确映射目录中的明确品类;旧资料缺品类保持空值,不能按近似名称套模板。项目按品牌和品类自动绑定已就绪规则;没有对应模板时显示待配置,不借用其他品类。
|
||||
- 规则及模板模块目录由生产服务提供,首次下载后在所属账户本机缓存,使用内容 SHA 校验;后续先读本机,每五分钟在使用时后台检查一次。联网接口包括 304 响应之前均实时校验权限。已有项目使用固定快照,新版缓存不自动改写旧方案;延迟回包不能覆盖未保存输入。当前缓存范围是规则与模块元数据,完整 PSD、人物与参考图片资源包需另行接入和验收。
|
||||
- 画布、图片处理、预览和导出在用户设备上执行。平台负责鉴权、目录、知识、私有文件传输与项目服务;不宣称平台没有资源开销。
|
||||
- 以本机工程为主要工作副本:`.pcraft`、工作素材缓存、撤销历史与生成任务日志留在用户设备;个人 Key 的模型请求由客户端直连 98k。生产机不承担客户端的画布合成、PSD 导出或自动重跑任务。
|
||||
- 服务端保留项目索引、权限、品牌/模板快照版本和必要的任务摘要(请求号、状态、所属项目与版本);完成后接收成果。为跨设备与本机故障恢复保留可选工程备份及版本同步,不能只上传一张最终图片。
|
||||
@ -83,4 +86,4 @@
|
||||
- 原生界面按 Impeccable critique / audit 检查布局、对比度、焦点、文案、溢出和反馈,保留实际窗口截图。
|
||||
- 本次 Agent 停靠面板的局部 ship 裁定、真实流式调用与截图矩阵见 [Agent 面板验收](photocraft-agent-panel-acceptance-2026-10-21.md);不据此扩大为所有模型、系统辅助技术或完整客户端验收完成。
|
||||
- 后续项目首页、删除、双模型及导航验收见 [本轮记录](photocraft-projects-agent-acceptance-2026-10-21.md),独立审查按对应截图和实际范围记录。
|
||||
- 本轮只本地运行,不改生产数据、不部署,也不把未完成项写成已交付。
|
||||
- 每次提交与发布以该次验收记录为准;设计标准不代表所有能力均已交付。同事表格的输入、输出和现有实现差距见[流程对照](photocraft-colleague-workflow-2026-10-23.md)。
|
||||
|
||||
78
docs/photocraft-colleague-workflow-2026-10-23.md
Normal file
78
docs/photocraft-colleague-workflow-2026-10-23.md
Normal file
@ -0,0 +1,78 @@
|
||||
# 同事表格流程与原生客户端对照
|
||||
|
||||
核对日期:2026-10-23。来源:[索菲亚·无扶手硬座椅·整套流程测试](https://xcnaqb3wszn7.feishu.cn/sheets/Rn2is0TWghZBq6tH95Scebwjnrf?sheet=66c0de)。本次通过公开页面正常操作,只读核对 11 个工作表的字段、总览及代表性任务;可见单元格记录位于 `output/client-feedback-20261023/feishu-visible-cells.json`。图片单元格未随文字提取,不据此判定图片为空,也不把本记录当成完整表格或 PSD 导入验收。
|
||||
|
||||
## 这套流程的主线
|
||||
|
||||
人工确认产品资料和制作范围 → 给产品参考图编号 → 按品牌、品类选模板 → 按既定屏幕与图位改写文字和提示词 → 图片生成 A/B 候选 → 人工选择、必要时修改 → 按稳定字段编号回填文字和图片 → 检查排版、外观与规格 → 分层导出。
|
||||
|
||||
它以现有模板的屏序、图框和文字空间为基础。每张图有明确用途、比例和回填位置;不是生成一张长图后再补文字,也不是只交一份大纲。
|
||||
|
||||
## 需要准备的资料
|
||||
|
||||
“产品资料”分为资料项、填写要求、模板默认资料、本次资料四列。需要逐项判断哪些默认值适用于当前产品,明确差异优先,不能把模板中的产品参数直接当成本款事实。
|
||||
|
||||
| 资料项 | 本表的实际要求与例子 |
|
||||
|---|---|
|
||||
| 品牌 | 人工确认,本次为索菲亚。 |
|
||||
| 产品名称/系列名 | 与首屏名称一致;本次为东方叙实木餐椅的无扶手硬座款。 |
|
||||
| 品类与款式 | 写清外观与结构;本款是无扶手、木质硬座、横向椅背、四腿及可见横撑。 |
|
||||
| 实际颜色 | 颜色名与产品参考图对应;本次名称为朴橡胡桃木色,画面以 P01 为准。 |
|
||||
| 尺寸规格 | 按测量部位分别记录。底部宽、进深、整体高、坐面宽、靠背宽不是同一组长宽高。另有 62.26cm 高度值用途待确认,不能改称坐高。 |
|
||||
| 木材、坐垫与结构 | 区分材质资料和可见结构;无扶手硬座款删除软垫、仿棉麻、绑带及扶手内容。 |
|
||||
| 表面工艺 | 记录适用的工艺及变化;不能仅凭实拍图认定油漆品牌、遍数或等级。 |
|
||||
| 使用场景与功能 | 以当前产品和参考图组织用餐、小坐、阅读等场景,不补造隐藏结构或功能。 |
|
||||
| 产地与安装 | 分别确认产地、整装或安装方式。 |
|
||||
| 本款差异说明(选填) | 集中说明删改及交付范围。本次只用 P01,制作详情、10 张方版主图、1 个 SKU 的方竖两版;不可见结构不做拆解。 |
|
||||
|
||||
**事实边界:** 表中的橡胶木、FAS/进口 5A、6 遍立邦/大宝漆、常州和整装等内容,是该次流程测试沿用的资料;本次没有独立核验这些产品事实。实际项目应记录来源和确认状态,未经确认不能作为新产品的性能、等级或认证背书。
|
||||
|
||||
“产品素材”另记资产编号、资产图(可含多视角)、适用颜色/SKU、资产说明。本次唯一有效外观引用为 **P01 → 朴橡胡桃木色/SKU01**,只允许依据可见角度,不推测背面和内部结构。P02、P03 只是预留编号,不能算作已提交参考图。
|
||||
|
||||
## 每类产出怎么组织
|
||||
|
||||
| 工作表 | 保存的内容与用途 |
|
||||
|---|---|
|
||||
| 产品资料 | 当前产品输入、适用默认值及差异。 |
|
||||
| 产品素材 | P 资产与颜色/SKU 的对应关系。 |
|
||||
| 模板-屏幕总览 | 屏幕职责、内容主题、图文适配、画幅及关联字段。详情编号为 S01—S14;本次主图为 M01—M05、M11—M15;SKU 为 K01、K02。 |
|
||||
| 详情页-PS字段表 | 模板 `SFY-CHAIR-001`、映射版本 `20261016.2`、组件 `detail`;表头登记 69 个需求字段。 |
|
||||
| 主图-PS字段表 | 同模板和映射版本,组件 `main_images`;表头登记 31 个需求字段,并登记已应用画幅。 |
|
||||
| SKU-PS字段表 | 同模板和映射版本,组件 `sku_images`;表头登记 24 个需求字段。同一规格共用参数及两张素材,分别输出 K01 方版、K02 竖版。 |
|
||||
| 详情页-图片制作任务 | 图片字段、图位/比例、模板参考、完整提示词、A/B 候选、意见、最终采用图、制作要求。 |
|
||||
| 主图-图片制作任务 | 同上;主图按自己的用途独立策划,样本明确不直接复用详情场景或成图。 |
|
||||
| SKU-图片制作任务 | 增加 SKU 编号;完整产品图和材质色块分别制作,方竖版按规则复用。 |
|
||||
| 主图视频-制作任务 | 整片提示词及关键场景;表内默认 30 秒、3:4,允许按产品调整。所读样本没有完整视频总提示词。 |
|
||||
| 买家秀-制作任务 | 卖点、明确标记为非真实评价的 AI 模拟评论、手机随拍提示词、A/B、最终采用图及 4 个裁切图位。所读 BX01/BX02 样本尚未填写。 |
|
||||
|
||||
上述字段数量来自表头声明,未逐条核验全表字段,也未验证全部候选图片、最终采用文件或视频已产出。
|
||||
|
||||
详情的 14 屏中包含章节过渡页,并非 14 张同构大图。总览包括首屏、六图总览、坐靠/硬座细节、外部框架、搭配场景、木纹工艺、连接细节、尺寸和规格等。无扶手硬座款会替换原扶手、软垫主题;不能保持原文字却把图片换掉。
|
||||
|
||||
## 模板回填和验收的关键约束
|
||||
|
||||
- **稳定编号:** `S01-T01` 等文字字段、`S01-I01` 等图片字段,以及 M、K 系列编号,是任务、图位和输出的共同定位依据。更换文案或图片不应更换字段身份;模板编号、映射版本要与项目绑定。
|
||||
- **排版约束:** 字段同时保存名称、填写要求、输出规格、示例和实际内容。比如 S01-T01 要保留一行及原字体、字号、颜色、换行与文字空间;S01-T02 是两行。原文字数是空间参考,不是为凑字数而增加事实。回填后必须检查超出文本框、意外换行和留白。
|
||||
- **画幅约束:** 样本有首屏 2:3、双椅总览 16:9、主图 1:1、SKU 完整产品 1:1 和木纹色块 16:9。主图本次采用 1440×1440,不能把全部图位统一改为同一比例。
|
||||
- **提示词结构:** 样本按主体、主体配饰、镜头与构图、场景、风格五段组织。产品颜色、结构、比例及可见部件引用 P01;环境、人物、道具与光影服务当前图位,文字和参数由独立文字层承担。
|
||||
- **先选再回填:** A/B 是候选;推荐意见不等于用户已选定。采用后按字段回填,保留对应资产、提示词、版本和选择记录。外观、道具接触、完整轮廓、文字覆盖区和比例均要核对。
|
||||
- **明确复用:** SKU 样本允许同批纯白完整产品候选供 S12、S13 和双版 SKU 按各自字段复用,色块两版共用;复用已有结果,不重复派发同一任务。该复用范围不扩展到全部主图。
|
||||
- **分层交付:** 文字、图片、图框和规格标注应保留各自编辑能力;导出时检查稳定字段与图层映射。已有 PSD 导出能力不代表这张表的字段映射已经接通。
|
||||
|
||||
## 与当前客户端的差距
|
||||
|
||||
对照本轮源码中的 `jiansun_creation_model.rs`、`jiansun_creation.rs`、`jiansun_rule_cache.rs` 和服务端 `agent-rule-catalog.json`:
|
||||
|
||||
| 环节 | 当前能力与仍需补齐的部分 |
|
||||
|---|---|
|
||||
| 产品输入 | 已有上传/素材库双来源、品牌、颜色材质、长宽高、图片和备注,本轮补品牌/品类绑定。尚缺上述多测量部位、每项事实来源与确认状态的结构化表达。 |
|
||||
| 产品参考 | 已分产品图与场景图并保存来源。尚未形成表格中 P01 → 颜色 → SKU → 多个输出字段的完整关系。 |
|
||||
| 云端模板与本机缓存 | 本轮缓存的是版本化规则和屏幕清单;旧项目固定快照不随公共更新改写。现有 ready 绑定只有顾家电脑桌 `GJ-DESK-DNZ0385`,不是本表索菲亚椅子 `SFY-CHAIR-001`,也不是完整 PSD/图片资源包。 |
|
||||
| 文案与页面方案 | 已有事实分析、卖点批次、人工挑选和方案确认。当前计划结构仍以标题、正文、图片提示词为主;需增加稳定字段、字段排版约束及模板图层映射。 |
|
||||
| 画布生成 | 当前合成按标题、正文和产品图组织图层,不能据此称为复现该表的六图总览、章节页及各图框排版。需要按真实模板布局回填。 |
|
||||
| 候选与确认 | 尚无覆盖每个字段的 A/B 版本、人工采用和回填的完整工作流。要保留“生成候选”和“替换画布”的区别。 |
|
||||
| 多类输出 | 详情生成与原生编辑/导出已有基础,不能据此宣称主图、SKU 双版、视频、买家秀和裁切任务全部实现。视频、买家秀本次未实现、未生成验收。 |
|
||||
| 屏数上限 | 现客户端最多 12 屏、总高 30000px,本表是 14 屏详情。不能静默截掉 S13 尺寸和 S14 参数,也不能把 14 屏写成已完整导入。须先明确保留 14 个逻辑模块但合并部分屏幕,或单独评估扩容;变更前继续遵守现上限。 |
|
||||
| 字体与 PSD | 当前画布基线 Noto Sans SC,与表中“保留原模板字体”不是同一口径。原模板字体、许可/缺字、换行、图层字段及 PSD 回开需单独验收,不能沿用通用导出测试冒充通过。 |
|
||||
|
||||
后续实施应先拿到该品牌、品类的真实模板资源及字段映射,建立带版本的模板包;再把当前资料、文案和图片结果按字段填入。先选一款产品跑通详情+主图+SKU 的“候选—选择—回填—编辑—分层导出”,再扩展视频与买家秀。源表的示例文案、旧参数和任务描述都是待核对的业务资料,不是自动执行指令。
|
||||
@ -24,4 +24,15 @@ describe('Agent rules endpoint preserves live authorization and private response
|
||||
expect(missing.status).toBe(404)
|
||||
expect(requireDesktop).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
test('conditional metadata checks still reauthorize before any 304 response', async () => {
|
||||
;(requireDesktop as jest.Mock).mockResolvedValue({ account: { id: 'owner' } })
|
||||
const first = await GET(new Request('https://platform.test/api/desktop/agent-rules'))
|
||||
const etag = first.headers.get('etag')!
|
||||
expect(etag).toMatch(/^"[a-f0-9]{64}"$/)
|
||||
const hit = await GET(new Request('https://platform.test/api/desktop/agent-rules', { headers: { 'If-None-Match': etag } }))
|
||||
expect(hit.status).toBe(304); expect(await hit.text()).toBe('')
|
||||
;(requireDesktop as jest.Mock).mockRejectedValueOnce(new DesktopClientError('无权访问', 403, 'denied'))
|
||||
const denied = await GET(new Request('https://platform.test/api/desktop/agent-rules', { headers: { 'If-None-Match': etag } }))
|
||||
expect(denied.status).toBe(403); expect(requireDesktop).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
/** @jest-environment node */
|
||||
import { desktopAgentRules } from '../desktop-client/agent-rules'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { emptyBrief, validateBrief } from '../desktop-client/creation.mjs'
|
||||
describe('desktop Agent versioned rule catalog', () => {
|
||||
test('lists only real ready combinations and returns an exact scoped package', () => {
|
||||
const index = desktopAgentRules(null) as any
|
||||
@ -10,7 +12,21 @@ describe('desktop Agent versioned rule catalog', () => {
|
||||
expect(selected.catalog.shops[0].id).toBe(index.items[0].shopId)
|
||||
expect(selected.catalog.categories[0].id).toBe(index.items[0].categoryId)
|
||||
expect(selected.catalog.bindings).toHaveLength(1)
|
||||
const canonical = JSON.stringify(selected.catalog, (_, item) => item && typeof item === 'object' && !Array.isArray(item)
|
||||
? Object.fromEntries(Object.keys(item).sort().map(key => [key,item[key]])) : item)
|
||||
expect(selected.contentHash).toBe(createHash('sha256').update(canonical).digest('hex'))
|
||||
expect(index.items[0].contentHash).toBe(selected.contentHash)
|
||||
expect(index.items[0].projectBrandId).toBe(index.items[0].shopId)
|
||||
expect(index.categories.some((c: any) => c.name === '化妆台')).toBe(true)
|
||||
expect(index.items.some((c: any) => c.categoryName === '化妆台')).toBe(false)
|
||||
expect(() => desktopAgentRules('unknown')).toThrow('尚未配置')
|
||||
expect(() => desktopAgentRules('../other')).toThrow('编号无效')
|
||||
})
|
||||
test('old briefs keep an empty category, while an explicit category survives cloud validation', () => {
|
||||
const old = emptyBrief() as any
|
||||
delete old.categoryId; delete old.categoryName
|
||||
expect(validateBrief(old)).toMatchObject({ categoryId: '', categoryName: '' })
|
||||
expect(validateBrief({ ...old, categoryId: 'real-category', categoryName: '电脑桌' })).toMatchObject({ categoryId: 'real-category', categoryName: '电脑桌' })
|
||||
expect(() => validateBrief({ ...old, categoryId: false })).toThrow('品类格式无效')
|
||||
})
|
||||
})
|
||||
|
||||
@ -92,3 +92,27 @@ test('linked web tombstones are not hidden by their deleted desktop continuation
|
||||
})
|
||||
expect(await listDesktopProjects('owner', null)).toMatchObject({ items: [], deleted: [{ id: 'web-old', source: 'web' }, { id: 'native-old', source: 'desktop' }] })
|
||||
})
|
||||
|
||||
test('the list exposes safe deletion reasons in one batch and keeps tombstones out of that batch', async () => {
|
||||
const updatedAt = new Date('2026-10-23T00:00:00Z')
|
||||
;(prisma.$queryRawUnsafe as jest.Mock)
|
||||
.mockResolvedValueOnce([
|
||||
{ id: 'web-pending', source: 'web', name: '旧验收', revision: 3, updatedAt },
|
||||
{ id: 'native-idle', source: 'desktop', name: '正常项目', revision: 2, updatedAt },
|
||||
{ id: 'web-old', source: 'web', deletedAt: updatedAt, updatedAt },
|
||||
])
|
||||
.mockResolvedValueOnce([
|
||||
{ id: 'web-pending', source: 'web', deleteBlocked: true, deleteBlockedReason: 'pending_request' },
|
||||
{ id: 'native-idle', source: 'desktop', deleteBlocked: false, deleteBlockedReason: null },
|
||||
])
|
||||
const value = await listDesktopProjects('owner', null)
|
||||
expect(value.items).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ id: 'web-pending', revision: 3, deleteBlocked: true, deleteBlockedReason: 'pending_request' }),
|
||||
expect.objectContaining({ id: 'native-idle', deleteBlocked: false, deleteBlockedReason: null }),
|
||||
]))
|
||||
expect(value.deleted).toEqual([{ id: 'web-old', source: 'web' }])
|
||||
const calls = (prisma.$queryRawUnsafe as jest.Mock).mock.calls
|
||||
expect(calls).toHaveLength(2)
|
||||
expect(calls[1][1]).toBe('owner')
|
||||
expect(JSON.parse(calls[1][2])).toEqual([{ id: 'web-pending', source: 'web' }, { id: 'native-idle', source: 'desktop' }])
|
||||
})
|
||||
|
||||
32
lib/__tests__/desktop-product-category.test.ts
Normal file
32
lib/__tests__/desktop-product-category.test.ts
Normal file
@ -0,0 +1,32 @@
|
||||
/** @jest-environment node */
|
||||
import { desktopProducts } from '../desktop-client/catalog'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { findDetailMaterialMatches } from '@/lib/detail-generator/materials'
|
||||
|
||||
jest.mock('@/lib/prisma', () => ({ prisma: { material: { findMany: jest.fn() }, productCategory: { findMany: jest.fn() } } }))
|
||||
jest.mock('@/lib/department-permission', () => ({ canUserViewMaterial: jest.fn() }))
|
||||
jest.mock('@/lib/task-detail-privacy', () => ({ buildMaterialPrivacyWhere: jest.fn() }))
|
||||
jest.mock('@/lib/detail-generator/brand-profiles', () => ({ listDetailBrandProfiles: jest.fn() }))
|
||||
jest.mock('@/lib/detail-generator/materials', () => ({ findDetailMaterialMatches: jest.fn(), readDetailMaterialImage: jest.fn(), readDetailMaterialPreview: jest.fn() }))
|
||||
|
||||
describe('desktop product category is copied from the explicit material catalogue', () => {
|
||||
beforeEach(() => jest.clearAllMocks())
|
||||
test('maps the exact unique catalogue name and preserves asset identities', async () => {
|
||||
;(findDetailMaterialMatches as jest.Mock).mockResolvedValue([{ materialId: 'material', productModel: '电脑桌字样不作为推断', assets: [{ id: 'image', source: 'asset', name: '原图' }] }])
|
||||
;(prisma.material.findMany as jest.Mock).mockResolvedValue([{ id: 'material', categoryName: '顾家', productCategoryName: '化妆台' }])
|
||||
;(prisma.productCategory.findMany as jest.Mock).mockResolvedValue([{ id: 'real-category', name: '化妆台' }])
|
||||
const value = await desktopProducts('owner', new URLSearchParams('identifierType=sku&identifier=SKU1'))
|
||||
expect(value.items[0]).toMatchObject({ brandName: '顾家', categoryId: 'real-category', categoryName: '化妆台', assets: [{ id: 'image', kind: 'asset', name: '原图' }] })
|
||||
expect(prisma.productCategory.findMany).toHaveBeenCalledWith({ where: { name: { in: ['化妆台'] } }, select: { id: true, name: true } })
|
||||
})
|
||||
test('a missing or unregistered category stays empty instead of matching a similar name', async () => {
|
||||
;(findDetailMaterialMatches as jest.Mock).mockResolvedValue([{ materialId: 'material', productModel: '电脑桌', assets: [] }])
|
||||
;(prisma.material.findMany as jest.Mock).mockResolvedValue([{ id: 'material', categoryName: '顾家', productCategoryName: '书桌' }])
|
||||
;(prisma.productCategory.findMany as jest.Mock).mockResolvedValue([{ id: 'computer-desk', name: '电脑桌' }])
|
||||
expect((await desktopProducts('owner', new URLSearchParams())).items[0]).toMatchObject({ categoryId: '', categoryName: '' })
|
||||
;(prisma.material.findMany as jest.Mock).mockResolvedValue([{ id: 'material', categoryName: '顾家', productCategoryName: '' }])
|
||||
jest.clearAllMocks()
|
||||
expect((await desktopProducts('owner', new URLSearchParams())).items[0]).toMatchObject({ categoryId: '', categoryName: '' })
|
||||
expect(prisma.productCategory.findMany).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@ -1,19 +1,19 @@
|
||||
/** @jest-environment node */
|
||||
import { deleteLinkedProject } from '@/lib/desktop-client/project-lifecycle'
|
||||
import { deleteLinkedProject, projectDeletionSummaries } from '@/lib/desktop-client/project-lifecycle'
|
||||
import { assertDetailProjectIdle } from '@/lib/detail-generator/repository'
|
||||
|
||||
jest.mock('@/lib/detail-generator/repository', () => ({ detailTransactionLock: jest.fn(async () => {}), assertDetailProjectIdle: jest.fn(async () => {}) }))
|
||||
|
||||
function fixture({ unknown = false, revision = 3, owner = true, deleted = false } = {}) {
|
||||
function fixture({ unknown = false, webUnknown = false, conversation = [] as any[], revision = 3, owner = true, deleted = false } = {}) {
|
||||
const writes: any[][] = []
|
||||
const tx = {
|
||||
$queryRawUnsafe: jest.fn(async (sql: string, ...params: any[]) => {
|
||||
expect(params).toContain('owner')
|
||||
if (sql.includes('SELECT id,revision')) return owner ? [{ id: 'desktop-one', revision, sourceWebId: 'web-one', deleted }] : []
|
||||
if (sql.includes('SELECT id FROM desktop_workspace_projects')) return [{ id: 'desktop-one' }]
|
||||
if (sql.includes('FOR UPDATE')) return [{ revision, deleted, conversation: [] }]
|
||||
if (sql.includes('FOR UPDATE')) return [{ revision, deleted, conversation }]
|
||||
if (sql.includes('desktop_creation_tasks')) return unknown ? [{ id: 'unknown-request' }] : []
|
||||
if (sql.includes('detail_generator_jobs')) return []
|
||||
if (sql.includes('detail_generator_jobs')) return webUnknown ? [{ id: 'original-web-request' }] : []
|
||||
throw new Error(sql)
|
||||
}),
|
||||
$executeRawUnsafe: jest.fn(async (...args: any[]) => { writes.push(args); return 1 }),
|
||||
@ -23,6 +23,28 @@ function fixture({ unknown = false, revision = 3, owner = true, deleted = false
|
||||
}
|
||||
|
||||
beforeEach(() => jest.clearAllMocks())
|
||||
test('one bounded read-only summary query covers the whole page without requesting task payloads', async () => {
|
||||
const rows = [{ id: 'web-one', source: 'web', deleteBlocked: true, deleteBlockedReason: 'pending_request' }]
|
||||
const db = { $queryRawUnsafe: jest.fn().mockResolvedValue(rows) }
|
||||
const refs = [{ id: 'web-one', source: 'web' as const }, { id: 'desktop-one', source: 'desktop' as const }]
|
||||
expect(await projectDeletionSummaries(db, 'owner', refs)).toEqual(rows)
|
||||
expect(db.$queryRawUnsafe).toHaveBeenCalledTimes(1)
|
||||
const [sql, owner, requested] = db.$queryRawUnsafe.mock.calls[0]
|
||||
expect(owner).toBe('owner'); expect(JSON.parse(requested)).toEqual(refs)
|
||||
expect(sql).toContain('p.source_web_id=s.web_id AND p.owner_id=$1')
|
||||
expect(sql).toContain("j.status IN ('queued','running','unknown')")
|
||||
expect(sql).toContain("j.status IN ('queued','running','received','unknown')")
|
||||
expect(sql).toContain('j.lease_until>NOW()')
|
||||
expect(sql).toContain("item->'pending'")
|
||||
expect(sql).toContain("item->'unknown'")
|
||||
expect(sql).not.toMatch(/UPDATE |DELETE |INSERT |payload|request_id|lease_hash/i)
|
||||
})
|
||||
test('empty and oversized lists cannot create unbounded deletion-summary work', async () => {
|
||||
const db = { $queryRawUnsafe: jest.fn() }
|
||||
expect(await projectDeletionSummaries(db, 'owner', [])).toEqual([])
|
||||
await expect(projectDeletionSummaries(db, 'owner', Array.from({ length: 51 }, (_, n) => ({ id: 'project-'+n, source: 'web' as const })))).rejects.toThrow('分页')
|
||||
expect(db.$queryRawUnsafe).not.toHaveBeenCalled()
|
||||
})
|
||||
test('deletion atomically covers a web project and its desktop continuation under the same owner', async () => {
|
||||
const f = fixture()
|
||||
const result = await deleteLinkedProject(f.db, 'owner', 'desktop', 'desktop-one', { revision: 3 })
|
||||
@ -40,6 +62,29 @@ test('an unknown request blocks the entire deletion without modifying task ident
|
||||
await expect(deleteLinkedProject(f.db, 'owner', 'desktop', 'desktop-one', { revision: 3 })).rejects.toMatchObject({ code: 'task_busy' })
|
||||
expect(f.writes).toHaveLength(0)
|
||||
})
|
||||
test.each([
|
||||
{ pending: true },
|
||||
{ unknown: true },
|
||||
])('an unresolved conversation blocks deletion even when the queue is empty: %j', async marker => {
|
||||
const original = { id: 'original-request', role: 'assistant', text: '原结果待核查', requestId: 'upstream-original', ...marker }
|
||||
const f = fixture({ conversation: [original] })
|
||||
await expect(deleteLinkedProject(f.db, 'owner', 'desktop', 'desktop-one', { revision: 3 })).rejects.toMatchObject({ status: 409, code: 'task_busy' })
|
||||
expect(f.writes).toHaveLength(0)
|
||||
expect(original).toEqual({ id: 'original-request', role: 'assistant', text: '原结果待核查', requestId: 'upstream-original', ...marker })
|
||||
})
|
||||
test('a historical successful or explicitly failed conversation does not block an otherwise idle project', async () => {
|
||||
const f = fixture({ conversation: [
|
||||
{ id: 'complete-original', role: 'assistant', text: '已完成', pending: false, unknown: false },
|
||||
{ id: 'failed-original', role: 'assistant', text: '已明确失败', error: true },
|
||||
] })
|
||||
await expect(deleteLinkedProject(f.db, 'owner', 'desktop', 'desktop-one', { revision: 3 })).resolves.toMatchObject({ deleted: true })
|
||||
expect(f.writes).toHaveLength(2)
|
||||
})
|
||||
test('an old web unknown request still protects both linked projects, without clearing history', async () => {
|
||||
const f = fixture({ webUnknown: true })
|
||||
await expect(deleteLinkedProject(f.db, 'owner', 'desktop', 'desktop-one', { revision: 3 })).rejects.toMatchObject({ status: 409, code: 'task_busy' })
|
||||
expect(f.writes).toHaveLength(0)
|
||||
})
|
||||
test('missing ownership, invalid source, and invalid revision cannot delete data', async () => {
|
||||
const f = fixture({ owner: false })
|
||||
await expect(deleteLinkedProject(f.db, 'owner', 'desktop', 'desktop-one', { revision: 3 })).rejects.toMatchObject({ status: 404 })
|
||||
|
||||
@ -1,5 +1,16 @@
|
||||
import catalog from './agent-rule-catalog.json'
|
||||
import { desktopAssert } from './contract.mjs'
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
const canonical = (value: unknown): string => JSON.stringify(value, (_, item) => item && typeof item === 'object' && !Array.isArray(item)
|
||||
? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item)
|
||||
const contentHash = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex')
|
||||
|
||||
function scopedCatalog(binding: typeof catalog.bindings[number]) {
|
||||
const shop = catalog.shops.find(item => item.id === binding.shopId)!
|
||||
return { ...catalog, brands: catalog.brands.filter(item => item.id === shop.brandId), shops: [shop],
|
||||
categories: catalog.categories.filter(item => item.id === binding.categoryId), bindings: [binding] }
|
||||
}
|
||||
|
||||
/** Versioned source package. Never executes the knowledge-base's software workflow. */
|
||||
export function desktopAgentRules(bindingId: string | null) {
|
||||
@ -8,15 +19,14 @@ export function desktopAgentRules(bindingId: string | null) {
|
||||
desktopAssert(bindingId.length <= 100 && /^[a-zA-Z0-9_-]+$/.test(bindingId), '规则编号无效')
|
||||
const binding = ready.find(item => item.id === bindingId)
|
||||
desktopAssert(binding, '此店铺和品类尚未配置规则', 404, 'rules_unavailable')
|
||||
const shop = catalog.shops.find(item => item.id === binding!.shopId)!
|
||||
return { revision: catalog.revision, catalog: { ...catalog,
|
||||
brands: catalog.brands.filter(item => item.id === shop.brandId), shops: [shop],
|
||||
categories: catalog.categories.filter(item => item.id === binding!.categoryId), bindings: [binding!] } }
|
||||
const selected = scopedCatalog(binding!)
|
||||
return { revision: catalog.revision, contentHash: contentHash(selected), catalog: selected }
|
||||
}
|
||||
return { revision: catalog.revision, items: ready.map(binding => {
|
||||
return { revision: catalog.revision, categories: catalog.categories.map(({ id, name }) => ({ id, name })), items: ready.map(binding => {
|
||||
const shop = catalog.shops.find(item => item.id === binding.shopId)!
|
||||
const category = catalog.categories.find(item => item.id === binding.categoryId)!
|
||||
return { id: binding.id, shopId: shop.id, brandId: shop.brandId, categoryId: category.id,
|
||||
shopName: shop.name, categoryName: category.name, label: `${shop.name} · ${category.name}`, version: binding.revision }
|
||||
return { id: binding.id, shopId: shop.id, projectBrandId: shop.id, brandId: shop.brandId, categoryId: category.id,
|
||||
shopName: shop.name, categoryName: category.name, label: `${shop.name} · ${category.name}`, version: binding.revision,
|
||||
contentHash: contentHash(scopedCatalog(binding)) }
|
||||
}) }
|
||||
}
|
||||
|
||||
@ -57,9 +57,16 @@ export async function desktopMaterialThumbnail(ownerId: string, id: string) {
|
||||
}
|
||||
export async function desktopProducts(ownerId: string, params: URLSearchParams) {
|
||||
const matches = await findDetailMaterialMatches(ownerId, params.get('identifierType'), params.get('identifier'))
|
||||
const rows = await prisma.material.findMany({ where: { id: { in: matches.map(item => item.materialId) } }, select: { id: true, categoryName: true } })
|
||||
return { items: matches.map(item => ({ ...item, brandName: rows.find(row => row.id === item.materialId)?.categoryName || '',
|
||||
assets: item.assets.map((asset: { id: string; source: string; name: string }) => ({ id: asset.id, kind: asset.source, name: asset.name })) })) }
|
||||
const rows = await prisma.material.findMany({ where: { id: { in: matches.map(item => item.materialId) } }, select: { id: true, categoryName: true, productCategoryName: true } })
|
||||
const names = [...new Set(rows.map(row => row.productCategoryName).filter((name): name is string => !!name))]
|
||||
// Material stores the explicit category name; ProductCategory.name is unique.
|
||||
// Do not infer category from model text or borrow a similar registered name.
|
||||
const categories = names.length ? await prisma.productCategory.findMany({ where: { name: { in: names } }, select: { id: true, name: true } }) : []
|
||||
return { items: matches.map(item => {
|
||||
const row = rows.find(row => row.id === item.materialId), category = categories.find(category => category.name === row?.productCategoryName)
|
||||
return { ...item, brandName: row?.categoryName || '', categoryId: category?.id || '', categoryName: category?.name || '',
|
||||
assets: item.assets.map((asset: { id: string; source: string; name: string }) => ({ id: asset.id, kind: asset.source, name: asset.name })) }
|
||||
}) }
|
||||
}
|
||||
export async function desktopProductImage(ownerId: string, materialId: string, kind: string, id: string) {
|
||||
desktopId(materialId); desktopId(id)
|
||||
|
||||
@ -31,7 +31,7 @@ export function mergeCreationCanvas(local,canonical,base){
|
||||
return screens
|
||||
}
|
||||
export function emptyBrief() {
|
||||
return { source: 'upload', name: '', brandId: '', brandName: '', identifierType: 'sku', identifier: '', variant: '',
|
||||
return { source: 'upload', name: '', brandId: '', brandName: '', categoryId: '', categoryName: '', identifierType: 'sku', identifier: '', variant: '',
|
||||
colorMaterialId: '', colorName: '', dimensions: { length: '', width: '', height: '', unit: 'mm' }, images: [], note: '' }
|
||||
}
|
||||
export function emptyCreation() {
|
||||
@ -43,6 +43,7 @@ export function validateBrief(value) {
|
||||
const input = object(value), dimensions = object(input.dimensions)
|
||||
const clean = { source: states(input.source, ['upload', 'library']), name: string(input.name, 120, '产品名称'),
|
||||
brandId: string(input.brandId, 150, '品牌'), brandName: string(input.brandName, 120, '品牌名称'),
|
||||
categoryId: string(input.categoryId ?? '', 150, '品类'), categoryName: string(input.categoryName ?? '', 120, '品类名称'),
|
||||
identifierType: states(input.identifierType, ['sku', 'spu', 'barcode']), identifier: string(input.identifier, 200, '产品编号'),
|
||||
variant: string(input.variant, 200, '产品款式'), colorMaterialId: string(input.colorMaterialId, 150, '材质编号'),
|
||||
colorName: string(input.colorName, 200, '材质颜色'), dimensions: { unit: states(dimensions.unit, ['mm', 'cm', 'm']) },
|
||||
|
||||
@ -3,8 +3,47 @@ import { assertDetailProjectIdle, detailTransactionLock } from '@/lib/detail-gen
|
||||
|
||||
type ProjectRef = { id: string; source: 'web' | 'desktop' }
|
||||
type Database = { $transaction: (action: (tx: any) => Promise<any>) => Promise<any> }
|
||||
type ReadDatabase = { $queryRawUnsafe: <T = unknown>(query: string, ...values: any[]) => Promise<T> }
|
||||
const tableFor = (source: string) => source === 'web' ? 'detail_generator_projects' : 'desktop_workspace_projects'
|
||||
|
||||
/** Advisory UI state only: the DELETE transaction must still recheck every task. */
|
||||
export async function projectDeletionSummaries(db: ReadDatabase, ownerId: string, requested: ProjectRef[]) {
|
||||
if (!requested.length) return []
|
||||
desktopAssert(requested.length <= 50, '项目分页超出限制')
|
||||
const rows = await db.$queryRawUnsafe<{ id: string; source: string; deleteBlocked: boolean; deleteBlockedReason: 'pending_request' | 'task_running' | null }[]>(`
|
||||
WITH requested AS (
|
||||
SELECT id,source FROM jsonb_to_recordset($2::jsonb) AS r(id text,source text)
|
||||
), scope AS (
|
||||
SELECT r.id,r.source,CASE WHEN r.source='web' THEN r.id ELSE p.source_web_id END AS web_id
|
||||
FROM requested r LEFT JOIN desktop_workspace_projects p ON r.source='desktop' AND p.id=r.id AND p.owner_id=$1
|
||||
), targets AS (
|
||||
SELECT id AS requested_id,source AS requested_source,id,source FROM scope
|
||||
UNION SELECT id,source,web_id,'web' FROM scope WHERE web_id IS NOT NULL
|
||||
UNION SELECT s.id,s.source,p.id,'desktop' FROM scope s JOIN desktop_workspace_projects p ON p.source_web_id=s.web_id AND p.owner_id=$1
|
||||
), blocked AS (
|
||||
SELECT t.requested_id,t.requested_source,CASE WHEN j.status='unknown' THEN 'pending_request' ELSE 'task_running' END AS reason
|
||||
FROM targets t JOIN detail_generator_jobs j ON t.source='web' AND j.project_id=t.id AND j.owner_id=$1
|
||||
JOIN detail_generator_projects p ON p.id=t.id AND p.owner_id=$1 AND p.deleted_at IS NULL
|
||||
WHERE j.status IN ('queued','running','unknown')
|
||||
UNION ALL
|
||||
SELECT t.requested_id,t.requested_source,CASE WHEN j.status IN ('received','unknown') THEN 'pending_request' ELSE 'task_running' END
|
||||
FROM targets t JOIN desktop_creation_tasks j ON t.source='desktop' AND j.project_id=t.id AND j.owner_id=$1
|
||||
JOIN desktop_workspace_projects p ON p.id=t.id AND p.owner_id=$1 AND p.deleted_at IS NULL
|
||||
WHERE j.status IN ('queued','running','received','unknown') OR j.lease_until>NOW()
|
||||
UNION ALL
|
||||
SELECT t.requested_id,t.requested_source,'pending_request'
|
||||
FROM targets t JOIN desktop_workspace_projects p ON t.source='desktop' AND p.id=t.id AND p.owner_id=$1 AND p.deleted_at IS NULL
|
||||
WHERE EXISTS (SELECT 1 FROM jsonb_array_elements(p.conversation) item WHERE
|
||||
(item->'pending' IS NOT NULL AND item->'pending' NOT IN ('null'::jsonb,'false'::jsonb,'0'::jsonb,'""'::jsonb)) OR
|
||||
(item->'unknown' IS NOT NULL AND item->'unknown' NOT IN ('null'::jsonb,'false'::jsonb,'0'::jsonb,'""'::jsonb)))
|
||||
)
|
||||
SELECT r.id,r.source,COUNT(b.reason)>0 AS "deleteBlocked",
|
||||
CASE WHEN bool_or(b.reason='pending_request') THEN 'pending_request' WHEN COUNT(b.reason)>0 THEN 'task_running' ELSE NULL END AS "deleteBlockedReason"
|
||||
FROM requested r LEFT JOIN blocked b ON b.requested_id=r.id AND b.requested_source=r.source GROUP BY r.id,r.source
|
||||
`, ownerId, JSON.stringify(requested))
|
||||
return rows
|
||||
}
|
||||
|
||||
/** A web project and its desktop continuation are one deletion scope. Files stay private. */
|
||||
export async function deleteLinkedProject(db: Database, ownerId: string, source: string, id: string, input: unknown) {
|
||||
desktopId(id)
|
||||
|
||||
@ -4,7 +4,7 @@ import { assertDetailGeneratorUser } from '@/lib/detail-generator/access'
|
||||
import { findDetailProject, listDetailAssets, findDetailAsset } from '@/lib/detail-generator/repository'
|
||||
import { readDetailFile, saveDetailFile, deleteDetailFile } from '@/lib/detail-generator/storage'
|
||||
import { desktopAssert, desktopAuthorization, desktopId, desktopProjectBody, DesktopClientError, DESKTOP_CLIENT_ID, DESKTOP_SCOPES } from './contract.mjs'
|
||||
import { deleteLinkedProject } from './project-lifecycle'
|
||||
import { deleteLinkedProject, projectDeletionSummaries } from './project-lifecycle'
|
||||
|
||||
const hash = (value: string | Buffer) => createHash('sha256').update(value).digest('hex')
|
||||
const db = prisma
|
||||
@ -61,8 +61,10 @@ export async function listDesktopProjects(ownerId: string, cursor: string | null
|
||||
SELECT p.id,'desktop' AS source,p.document->>'name' AS name,p.status,p.revision,p.source_web_id,p.updated_at,(p.document->'screens'->0->>'width')::int AS width,jsonb_array_length(p.document->'screens') AS screen_count,(p.status<>'completed' OR p.composer<>'') AS has_draft,p.deleted_at,p.document->'screens'->0->>'previewSource' AS preview_source,CASE WHEN p.document->>'version'='3' AND (p.document->'native'->>'documentSource' IS NULL OR EXISTS(SELECT 1 FROM jsonb_array_elements(p.document->'screens') screen WHERE screen->>'previewSource' IS NULL)) THEN 'pending' ELSE 'ready' END AS backup_state FROM desktop_workspace_projects p WHERE p.owner_id=$1
|
||||
UNION ALL SELECT p.id,'web',p.document->>'name','draft',p.revision,NULL::text,p.updated_at,COALESCE((p.document->'screens'->0->>'width')::int,750),jsonb_array_length(p.document->'screens'),true,p.deleted_at,NULL::text,'ready' FROM detail_generator_projects p WHERE p.owner_id=$1 AND (p.deleted_at IS NOT NULL OR NOT EXISTS(SELECT 1 FROM desktop_workspace_projects d WHERE d.owner_id=$1 AND d.source_web_id=p.id))
|
||||
) AS projects WHERE (updated_at,id,source)<($2::timestamptz,$3::text,$4::text) ORDER BY updated_at DESC,id DESC,source DESC LIMIT 51`, ownerId, point.date, point.id, point.source)
|
||||
const page = rows.slice(0,50), last = page.at(-1)
|
||||
return { items:page.filter(item=>!item.deletedAt), deleted:page.filter(item=>item.deletedAt).map(item=>({id:item.id,source:item.source})), nextCursor: rows.length > 50 && last ? Buffer.from(JSON.stringify({date:new Date(last.updatedAt).toISOString(),id:last.id,source:last.source})).toString('base64url') : null }
|
||||
const page = rows.slice(0,50), last = page.at(-1), items = page.filter(item=>!item.deletedAt)
|
||||
const deletion = await projectDeletionSummaries(db, ownerId, items.map(item=>({ id:item.id, source:item.source })))
|
||||
const summaries = new Map(deletion.map(item=>[item.source+':'+item.id,item]))
|
||||
return { items:items.map(item=>({...item,...summaries.get(item.source+':'+item.id)})), deleted:page.filter(item=>item.deletedAt).map(item=>({id:item.id,source:item.source})), nextCursor: rows.length > 50 && last ? Buffer.from(JSON.stringify({date:new Date(last.updatedAt).toISOString(),id:last.id,source:last.source})).toString('base64url') : null }
|
||||
}
|
||||
export async function getDesktopProject(ownerId: string, source: string, id: string) {
|
||||
desktopId(id)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user