合入 R4 修复到 R5(含生图链接结果、有界恢复与恢复队列收口)

This commit is contained in:
WuYongJie 2026-11-28 02:07:10 +08:00
commit 32fbc9fd06
14 changed files with 960 additions and 225 deletions

View File

@ -17,7 +17,7 @@ export function productionGoalPreflight(goal) {
export function productionObjective(requestedOutputs) {
const outputs = [...new Set(requestedOutputs.map(row=>row.label || row.outputId))].join('、');
return `按适用制作指引和模板制作并交付本轮所选输出:${outputs}。`;
return `按适用制作指引和模板制作并交付本轮所选输出:${outputs}。本轮为无人值守制作,没有人工后期,也没有人等待回答选择;指引中交给人工处理或需要用户确认的事项,可依据商品资料用现有工具处理,确实无法处理的在交付回执中如实列出。`;
}
export function piGoalState(manager) {

View File

@ -110,7 +110,7 @@ export const productionOperationTools = [
})],
['adopt_production_image','采用你选择的候选,返回画布修订和覆盖该图位的模板叠层。尺寸线、虚线、引线、文字和装饰角标的错位或数值是否匹配本款,可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit)})],
['retire_production_image','清理你已判为失败的当前图位候选,保留原因、提示词和原请求记录。返工需要旧图时,先让子代理读取再清理。若该图已在画布上,回执会给出应替换的图层。',obj({slotId:slotRef,candidateId:text,reason:text})],
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号;expired 表示原结果已过期,可以为同图位另备新请求。可指定成品和花色。',obj({...outputScope,slotIds:optional(ids)})],
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号,结果有留存时按原号取回,不重新付费。expired 表示原结果已不可取回:网关确认结果过期(HTTP 410)、结果链接下载返回 404 或 410,或原请求在 180 秒恢复预算用完后仍是 unresolved。expired 可以为同图位另备新请求;已派发的原请求仍计入该图位的生图次数上限。',obj({...outputScope,slotIds:optional(ids)})],
['read_output_screen',`读取整屏合成画面的实际像素和 overlayLayers。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。只保留最新一次查看图片。${COPY_IMAGE_SCREEN_GUIDANCE}需要修正时通过 native_catalog 查命令,再用 native_call 编辑叠层,或用 write_copy_fields、transform_slot_image 更新映射内容。`,obj({
page:optional(page),pages:optional(Type.Array(page)),
})],

View File

@ -1291,7 +1291,9 @@ test('the host can settle 410, failure and exhausted unresolved, then Pi can pre
const {host,ledger}=await tailFixture(t,['hero']);
let status='unknown';
const posted=[], reads=[];
const resultExpiry={httpStatus:410,requestId:'original-remote'};
const resultExpiry=terminal==='unresolved'
? {source:'unresolved',requestId:'original-remote',unresolvedSince:100,observedAt:280}
: {httpStatus:410,requestId:'original-remote'};
host.canvas.detailRecover=async(slotId,{candidateId})=>{
reads.push([slotId,candidateId]);
return {id:candidateId,status,...(status==='expired'?{resultExpiry}:null)};
@ -1308,10 +1310,10 @@ test('the host can settle 410, failure and exhausted unresolved, then Pi can pre
assert.equal((await generateAndWait(actions,{...input,prompt:'新提示词'})).pendingOriginal,original.candidateId);
assert.deepEqual(posted,[original.candidateId]);
// Exhaustion is a terminal receipt supplied by the Rust recovery owner.
status=terminal==='unresolved'?'failed':terminal;
status=terminal==='unresolved'?'expired':terminal;
const [settled]=await actions.reconcile_image_slots({});
assert.equal(settled.phase,status);
if(terminal==='expired')assert.deepEqual(settled.resultExpiry,resultExpiry);
if(status==='expired')assert.deepEqual(settled.resultExpiry,resultExpiry);
assert.equal((await actions.dispatch_image_request({requestId:original.candidateId})).phase,status);
const next=await generateAndWait(actions,{...input,prompt:'新提示词'});
assert.equal(next.phase,'complete');

View File

@ -110,6 +110,7 @@ test('the unattended objective records the intended delivery', () => {
assert.doesNotMatch(source('skills/product-image-sources/SKILL.md'),technicalBrand);
assert.match(objective, /按适用制作指引和模板制作并交付[^。]*详情图/);
assert.doesNotMatch(objective, /useTemplateReference|read_output_screen/);
assert.match(objective, /无人值守制作,没有人工后期[^。]*交付回执中如实列出/);
assert.doesNotMatch(objective, technicalBrand);
});

View File

@ -63,9 +63,15 @@ cargo xtask wasm
不会转为新的生成请求。缺少请求号、且没有已保存原响应或异步任务号时,使用原幂等键调用
`GET /api/external/requests/by-idempotency-key`。只有明确成功、结果可取回、请求号有效,且
结果路径精确为该请求的相对公开接口时,才先把请求号保存到两份原任务记录,再 GET 原结果。
查询失败、运行中、不可取回或状态不明仍保留待核查,不转换为生成重试。人工补充原请求号
查询失败、运行中、不可取回或状态不明仍保留待核查,不转换为生成重试。原幂等键查询为
`unresolved` 时,从首次看到它起计 180 秒恢复预算;预算用完仍为 `unresolved` 的原请求记为
`expired`,图位可以另备新请求。人工补充原请求号
也须通过原 Key 校验,不能覆盖已有的不同请求号。98k 留存接口的原始响应直接解析,另支持
明确的 `data` 对象封装。
明确的 `data` 对象封装。参考图按线路契约传输:线路接受时,不透明参考图以 JPEG 上传,
带透明像素的参考图和实拍合成的模板底图保持 PNG。线路声明压缩出图格式且背景为不透明时,
出图请求使用该格式。线路明确列出 `response_format` 可取 `url` 时,生图请求取 URL 结果:
网关只返回 `https://api.vip98k.com/api/external/assets/` 下的限时链接,宿主下载时不附带个人
Key,解码后照常保存为 `generated.png`。链接下载返回 404 或 410 时,原请求记为 `expired`。
启动后按原账户扫描本机未决任务,只使用原 Key 核查。处理中或临时网络失败按逐渐延长的
间隔继续 GET,本次启动共用最多 180 秒恢复窗口;404、410、无法确认归属或结果不可取回

View File

@ -829,6 +829,22 @@ fn records(dir: &Path, state: &Value) -> R<Vec<Value>> {
Ok(out)
}
fn pending_production_image(record: &Value, task: &Value) -> R<Option<Value>> {
let binding = &record["binding"];
if binding["detailBatch"] != true || !task["outputScope"].is_string() || !record["sourceType"].is_null()
|| !record["retirement"].is_null()
|| !matches!(task["phase"].as_str(), Some("dispatched" | "running" | "unknown")) {
return Ok(None);
}
let id = uuid(&record["id"], "原候选")?;
if task["id"] != id || task["slotBinding"] != *binding {
return Err("原候选任务与图位记录不一致".into());
}
Ok(Some(json!({"candidateId":id,"operationId":record["workflowOperationId"].as_str().unwrap_or(&id),
"slotId":binding["slotId"],"variantId":binding["variantId"],"outputId":task["outputScope"],
"phase":task["phase"],"reason":task["message"]})))
}
fn pending_production_images(dir: &Path, state: &Value) -> R<Value> {
let mut pending = Vec::new();
for record in records(dir, state)? {
@ -841,15 +857,7 @@ fn pending_production_images(dir: &Path, state: &Value) -> R<Value> {
let id = uuid(&record["id"], "原候选")?;
let file = dir.join("image-jobs").join(&id).join("task.json");
if !file.try_exists().map_err(|error| error.to_string())? { continue; }
let task = read_json(&file)?;
if task["id"] != id || task["slotBinding"] != *binding {
return Err("原候选任务与图位记录不一致".into());
}
if matches!(task["phase"].as_str(), Some("dispatched" | "running" | "unknown")) {
pending.push(json!({"candidateId":id,"operationId":record["workflowOperationId"].as_str().unwrap_or(&id),
"slotId":binding["slotId"],"variantId":binding["variantId"],"outputId":task["outputScope"],
"phase":task["phase"],"reason":task["message"]}));
}
pending.extend(pending_production_image(&record, &read_json(&file)?)?);
}
Ok(json!(pending))
}
@ -915,7 +923,7 @@ pub(super) fn pending_summary(dir: &Path) -> R<Vec<Value>> {
let state = load(dir)?;
let mut pending = Vec::new();
for record in records(dir, &state)? {
if !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
if candidate_needs_recovery(dir, &record)? {
pending.push(json!({"id":record["id"],"phase":record["phase"],"kind":"canvas-candidate"}));
}
}
@ -1202,6 +1210,15 @@ fn candidate_projection_task(dir: &Path, record: &Value) -> R<Option<Value>> {
if task.is_file() { read_json(&task).map(Some) } else { Ok(None) }
}
fn candidate_needs_recovery(dir: &Path, record: &Value) -> R<bool> {
if matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
return Ok(false);
}
let task = candidate_projection_task(dir, record)?;
Ok(!task.is_some_and(|task|
matches!(task["phase"].as_str(), Some("complete" | "applied" | "failed" | "expired"))))
}
fn generation_was_dispatched(record: &Value, task: Option<&Value>) -> bool {
record["sourceType"].is_null() && record["reusedFrom"].is_null()
&& task.map_or_else(|| matches!(record["phase"].as_str(), Some("complete" | "expired")),
@ -1601,8 +1618,7 @@ fn local_pending(dir: &Path, state: &Value, except: Option<&Value>, batch: Optio
return Ok(true);
}
for record in records(dir, state)? {
if !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired"))
&& !except.is_some_and(|binding| record["binding"] == *binding && matches!(record["phase"].as_str(), Some("prepared" | "dispatched")))
if !except.is_some_and(|binding| record["binding"] == *binding && matches!(record["phase"].as_str(), Some("prepared" | "dispatched")))
&& !batch.is_some_and(|binding| {
let sibling = &record["binding"];
sibling["detailBatch"] == true && (sibling["slotId"] != binding["slotId"]
@ -1610,7 +1626,7 @@ fn local_pending(dir: &Path, state: &Value, except: Option<&Value>, batch: Optio
&& sibling["taskId"] != binding["taskId"])
&& (sibling["variantId"] == binding["variantId"] && sibling["templateHash"] == binding["templateHash"]
|| product_slot_binding(state, binding) && product_slot_binding(state, sibling))
})
}) && candidate_needs_recovery(dir, &record)?
{
return Ok(true);
}
@ -1630,13 +1646,23 @@ fn transient_image_preflight(error: &str) -> bool {
pub(super) fn reconcile_candidate(dir: &Path, journal: &Value) -> R<Value> {
let _guard = sync::context_guard();
let (_, mut record) = checked_binding(dir, &journal["slotBinding"], true)?;
let (_, record) = checked_binding(dir, &journal["slotBinding"], true)?;
let mut projected = project_candidate(dir, &record, journal)?;
if projected != record {
projected["updatedAt"] = json!(now());
write_json(&candidate_path(dir, record["id"].as_str().ok_or("原候选身份缺失")?)?, &projected)?;
}
Ok(projected)
}
fn project_candidate(dir: &Path, record: &Value, journal: &Value) -> R<Value> {
if journal["id"] != record["id"] || record["requestId"].is_string() && journal["requestId"].is_string() && record["requestId"] != journal["requestId"] {
return Err("原候选请求号不匹配,未修改记录".into());
}
if matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
return Ok(record);
return Ok(record.clone());
}
let mut record = record.clone();
let phase = match journal["phase"].as_str() {
Some("prepared") if journal["notDispatched"] == true => "failed",
Some("prepared" | "dispatched") => "dispatched",
@ -1651,7 +1677,6 @@ pub(super) fn reconcile_candidate(dir: &Path, journal: &Value) -> R<Value> {
let artifact = template_slots::artifact(dir, record["id"].as_str().ok_or("原候选身份缺失")?, journal)?;
record["artifact"] = artifact;
}
let previous = record.clone();
record["phase"] = json!(phase);
if phase == "expired" { record["resultExpiry"] = journal["resultExpiry"].clone(); }
let preflight_retry = journal["phase"] == "prepared" && journal["notDispatched"] == true
@ -1667,10 +1692,6 @@ pub(super) fn reconcile_candidate(dir: &Path, journal: &Value) -> R<Value> {
if journal["message"].is_string() {
record["message"] = journal["message"].clone();
}
if record != previous {
record["updatedAt"] = json!(now());
write_json(&candidate_path(dir, record["id"].as_str().ok_or("原候选身份缺失")?)?, &record)?;
}
Ok(record)
}
fn mapping_key(variant: &str, component: &str, document: Option<&str>) -> String {
@ -1881,10 +1902,10 @@ impl Backend {
// POST yet. It owns recovery until it releases the dispatch lock.
let _dispatch = if let Some(record) = local_candidate.as_ref() {
let Some(dispatch) = lock_candidate_dispatch(&source_dir, &candidate)? else {
return Ok(pending_candidate(record));
return Ok((pending_candidate(record), false));
};
if !file.try_exists().map_err(|error| error.to_string())? {
return recover_candidate_without_task(&source_dir, record);
return recover_candidate_without_task(&source_dir, record).map(|record| (record, true));
}
Some(dispatch)
} else { None };
@ -1892,20 +1913,27 @@ impl Backend {
if original["id"] != candidate {
return Err("原候选任务身份已变化".into());
}
if let Some(record) = local_candidate.as_ref()
&& original["outputScope"].is_string() && original["slotBinding"]["detailBatch"] == true {
if original["slotBinding"] != record["binding"] {
return Err("原候选任务与图位记录不一致".into());
}
return project_candidate(&source_dir, record, &original).map(|record| (record, false));
}
let record = reconcile_candidate(&source_dir, &original)?;
if matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
return Ok(record);
return Ok((record, true));
}
// Query the saved task by its original request information.
self.image_job(None, &json!({"doc":source_doc,"taskId":candidate,"recoveryBudgetMs":9000}), true, events, ctx)?;
reconcile_candidate(&source_dir, &read_json(&file)?)
reconcile_candidate(&source_dir, &read_json(&file)?).map(|record| (record, true))
})();
if doc != source_doc {
self.owners.remove(&source_doc);
self.locations.remove(&source_doc);
}
let record = result?;
if doc == source_doc {
let (record, refresh) = result?;
if refresh && doc == source_doc {
publish_prepared(events, self.canvas_workspace_result(doc, &dir)?)?;
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
@ -3195,14 +3223,23 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>, read_only: bool) -> R<Valu
};
let active = state["activeVariantId"].as_str().ok_or("当前花色缺失")?;
let mut dispatched_generations = std::collections::HashSet::new();
let mut pending_image_requests = Vec::new();
for record in &mut history {
let task = candidate_projection_task(dir, record)?;
if generation_was_dispatched(record, task.as_ref()) {
dispatched_generations.insert(uuid(&record["id"], "候选")?);
}
if !read_only && !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired"))
&& let Some(task) = task {
*record = reconcile_candidate(dir, &task)?;
if let Some(task) = task {
if !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
if !read_only {
*record = reconcile_candidate(dir, &task)?;
} else if matches!(task["phase"].as_str(), Some("complete" | "applied" | "failed" | "expired")) {
*record = project_candidate(dir, record, &task)?;
}
}
if let Some(row) = pending_production_image(record, &task)? {
pending_image_requests.push(json!({"candidateId":row["candidateId"],"outputId":row["outputId"],"variantId":row["variantId"]}));
}
}
}
let current = creation::load(dir)?;
@ -3290,6 +3327,7 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>, read_only: bool) -> R<Valu
workflow["productionStages"] = json!(runnable_stages(&state, remaining_stages(dir, &state, &current["revision"], false)));
workflow["productionBlocks"] = json!(blocked_production_stages(&state));
workflow["scopedProductionPending"] = json!(scoped_production_pending);
workflow["pendingImageRequests"] = json!(pending_image_requests);
}
Ok(workflow)
}
@ -3474,7 +3512,7 @@ impl Backend {
}
let call = self.image_job(None, &input, false, events, ctx);
let dispatch_error = |error, backend: &Self| BridgeFailure::new("image_request_failed", false, backend.image_dispatch_may_have_started(doc, &id), error);
let result = self.settle_image_candidate(dir, doc, &id, slot, call, events, ctx)
let result = self.settle_image_candidate(dir, doc, &id, slot, call, events, ctx, !admitted)
.map_err(|error| dispatch_error(error, self))
.and_then(|(mut receipt, failure)| {
if receipt["status"] == "failed" && let Some(message) = failure {
@ -3496,14 +3534,14 @@ impl Backend {
}
fn settle_image_candidate(&mut self, dir: &Path, doc: u64, id: &str, binding: &Value, mut call: R<Value>,
events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<(Value, Option<String>)> {
events: &mpsc::Sender<Event>, ctx: &egui::Context, recover_inline: bool) -> R<(Value, Option<String>)> {
let file = dir.join("image-jobs").join(id).join("task.json");
let mut journal = if file.try_exists().map_err(|_| "原生图记录无法核对,保留原候选")? {
read_json(&file)?
} else {
json!({"id":id,"slotBinding":binding,"phase":"prepared","notDispatched":true,"message":call.as_ref().err()})
};
if matches!(journal["phase"].as_str(), Some("dispatched" | "running" | "unknown")) {
if recover_inline && matches!(journal["phase"].as_str(), Some("dispatched" | "running" | "unknown")) {
call = self.recover_original_image(doc, id, events, ctx);
journal = read_json(&file)?;
} else if journal["phase"] == "prepared" && let Err(error) = &call {
@ -3553,10 +3591,13 @@ impl Backend {
self.recover_archived_image(input, &check)?;
}
check()?;
// The regular workflow read reconciles this journal on return to the output.
let journal = read_json(&file)?;
let status = if journal["phase"] == "applied" { json!("complete") } else { journal["phase"].clone() };
Ok(json!({"id":id,"status":status}))
let mut receipt = json!({"id":id,"status":status,"variantId":input["variantId"]});
if matches!(status.as_str(), Some("complete" | "failed" | "expired")) {
receipt["workflow"] = snapshot_for_view(&dir, None, true)?;
}
Ok(receipt)
}
pub(super) fn canvas_workspace_action(&mut self, method: &str, input: &Value, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<Value> {
@ -5786,6 +5827,47 @@ mod tests {
assert!(!candidate_path(&dir, record["id"].as_str().unwrap()).unwrap().with_file_name("task.json").exists());
}
#[test]
fn production_original_reads_the_host_expiry_without_recovering_or_rewriting() {
let fixture = fixture();
let mut backend = Backend::new(fixture.dir.join("profile")).unwrap();
let doc = 1;
backend.bind_new(doc);
let dir = backend.project_dir(doc).unwrap();
write_json(&dir.join("context.json"), &json!({"doc":doc})).unwrap();
let mut state = load(&fixture.dir).unwrap();
state["productTemplates"] = json!({"detail":state["template"]});
persist(&dir, state, 0).unwrap();
let state = load(&dir).unwrap();
let mut record = candidate(&dir, "unknown");
record["binding"]["detailBatch"] = json!(true);
reserve(&dir, state.clone(), &record).unwrap();
let id = record["id"].as_str().unwrap();
let file = dir.join("image-jobs").join(id).join("task.json");
let mut task = json!({"id":id,"phase":"unknown","requestId":Uuid::new_v4(),
"outputScope":"detail","slotBinding":record["binding"]});
let target = json!({"projectScope":true,"workspaceId":state["id"],"outputId":"detail",
"variantId":state["activeVariantId"],"slotId":record["binding"]["slotId"],
"source":{"candidateId":id,"recover":true}});
let (events, receiver) = mpsc::channel();
let ctx = egui::Context::default();
super::super::images::settle_unresolved(&mut task, 100);
write_json(&file, &task).unwrap();
assert_eq!(backend.detail_archive(doc, &target, &events, &ctx).unwrap()["status"], "unknown");
assert_eq!(read_json(&file).unwrap(), task);
super::super::images::settle_unresolved(&mut task, 280);
write_json(&file, &task).unwrap();
let receipt = backend.detail_archive(doc, &target, &events, &ctx).unwrap();
assert_eq!(receipt["id"], id);
assert_eq!(receipt["status"], "expired");
assert_eq!(receipt["resultExpiry"], task["resultExpiry"]);
assert!(pending_summary(&dir).unwrap().is_empty());
assert_eq!(read_candidate(&dir, id).unwrap(), record);
assert_eq!(read_json(&file).unwrap(), task);
assert!(receiver.try_recv().is_err());
}
#[test]
#[ignore = "child process for the native candidate recovery test"]
fn candidate_dispatch_lock_child() {
@ -5917,6 +5999,53 @@ mod tests {
assert_eq!(pending_summary(&fixture.dir).unwrap()[0]["id"], next["id"]);
}
#[test]
fn unresolved_original_releases_its_slot_once_the_recovery_budget_is_spent() {
let fixture = fixture();
let original = candidate(&fixture.dir, "dispatched");
let next = candidate(&fixture.dir, "dispatched");
reserve(&fixture.dir, load(&fixture.dir).unwrap(), &original).unwrap();
let request_id = Uuid::new_v4().to_string();
let mut task = json!({"id":original["id"],"slotBinding":original["binding"],"phase":"unknown","requestId":request_id});
let first = 1_795_781_555;
super::super::images::settle_unresolved(&mut task, first);
reconcile_candidate(&fixture.dir, &task).unwrap();
assert!(reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).is_err(), "inside its budget the original keeps the slot");
super::super::images::settle_unresolved(&mut task, first + super::super::images::IMAGE_REQUEST_TIMEOUT.as_secs());
assert_eq!(reconcile_candidate(&fixture.dir, &task).unwrap()["phase"], "expired");
assert!(pending_summary(&fixture.dir).unwrap().is_empty());
reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).unwrap();
let receipt = candidate_receipt(&read_candidate(&fixture.dir, original["id"].as_str().unwrap()).unwrap());
assert_eq!(receipt["status"], "expired");
assert_eq!(receipt["retryable"], false);
assert_eq!(receipt["requestId"], request_id);
assert_eq!(receipt["resultExpiry"]["source"], "unresolved");
}
#[test]
fn an_expired_result_link_releases_its_slot_like_a_retained_result_gone() {
for code in [404, 410] {
let fixture = fixture();
let original = candidate(&fixture.dir, "dispatched");
let next = candidate(&fixture.dir, "dispatched");
reserve(&fixture.dir, load(&fixture.dir).unwrap(), &original).unwrap();
let request_id = Uuid::new_v4().to_string();
let mut task = json!({"id":original["id"],"slotBinding":original["binding"],"phase":"unknown","requestId":request_id});
reconcile_candidate(&fixture.dir, &task).unwrap();
assert!(reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).is_err());
super::super::images::retain_result_expiry(&mut task, "image-asset", code);
assert_eq!(reconcile_candidate(&fixture.dir, &task).unwrap()["phase"], "expired");
assert!(pending_summary(&fixture.dir).unwrap().is_empty());
reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).unwrap();
let receipt = candidate_receipt(&read_candidate(&fixture.dir, original["id"].as_str().unwrap()).unwrap());
assert_eq!(receipt["status"], "expired");
assert_eq!(receipt["retryable"], false);
assert_eq!(receipt["requestId"], request_id);
assert_eq!(receipt["resultExpiry"]["source"], "image-asset");
assert_eq!(receipt["resultExpiry"]["httpStatus"], code);
}
}
#[test]
fn distinct_frozen_requests_can_reserve_the_same_slot_while_the_first_is_pending() {
let fixture = fixture();

View File

@ -2,6 +2,9 @@
//! inline private references, and no model-name-specific transport guesses.
use serde_json::{Value, json};
/// Quality used when a route declares a compressed result format.
pub(super) const OUTPUT_COMPRESSION: u8 = 95;
fn parts(s: &Value, depth: usize) -> Vec<&Value> {
if depth > 5 {
return vec![];
@ -252,7 +255,13 @@ pub fn select_model(m: &Value) -> Result<Value, String> {
continue;
}
let candidates = if name == "response_format" {
vec![json!("b64_json"), json!("url")]
// A URL result keeps the success body small enough for the gateway to
// retain, so it is preferred wherever the route explicitly lists it.
if rules.iter().any(|rule| rule["const"] == "url" || rule["enum"].as_array().is_some_and(|values| values.contains(&json!("url")))) {
vec![json!("url"), json!("b64_json")]
} else {
vec![json!("b64_json"), json!("url")]
}
} else if name == "quality" && rules.iter().any(|s| s["enum"].as_array().is_some_and(|a| a.contains(&json!("medium")))) {
vec![json!("medium")]
} else {
@ -269,14 +278,38 @@ pub fn select_model(m: &Value) -> Result<Value, String> {
params.remove(name);
}
}
let mut body = Value::Object(params.clone());
body["model"] = json!(model);
body["prompt"] = json!("product scene");
body[field] = json!(["data:image/png;base64,AA=="]);
if !multipart && !accepts(&body, schema, 0) {
let admitted = |params: &serde_json::Map<String, Value>| {
let mut body = Value::Object(params.clone());
body["model"] = json!(model);
body["prompt"] = json!("product scene");
body[field] = json!(["data:image/png;base64,AA=="]);
multipart || accepts(&body, schema, 0)
};
if !admitted(&params) {
continue;
}
found.push(json!({"path":path,"route":id,"field":field,"multipart":multipart,"probe":probe,"maxImages":max,"schema":schema,"parameters":params}));
let declared = |name: &str, value: &Value| {
let rules: Vec<_> = nodes.iter().filter_map(|n| n["properties"].get(name)).collect();
!rules.is_empty() && rules.iter().all(|rule| accepts(value, rule, 0))
};
// An opaque result may come back as a compressed raster when the route
// declares one. The smaller success body stays within the retained-result limit.
if params.get("background") == Some(&json!("opaque"))
&& let Some(format) = ["jpeg", "webp"].into_iter().find(|format| declared("output_format", &json!(format)))
{
let mut compressed = params.clone();
compressed.insert("output_format".into(), json!(format));
if declared("output_compression", &json!(OUTPUT_COMPRESSION)) {
compressed.insert("output_compression".into(), json!(OUTPUT_COMPRESSION));
}
if admitted(&compressed) {
params = compressed;
}
}
// Multipart files carry their own type; an inline field must accept a JPEG data URL.
let jpeg_references = multipart || nodes.iter().all(|n| accepts(&json!(["data:image/jpeg;base64,AA=="]), &n["properties"][field], 0));
found.push(json!({"path":path,"route":id,"field":field,"multipart":multipart,"probe":probe,"maxImages":max,"schema":schema,
"parameters":params,"jpegReferences":jpeg_references}));
}
}
found.sort_by_key(|p| (p["probe"] == true, p["path"] != "/extensions/v1/tasks", p["multipart"] == true));
@ -328,6 +361,84 @@ mod tests {
assert_eq!(p["maxImages"], 8);
assert_eq!(p["parameters"], json!({"n":1,"response_format":"b64_json"}));
}
fn route(path: &str, content_type: &str, schema: Value) -> Result<Value, String> {
let mut c = catalog();
let invocation = &mut c["data"]["sections"][0]["models"][0]["service_offers"][0]["route_options"][0]["invocation"];
invocation["path"] = json!(path);
invocation["content_type"] = json!(content_type);
invocation["input_schema"] = schema;
select(&c, "test-image")
}
fn edit_schema(output_format: Value, output_compression: Option<Value>, background: &str) -> Value {
let mut schema = json!({"type":"object","additionalProperties":true,"properties":{"model":{"type":"string"},"prompt":{"type":"string"},
"image[]":{},"n":{"type":"integer"},"response_format":{"enum":["url","b64_json"]},
"background":{"enum":["opaque","auto","transparent"],"default":background},"output_format":output_format}});
if let Some(rule) = output_compression {
schema["properties"]["output_compression"] = rule;
}
schema
}
#[test]
fn opaque_results_use_only_a_compressed_format_the_route_declares() {
let edits = |schema| route("/v1/images/edits", "multipart/form-data", schema).unwrap()["parameters"].clone();
let png_or_jpeg = json!({"enum":["png","jpeg","webp"],"default":"png"});
let compression = json!({"type":["integer","null"],"minimum":0,"maximum":100});
let declared = edits(edit_schema(png_or_jpeg.clone(), Some(compression.clone()), "opaque"));
assert_eq!(declared["output_format"], "jpeg");
assert_eq!(declared["output_compression"], OUTPUT_COMPRESSION);
assert_eq!(declared["background"], "opaque");
assert_eq!(edits(edit_schema(json!({"enum":["png","webp"],"default":"png"}), Some(compression.clone()), "opaque"))["output_format"], "webp");
let uncontrolled = edits(edit_schema(png_or_jpeg.clone(), None, "opaque"));
assert_eq!(uncontrolled["output_format"], "jpeg");
assert!(uncontrolled.get("output_compression").is_none(), "an undeclared compression control is never sent");
// The R3 route publishes PNG/GIF only and disables output_compression.
let png_only = edits(edit_schema(json!({"enum":["png","gif"],"type":"string","default":"png"}), Some(json!(false)), "opaque"));
assert_eq!(png_only["output_format"], "png");
assert!(png_only.get("output_compression").is_none());
for background in ["auto", "transparent"] {
let kept = edits(edit_schema(png_or_jpeg.clone(), Some(compression.clone()), background));
assert_eq!(kept["output_format"], "png", "{background} results keep their lossless format");
assert!(kept.get("output_compression").is_none());
}
// A JSON route whose whole contract refuses the compressed body keeps the original choice.
let mut strict = edit_schema(png_or_jpeg, Some(compression), "opaque");
strict["properties"]["images"] = json!({"type":"array","items":{"type":"string","pattern":"^data:image/"}});
strict["not"] = json!({"required":["output_compression"]});
let kept = route("/v1/images/edits", "application/json", strict).unwrap();
assert_eq!(kept["field"], "images");
assert_eq!(kept["parameters"]["output_format"], "png");
}
#[test]
fn url_results_are_requested_only_where_the_route_lists_them() {
let format = |rule: Option<Value>| {
let mut schema = edit_schema(json!({"enum":["png"],"default":"png"}), None, "opaque");
match rule {
Some(rule) => schema["properties"]["response_format"] = rule,
None => { schema["properties"].as_object_mut().unwrap().remove("response_format"); }
}
route("/v1/images/edits", "multipart/form-data", schema).unwrap()["parameters"]["response_format"].clone()
};
// The R3 route publishes {"enum":["url","b64_json"]}.
assert_eq!(format(Some(json!({"enum":["url","b64_json"]}))), "url");
assert_eq!(format(Some(json!({"const":"url"}))), "url");
assert_eq!(format(Some(json!({"enum":["b64_json"]}))), "b64_json");
assert_eq!(format(Some(json!({"type":["string","null"]}))), "b64_json", "an open string does not list URL delivery");
assert_eq!(format(None), "b64_json");
assert_eq!(select(&catalog(), "test-image").unwrap()["parameters"]["response_format"], "b64_json");
}
#[test]
fn references_compress_only_where_the_route_accepts_a_jpeg_reference() {
let multipart = route("/v1/images/edits", "multipart/form-data", edit_schema(json!({"enum":["png"]}), None, "opaque")).unwrap();
assert_eq!(multipart["jpegReferences"], true, "multipart files declare their own type");
let schema = |pattern: &str| json!({"type":"object","additionalProperties":true,"properties":{"model":{"type":"string"},
"prompt":{"type":"string"},"images":{"type":"array","items":{"type":"string","pattern":pattern}}}});
let png_only = route("/v1/images/edits", "application/json", schema("^data:image/png;base64,")).unwrap();
assert_eq!(png_only["field"], "images");
assert_eq!(png_only["jpegReferences"], false);
let any_image = route("/v1/images/edits", "application/json", schema("^data:image/[^;,]+;base64,")).unwrap();
assert_eq!(any_image["jpegReferences"], true);
assert_eq!(select(&catalog(), "test-image").unwrap()["jpegReferences"], true, "an open probe field is unrestricted");
}
#[test]
fn explicit_reference_denial_and_nondefault_scopes_are_not_probed() {
let mut c = catalog();

File diff suppressed because it is too large Load Diff

View File

@ -48,7 +48,7 @@ fn project_entry(relative: &Path) -> bool {
|| root == "product-exports" && matches!(relative.extension().and_then(|ext| ext.to_str()), Some("psd" | "psb")),
"image-jobs" => relative.file_name().and_then(|name| name.to_str()).is_some_and(|name|
matches!(name, "canvas-candidate.json" | "task.json" | "generated.png" | "failure.json" | "scene-product.png")
|| name.starts_with("reference-") && name.ends_with(".png")),
|| name.starts_with("reference-") && (name.ends_with(".png") || name.ends_with(".jpg"))),
_ => false,
}
}

View File

@ -2274,7 +2274,7 @@ impl Workspace {
fn automatic_image_recovery(&mut self, app: &PhotocraftApp, now: Instant) {
if !self.unknown || self.pi_unknown && !self.scoped_production_pending() { return; }
let Some(doc) = self.automatic_recovery_doc(app).filter(|doc| self.loaded_draft == Some(*doc)) else { return };
let production = self.product_production.as_ref().filter(|run| run.waiting_for_originals());
let production = self.product_production.as_ref();
let Some((method, task)) = self.original_image_recoveries().filter(|(_, id)| {
if production.is_some_and(|run| run.owns_deferred_image(id)) { return false; }
let keep_checking = production.is_some_and(|run| run.waiting_for_image(id));
@ -4371,7 +4371,7 @@ pub(crate) fn begin_native_dock(app: &mut PhotocraftApp) {
initialize_agent_dock(app);
app.ui.dock.agent_available = app.jiansun.is_some();
if let Some(w) = app.jiansun.as_mut() {
w.panel_geometry = json!({"open":false});
w.panel_geometry = json!({"open":false,"productionImagesTag":null,"imageResourcesClip":null});
if !w.pending() {
w.agent_effects_paused = false;
}

View File

@ -932,19 +932,6 @@ fn rect_geometry(rect: Rect) -> [f32; 4] {
[rect.left(), rect.top(), rect.width(), rect.height()]
}
fn reference_dock_button(ui: &mut Ui, label: &str, glyph: &str, count: usize, selected: bool) -> egui::Response {
let t = Tokens::get(ui.ctx()).agent();
let icon = crate::icons::image(glyph, 16.0, t.text);
let button = egui::Button::image_and_text(icon, egui::RichText::new(count.to_string()).size(12.0).color(t.text))
.selected(selected).min_size(vec2(42.0, 28.0));
let response = ui.add(button);
response.widget_info(|| egui::WidgetInfo::selected(
egui::Role::Button, ui.is_enabled(), selected, format!("{label} · {count} 张"),
));
super::stitch_ui::focus_ring(ui, &response, 8.0, super::stitch_ui::FocusRing::Control);
response
}
impl ReferenceDockTab {
fn label(self) -> &'static str {
match self {
@ -2703,7 +2690,7 @@ impl Workspace {
}
fn reference_dock(&mut self, app: &PhotocraftApp, ui: &mut Ui, doc: u64, mut viewport: Rect) -> Rect {
use crate::theme::agent_scale::{control, motion};
use crate::theme::agent_scale::{Type, control, motion};
if self.professional_mode || self.library || self.material || (self.creation_open && self.creation_step != 3)
|| self.professional_child_active(app) || self.production_canvas_unbound(app) || !self.canvas_scope_valid(app)
@ -2752,7 +2739,10 @@ impl Workspace {
if !open || (tab == ReferenceDockTab::Products && !enabled) { shelf.disable(); }
super::stitch_ui::scope_with_motion(&mut shelf, self.reduce_motion, |ui| match tab {
ReferenceDockTab::Products => self.product_dock_thumbnails(app, ui, doc, &images),
ReferenceDockTab::Resources => self.production_assets_ui(ui),
ReferenceDockTab::Resources => {
self.panel_geometry["imageResourcesClip"] = super::agent_panel::rect_value(ui.clip_rect());
self.production_assets_ui(ui);
}
});
}
@ -2771,8 +2761,11 @@ impl Workspace {
] {
if count == 0 { continue; }
let selected = open && tab == item;
let response = reference_dock_button(ui, item.label(), glyph, count, selected);
let response = kit::counted_icon_button(ui, glyph, count, &format!("{} · {count} 张", item.label()), selected);
self.canvas_workspace.geometry.insert(geometry.into(), rect_geometry(response.rect));
if item == ReferenceDockTab::Resources {
self.panel_geometry["productionImagesTag"] = super::agent_panel::rect_value(response.rect);
}
if response.hovered() || response.has_focus() {
label = Some(item.label());
}
@ -2786,7 +2779,7 @@ impl Workspace {
}
}
if let Some(label) = label {
ui.label(egui::RichText::new(label).size(12.0).color(t.text_dim));
ui.label(egui::RichText::new(label).size(Type::Meta.size()).color(t.text_dim));
}
});
});

View File

@ -898,8 +898,7 @@ impl Run {
}
pub(super) fn owns_deferred_image(&self, id: &str) -> bool {
self.deferred_images.iter().any(|(stage, ids)|
Some(stage) != self.bound.as_ref() && ids.iter().any(|pending| pending == id))
self.deferred_images.values().flatten().any(|pending| pending == id)
}
fn recovering_deferred_image(&self, id: &str) -> bool {
@ -908,10 +907,8 @@ impl Run {
fn queued_deferred_images(&self) -> impl Iterator<Item = (Option<Instant>, &Stage, &String)> {
self.stages.iter()
.filter(move |stage| Some(*stage) != self.bound.as_ref() || self.opening.is_some()
|| matches!(self.phase, Phase::Paused(_)))
.flat_map(move |stage| self.deferred_images.get(stage).into_iter().flatten().map(move |id| (stage, id)))
.filter(move |(_, id)| !self.recovering_deferred_image(id) && !self.waiting_for_image(id))
.filter(move |(_, id)| !self.recovering_deferred_image(id))
.map(move |(stage, id)| (self.deferred_image_due.get(id).copied(), stage, id))
}
@ -1412,7 +1409,6 @@ impl Workspace {
let Some(canvas) = app.session.active() else { return; };
let Some(run) = self.product_production.as_mut() else { return; };
let Some(stage) = run.opening.take() else { return; };
run.clear_deferred(&stage);
self.write_epoch += 1;
self.pi_request_scope["writeEpoch"] = json!(self.write_epoch);
self.pi_request_scope["outputId"] = json!(stage.output);
@ -1444,9 +1440,6 @@ impl Workspace {
self.pi_request_scope["variantId"] = Value::Null;
self.pi_canvas_basis = app.session.active().map(|canvas| canvas.doc.clone());
}
if let Some(bound) = run.bound.clone() {
run.clear_deferred(&bound);
}
run.opening = None;
run.phase = Phase::Agent;
}
@ -1480,9 +1473,6 @@ impl Workspace {
return;
}
let Some(run) = self.product_production.as_mut() else { return };
if let Some(bound) = run.bound.clone() {
run.clear_deferred(&bound);
}
run.phase = Phase::Agent;
self.agent_effects_paused = false;
self.submit_turn(app, "继续本轮制作".into(), true);
@ -1531,6 +1521,14 @@ impl Workspace {
let goal = originals["goal"].as_str().map(str::to_owned);
self.pi_recovery_schedule = None;
if let Some(run) = self.product_production.as_mut() {
if let Some(stage) = run.bound.clone() {
let dispatched = self.template_workflow["slots"].as_array().into_iter().flatten()
.flat_map(|slot| slot["generationRequestIds"].as_array().into_iter().flatten())
.filter_map(Value::as_str).collect::<HashSet<_>>();
let native = images.iter().filter(|id| dispatched.contains(id.as_str()))
.cloned().collect();
run.defer_images(stage, native);
}
run.phase = Phase::WaitingOriginals { models, images, goal };
}
self.checkpoint_production();
@ -1855,21 +1853,36 @@ impl Workspace {
return;
}
let Some(run) = self.product_production.as_mut() else { return; };
// Both the bound output and previously opened outputs use the same queue.
// The workspace snapshot supplies original identities after a restart.
for row in self.template_workflow["pendingImageRequests"].as_array().into_iter().flatten() {
if let Some(stage) = Stage::read(row).filter(|stage| run.stages.contains(stage))
&& let Some(id) = row["candidateId"].as_str() {
run.defer_images(stage, vec![id.into()]);
}
}
let mut settled = Vec::new();
run.deferred_image_in_flight.retain(|pending| match pending.receipt.try_recv() {
Err(mpsc::TryRecvError::Empty) => true,
Ok(Ok(value)) if value["id"] == pending.id
&& matches!(value["status"].as_str(), Some("complete" | "failed" | "expired")) => {
settled.push((pending.stage.clone(), pending.id.clone()));
settled.push((pending.stage.clone(), value));
false
}
_ => false,
});
let mut changed = false;
for (stage, id) in settled {
changed |= run.settle_deferred_image(&stage, &id);
for (stage, receipt) in &settled {
let id = receipt["id"].as_str().unwrap();
changed |= run.settle_deferred_image(stage, id);
if let Some(rows) = self.template_workflow.get_mut("pendingImageRequests").and_then(Value::as_array_mut) {
rows.retain(|row| row["candidateId"] != id);
}
if let Some(ids) = self.template_workflow.get_mut("recoveryCandidateIds").and_then(Value::as_array_mut) {
ids.retain(|candidate| candidate != id);
self.template_workflow["recoveryCandidateId"] = ids.first().cloned().unwrap_or(Value::Null);
}
}
// The bound stage uses foreground recovery while it blocks production.
while run.deferred_image_in_flight.len() < MAX_DEFERRED_IMAGE_CONCURRENCY {
let next = run.queued_deferred_images()
.filter(|(due, _, _)| due.is_none_or(|due| now >= due))
@ -1894,7 +1907,21 @@ impl Workspace {
{
ctx.request_repaint_after(next_due.saturating_duration_since(now));
}
let workspace = run.workspace.clone();
let doc = run.doc;
let bound = run.bound.clone();
if changed { self.checkpoint_production(); }
for (stage, mut receipt) in settled {
let workflow = std::mem::take(&mut receipt["workflow"]);
if workflow["workspaceId"] == workspace && Stage::read(&workflow) == Stage::read(&self.template_workflow)
&& !self.product_view_detached() && self.receive_template_snapshot(&workflow, true) && self.busy.is_none() {
self.unknown = workflow["pending"] == true;
}
if bound.as_ref() == Some(&stage) {
self.production_recovery_received(app, &json!({"doc":doc,"accountId":self.account["id"],"origin":self.origin,
"workflow":{"workspaceId":workspace},"candidateResult":receipt}));
}
}
}
pub(super) fn production_recovery_received(&mut self, app: &PhotocraftApp, value: &Value) {
@ -2626,7 +2653,7 @@ mod tests {
let now = Instant::now();
w.tick_deferred_image_recovery(&app, &ctx, now);
let mut workers = Vec::new();
for id in ["detail-0", "detail-1", "detail-2", "detail-3", "sku-0", "sku-1"] {
for id in ["foreground", "detail-0", "detail-1", "detail-2", "detail-3", "sku-0"] {
let Request::RecoverDeferredImage(input, cancellation, reply) = requests.try_recv().unwrap() else { panic!("expected {id}") };
assert_eq!(input["taskId"], id);
assert_eq!(input["recoveryBudgetMs"], 9000);
@ -2637,13 +2664,13 @@ mod tests {
w.tick_deferred_image_recovery(&app, &ctx, now + Duration::from_secs(8));
assert!(requests.try_recv().is_err(), "overdue in-flight tasks still occupy exactly six slots");
for (index, id, status) in [(1, "detail-1", "complete"), (2, "detail-2", "failed"), (4, "sku-0", "expired")] {
for (index, id, status) in [(2, "detail-1", "complete"), (3, "detail-2", "failed"), (5, "sku-0", "expired")] {
workers[index].1.send(Ok(json!({"id":id,"status":status}))).unwrap();
}
let (disconnected, reply) = workers.pop().unwrap();
let (disconnected, reply) = workers.remove(1);
drop(reply);
w.tick_deferred_image_recovery(&app, &ctx, now + Duration::from_secs(8));
for id in ["sku-2", "sku-3", "sku-4", "sku-5"] {
for id in ["sku-1", "sku-2", "sku-3", "sku-4"] {
let Request::RecoverDeferredImage(input, cancellation, reply) = requests.try_recv().unwrap() else { panic!("expected {id}") };
assert_eq!(input["taskId"], id);
workers.push((cancellation, reply));
@ -2658,7 +2685,7 @@ mod tests {
let run = w.product_production.as_mut().unwrap();
assert_eq!(run.deferred_image_in_flight.len(), 6);
run.clear_deferred(detail);
assert!(workers[..4].iter().all(|(cancel, _)| cancel.load(Ordering::Acquire)));
assert!(workers[1..4].iter().all(|(cancel, _)| cancel.load(Ordering::Acquire)));
assert!(workers[5..].iter().all(|(cancel, _)| !cancel.load(Ordering::Acquire)));
assert!(!run.deferred_image_due.contains_key("detail-0"));
run.cancel_deferred_image_recovery();
@ -2667,7 +2694,7 @@ mod tests {
}
#[test]
fn deferred_image_cooldown_keeps_a_single_owner_for_the_other_output() {
fn one_image_recovery_queue_keeps_both_originals_when_the_output_switches() {
let (tx, requests) = mpsc::channel();
let (_, rx) = mpsc::channel();
let mut w = Workspace::new(tx, rx);
@ -2707,17 +2734,20 @@ mod tests {
let run = w.product_production.as_mut().unwrap();
assert_eq!(run.deferred_image_due["background"], retry_at + Duration::from_secs(15));
run.phase = Phase::WaitingOriginals { models: vec![], images: vec!["foreground".into()], goal: None };
w.template_workflow["pendingImageRequests"] = json!([{"outputId":"detail","variantId":"wood","candidateId":"foreground"}]);
for id in ["background", "foreground"] {
w.image_recovery_schedules.insert(id.into(), super::super::RecoverySchedule::start(now));
}
w.automatic_image_recovery(&app, retry_at);
let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("foreground recovery") };
assert_eq!(method, "slot-recover");
assert_eq!(input["candidateId"], "foreground");
reply.send(Ok(json!({"id":"background","status":"unknown"}))).unwrap();
w.busy = None;
w.tick_deferred_image_recovery(&app, &ctx, retry_at);
w.automatic_image_recovery(&app, retry_at);
let Request::RecoverDeferredImage(input, _, foreground) = requests.try_recv().unwrap() else { panic!("bound original uses the same queue") };
assert_eq!(input["taskId"], "foreground");
assert_eq!(input["outputId"], "detail");
reply.send(Ok(json!({"id":"background","status":"unknown"}))).unwrap();
foreground.send(Ok(json!({"id":"foreground","status":"expired","variantId":"wood"}))).unwrap();
w.tick_deferred_image_recovery(&app, &ctx, retry_at);
assert!(matches!(w.product_production.as_ref().unwrap().phase, Phase::AwaitingSave));
assert!(requests.try_iter().all(|request| matches!(request, Request::Action(method, _) if method == "product-run-checkpoint")));
assert!(requests.try_recv().is_err());
w.tick_deferred_image_recovery(&app, &ctx, retry_at + Duration::from_secs(15));
let Request::RecoverDeferredImage(input, _, _) = requests.try_recv().unwrap() else { panic!("background retry") };

View File

@ -1852,6 +1852,18 @@ pub(super) fn icon_action_button(ui: &mut Ui, icon: &str, label: &str, compact:
response
}
/// Compact toolbar toggle with a visible count and a full accessible label.
pub(super) fn counted_icon_button(ui: &mut Ui, glyph: &str, count: usize, label: &str, selected: bool) -> Response {
let t = Tokens::get(ui.ctx()).agent();
let image = crate::icons::image(glyph, icon::LG, t.text);
let text = RichText::new(count.to_string()).size(Type::Meta.size()).color(t.text);
let response = ui.add(egui::Button::image_and_text(image, text)
.selected(selected).min_size(vec2(42.0, control::STANDARD)));
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), selected, label));
focus_ring(ui, &response, 8.0, FocusRing::Control);
response
}
/// The composer owns when sending is allowed; this owns the shared native
/// button, focus treatment and icon without drawing an improvised arrow.
pub(super) fn send_action_button(ui: &mut Ui, id: egui::Id, _reduced: bool) -> Response {

View File

@ -1453,6 +1453,7 @@ mod tests {
w.reduce_motion = true;
w.library = false;
w.material = false;
let doc = app.session.active().unwrap().doc.id.0;
w.pi_request_scope["productProduction"] = json!(true);
w.workflow.set_production_progress(&json!({"heading":"正在核对详情图",
"total":21,"rendered":2,"workers":[
@ -1474,11 +1475,15 @@ mod tests {
crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium);
crate::cjk_fonts::install_system_provider_for_tests(&ctx);
let frame = |app: &mut PhotocraftApp, events| ctx.run_ui(egui::RawInput {
screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 1020.0))),
screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width + 540.0, 1020.0))),
events, ..Default::default()
}, |ui| {
if super::super::stitch_ui::ui_fonts_ready(ui) {
super::super::agent_dock(app, ui);
super::super::begin_frame(app);
super::super::begin_native_dock(app);
egui::Panel::right("worker-image-agent").exact_size(width).frame(egui::Frame::NONE)
.show(ui, |ui| super::super::agent_dock(app, ui));
super::super::canvas_workspace::reference_dock(app, ui, doc, ui.available_rect_before_wrap());
}
});
for _ in 0..4 {
@ -1536,11 +1541,13 @@ mod tests {
}
assert!(app.jiansun.as_ref().unwrap().panel_geometry["imageResourcesClip"].is_null());
click(&mut app, "productionImagesTag").drop_without_applying_deltas();
frame(&mut app, vec![]).drop_without_applying_deltas();
let geometry = &app.jiansun.as_ref().unwrap().panel_geometry;
assert!(geometry["imageResourcesClip"].is_array(),
"width {width}, resource row {}, transcript clip {}",
geometry["productionImagesTag"], geometry["conversationClip"]);
click(&mut app, "productionImagesTag").drop_without_applying_deltas();
frame(&mut app, vec![]).drop_without_applying_deltas();
assert!(app.jiansun.as_ref().unwrap().panel_geometry["imageResourcesClip"].is_null());
}
}