fix(photocraft): remove budget truncation, expose delivery dir, natural summary, canvas presence, and unblock stale checks

This commit is contained in:
WuYongJie 2026-12-05 15:32:20 +08:00
parent 684d35f106
commit 29ebb3c41d
17 changed files with 608 additions and 126 deletions

View File

@ -2634,7 +2634,30 @@ impl Backend {
|| state["activeVariantId"].as_str() != Some(variant_id.as_str()) {
return Err("当前模板、输出或花色已变化".into());
}
let candidate_id = target["candidateId"].as_str();
let scoped_adopted_canvas = if scoped && target["adopted"] == true {
jiansun_image_transform::source_canvas(&dir, &state, &variant_id, component, &state["template"]["contentHash"], adopted_canvas)?
} else {
None
};
let scoped_adopted_id = if scoped && target["adopted"] == true {
let Some(placed) = jiansun_image_transform::adopted_candidate(scoped_adopted_canvas.as_deref(), &variant_id, slot) else {
let candidates: Vec<_> = state["candidates"].as_array().into_iter().flatten().filter_map(Value::as_str)
.filter_map(|id| read_candidate(&dir, id).ok()
.filter(|row| row["binding"]["slotId"] == slot && row["binding"]["variantId"] == variant_id)
.map(|row| json!({"id":id,"status":if row["phase"] == "complete" { "complete" } else { row["phase"].as_str().unwrap_or("unknown") }})))
.collect();
return Ok(json!({"slotId":slot,"outputId":component,"variantId":variant_id,
"adopted":false,"candidateId":null,"candidateReady":false,"candidates":candidates,"images":[]}));
};
if target["candidateId"].as_str().is_some_and(|id| id != placed) {
return Err("当前图位已改变,保留编辑,未记录旧候选验图".into());
}
Some(placed.to_owned())
} else {
None
};
let adopted_canvas = scoped_adopted_canvas.as_deref().or(adopted_canvas);
let candidate_id = scoped_adopted_id.as_deref().or_else(|| target["candidateId"].as_str());
let candidate_record = candidate_id.map(|id| {
read_candidate(&dir, id).map_err(|error| {
let valid: Vec<_> = state["candidates"].as_array().into_iter().flatten().filter_map(Value::as_str)
@ -2785,7 +2808,7 @@ impl Backend {
file
});
let mut preview = if let Some(canvas) = adopted_canvas {
if !is_production_review || canvas.id.0 != doc { return Err("当前画布不属于已回填候选的复验项目".into()); }
if !is_production_review || (!scoped && canvas.id.0 != doc) { return Err("当前画布不属于已回填候选的复验项目".into()); }
let mapped = mapped_slot(&state, slot, &variant_id).ok_or("已回填图位没有当前模板映射")?;
if raw_candidate {
verify_adopted_source(&dir, canvas, mapped, &record["artifact"])?;
@ -6398,9 +6421,6 @@ impl Backend {
state["structureHash"].as_str().unwrap_or("")
));
}
if !candidate_uses_current_inputs(&dir, &state, &record, &variant_id)? {
return Err("当前商品或花色资料已更新,旧候选已保留,未采纳".into());
}
let journal = read_json(&dir.join("image-jobs").join(&candidate).join("task.json"))?;
let artifact = template_slots::artifact(&dir, &candidate, &journal)?;
if artifact != record["artifact"] {
@ -10000,10 +10020,10 @@ mod tests {
assert_eq!(late["requestId"], result["requestId"]);
assert!(!candidate_uses_current_inputs(&dir, &current, &late, &oak).unwrap());
assert!(candidate_uses_current_inputs(&dir, &current, &other, &white).unwrap());
let error = backend.canvas_workspace_action("slot-adopt-prep", &json!({"doc":doc,"baseRevision":0,
let adopted = backend.canvas_workspace_action("slot-adopt-prep", &json!({"doc":doc,"baseRevision":0,
"slotRevision":load(&dir).unwrap()["revision"],"variantId":oak,"slotId":first["binding"]["slotId"],
"candidateId":first["id"]}), &events, &egui::Context::default()).unwrap_err();
assert!(error.contains("未采纳"), "{error}");
"candidateId":first["id"]}), &events, &egui::Context::default()).unwrap();
assert_eq!(adopted["candidateId"], first["id"]);
}
#[test]

View File

@ -76,7 +76,7 @@ fn crop_source_candidate(dir: &Path, state: &Value, candidate: &str, slot: &str,
Ok(record)
}
fn source_canvas<'a>(
pub(super) fn source_canvas<'a>(
dir: &Path, state: &Value, variant: &str, component: &str, template: &Value,
active: Option<&'a super::Document>,
) -> R<Option<std::borrow::Cow<'a, super::Document>>> {
@ -95,7 +95,7 @@ fn source_canvas<'a>(
Ok(matches(&saved).then_some(std::borrow::Cow::Owned(saved)))
}
fn adopted_candidate<'a>(canvas: Option<&'a super::Document>, variant: &str, slot: &str) -> Option<&'a str> {
pub(super) fn adopted_candidate<'a>(canvas: Option<&'a super::Document>, variant: &str, slot: &str) -> Option<&'a str> {
let marker = format!("jiansun.adopted.{variant}.{slot}");
canvas?.metadata.text.iter().find(|(key, _)| key == &marker).map(|(_, id)| id.as_str())
}

View File

@ -4517,7 +4517,6 @@ impl Workspace {
self.with_product_target(app, |w, app| {
let now = Instant::now();
w.production_tick(app);
if let Some(delay) = w.production_budget_delay() { ctx.request_repaint_after(delay); }
if let Some(delay) = w.production_canvas_save_delay(now) { ctx.request_repaint_after(delay); }
if let Some(delay) = w.production_retry_delay(now) {
ctx.request_repaint_after(delay);

View File

@ -3022,7 +3022,7 @@ impl Workspace {
let head = super::production_controls::HeadControls::read(&self.production_control_state());
let resume_ready = self.can_resume_product();
let budget = if let Some(run) = run {
GoalBudget::Time { elapsed: run.elapsed(), limit: head.budget.and_then(|budget| Duration::try_from_secs_f64(budget.budget_minutes * 60.0).ok()) }
GoalBudget::Time { elapsed: run.elapsed(), limit: None }
} else if let Some(used) = usage_count(&progress["tokensUsed"]) {
GoalBudget::Tokens { used, limit: usage_count(&progress["tokenBudget"]) }
} else {
@ -3030,7 +3030,7 @@ impl Workspace {
};
let clock_paused = run.is_some_and(|run| run.clock_paused());
let mut controls = head.view(resume_ready);
if clock_paused && controls.stop == timeline::StopPhase::Idle {
if clock_paused && matches!(controls.stop, timeline::StopPhase::Idle | timeline::StopPhase::Delivered) {
controls.stop = timeline::StopPhase::Paused;
}
let state = if clock_paused { RunState::WaitingResume }

View File

@ -205,15 +205,18 @@ impl Cursor {
}
/// 文档换了修订:确认字是否真的落下、图位是否真的换了采纳图,并刷新目标外框。
fn observe(&mut self, doc: &Document, mapping: &Value, workflow: &Value, variant: &str, revision: u64, now: Instant) {
fn observe(&mut self, doc: &Document, mapping: &Value, workflow: &Value, variant: &str, revision: u64, now: Instant) -> Option<[f32; 4]> {
let mut completed = false;
if let Some(write) = self.write.as_mut() {
write.observe(doc, now);
completed = true;
}
if let (Some(before), Target::Slot(slot)) = (&self.adopted, &self.target) {
let current = canvas_workspace::adopted(doc, slot, variant).map(str::to_owned);
if *before != current {
self.reveal = self.tip.map(|tip| (tip, now));
self.adopted = Some(current);
completed = true;
}
}
let previous = self.revision.and(self.geometry.as_ref().map(|geometry| geometry.bounds));
@ -226,14 +229,31 @@ impl Cursor {
self.morph = Some((old, now));
}
self.revision = Some(revision);
completed.then(|| self.geometry.as_ref().map(|g| g.bounds)).flatten()
}
}
const PULSE_DURATION: f32 = 1.8;
#[derive(Clone, Debug, PartialEq, Eq)]
struct CrossOutputNotice {
output_id: String,
label: String,
}
struct CompletionPulse {
bounds: [f32; 4],
color: Color32,
started_at: Instant,
}
#[derive(Default)]
pub(super) struct Presence {
scope: Option<Scope>,
main_call: String,
cursors: Vec<Cursor>,
cross_output: Option<CrossOutputNotice>,
pulses: Vec<CompletionPulse>,
}
impl Presence {
@ -280,6 +300,7 @@ impl Presence {
}
pub(super) fn finish_run(&mut self, now: Instant) {
self.cross_output = None;
for cursor in &mut self.cursors {
Self::finish(cursor, now);
}
@ -334,14 +355,38 @@ pub(super) fn production_progress(w: &mut Workspace, app: &PhotocraftApp, progre
production_progress_at(w, app, progress, Instant::now());
}
fn cross_output_label(output_id: &str) -> &'static str {
match output_id {
"main_images" => "小壹正在同步处理主图,完成后会自动更新",
"sku_images" => "小壹正在同步处理 SKU 图,完成后会自动更新",
"detail" => "小壹正在同步处理详情页,完成后会自动更新",
_ => "小壹正在同步处理其他成品,完成后会自动更新",
}
}
fn production_progress_at(w: &mut Workspace, app: &PhotocraftApp, progress: &Value, now: Instant) {
let Some(scope) = Scope::capture(w, app) else { return };
if progress["outputId"] != scope.output || progress["variantId"] != scope.variant {
let output_id = progress["outputId"].as_str().unwrap_or_default().to_owned();
let active = ["workers", "reviews"].into_iter().any(|key| {
progress[key].as_array().into_iter().flatten().any(|row| row["active"] == true)
}) || !progress["checkingScreens"].as_array().is_none_or(Vec::is_empty);
let presence = &mut w.agent_presence;
presence.bind(scope);
if active {
presence.cross_output = Some(CrossOutputNotice {
label: cross_output_label(&output_id).to_owned(),
output_id,
});
} else if presence.cross_output.as_ref().is_some_and(|n| n.output_id == output_id) {
presence.cross_output = None;
}
return;
}
let variant = scope.variant.clone();
let presence = &mut w.agent_presence;
presence.bind(scope);
presence.cross_output = None;
let mut active = Vec::new();
for (key, actor) in [("workers", Actor::Image as fn(u64) -> Actor), ("reviews", Actor::Review)] {
for row in progress[key].as_array().into_iter().flatten().filter(|row| row["active"] == true) {
@ -461,17 +506,23 @@ pub(super) fn paint(w: &mut Workspace, app: &PhotocraftApp, ui: &Ui, xf: ViewXfo
fn paint_at(w: &mut Workspace, app: &PhotocraftApp, ui: &Ui, xf: ViewXform, doc: u64, now: Instant) {
let state = &mut w.agent_presence;
if state.cursors.is_empty() {
let pulse_ttl = Duration::from_secs_f32(PULSE_DURATION);
state.pulses.retain(|pulse| now < pulse.started_at + pulse_ttl);
if state.cursors.is_empty() && state.cross_output.is_none() && state.pulses.is_empty() {
return;
}
let Some(scope) = state.scope.as_ref() else { return };
if w.agent_effects_paused || w.pi_run.as_ref() != Some(&scope.run) {
state.cross_output = None;
for cursor in &mut state.cursors {
Presence::finish(cursor, now);
}
}
let fade = Duration::from_secs_f32(FADE_OUT);
state.cursors.retain(|cursor| cursor.fade_at.is_none_or(|start| now < start + fade));
if state.cursors.is_empty() && state.cross_output.is_none() && state.pulses.is_empty() {
return;
}
if w.library
|| w.material
|| (w.creation_open && w.creation_step != 3)
@ -491,16 +542,32 @@ impl Presence {
return;
}
let (doc, revision) = (&*active.doc, active.revision);
let Self { scope, cursors, .. } = self;
let Self { scope, cursors, cross_output, pulses, .. } = self;
let variant = scope.as_ref().map_or("", |scope| scope.variant.as_str());
let painter = ui.painter().with_clip_rect(clip);
let mut mapping = None;
let mut tags = Vec::new();
let mut repaint: Option<Duration> = None;
for pulse in pulses.iter() {
let age = now.saturating_duration_since(pulse.started_at).as_secs_f32();
let t = (1.0 - age / PULSE_DURATION).clamp(0.0, 1.0);
if t > 0.0 {
let rect = canvas_workspace::world_rect(xf, pulse.bounds);
if clip.intersects(rect) {
draw::completion_pulse(&painter, rect, pulse.color, t);
if !reduced {
let step = Duration::from_millis(32);
repaint = Some(repaint.map_or(step, |current| current.min(step)));
}
}
}
}
for cursor in cursors.iter_mut() {
if cursor.revision != Some(revision) {
let mapping = mapping.get_or_insert_with(|| canvas_workspace::document_mapping(doc).unwrap_or_default());
cursor.observe(doc, mapping, workflow, variant, revision, now);
if let Some(bounds) = cursor.observe(doc, mapping, workflow, variant, revision, now) {
pulses.push(CompletionPulse { bounds, color: cursor.color, started_at: now });
}
}
if let Some(write) = cursor.write.as_mut() {
write.upload(ui.ctx());
@ -521,6 +588,14 @@ impl Presence {
}
}
draw::tags(&painter, clip, &tags);
if let Some(notice) = cross_output.as_ref() {
let pulse = if reduced { 1.0 } else { 0.55 + 0.45 * (now.elapsed().as_secs_f32() * 3.0).sin().abs() };
draw::cross_output_capsule(&painter, clip, &notice.label, pulse);
if !reduced {
let step = Duration::from_millis(100);
repaint = Some(repaint.map_or(step, |current| current.min(step)));
}
}
if let Some(delay) = repaint {
ui.ctx().request_repaint_after(delay);
}

View File

@ -157,6 +157,36 @@ pub(super) fn tags(p: &Painter, clip: Rect, tags: &[Tag]) -> Vec<Rect> {
placed
}
pub(super) fn completion_pulse(p: &Painter, rect: Rect, color: Color32, strength: f32) {
let alpha = strength.clamp(0.0, 1.0);
let radius = 6.0;
p.rect_filled(rect, radius, color.gamma_multiply(0.14 * alpha));
p.rect_stroke(rect, radius, Stroke::new(2.2, color.gamma_multiply(0.85 * alpha)), StrokeKind::Outside);
}
pub(super) fn cross_output_capsule(p: &Painter, clip: Rect, label: &str, pulse: f32) {
if clip.width() < 120.0 || clip.height() < 48.0 {
return;
}
let accent = agent_cursor::ACTORS[0];
let mut job = LayoutJob::default();
job.append(label, 0.0, TextFormat::simple(Type::Caption.semibold(), Color32::WHITE));
job.wrap = TextWrapping { max_width: (clip.width() - 56.0).max(40.0), max_rows: 1, break_anywhere: true, overflow_character: Some('…') };
let galley = p.layout_job(job);
let dot_space = 14.0;
let size = galley.size() + vec2(20.0 + dot_space, 10.0);
let min_x = (clip.center().x - size.x * 0.5).max(clip.left() + 12.0);
let min_y = clip.top() + 12.0;
let rect = Rect::from_min_size(pos2(min_x, min_y), size);
let radius = size.y * 0.5;
p.add(Shadow { offset: [0, 2], blur: 10, spread: 0, color: Color32::from_black_alpha(72) }.as_shape(rect, radius));
p.rect_filled(rect, radius, agent_cursor::label_background(accent).gamma_multiply(0.94));
p.rect_stroke(rect, radius, Stroke::new(1.0, Color32::from_white_alpha(48)), StrokeKind::Inside);
let dot_center = pos2(rect.left() + 13.0, rect.center().y);
p.circle_filled(dot_center, 3.5, accent.gamma_multiply(pulse.clamp(0.35, 1.0)));
p.galley(pos2(rect.left() + 10.0 + dot_space, rect.center().y - galley.size().y * 0.5), galley, Color32::WHITE);
}
fn within(rect: Rect, clip: Rect) -> Rect {
let x = (clip.right() - rect.right()).min(0.0).max(clip.left() - rect.left());
let y = (clip.bottom() - rect.bottom()).min(0.0).max(clip.top() - rect.top());

View File

@ -539,3 +539,21 @@ fn presence_visual_acceptance() {
assert_eq!(requests.try_iter().filter(|request| matches!(request, Request::Action(method, _) if method == "slot-append")).count(), 0);
}
}
#[test]
fn cross_output_progress_sets_and_clears_capsule_notice() {
let (mut app, _requests, _doc) = fixture();
let w = app.jiansun.as_mut().unwrap();
w.pi_run = Some("run-1".into());
w.template_workflow = json!({"outputId":"detail","variantId":"oak"});
let mut w = app.jiansun.take().unwrap();
production_progress(&mut w, &app, &json!({
"outputId": "main_images",
"variantId": "oak",
"workers": [{"number": 1, "slotId": "M01", "active": true, "step": "正在生图"}]
}));
assert_eq!(w.agent_presence.cross_output.as_ref().map(|n| n.label.as_str()),
Some("小壹正在同步处理主图,完成后会自动更新"));
w.agent_presence.finish_run(Instant::now());
assert!(w.agent_presence.cross_output.is_none());
}

View File

@ -2634,7 +2634,7 @@ impl Workspace {
self.creation_dirty = false;
self.creation_read_failed = false;
self.creation_width = 0;
self.creation_delivery_dir = None;
self.creation_delivery_dir = preferred_delivery_dir(app);
self.creation_selected.clear();
self.creation_direction.clear();
self.creation_plan = json!([]);
@ -3469,6 +3469,7 @@ impl Workspace {
let id = egui::Id::unique(("production-refinement", self.local_identity(""), doc));
let _ = self.refinement_ui(ui, Some((id, editable)));
}
self.delivery_directory_control(app, ui, editable);
self.advanced_export_settings_ui(app, ui, scope, width, editable);
pending
}
@ -3579,6 +3580,8 @@ impl Workspace {
});
let _ = self.refinement_ui(ui, pending);
ui.add_space(space::SM);
self.delivery_directory_control(app, ui, editable);
ui.add_space(space::SM);
self.advanced_export_settings_ui(app, ui, field_scope, width, editable);
barcode_pending
}
@ -4034,19 +4037,15 @@ impl Workspace {
field_group(ui, width, "模板 *", |ui| self.template_select(app, ui, width));
}
fn advanced_export_settings_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32, editable: bool) {
fn advanced_export_settings_ui(&mut self, _app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32, _editable: bool) {
let variants = brief_variants(&self.creation_brief);
let has_dir = self.creation_delivery_dir.is_some();
let has_variant_subsets = variants.len() > 1;
let has_legacy_sku = self.creation_brief.get("barcodeBindings").is_none();
let summary = if let Some(dir) = self.creation_delivery_dir.as_deref() {
format!("导出目录与高级设置 · 已指定目录({dir})")
} else {
"导出目录与高级设置(选填)".into()
};
let disclosure = stitch_ui::disclosure(ui, field_scope.with("advanced-export-settings"), &summary, has_dir, self.reduce_motion, |ui| {
if !has_variant_subsets && !has_legacy_sku {
return;
}
let disclosure = stitch_ui::disclosure(ui, field_scope.with("advanced-export-settings"), "高级导出设置(选填)", false, self.reduce_motion, |ui| {
ui.spacing_mut().item_spacing.y = space::SM;
self.delivery_directory_control(app, ui, editable);
if has_variant_subsets {
ui.add_space(space::XS);
stitch_kit::label(ui, "指定出图花色范围", Type::Meta, Tone::Quiet);
@ -4860,7 +4859,7 @@ impl Workspace {
}
fn delivery_directory_control(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, editable: bool) {
stitch_kit::label(ui, "成品自动保存目录", Type::Meta, Tone::Quiet);
stitch_kit::label(ui, "成品保存位置", Type::Meta, Tone::Quiet);
let path = self.creation_delivery_dir.as_deref().unwrap_or("未选择(默认仅保存到项目内)");
ui.add(egui::Label::new(egui::RichText::new(path).font(Type::Meta.font_id())).wrap()).on_hover_text(path);
ui.horizontal_wrapped(|ui| {
@ -4888,8 +4887,9 @@ impl Workspace {
{
return Err("请选择项目草稿目录以外的位置".into());
}
w.creation_delivery_dir = Some(path);
w.creation_delivery_dir = Some(path.clone());
w.creation_dirty = true;
remember_delivery_dir(app, &path);
Ok(Value::Null)
}) {
self.error = error;
@ -9852,3 +9852,83 @@ fn parse_review_hints(value: &Value, out: &mut Vec<ReviewHintItem>) {
}
}
}
const DELIVERY_DIR_PREF_KEY: &str = "jiansun.deliveryDir";
fn remembered_delivery_dir(app: &PhotocraftApp) -> Option<String> {
app.session.prefs().dialogs.get(DELIVERY_DIR_PREF_KEY)
.and_then(Value::as_str)
.map(str::trim)
.filter(|path| !path.is_empty())
.map(str::to_owned)
}
fn remember_delivery_dir(app: &mut PhotocraftApp, path: &str) {
let trimmed = path.trim();
if trimmed.is_empty() {
return;
}
app.session.prefs.edit(|prefs| {
prefs.dialogs.insert(DELIVERY_DIR_PREF_KEY.into(), json!(trimmed));
});
let _ = crate::prefs_ui::save_preferences(app);
}
fn default_delivery_dir_for_home(home: &std::path::Path) -> Option<String> {
let desktop = home.join("Desktop");
let onedrive_desktop = home.join("OneDrive").join("Desktop");
let documents = home.join("Documents");
let base = if desktop.is_dir() {
desktop
} else if onedrive_desktop.is_dir() {
onedrive_desktop
} else if documents.is_dir() {
documents
} else {
desktop
};
base.join("小壹成品").to_str().map(str::to_owned)
}
fn default_delivery_dir() -> Option<String> {
let home = std::env::var_os("USERPROFILE")
.or_else(|| std::env::var_os("HOME"))
.map(std::path::PathBuf::from)?;
default_delivery_dir_for_home(&home)
}
fn preferred_delivery_dir(app: &PhotocraftApp) -> Option<String> {
remembered_delivery_dir(app).or_else(default_delivery_dir)
}
#[cfg(test)]
mod delivery_dir_tests {
use super::*;
use std::sync::mpsc;
#[test]
fn default_delivery_dir_prefers_desktop_then_documents() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path();
let docs = home.join("Documents");
std::fs::create_dir_all(&docs).unwrap();
assert_eq!(default_delivery_dir_for_home(home).as_deref(), docs.join("小壹成品").to_str());
let desktop = home.join("Desktop");
std::fs::create_dir_all(&desktop).unwrap();
assert_eq!(default_delivery_dir_for_home(home).as_deref(), desktop.join("小壹成品").to_str());
}
#[test]
fn begin_staged_new_project_remembers_last_delivery_dir() {
let (tx, _rx) = mpsc::channel();
let (_, event_rx) = mpsc::channel();
let mut w = Workspace::new(tx, event_rx);
let session = photocraft_engine::Session::new();
let mut app = PhotocraftApp::new(session, crate::Services::default());
remember_delivery_dir(&mut app, "/tmp/custom-xiaoyi-output");
w.begin_staged_new_project(&app);
assert_eq!(w.creation_delivery_dir.as_deref(), Some("/tmp/custom-xiaoyi-output"));
}
}

View File

@ -5,6 +5,7 @@ use std::collections::{HashMap, HashSet, VecDeque};
#[path = "creation_wizard.rs"] pub(super) mod wizard;
const READ_WAIT: Duration = Duration::from_secs(45);
const TEMPLATE_READ_WAIT: Duration = Duration::from_secs(180);
const CACHE_LIMIT: usize = 48;
const QUEUE_LIMIT: usize = 128;
pub(super) const TEST_PRESETS: &str = "test-product-presets";
@ -78,6 +79,12 @@ fn kind(request: &Queued) -> &str {
fn test_preset(request: &Queued) -> bool {
matches!(kind(request), TEST_PRESETS | TEST_PRESET_IMPORT)
}
fn template_read(request: &Queued) -> bool {
matches!(kind(request), "resource-set" | "resource-component" | "templates")
}
fn read_wait(request: &Queued) -> Duration {
if template_read(request) { TEMPLATE_READ_WAIT } else { READ_WAIT }
}
fn id(request: &Queued) -> &str {
request.input["id"].as_str().unwrap_or("")
}
@ -441,7 +448,8 @@ impl Workspace {
request.attempts += 1;
let method = request.method;
let input = request.input.clone();
self.creation_reads.pending.insert(serial, Pending { request, deadline: Instant::now() + READ_WAIT, progress: Value::Null });
let wait = read_wait(&request);
self.creation_reads.pending.insert(serial, Pending { request, deadline: Instant::now() + wait, progress: Value::Null });
if self.tx.send(Request::Action(method.into(), input)).is_err()
&& let Some(pending) = self.creation_reads.pending.remove(&serial)
{
@ -454,7 +462,12 @@ impl Workspace {
let expired: Vec<u64> = self.creation_reads.pending.iter().filter_map(|(id, p)| (Instant::now() >= p.deadline).then_some(*id)).collect();
for serial in expired {
if let Some(pending) = self.creation_reads.pending.remove(&serial) {
self.creation_read_failed(pending.request, "只读加载超时,请重读;未影响模型原请求", false);
let msg = if template_read(&pending.request) {
"模板资料加载时间较长,可能仍在下载缓存,请稍候点击重试"
} else {
"只读加载时间较长,请稍候点击重试"
};
self.creation_read_failed(pending.request, msg, false);
}
}
// Continues after closing the popup; no render loop must keep it open.
@ -467,7 +480,8 @@ impl Workspace {
let Some(pending) = self.creation_reads.pending.get_mut(&read_id) else { return; };
if ["doc", "accountId", "origin"].iter().any(|key| value[*key] != pending.request.input[*key]) { return; }
let wait = value["retryAfterSeconds"].as_u64().unwrap_or(0).min(86_400);
pending.deadline = Instant::now() + Duration::from_secs(wait) + READ_WAIT;
let extra = read_wait(&pending.request);
pending.deadline = Instant::now() + Duration::from_secs(wait) + extra;
pending.progress = value;
}
pub(super) fn resource_progress(&self) -> Option<Value> {
@ -1078,4 +1092,40 @@ mod tests {
w.queue_creation_reference(&app, "../../outside.png");
assert!(rx.try_recv().is_err());
}
#[test]
fn template_reads_allow_180s_and_report_natural_timeout_copy() {
let (mut w, app, rx) = fixture();
w.creation_doc = app.session.active().map(|state| state.doc.id.0);
for kind in ["resource-set", "resource-component", "templates"] {
let queued = Queued {
method: "creation-catalog",
input: json!({"kind": kind}),
signature: kind.into(),
attempts: 0,
ready: Instant::now(),
};
assert_eq!(read_wait(&queued), TEMPLATE_READ_WAIT, "{kind}");
}
let light = Queued {
method: "creation-catalog",
input: json!({"kind": "brands"}),
signature: "brands".into(),
attempts: 0,
ready: Instant::now(),
};
assert_eq!(read_wait(&light), READ_WAIT);
w.creation_brief["brandId"] = json!("brand-a");
w.creation_brief["brandName"] = json!("品牌A");
w.creation_brief["categoryId"] = json!("category-a");
w.creation_brief["categoryName"] = json!("品类A");
w.request_creation_catalog(&app, "templates", String::new(), false);
let _req = request(&rx);
let serial = *w.creation_reads.pending.keys().next().unwrap();
assert!(w.creation_reads.pending[&serial].deadline > Instant::now() + Duration::from_secs(120));
w.creation_reads.pending.get_mut(&serial).unwrap().deadline = Instant::now() - Duration::from_secs(1);
w.creation_reads_tick(&app);
assert!(w.creation_reads.catalog_errors.values().any(|err| err.contains("模板资料加载时间较长")), "{:?}", w.creation_reads.catalog_errors);
}
}

View File

@ -433,7 +433,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
let scoped_read = private && (method == "pi-detail-archive" && input["source"].is_null()
&& (input["projectPlan"] == true || input["projectImages"] == true)
|| method == "pi-detail-copy-fields" && input["targetOutput"].is_object()
|| method == "pi-detail-images" && input["targetOutput"].is_object() && input["adopted"] != true
|| method == "pi-detail-images" && input["targetOutput"].is_object()
|| method == "pi-product-screen" && input["targetOutput"].is_object()
&& input["candidatePreview"].is_object() && input["candidatePreview"]["adopted"] != true);
let scoped_image = private && method == "pi-image-request"
@ -790,6 +790,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
}
return Ok(json!({"projectScope":true,"workspaceId":w.template_workflow["workspaceId"],
"outputId":target["outputId"],"variantId":target["variantId"],"slotId":input["slotId"],
"adopted":input["adopted"] == true,
"candidateId":input["candidateId"],"candidatePixels":input["candidatePixels"] == true,"includeProductReferences":input["includeProductReferences"] != false,
"includeTemplateReference":input["includeTemplateReference"] != false}));
}
@ -872,12 +873,12 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
{
w.workflow.set_waiting_canvas(output, variant, count);
}
} else if production_progress
&& input["production"]["outputId"] == key["outputId"]
&& input["production"]["variantId"] == key["variantId"]
{
} else if production_progress {
super::agent_presence::production_progress(w, app, &input["production"]);
if let Some(notice) = w.workflow.set_production_progress(&input["production"]) {
if input["production"]["outputId"] == key["outputId"]
&& input["production"]["variantId"] == key["variantId"]
&& let Some(notice) = w.workflow.set_production_progress(&input["production"])
{
w.messages.push(json!({"role":"assistant","kind":"activity","text":notice,"run":w.pi_run}));
w.draft_changed = true;
}
@ -2400,6 +2401,12 @@ mod tests {
let images = action_impl(&mut w, &mut app, None, "pi-detail-images", &json!({"run":run,"slotId":"S01-I01","candidateId":"cand-1"}), true).unwrap();
assert_eq!(images["slotId"], "S01-I01");
let cross_adopted = action_impl(&mut w, &mut app, None, "pi-detail-images", &json!({
"run":run,"slotId":"S01-I01","adopted":true,"targetOutput":{"outputId":"main_images","variantId":"oak"}
}), true).unwrap();
assert_eq!(cross_adopted["projectScope"], true);
assert_eq!(cross_adopted["adopted"], true);
let archive = action_impl(&mut w, &mut app, None, "pi-detail-archive", &json!({"run":run,"slotId":"S01-I01","projectImages":true,"outputId":"detail","variantId":"oak"}), true).unwrap();
assert_eq!(archive["projectImages"], true);

View File

@ -98,6 +98,7 @@ pub(super) struct Run {
agent_retries: usize,
turn_waits: u8,
stop_deadline: Option<Instant>,
waiting_originals_since: Option<Instant>,
}
impl Run {
@ -105,6 +106,7 @@ impl Run {
goal_user_entry: Option<String>, phase: Phase) -> Self {
let started_at = production_time();
let paused_at = matches!(phase, Phase::Paused(_)).then_some(started_at);
let waiting_originals_since = matches!(phase, Phase::WaitingOriginals { .. }).then(Instant::now);
Self { doc, project, workspace, total: stages.len(), requested_outputs: stages.iter().cloned().collect(), stages,
goal_user_entry, reset_goal: false, bound: None, opening: None, knowledge: Value::Null, previous_save: Value::Null, session_epoch: None,
finish: None, finish_receipt: Value::Null, phase, drafts: Vec::new(),
@ -112,6 +114,7 @@ impl Run {
deferred_images: HashMap::new(), deferred_image_due: HashMap::new(), deferred_image_stopped: HashSet::new(),
deferred_image_in_flight: Vec::new(),
started_at, paused_at, paused_seconds: 0, agent_retries: 0, turn_waits: 0, stop_deadline: None,
waiting_originals_since,
delivery_dir: None, delivery_id: None, published: Vec::new(), delivery_receipt: Value::Null,
delivery_cancellation: None, delivery_write_epoch: None, all_outputs_completed: false }
}
@ -133,14 +136,6 @@ fn original_ids(originals: &Value, name: &str) -> Vec<String> {
originals[name].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect()
}
pub(super) fn slot_coverage_label(coverage: &Value) -> Option<String> {
let total = coverage["total"].as_u64()?;
let preview = coverage["preview"].as_u64()?;
let empty = coverage["empty"].as_u64()?;
(preview + empty > 0).then(|| format!("已采纳 {total_filled}/{total} · 待采纳候选 {preview} · 空图位 {empty}",
total_filled = total.saturating_sub(preview + empty)))
}
fn production_time() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()
}

View File

@ -5,6 +5,7 @@ use std::sync::{Arc, mpsc, atomic::Ordering};
use std::time::{Duration, Instant};
const MAX_DEFERRED_IMAGE_CONCURRENCY: usize = 6;
const WAITING_ORIGINALS_TIMEOUT: Duration = Duration::from_secs(90);
pub(super) struct DeferredImageRecovery {
stage: Stage,
@ -143,19 +144,26 @@ impl Workspace {
}
});
for id in retry {
let delay = match run.deferred_image_due.get(&id).map(|(_, previous)| *previous) {
None => 8,
Some(8) => 15,
Some(15) => 30,
_ => 60,
};
run.deferred_image_due.insert(id, (now + Duration::from_secs(delay), delay));
match run.deferred_image_due.get(&id).map(|(_, previous)| *previous) {
Some(previous) if previous >= 30 => {
run.deferred_image_stopped.insert(id);
}
previous => {
let delay = match previous {
None => 8,
Some(8) => 15,
_ => 30,
};
run.deferred_image_due.insert(id, (now + Duration::from_secs(delay), delay));
}
}
}
for (id, error) in stopped {
run.deferred_image_stopped.insert(id);
self.error = error;
}
let mut changed = false;
let mut released_waiting_note = false;
for (stage, receipt) in &settled {
let id = receipt["id"].as_str().unwrap();
changed |= run.settle_deferred_image(stage, id);
@ -167,6 +175,34 @@ impl Workspace {
self.template_workflow["recoveryCandidateId"] = ids.first().cloned().unwrap_or(Value::Null);
}
}
if let Phase::WaitingOriginals { models, images, .. } = &run.phase {
let since = *run.waiting_originals_since.get_or_insert(now);
let timed_out = now.saturating_duration_since(since) >= WAITING_ORIGINALS_TIMEOUT;
let all_stopped = models.is_empty() && !images.is_empty()
&& images.iter().all(|id| run.deferred_image_stopped.contains(id));
if timed_out || all_stopped {
let stalled = images.clone();
let stages: Vec<_> = run.deferred_images.keys().cloned().collect();
for id in &stalled {
for stage in &stages {
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.as_str());
}
if let Some(ids) = self.template_workflow.get_mut("recoveryCandidateIds").and_then(Value::as_array_mut) {
ids.retain(|candidate| candidate != id.as_str());
self.template_workflow["recoveryCandidateId"] = ids.first().cloned().unwrap_or(Value::Null);
}
}
run.waiting_originals_since = None;
run.await_canvas_save();
changed = true;
released_waiting_note = true;
}
} else {
run.waiting_originals_since = None;
}
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))
@ -193,6 +229,9 @@ impl Workspace {
let doc = run.doc;
let bound = run.bound.clone();
if changed { self.checkpoint_production(); }
if released_waiting_note {
self.note("部分生图原请求暂未返回终态,已移出阻塞并继续当前制作。");
}
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)

View File

@ -1,4 +1,4 @@
use super::{Phase, Run, Stage, original_ids, output_has_no_missing_images, production_time, slot_coverage_label};
use super::{Phase, Run, Stage, original_ids, output_has_no_missing_images, production_time};
use crate::jiansun::{PhotocraftApp, Request, Value, Workspace, json};
use crate::jiansun::multi_project_state::ProjectRunVisualStatus;
use std::time::{Duration, Instant};
@ -358,29 +358,60 @@ impl Workspace {
let exported = if receipt["path"].is_string() {
receipt["completedOutputs"].as_u64().unwrap_or(0)
} else { 0 };
let mut text = if let Some(label) = slot_coverage_label(&coverage) {
label
} else if run.finish_receipt["deliveryReason"].is_string() && complete {
format!("{},已交付 {} 份当前成果。", run.finish_receipt["deliveryReason"].as_str().unwrap_or_default(), exported)
} else if complete {
format!("整套制作完成,已交付 {exported} 份成品。")
} else if partial {
"已有编辑稿保存在当前项目,可继续补齐制作。".into()
let empty = coverage["empty"].as_u64().unwrap_or(0);
let preview = coverage["preview"].as_u64().unwrap_or(0);
let folder = receipt["path"].as_str().map(clean_delivery_folder_name);
let non_zero_counts = receipt["path"].as_str().map(|_| {
["工程文件", "PSD", "详情页长图", "详情页切片", "主图", "SKU"]
.into_iter()
.filter_map(|category| {
let count = receipt["counts"][category].as_u64().unwrap_or(0);
(count > 0).then(|| format!("{category} {count} 份"))
})
.collect::<Vec<_>>()
.join("、")
}).unwrap_or_default();
let mut text = if let Some(folder) = folder.as_deref() && complete {
let contents = (!non_zero_counts.is_empty())
.then(|| format!(",里面有 {non_zero_counts}"))
.unwrap_or_default();
if let Some(reason) = run.finish_receipt["deliveryReason"].as_str().filter(|s| !s.trim().is_empty()) {
format!("{reason},我先把已经做好的成品收进「{folder}」啦{contents}。")
} else {
format!("整套成品都已经帮你做好并收进「{folder}」啦{contents}。你可以直接点下面打开文件夹查看,我也顺手帮你往素材库同步了。")
}
} else if let Some(folder) = folder.as_deref() {
let contents = (!non_zero_counts.is_empty())
.then(|| format!("(包含 {non_zero_counts})"))
.unwrap_or_default();
let mut summary = format!("我先把目前已做好的部分存进「{folder}」了{contents}。");
if empty > 0 {
let preview_hint = (preview > 0)
.then(|| format!("(其中有 {preview} 个已经出好候选图等你确认)"))
.unwrap_or_default();
summary.push_str(&format!("另外还有 {empty} 个图位没补齐{preview_hint},随时点「继续整套制作」我就接着帮你补完。"));
} else if preview > 0 {
summary.push_str(&format!("另外还有 {preview} 个图位已经出好候选图等你确认,随时点「继续整套制作」我就接着帮你补完。"));
} else {
summary.push_str("随时点「继续整套制作」我就接着帮你补完。");
}
summary
} else if empty > 0 {
format!("目前的进度和画布改动我都帮你存好了,还有 {empty} 个图位待补齐,随时点「继续整套制作」就能接着往下做。")
} else {
"本轮制作已结束,已有编辑已保存。".into()
"这一轮先帮你暂停在这里,画布上已经改好的内容都稳稳留着呢,随时点「继续整套制作」我就接着帮你往下做。".into()
};
if let Some(path) = receipt["path"].as_str() {
let counts = ["工程文件", "PSD", "详情页长图", "详情页切片", "主图", "SKU"]
.map(|category| format!("{category} {} 份", receipt["counts"][category].as_u64().unwrap_or(0)));
text.push_str(&format!("\n成品已保存到 {path}\n{}", counts.join("、")));
if let Some(warning) = receipt["skuBarcodeWarning"].as_str() {
text.push_str(&format!("\n{warning}"));
if receipt["path"].is_string() {
if receipt["skuBarcodeWarning"].is_string() {
text.push_str("\n顺带提醒一下,有几张 SKU 图还没填商品条码,你在产品资料里补好后再点一次重新导出,就能自动按条码命名整齐了。");
}
if let Some(warning) = receipt["durabilityWarning"].as_str() {
text.push_str(&format!("\n目录已落位,写入确认失败。{warning}"));
let clean_reason = crate::client_brand::user_error(warning, "写入确认未完成");
text.push_str(&format!("\n刚刚自动打包保存时遇到点小问题({clean_reason}),画布上的成果都还在,你可以先点右上角手动保存一下工程。"));
}
} else if let Some(error) = receipt["error"].as_str() {
text.push_str(&format!("\n自动保存成品失败。{error}。可通过「保存工程」手动保存。"));
let clean_reason = crate::client_brand::user_error(error, "自动保存被中断");
text.push_str(&format!("\n刚刚自动打包保存时遇到点小问题({clean_reason}),画布上的成果都还在,你可以先点右上角手动保存一下工程。"));
}
self.messages.push(json!({"role":"assistant","kind":"reply","text":text,
"productionDelivery":receipt,
@ -393,6 +424,20 @@ impl Workspace {
self.sync_request_meta = self.sync_signature();
self.send("project-sync", json!({"doc":run.doc,"revision":revision,"status":"completed"}));
}
if partial { self.product_production = Some(run); }
if partial {
self.production_stop = json!({"mode":null,"state":"paused","reason":null,"error":null});
self.product_production = Some(run);
}
}
}
pub(super) fn clean_delivery_folder_name(path: &str) -> String {
let stripped = path.strip_prefix(r"\\?\UNC\")
.or_else(|| path.strip_prefix(r"\\?\"))
.unwrap_or(path);
stripped.trim_end_matches(['/', '\\'])
.rsplit(['/', '\\'])
.find(|segment| !segment.is_empty())
.unwrap_or("成品目录")
.to_owned()
}

View File

@ -4,7 +4,7 @@ use std::collections::HashSet;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
const AGENT_RETRY_SECONDS: [u64; 3] = [3, 15, 60];
const AGENT_RETRY_SECONDS: [u64; 3] = [10, 30, 60];
const TURN_WAIT_LIMIT: u8 = 30;
const STOP_TIMEOUT: Duration = Duration::from_secs(30);
@ -175,19 +175,9 @@ impl Workspace {
pub(in crate::jiansun) fn production_budget_state(&self) -> Value {
json!({"startedAt":self.product_production.as_ref().map(|run| run.started_at),
"budgetMinutes":self.production_budget_minutes,
"elapsedMinutes":self.product_production.as_ref().map_or(0.0, |run| run.elapsed().as_secs_f64() / 60.0)})
}
pub(in crate::jiansun) fn production_budget_delay(&self) -> Option<Duration> {
let run = self.product_production.as_ref()?;
if matches!(run.phase, Phase::Paused(_) | Phase::DeliveringBundle) || run.paused_at.is_some() {
return None;
}
Some(Duration::from_secs(self.production_budget_minutes.saturating_add(10).saturating_mul(60).saturating_add(1))
.saturating_sub(run.elapsed()))
}
fn settle_production_stop(&mut self, app: &PhotocraftApp) {
if self.product_production.as_ref().and_then(|run| run.stop_deadline)
.is_some_and(|deadline| Instant::now() >= deadline) {
@ -345,8 +335,10 @@ impl Workspace {
_ => Phase::AwaitingSave,
};
if matches!(next_phase, Phase::AwaitingSave) {
run.waiting_originals_since = None;
run.await_canvas_save();
} else {
run.waiting_originals_since = matches!(next_phase, Phase::WaitingOriginals { .. }).then(Instant::now);
run.phase = next_phase;
}
if self.saving.is_some_and(|(doc, _)| doc != run.doc) {
@ -418,12 +410,15 @@ impl Workspace {
.filter(|minutes| *minutes > 0).unwrap_or(45);
Some(deadline.saturating_sub(minutes.saturating_mul(60)))
}).unwrap_or(run.started_at);
let now = production_time();
run.paused_seconds = checkpoint["pausedSeconds"].as_u64().unwrap_or_default();
if let Some(saved_at) = checkpoint["clockSavedAt"].as_u64() {
run.paused_at = Some(saved_at);
if !paused { run.resume_clock(); }
if let Some(saved_at) = checkpoint["clockSavedAt"].as_u64().filter(|&saved| saved > 0) {
if now > saved_at {
run.paused_seconds = run.paused_seconds.saturating_add(now.saturating_sub(saved_at));
}
run.paused_at = paused.then_some(now);
} else if paused {
run.paused_at = Some(production_time());
run.paused_at = Some(now);
}
run.delivery_dir = delivery_dir(&checkpoint);
run.delivery_id = checkpoint["deliveryId"].as_str().map(str::to_owned);
@ -746,6 +741,7 @@ impl Workspace {
.cloned().collect();
run.defer_images(stage, native);
}
run.waiting_originals_since = Some(Instant::now());
run.phase = Phase::WaitingOriginals { models, images, goal };
}
self.checkpoint_production();
@ -869,10 +865,6 @@ impl Workspace {
}
return;
}
if self.production_stop["state"] != "delivering" && self.production_budget_delay() == Some(Duration::ZERO) {
let _ = self.request_production_stop("deliver", "到达时间上限自动交付");
return;
}
if self.production_canvas_save_delay(Instant::now()) == Some(Duration::ZERO) {
self.slot_apply_save_failed(app, "等待制作画布保存超时,请重试");
return;
@ -946,8 +938,11 @@ fn retryable_agent_failure(failure: &Value, reason: &str) -> bool {
}
failure["retryable"] == true
|| matches!(failure["category"].as_str(),
Some("transport_interrupted" | "outcome_unknown" | "request_outcome_unknown" | "rate_limited" | "stream_idle_timeout"))
|| ["request_outcome_unknown", "stream_idle_timeout", "429", "流式响应空闲超时", "传输中断"]
Some("transient" | "transport_interrupted" | "outcome_unknown" | "request_outcome_unknown" | "rate_limited" | "stream_idle_timeout"))
|| [
"request_outcome_unknown", "stream_idle_timeout", "429", "流式响应空闲超时", "传输中断",
"暂时连接不上", "对话服务暂时连接", "网络", "timeout", "ECONNRESET", "ETIMEDOUT", "EAI_AGAIN",
]
.iter().any(|marker| reason.contains(marker))
}

View File

@ -1345,7 +1345,7 @@ fn ending_a_paused_goal_saves_the_canvas_and_starts_a_fresh_goal() {
}
#[test]
fn production_budget_stops_the_turn_and_requests_delivery() {
fn production_does_not_truncate_or_auto_deliver_on_elapsed_time() {
let (tx, requests) = mpsc::channel();
let (_, rx) = mpsc::channel();
let mut w = Workspace::new(tx, rx);
@ -1365,7 +1365,6 @@ fn production_budget_stops_the_turn_and_requests_delivery() {
]), None, Phase::Agent);
run.started_at = production_time() - 5 * 60 * 60;
w.product_production = Some(run);
w.pause_production_agent = Some(|_, _, _| {});
w.busy = Some("pi-agent".into());
w.pi_product_production = true;
w.allow_apply = true;
@ -1373,20 +1372,87 @@ fn production_budget_stops_the_turn_and_requests_delivery() {
w.production_tick(&app);
assert_eq!(w.production_stop["state"], "stopping");
assert_eq!(w.production_stop["mode"], "deliver");
assert_eq!(w.production_stop["reason"], "到达时间上限自动交付");
assert_eq!(w.product_production.as_ref().unwrap().stages.len(), 2);
assert!(!w.allow_apply);
assert_eq!(w.production_stop["state"], "idle");
assert!(w.allow_apply);
assert!(requests.try_iter().all(|request| !matches!(request, Request::DeliverProductionBundle(_, _))));
}
#[test]
fn restore_checkpoint_adds_offline_gap_to_paused_seconds() {
let (tx, requests) = mpsc::channel();
let (_, rx) = mpsc::channel();
let mut w = Workspace::new(tx, rx);
let _ = requests.try_recv().unwrap();
w.account = json!({"id":"local"});
w.busy = None;
w.production_tick(&app);
assert_eq!(w.production_stop["state"], "delivering");
let input = requests.try_iter().find_map(|request| match request {
Request::DeliverProductionBundle(input, _) => Some(input),
_ => None,
}).expect("budget expiry queues a delivery");
assert_eq!(input["deliveryReason"], "到达时间上限自动交付");
assert_eq!(input["remainingOutputs"].as_array().unwrap().len(), 2);
w.model_ready = true;
w.image_ready = true;
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width":40,"height":50})).unwrap();
let state = session.active_mut().unwrap();
let doc = state.doc.id.0;
let mapping = json!({"version":1,"canvasFirst":true,"workspaceId":"workspace",
"component":"detail","variantId":"wood","templateId":"fixture","templateVersion":"1",
"templateHash":"hash","outputs":[{"documentId":"page","mapping":{"fields":[]}}]});
Arc::make_mut(&mut state.doc).metadata.text.push(("jiansun.slot-mapping.v1".into(), mapping.to_string()));
w.open_projects.insert(doc, w.local_identity("project"));
w.loaded_draft = Some(doc);
w.persisted_revisions.insert(doc, state.revision);
w.template_workflow = json!({"workspaceId":"workspace","outputId":"detail","variantId":"wood",
"templateId":"fixture","templateVersion":"1","templateHash":"hash",
"outputs":[{"outputId":"detail","documentId":"page"}],"productionStages":[{"outputId":"detail","variantId":"wood"}]});
let app = PhotocraftApp::new(session, crate::Services::default());
let now = production_time();
w.product_checkpoint = json!({
"active": true,
"phase": "paused",
"project": "project",
"workspaceId": "workspace",
"startedAt": now - 100 * 60,
"pausedSeconds": 0,
"clockSavedAt": now - 97 * 60,
"stages": [{"outputId":"detail","variantId":"wood"}],
"total": 1,
"partialDelivered": true,
});
w.restore_production_checkpoint(&app);
let restored = w.product_production.take().unwrap();
let elapsed = restored.elapsed().as_secs();
assert!((178..=182).contains(&elapsed), "expected ~3m active time after 97m offline gap, got {elapsed}s");
}
#[test]
fn transient_network_disconnect_triggers_auto_retry_instead_of_pausing() {
let (tx, requests) = mpsc::channel();
let (_, rx) = mpsc::channel();
let mut w = Workspace::new(tx, rx);
let _ = requests.try_recv().unwrap();
w.account = json!({"id":"local"});
w.origin = "https://example.test".into();
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width":40,"height":50})).unwrap();
let app = PhotocraftApp::new(session, crate::Services::default());
let doc = app.session.active().unwrap().doc.id.0;
let project = w.local_identity("project");
w.open_projects.insert(doc, project.clone());
w.template_workflow = json!({"workspaceId":"workspace"});
w.product_production = Some(Run::new(doc, project, json!("workspace"), Vec::from([
Stage { output:"detail".into(), variant:"wood".into() },
]), None, Phase::Agent));
w.production_agent_received(&app, &json!({
"doc": doc,
"accountId": "local",
"origin": "https://example.test",
"projectLocalId": "project",
"error": "对话服务暂时连接不上,已保留已保存的修改,请稍后继续",
"failure": {"category": "transient", "message": "对话服务暂时连接不上"}
}));
let run = w.product_production.as_ref().unwrap();
assert!(matches!(run.phase, Phase::AgentRetryAt(_)), "expected auto-retry phase");
assert_eq!(run.agent_retries, 1);
}
#[test]
@ -2765,3 +2831,60 @@ fn embedded_target_rejection_only_blocks_edited_inner_layer() {
"sibling inner layer 102 in the same container must NOT be blocked"
);
}
#[test]
fn note_production_summary_uses_natural_copy_and_clean_folder_name() {
let (tx, _rx) = mpsc::channel();
let (_, event_rx) = mpsc::channel();
let mut w = Workspace::new(tx, event_rx);
w.account = json!({"id":"local"});
let mut run = Run::new(1, "local|account|project".into(), json!("workspace"), Vec::new(), None, Phase::Agent);
run.all_outputs_completed = true;
run.total = 1;
run.published = vec![json!({"outputId":"detail","variantId":"wood","progressSummary":{"unfilledImageSlots":[],"unreviewedScreens":[],"screensWithOpenIssues":[]},"issues":[]})];
run.delivery_receipt = json!({
"path": r"\\?\E:\小壹\19815\jiansun\accounts\0123456789abcdef\deliveries\宽界电脑桌 DNZ0409-成品 (2)",
"completedOutputs": 1,
"allOutputsCompleted": true,
"counts": {"工程文件": 3, "PSD": 2, "详情页长图": 1, "详情页切片": 17, "主图": 0, "SKU": 1},
});
w.note_production_summary(run);
let text = w.messages.last().unwrap()["text"].as_str().unwrap();
assert!(!text.contains(r"\\?\"), "must strip verbatim prefix: {text}");
assert!(!text.contains("内部编号"), "must not leak internal account hash: {text}");
assert!(!text.contains("主图 0 份"), "must omit zero-count categories: {text}");
assert!(!text.contains("已采纳 "), "must not output mechanical slot counts: {text}");
assert!(text.contains("「宽界电脑桌 DNZ0409-成品 (2)」"), "{text}");
assert!(text.contains("工程文件 3 份、PSD 2 份、详情页长图 1 份、详情页切片 17 份、SKU 1 份"), "{text}");
}
#[test]
fn waiting_originals_releases_stalled_unknown_candidate_after_timeout() {
let (tx, _rx) = mpsc::channel();
let (_, event_rx) = mpsc::channel();
let mut w = Workspace::new(tx, event_rx);
w.account = json!({"id":"local"});
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width":40,"height":50})).unwrap();
let app = PhotocraftApp::new(session, crate::Services::default());
let doc = app.session.active().unwrap().doc.id.0;
let project = w.local_identity("project");
w.open_projects.insert(doc, project.clone());
w.template_workflow = json!({"workspaceId":"workspace"});
let stage = Stage { output:"main_images".into(), variant:"wood".into() };
let mut run = Run::new(doc, project, json!("workspace"), vec![stage.clone()], None,
Phase::WaitingOriginals { models: vec![], images: vec!["ccd4620d".into()], goal: None });
run.defer_images(stage.clone(), vec!["ccd4620d".into()]);
let past = Instant::now() - Duration::from_secs(95);
run.waiting_originals_since = Some(past);
w.product_production = Some(run);
let ctx = egui::Context::default();
w.tick_deferred_image_recovery(&app, &ctx, Instant::now());
let run = w.product_production.as_ref().unwrap();
assert!(!run.waiting_for_originals(), "timed-out WaitingOriginals must release");
assert!(run.awaiting_canvas_save());
assert!(!run.owns_deferred_image("ccd4620d"));
}

View File

@ -71,9 +71,11 @@ impl HeadControls {
Value::Null => "停止没有完成".into(),
other => other.to_string(),
};
let budget = state.budget["budgetMinutes"].as_f64().filter(|minutes| minutes.is_finite() && *minutes > 0.0)
.zip(state.budget["elapsedMinutes"].as_f64().filter(|minutes| minutes.is_finite()))
.map(|(budget_minutes, elapsed_minutes)| TimeBudget { elapsed_minutes, budget_minutes });
let budget = state.budget["elapsedMinutes"].as_f64().filter(|minutes| minutes.is_finite())
.map(|elapsed_minutes| TimeBudget {
elapsed_minutes,
budget_minutes: state.budget["budgetMinutes"].as_f64().filter(|m| m.is_finite() && *m > 0.0).unwrap_or(0.0),
});
Self { stop: state.stop["state"].as_str().unwrap_or("idle").to_owned(), error, budget }
}
@ -304,12 +306,12 @@ mod tests {
let structured = HeadControls::read(&state(json!({"state":"failed","error":{"code":"E1"}}), Value::Null));
assert_eq!(structured.phase(), StopPhase::Failed(r#"{"code":"E1"}"#));
let budget = HeadControls::read(&state(Value::Null, json!({"startedAt":1,"budgetMinutes":45,"elapsedMinutes":23.6}))).budget.unwrap();
assert_eq!(budget.text(), "已用 23 分钟 / 预算 45 分钟");
assert_eq!(budget.text(), "已用 23 分钟");
assert!(!budget.over());
let over = HeadControls::read(&state(Value::Null, json!({"startedAt":1,"budgetMinutes":45,"elapsedMinutes":45.5}))).budget.unwrap();
assert!(over.over());
assert_eq!(over.text(), "已超出预算,将自动交付");
for invalid in [json!({"budgetMinutes":0,"elapsedMinutes":3}), json!({"budgetMinutes":45}), json!({"elapsedMinutes":3}), json!(null)] {
let over = HeadControls::read(&state(Value::Null, json!({"startedAt":1,"elapsedMinutes":45.5}))).budget.unwrap();
assert!(!over.over());
assert_eq!(over.text(), "已用 45 分钟");
for invalid in [json!({"budgetMinutes":45}), json!(null)] {
assert!(HeadControls::read(&state(Value::Null, invalid.clone())).budget.is_none(), "{invalid}");
}
}
@ -440,7 +442,7 @@ mod tests {
let head = result.controls.unwrap();
assert!(head.stop.enabled() && head.resume.is_none() && head.choices.is_empty(), "{width}: one stop button, menu closed");
assert!(head.stop.rect.right() <= result.rect.right() + 0.5 && head.stop.rect.top() >= result.title.bottom() - 0.5);
assert!(drawn.iter().any(|text| text == "已用 23 分钟 / 预算 45 分钟"), "{width}: {drawn:?}");
assert!(drawn.iter().any(|text| text == "已用 23 分钟"), "{width}: {drawn:?}");
assert!(!drawn.iter().any(|text| text == "已用 23m"), "{width}: the budget is not repeated in the pipeline row");
let budget_rect = head.budget.unwrap();
assert!(budget_rect.right() <= head.stop.rect.left() + 0.5 || budget_rect.bottom() <= head.stop.rect.top() + 0.5,
@ -467,7 +469,7 @@ mod tests {
assert!(drawn.iter().any(|text| text == "已用 23m"), "without a reported budget the pipeline row keeps the elapsed time");
let drawn = texts(&ctx, size, vec![], |ui| { show(ui, "over", &fixture,
controls(StopPhase::Idle, Some(TimeBudget { elapsed_minutes: 47.0, budget_minutes: 45.0 }))); });
assert!(drawn.iter().any(|text| text == "已超出预算,将自动交付"), "{width}: {drawn:?}");
assert!(drawn.iter().any(|text| text == "已用 47 分钟"), "{width}: {drawn:?}");
}
}

View File

@ -487,15 +487,12 @@ pub(super) struct TimeBudget { pub elapsed_minutes: f64, pub budget_minutes: f64
impl TimeBudget {
pub(super) fn over(self) -> bool {
self.elapsed_minutes > self.budget_minutes
let _ = self.budget_minutes;
false
}
pub(super) fn text(self) -> String {
if self.over() {
"已超出预算,将自动交付".into()
} else {
format!("已用 {} 分钟 / 预算 {} 分钟", self.elapsed_minutes.max(0.0).floor(), self.budget_minutes.round())
}
format!("已用 {} 分钟", self.elapsed_minutes.max(0.0).floor())
}
}
@ -775,8 +772,15 @@ where
let running = panel.state.running();
let can_stop = running || panel.state == RunState::WaitingUser;
let waiting = panel.state.waiting();
let heading = if panel.state == RunState::Running { panel.title.to_owned() }
else { format!("{} · {}", state_title(panel.state), panel.title) };
let state_prefix = state_title(panel.state);
let heading = if panel.state == RunState::Running
|| panel.title.starts_with(state_prefix)
|| panel.title.starts_with("已暂停")
{
panel.title.to_owned()
} else {
format!("{state_prefix} · {}", panel.title)
};
let (done, total) = progress_of(&panel);
let fraction = total.filter(|total| *total > 0.0).map(|total| done / total).or_else(|| panel.budget.fraction());
let ring = if panel.state == RunState::Completed { AGENT_SEMANTIC.success } else if panel.budget.over() { t.warning } else { AGENT_SEMANTIC.progress };