修复小壹旧工程兼容与中断续作
This commit is contained in:
parent
b989cd0038
commit
5f12ca834a
@ -1010,16 +1010,23 @@ impl Backend {
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for entry in fs::read_dir(dir).map_err(|_| "项目目录无法读取")?.take(10000) {
|
||||
let entry = entry.map_err(|_| "项目目录无法读取")?;
|
||||
let entry = match entry {
|
||||
Ok(entry) => entry,
|
||||
Err(error) => { log::warn!("跳过无法读取的本机项目目录:{error}"); continue; }
|
||||
};
|
||||
let p = entry.path().join("context.json");
|
||||
if p.exists() {
|
||||
let v = read_json(&p)?;
|
||||
let id = entry.file_name().to_str().ok_or("本机项目编号无效")?.to_owned();
|
||||
let name = entry.file_name();
|
||||
// Numeric directories belong to the first local preview. Keep those existing
|
||||
// drafts readable; new projects always receive independent UUID identities.
|
||||
if Uuid::parse_str(&id).is_err() && id.parse::<u64>().is_err() {
|
||||
return Err("本机项目编号无效".into());
|
||||
}
|
||||
let Some(id) = name.to_str().filter(|id| Uuid::parse_str(id).is_ok() || id.parse::<u64>().is_ok()) else {
|
||||
log::warn!("跳过无效本机项目目录:{}", entry.path().display());
|
||||
continue;
|
||||
};
|
||||
let v = match read_json(&p) {
|
||||
Ok(value) if value.is_object() => value,
|
||||
_ => { log::warn!("跳过损坏的本机项目上下文:{}", p.display()); continue; }
|
||||
};
|
||||
let brief = creation::load(&entry.path()).ok().map(|value| value["brief"].clone()).unwrap_or_default();
|
||||
let updated = v["time"].as_str().and_then(|value| value.parse::<i64>().ok())
|
||||
.and_then(|time| chrono::DateTime::from_timestamp(time, 0))
|
||||
@ -1068,12 +1075,17 @@ impl Backend {
|
||||
Ok(out)
|
||||
}
|
||||
fn legacy_text_choices(&self, saved: &Value) -> Vec<Value> {
|
||||
self.checked_legacy_text_choices(saved).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn checked_legacy_text_choices(&self, saved: &Value) -> R<Vec<Value>> {
|
||||
let keys = [&saved["model"], crate::jiansun_models::copy_selection(saved)];
|
||||
if !keys.iter().any(|key| key.as_str().is_some_and(|id| Uuid::parse_str(id).is_ok())) {
|
||||
return vec![];
|
||||
return Ok(vec![]);
|
||||
}
|
||||
self.json("agent-models").ok().and_then(|value| value["models"].as_array().cloned())
|
||||
.unwrap_or_default().into_iter().filter(|option| keys.contains(&&option["key"])).collect()
|
||||
let catalog = self.json("agent-models")?;
|
||||
Ok(catalog["models"].as_array().ok_or("原对话模型目录无效")?.iter()
|
||||
.filter(|option| keys.contains(&&option["key"])).cloned().collect())
|
||||
}
|
||||
|
||||
fn text_models(catalog: &Value, aliases: &[Value], key: Option<&crate::jiansun_models::KeyCatalog>) -> R<Vec<Value>> {
|
||||
@ -1119,13 +1131,13 @@ impl Backend {
|
||||
.ok_or_else(|| "98K 当前未发布此模型的可用对话契约,请重新选择".into())
|
||||
}
|
||||
|
||||
fn refresh_models(&mut self, catalog: &Value, saved: &Value, key: Option<&crate::jiansun_models::KeyCatalog>) -> R<()> {
|
||||
let aliases = self.legacy_text_choices(saved);
|
||||
self.models = Self::text_models(catalog, &aliases, key)?;
|
||||
fn refresh_models(&mut self, catalog: &Value, saved: &Value, key: Option<&crate::jiansun_models::KeyCatalog>) -> R<bool> {
|
||||
let aliases = self.checked_legacy_text_choices(saved);
|
||||
self.models = Self::text_models(catalog, aliases.as_deref().unwrap_or_default(), key)?;
|
||||
let _ = pi_runtime::enrich_models(&mut self.models);
|
||||
self.copy_models = self.models.clone();
|
||||
self.copy_error.clear();
|
||||
Ok(())
|
||||
self.copy_error = aliases.as_ref().err().cloned().unwrap_or_default();
|
||||
Ok(aliases.is_ok())
|
||||
}
|
||||
fn public_model_catalog(&self) -> R<Value> {
|
||||
self.public_model_catalog_with_timings().map(|(value, _)| value)
|
||||
@ -1191,21 +1203,55 @@ impl Backend {
|
||||
let contract = crate::jiansun_image_protocol::select(&catalog, &id, Some(&permitted))?;
|
||||
Ok((id, contract))
|
||||
}
|
||||
fn refresh_image_models(&mut self, catalog: &Value, saved: &Value, available: Option<&crate::jiansun_models::KeyCatalog>) {
|
||||
fn refresh_image_models(&mut self, catalog: &Value, saved: &Value, available: Option<&crate::jiansun_models::KeyCatalog>) -> bool {
|
||||
let choice = saved["imageModel"].as_str().unwrap_or_default();
|
||||
let legacy = Uuid::parse_str(choice).is_ok().then(|| self.image_model_id(choice));
|
||||
let previous = legacy.as_ref().and_then(|result| result.as_deref().ok()).map(|id| (choice, id));
|
||||
let legacy = Uuid::parse_str(choice).is_ok().then(|| self.json("models"));
|
||||
let original = legacy.as_ref().and_then(|result| result.as_ref().ok())
|
||||
.and_then(|catalog| crate::jiansun_models::legacy_image_id(catalog, choice).ok());
|
||||
let previous = original.as_deref().map(|id| (choice, id));
|
||||
match crate::jiansun_models::image_choices(catalog, available, previous) {
|
||||
Ok(items) => {
|
||||
self.image_models = items;
|
||||
self.image_error = legacy.and_then(Result::err).unwrap_or_default();
|
||||
self.image_error = legacy.as_ref().and_then(|result| result.as_ref().err()).cloned().unwrap_or_default();
|
||||
legacy.is_none_or(|result| result.is_ok())
|
||||
}
|
||||
Err(error) => {
|
||||
self.image_models.clear();
|
||||
self.image_error = error;
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
fn migrate_legacy_model_settings(&mut self, saved: &mut Value, available: &[String], text_aliases_checked: bool, image_aliases_checked: bool) -> R<()> {
|
||||
let mut updated = saved.clone();
|
||||
for (field, models, aliases_checked) in [
|
||||
("model", &self.models, text_aliases_checked),
|
||||
("copyModel", &self.copy_models, text_aliases_checked),
|
||||
("imageModel", &self.image_models, image_aliases_checked),
|
||||
] {
|
||||
if !aliases_checked { continue; }
|
||||
let choice = if field == "copyModel" { crate::jiansun_models::copy_selection(saved) } else { &saved[field] };
|
||||
let Some(legacy) = choice.as_str().filter(|id| Uuid::parse_str(id).is_ok()) else { continue; };
|
||||
let permitted = || models.iter().filter(|row| row["id"].as_str().is_some_and(|id| available.iter().any(|allowed| allowed == id)));
|
||||
let resolved = permitted().find(|row| row["key"] == legacy);
|
||||
let Some(id) = resolved.or_else(|| permitted().next())
|
||||
.and_then(|row| row["id"].as_str()) else { continue; };
|
||||
updated[field] = json!(id);
|
||||
if resolved.is_some() && let Some(preferences) = updated["thinkingByModel"].as_object_mut()
|
||||
&& let Some(level) = preferences.get(legacy).cloned() {
|
||||
preferences.entry(id).or_insert(level);
|
||||
}
|
||||
}
|
||||
if updated != *saved {
|
||||
vault(&format!("models:{}", self.scope()))?.set_password(&updated.to_string())
|
||||
.map_err(|_| "模型设置未能保存到系统凭据库")?;
|
||||
*saved = updated;
|
||||
for row in self.models.iter_mut().chain(&mut self.copy_models).chain(&mut self.image_models) {
|
||||
row["key"] = row["id"].clone();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn key_catalog_full(&self, key: &str) -> R<crate::jiansun_models::KeyCatalog> {
|
||||
let url = format!("{UPSTREAM}/v1/models");
|
||||
#[cfg(test)]
|
||||
@ -1273,7 +1319,7 @@ impl Backend {
|
||||
if library_status == "connected" {
|
||||
knowledge_http::set_account(self);
|
||||
}
|
||||
let saved = self.settings().unwrap_or_else(|_| json!({}));
|
||||
let mut saved = self.settings().unwrap_or_else(|_| json!({}));
|
||||
// 模型目录来自 98k,与素材库是否在线无关;已登录账户在素材库暂不可用时照常加载。
|
||||
if library_status == "connected" || library_status == "unavailable" {
|
||||
let has_key = saved["key"].as_str().filter(|key| !key.is_empty());
|
||||
@ -1288,12 +1334,20 @@ impl Backend {
|
||||
}
|
||||
match load_catalog(self) {
|
||||
Ok(catalog) => {
|
||||
if has_key.is_none() || available.is_some() {
|
||||
self.refresh_image_models(&catalog, &saved, available.as_ref());
|
||||
}
|
||||
if let Err(error) = self.refresh_models(&catalog, &saved, available.as_ref()) {
|
||||
self.copy_error.clone_from(&error);
|
||||
if message.is_empty() { message = error; }
|
||||
let image_aliases_checked = (has_key.is_none() || available.is_some())
|
||||
&& self.refresh_image_models(&catalog, &saved, available.as_ref());
|
||||
let text_aliases_checked = match self.refresh_models(&catalog, &saved, available.as_ref()) {
|
||||
Ok(checked) => checked,
|
||||
Err(error) => {
|
||||
self.copy_error.clone_from(&error);
|
||||
if message.is_empty() { message = error; }
|
||||
false
|
||||
}
|
||||
};
|
||||
if let Some(available) = &available
|
||||
&& let Err(error) = self.migrate_legacy_model_settings(&mut saved, &available.ids, text_aliases_checked, image_aliases_checked)
|
||||
&& message.is_empty() {
|
||||
message = error;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
@ -1653,9 +1707,10 @@ impl Backend {
|
||||
}
|
||||
fn production_budget_minutes(&self, dir: &Path, project: &str) -> u64 {
|
||||
let settings = dir.join("agent").join(self.scope()).join(project).join("production-settings.json");
|
||||
// 精修设置按分钟数写入,可能是小数。
|
||||
read_json(&settings).ok().and_then(|value| value["timeBudgetMinutes"].as_f64())
|
||||
.filter(|minutes| *minutes > 0.0).map_or(120, |minutes| minutes.round() as u64)
|
||||
let settings = read_json(&settings).unwrap_or_default();
|
||||
let default = if settings["refinement"] == true { 120 } else { 45 };
|
||||
settings["timeBudgetMinutes"].as_f64().filter(|minutes| *minutes > 0.0)
|
||||
.map_or(default, |minutes| minutes.round() as u64)
|
||||
}
|
||||
|
||||
fn ensure_current_doc(&self, id: u64) -> R<()> {
|
||||
@ -1947,7 +2002,7 @@ impl Backend {
|
||||
let checkpoint = &input["checkpoint"];
|
||||
if checkpoint["active"] == true {
|
||||
self.ensure_owner(doc)?;
|
||||
self.check_dispatch()?;
|
||||
if checkpoint["phase"] != "paused" && method != "product-exit-checkpoint" { self.check_dispatch()?; }
|
||||
}
|
||||
if self.locations.get(&doc).is_none_or(|project| checkpoint["project"] != *project) {
|
||||
return Err("制作任务属于其他项目".into());
|
||||
@ -1956,8 +2011,8 @@ impl Backend {
|
||||
transfer::redact(&mut checkpoint);
|
||||
let path = self.project_dir(doc)?.join("production-run.json");
|
||||
if method == "product-exit-checkpoint" && checkpoint["active"].is_null() {
|
||||
let mut saved = if path.is_file() { read_json(&path)? }
|
||||
else { json!({"active":false,"project":checkpoint["project"]}) };
|
||||
if !path.try_exists().map_err(|error| error.to_string())? { return Ok(Value::Null); }
|
||||
let mut saved = read_json(&path)?;
|
||||
if saved["project"] != checkpoint["project"] { return Err("制作记录属于其他项目".into()); }
|
||||
saved["status"] = checkpoint["status"].clone();
|
||||
write_json(&path, &saved)?;
|
||||
@ -2697,6 +2752,59 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn native_project_listing_skips_corrupt_and_stray_entries() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let backend = Backend::new(tmp.path().into()).unwrap();
|
||||
let root = backend.dir().join("projects");
|
||||
let good = Uuid::new_v4().to_string();
|
||||
let corrupt = Uuid::new_v4().to_string();
|
||||
for (id, context) in [(&good[..], r#"{"name":"有效工程"}"#), (&corrupt, "{"), ("stray", "{}")] {
|
||||
let path = root.join(id).join("context.json");
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, context).unwrap();
|
||||
}
|
||||
let projects = backend.native_projects().unwrap();
|
||||
assert_eq!(projects.len(), 1);
|
||||
assert_eq!(projects[0]["id"], good);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_without_a_run_does_not_create_a_checkpoint_and_defaults_to_fast_budget() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut backend = Backend::new(tmp.path().into()).unwrap();
|
||||
backend.bind_new(7);
|
||||
let id = backend.locations[&7].clone();
|
||||
let dir = backend.project_dir(7).unwrap();
|
||||
let (tx, _) = mpsc::channel();
|
||||
backend.action("product-exit-checkpoint", &json!({"doc":7,"checkpoint":{"project":id,"status":"paused_on_exit"}}),
|
||||
&tx, &egui::Context::default()).unwrap();
|
||||
assert!(!dir.join("production-run.json").exists());
|
||||
assert_eq!(backend.production_budget_minutes(&dir, &id), 45);
|
||||
let settings = dir.join("agent").join(backend.scope()).join(&id).join("production-settings.json");
|
||||
write_json(&settings, &json!({"refinement":true})).unwrap();
|
||||
assert_eq!(backend.production_budget_minutes(&dir, &id), 120);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_model_ids_are_persisted_and_retired_choices_use_an_authorized_default() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut backend = Backend::new(tmp.path().into()).unwrap();
|
||||
backend.auth = json!({"account":{"id":Uuid::new_v4()}});
|
||||
let old = Uuid::new_v4().to_string();
|
||||
let retired = Uuid::new_v4().to_string();
|
||||
backend.models = vec![json!({"id":"model-a","key":old})];
|
||||
backend.copy_models = backend.models.clone();
|
||||
backend.image_models = vec![json!({"id":"denied","key":"denied"}), json!({"id":"image-default","key":"image-default"})];
|
||||
let mut saved = json!({"model":old,"imageModel":retired,"thinkingByModel":{(old.clone()):"low"}});
|
||||
backend.migrate_legacy_model_settings(&mut saved, &["model-a".into(), "image-default".into()], true, true).unwrap();
|
||||
assert_eq!(saved["model"], "model-a");
|
||||
assert_eq!(saved["copyModel"], "model-a");
|
||||
assert_eq!(saved["imageModel"], "image-default");
|
||||
assert_eq!(saved["thinkingByModel"]["model-a"], "low");
|
||||
assert_eq!(backend.models[0]["key"], "model-a");
|
||||
}
|
||||
|
||||
const CALLBACK_STATE: &str = "callback-test-state";
|
||||
const CALLBACK_CODE: &str = "dca_0123456789012345678901234567890123456789012";
|
||||
|
||||
@ -2934,12 +3042,13 @@ mod tests {
|
||||
assert_eq!(value["category"], "auth_revoked");
|
||||
assert!(!value.to_string().contains("test-secret"));
|
||||
backend.action("product-run-checkpoint", &json!({"doc":doc.id.0,"checkpoint":{
|
||||
"project":backend.locations[&doc.id.0],"active":false,"phase":"paused","reason":"auth_revoked",
|
||||
"project":backend.locations[&doc.id.0],"active":true,"phase":"paused","reason":"auth_revoked",
|
||||
"note":"Cookie: client=reflected-test-secret"
|
||||
}}), &events, &ctx).unwrap();
|
||||
assert_eq!(read_json(&dir.join("context.json")).unwrap()["composer"], "未提交编辑");
|
||||
let paused = read_json(&dir.join("production-run.json")).unwrap();
|
||||
assert_eq!(paused["phase"], "paused");
|
||||
assert_eq!(paused["active"], true);
|
||||
assert!(!paused.to_string().contains("reflected-test-secret"));
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
@ -3094,7 +3094,20 @@ pub(super) fn remaining_stages(dir: &Path, state: &Value, brief_revision: &Value
|
||||
Some(id) => {
|
||||
let source = &receipt["sourceDocument"];
|
||||
source["generationId"] == id && source["path"] == receipt["editable"]
|
||||
&& source["reopened"] == true && artifact_matches(source, verify_editable)
|
||||
&& source["reopened"] == true && (artifact_matches(source, verify_editable)
|
||||
|| source["path"].as_str().is_some_and(|path| {
|
||||
if Path::new(path).exists() { return false; }
|
||||
let parts: Vec<_> = path.split(['/', '\\']).collect();
|
||||
let Some(at) = parts.iter().rposition(|part| matches!(*part, "product-exports" | "image-jobs")) else { return false; };
|
||||
let relative = &parts[at..];
|
||||
if relative.iter().any(|part| {
|
||||
let mut components = Path::new(part).components();
|
||||
!matches!(components.next(), Some(std::path::Component::Normal(_))) || components.next().is_some()
|
||||
}) { return false; }
|
||||
let mut relocated = source.clone();
|
||||
relocated["path"] = json!(dir.join(relative.iter().collect::<PathBuf>()));
|
||||
artifact_matches(&relocated, true)
|
||||
}))
|
||||
}
|
||||
None => receipt["editable"].as_str().is_some_and(|path| Path::new(path).is_file()),
|
||||
};
|
||||
@ -3108,7 +3121,7 @@ fn resumable_stages(dir: &Path, state: &Value, brief_revision: &Value, verify_ed
|
||||
let mut remaining = remaining_stages(dir, state, brief_revision, verify_editable);
|
||||
let path = dir.join("production-run.json");
|
||||
if let Ok(checkpoint) = read_json(&path)
|
||||
&& checkpoint["status"] == "paused_on_exit" && checkpoint["active"] == false
|
||||
&& checkpoint["status"] == "paused_on_exit"
|
||||
&& checkpoint["workspaceId"] == state["id"]
|
||||
&& checkpoint["project"].as_str().is_some_and(|id| dir.file_name().is_some_and(|name| name == id))
|
||||
{
|
||||
@ -7081,6 +7094,20 @@ mod tests {
|
||||
let pending = || remaining_stages(&fixture.dir, &state, &snapshot["briefRevision"], true)
|
||||
.iter().any(|stage| stage["outputId"] == "detail" && stage["variantId"] == variant);
|
||||
assert!(!pending());
|
||||
let published = receipt_path(&fixture.dir, variant, "detail");
|
||||
let pointer = read_json(&published).unwrap();
|
||||
let manifest = published.parent().unwrap().join(pointer["publishedPointer"].as_str().unwrap());
|
||||
let saved_manifest = read_json(&manifest).unwrap();
|
||||
let mut relocated = saved_manifest.clone();
|
||||
let original = Path::new(snapshot["editable"].as_str().unwrap());
|
||||
relocated["editable"] = json!(fixture.dir.join("old-root").join(original.strip_prefix(&fixture.dir).unwrap()));
|
||||
relocated["sourceDocument"]["path"] = relocated["editable"].clone();
|
||||
write_json(&manifest, &relocated).unwrap();
|
||||
assert!(!pending(), "the matching editable bytes are available at the project's current path");
|
||||
relocated["sourceDocument"]["sha256"] = json!("0".repeat(64));
|
||||
write_json(&manifest, &relocated).unwrap();
|
||||
assert!(pending(), "relocated editable bytes must match the verified receipt");
|
||||
write_json(&manifest, &saved_manifest).unwrap();
|
||||
let creation = creation::load(&fixture.dir).unwrap();
|
||||
assert_eq!(check_delivery_export(&fixture.dir, &state, &creation, variant, "detail", &snapshot).unwrap_err(),
|
||||
STALE_DELIVERY_EXPORT);
|
||||
@ -7100,13 +7127,15 @@ mod tests {
|
||||
moved["screenFiles"] = json!([]);
|
||||
let reason = check_delivery_export(&fixture.dir, &state, &creation, variant, "detail", &moved).unwrap_err();
|
||||
assert!(reason.contains("图片数量或尺寸"));
|
||||
write_json(&fixture.dir.join("production-run.json"), &json!({
|
||||
"active":false,"status":"paused_on_exit","workspaceId":state["id"],"project":fixture.dir.file_name().unwrap().to_str(),
|
||||
"published":[{"outputId":"detail","variantId":variant,"generationId":snapshot["generationId"],
|
||||
"issues":[{"field":"S01-I01","reason":"需复核产品图"}]}]
|
||||
})).unwrap();
|
||||
assert!(resumable_stages(&fixture.dir, &state, &snapshot["briefRevision"], true)
|
||||
.contains(&json!({"outputId":"detail","variantId":variant})));
|
||||
for active in [false, true] {
|
||||
write_json(&fixture.dir.join("production-run.json"), &json!({
|
||||
"active":active,"status":"paused_on_exit","workspaceId":state["id"],"project":fixture.dir.file_name().unwrap().to_str(),
|
||||
"published":[{"outputId":"detail","variantId":variant,"generationId":snapshot["generationId"],
|
||||
"issues":[{"field":"S01-I01","reason":"需复核产品图"}]}]
|
||||
})).unwrap();
|
||||
assert!(resumable_stages(&fixture.dir, &state, &snapshot["briefRevision"], true)
|
||||
.contains(&json!({"outputId":"detail","variantId":variant})));
|
||||
}
|
||||
assert!(!pending(), "the published files remain a valid delivery snapshot");
|
||||
|
||||
let candidate_path = candidate_path(&fixture.dir, candidate["id"].as_str().unwrap()).unwrap();
|
||||
|
||||
@ -58,11 +58,19 @@ fn image_request_file(dir: &Path, id: &str) -> R<PathBuf> {
|
||||
}
|
||||
|
||||
pub(super) fn read_image_request(dir: &Path, id: &str) -> R<Value> {
|
||||
let request = read_json_with_missing(&image_request_file(dir, id)?,
|
||||
let file = image_request_file(dir, id)?;
|
||||
let mut request = read_json_with_missing(&file,
|
||||
"本项目没有该生图请求。请使用当前图位 prepare_image_request 返回的 requestId。")?;
|
||||
if request["id"] != id || !request["requestSpecHash"].is_string() {
|
||||
return Err("未找到此版本的生图请求".into());
|
||||
}
|
||||
for reference in request.get_mut("references").and_then(Value::as_array_mut).into_iter().flatten() {
|
||||
if let Some(path) = reference["path"].as_str()
|
||||
&& let std::borrow::Cow::Owned(relocated) = relocated_job_file(Path::new(path), file.parent())
|
||||
&& relocated.is_file() {
|
||||
reference["path"] = json!(relocated);
|
||||
}
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
@ -103,8 +111,19 @@ pub(super) fn image_request_receipt(task: &Value) -> Value {
|
||||
}
|
||||
|
||||
pub(super) fn verified_reference_at(reference: &Value) -> R<Vec<u8>> {
|
||||
verified_reference_in(reference, None)
|
||||
}
|
||||
|
||||
fn relocated_job_file<'a>(file: &'a Path, task_dir: Option<&Path>) -> std::borrow::Cow<'a, Path> {
|
||||
if !file.exists() && let (Some(dir), Some(name)) = (task_dir, file.file_name()) {
|
||||
return std::borrow::Cow::Owned(dir.join(name));
|
||||
}
|
||||
std::borrow::Cow::Borrowed(file)
|
||||
}
|
||||
|
||||
fn verified_reference_in(reference: &Value, task_dir: Option<&Path>) -> R<Vec<u8>> {
|
||||
let file = Path::new(reference["path"].as_str().ok_or("参考图记录无效")?);
|
||||
let bytes = fs::read(file).map_err(|_| "本机参考图不可读取")?;
|
||||
let bytes = fs::read(relocated_job_file(file, task_dir)).map_err(|_| "本机参考图不可读取")?;
|
||||
if bytes.len() > 10 * 1024 * 1024 {
|
||||
return Err("单张参考图超过10MiB,未提交".into());
|
||||
}
|
||||
@ -114,8 +133,10 @@ pub(super) fn verified_reference_at(reference: &Value) -> R<Vec<u8>> {
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn verified_reference_bytes(task: &Value) -> R<Vec<Vec<u8>>> {
|
||||
task["references"].as_array().ok_or("参考图记录无效")?.iter().map(verified_reference_at).collect()
|
||||
fn verified_reference_bytes(dir: &Path, task: &Value) -> R<Vec<Vec<u8>>> {
|
||||
let archive = image_request_file(dir, task["id"].as_str().ok_or("图片请求编号无效")?)?;
|
||||
task["references"].as_array().ok_or("参考图记录无效")?.iter()
|
||||
.map(|reference| verified_reference_in(reference, archive.parent())).collect()
|
||||
}
|
||||
|
||||
fn image_payload(task: &Value, files: &[Vec<u8>]) -> R<Value> {
|
||||
@ -176,7 +197,7 @@ pub(super) fn freeze_image_request_locked(dir: &Path, task: &mut Value, input: &
|
||||
if task["phase"] == "prepared" {
|
||||
validate_frozen_spec(dir, task)?;
|
||||
if task["frozenAt"].is_null() {
|
||||
verified_reference_bytes(task)?;
|
||||
verified_reference_bytes(dir, task)?;
|
||||
task["frozenAt"] = json!(now());
|
||||
job_save_locked(dir, task, false)?;
|
||||
}
|
||||
@ -631,6 +652,7 @@ fn recover_deferred_result(
|
||||
match status["status"].as_str() {
|
||||
Some("queued" | "in_progress" | "finalizing") => return Err("原任务仍在生成或归档,保留待核查".into()),
|
||||
Some("pending_review") => return Err("网关仍在核对原任务派发,保留待核查".into()),
|
||||
Some("failed" | "cancelled" | "expired") => return Err("原任务状态已结束,保留原请求供核查".into()),
|
||||
Some("succeeded" | "partially_succeeded") if status["result_available"] == true => {}
|
||||
_ => return Err("原任务暂无可确认的图片结果,保留待核查".into()),
|
||||
}
|
||||
@ -1125,7 +1147,7 @@ impl Backend {
|
||||
}
|
||||
t["requestSpecRevision"] = json!(1);
|
||||
t["requestSpecHash"] = json!(hash(&image_spec(&t).to_string()));
|
||||
image_payload(&t, &verified_reference_bytes(&t)?)?;
|
||||
image_payload(&t, &verified_reference_bytes(&dir, &t)?)?;
|
||||
job_save(&dir, &t)?;
|
||||
return read_image_request(&dir, t["id"].as_str().unwrap_or_default()).map(|task| image_request_receipt(&task));
|
||||
}
|
||||
@ -1256,7 +1278,7 @@ impl Backend {
|
||||
}
|
||||
} else {
|
||||
let p = t["protocol"].clone();
|
||||
let files = verified_reference_bytes(&t)?;
|
||||
let files = verified_reference_bytes(&dir, &t)?;
|
||||
let payload = image_payload(&t, &files)?;
|
||||
let mut req = self
|
||||
.http
|
||||
@ -1458,6 +1480,13 @@ impl Backend {
|
||||
// Report the durable original journal, never the discarded stale copy.
|
||||
t = read_json(&taskdir.join("task.json"))?;
|
||||
remove_settled_response(&taskdir, &t);
|
||||
if archive_check.is_some() && t["phase"] == "unknown"
|
||||
&& let Some(message) = t["message"].as_str()
|
||||
&& (message.contains("鉴权") || message.contains("HTTP 401") || message.contains("HTTP 403")
|
||||
|| message.contains("授权已失效") || message.contains("原任务状态已结束")
|
||||
|| message.contains("原结果与任务模型不一致")) {
|
||||
return Err(message.into());
|
||||
}
|
||||
Ok(public(&t, id, &self.auth["account"], &self.origin))
|
||||
}
|
||||
pub(super) fn image_applied(&self, input: &Value) -> R<Value> {
|
||||
@ -1476,12 +1505,16 @@ impl Backend {
|
||||
let doc = input["doc"].as_u64().ok_or("项目身份无效")?;
|
||||
self.ensure_owner(doc)?;
|
||||
self.validate()?;
|
||||
let t = read_json(&self.project_dir(doc)?.join("image-task.json"))?;
|
||||
let dir = self.project_dir(doc)?;
|
||||
let mut t = read_json(&dir.join("image-task.json"))?;
|
||||
require_ready_image(&t, input)?;
|
||||
let bytes = fs::read(t["artifact"].as_str().ok_or("图片文件缺失")?).map_err(|_| "生成图片不可读取")?;
|
||||
let archive = image_request_file(&dir, t["id"].as_str().ok_or("图片请求编号无效")?)?;
|
||||
let file = relocated_job_file(Path::new(t["artifact"].as_str().ok_or("图片文件缺失")?), archive.parent());
|
||||
let bytes = fs::read(&file).map_err(|_| "生成图片不可读取")?;
|
||||
if bytes.len() as u64 > IMAGE_BYTES || t["sha256"] != format!("{:x}", Sha256::digest(&bytes)) {
|
||||
return Err("生成图片已变化,未应用".into());
|
||||
}
|
||||
t["artifact"] = json!(file);
|
||||
let mut v = public(&t, doc, &self.auth["account"], &self.origin);
|
||||
v["revision"] = input["revision"].clone();
|
||||
Ok(v)
|
||||
@ -1491,6 +1524,25 @@ impl Backend {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn moved_job_reference_uses_archive_filename_and_requires_the_original_digest() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let file = image_request_file(dir.path(), &id).unwrap().with_file_name("reference-0.png");
|
||||
fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
fs::write(&file, b"original").unwrap();
|
||||
let task = json!({"id":id,"references":[{"path":dir.path().join("old/reference-0.png"),
|
||||
"sha256":format!("{:x}", Sha256::digest(b"original"))}],"requestSpecHash":"frozen"});
|
||||
let journal = image_request_file(dir.path(), &id).unwrap();
|
||||
write_json(&journal, &task).unwrap();
|
||||
let reopened = read_image_request(dir.path(), &id).unwrap();
|
||||
assert_eq!(verified_reference_at(&reopened["references"][0]).unwrap(), b"original");
|
||||
assert_eq!(read_json(&journal).unwrap(), task);
|
||||
assert_eq!(verified_reference_bytes(dir.path(), &task).unwrap(), vec![b"original".to_vec()]);
|
||||
fs::write(file, b"replacement").unwrap();
|
||||
assert_eq!(verified_reference_bytes(dir.path(), &task).unwrap_err(), "参考图已变化,未提交");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_outages_preserve_access_but_revocations_and_account_changes_block() {
|
||||
use std::net::TcpListener;
|
||||
@ -1593,13 +1645,13 @@ mod tests {
|
||||
}
|
||||
let saved = read_image_request(&fixture.dir, &id).unwrap();
|
||||
assert_eq!(image_request_receipt(&saved)["frozen"], true);
|
||||
let payload = image_payload(&saved, &verified_reference_bytes(&saved).unwrap()).unwrap();
|
||||
let payload = image_payload(&saved, &verified_reference_bytes(&fixture.dir, &saved).unwrap()).unwrap();
|
||||
assert_eq!(payload["prompt"], prompt);
|
||||
assert_eq!(payload["quality"], "medium");
|
||||
assert_eq!(payload["images"][0], format!("data:image/png;base64,{}", STANDARD.encode(pixels)));
|
||||
assert_eq!(payload["images"][1], format!("data:image/png;base64,{}", STANDARD.encode(b"scene bytes")));
|
||||
fs::write(&asset,b"modified").unwrap();
|
||||
assert!(verified_reference_bytes(&saved).is_err());
|
||||
assert!(verified_reference_bytes(&fixture.dir, &saved).is_err());
|
||||
let mut corrupt = saved;
|
||||
corrupt["prompt"] = json!("differs");
|
||||
assert!(validate_frozen_spec(&fixture.dir,&corrupt).is_err());
|
||||
@ -1685,11 +1737,11 @@ mod tests {
|
||||
let png = dir.path().join("reference-1.png");
|
||||
fs::write(&jpeg, [0xff, 0xd8, 0xff, 0x01]).unwrap();
|
||||
fs::write(&png, b"\x89PNG").unwrap();
|
||||
let task = json!({"modelId":"fixture-image","prompt":"保留原样",
|
||||
let task = json!({"id":Uuid::new_v4(),"modelId":"fixture-image","prompt":"保留原样",
|
||||
"protocol":{"field":"image[]","multipart":true,"parameters":{"output_format":"jpeg","output_compression":95}},
|
||||
"references":[{"path":jpeg,"sha256":format!("{:x}",Sha256::digest([0xff, 0xd8, 0xff, 0x01]))},
|
||||
{"path":png,"sha256":format!("{:x}",Sha256::digest(b"\x89PNG"))}]});
|
||||
let files = verified_reference_bytes(&task).unwrap();
|
||||
let files = verified_reference_bytes(dir.path(), &task).unwrap();
|
||||
let payload = image_payload(&task, &files).unwrap();
|
||||
assert_eq!(payload["image[]"], json!([format!("data:image/jpeg;base64,{}", STANDARD.encode([0xff, 0xd8, 0xff, 0x01])),
|
||||
format!("data:image/png;base64,{}", STANDARD.encode(b"\x89PNG"))]));
|
||||
|
||||
@ -251,7 +251,7 @@ pub(super) fn refresh_stale_exports(project: &Path, doc: u64, scope: &str) -> R<
|
||||
pub(super) fn detail_artifacts(project: &Path) -> R<Vec<Artifact>> {
|
||||
let checkpoint = project.join("production-run.json");
|
||||
let run = if checkpoint.try_exists().map_err(|error| error.to_string())? { read_json(&checkpoint)? } else { Value::Null };
|
||||
if run["active"] == true {
|
||||
if run["active"] == true && run["phase"] != "paused" && run["status"] != "paused_on_exit" {
|
||||
return Err("制作任务仍在运行,请完成或停止后再提交".into());
|
||||
}
|
||||
let state = canvas_workspace::load(project)?;
|
||||
|
||||
@ -110,17 +110,20 @@ fn checkpoint_file(project: &Path, source: &Path, output: &Path, logical: &str,
|
||||
CheckpointCopy::Reopen(old, new) => Some((old, new)),
|
||||
_ => None,
|
||||
};
|
||||
if matches!(logical, CONTEXT | "production-run.json") || reopen.is_some() && logical.ends_with(".json") {
|
||||
let production_settings = logical.starts_with("agent/") && logical.ends_with("/production-settings.json");
|
||||
if production_settings || matches!(logical, CONTEXT | "production-run.json") || reopen.is_some() && logical.ends_with(".json") {
|
||||
let mut value = read_json(source)?;
|
||||
if let Some((old, new)) = reopen { rebase_paths(&mut value, old, new); }
|
||||
if production_settings { transfer::redact(&mut value); }
|
||||
if let Some((old, new)) = reopen { rebase_project_json(&mut value, old, new, carries_template_bindings(logical)); }
|
||||
if logical == CONTEXT {
|
||||
let fields = value.as_object_mut().ok_or("工程上下文格式无效")?;
|
||||
fields.remove("projectFile");
|
||||
if !chat { fields.remove("messages"); }
|
||||
}
|
||||
if logical == "production-run.json" && value["active"] == true {
|
||||
value["active"] = json!(false);
|
||||
if logical == "production-run.json" && (value["active"] == true || value["phase"] == "paused") {
|
||||
value["active"] = json!(true);
|
||||
value["phase"] = json!("paused");
|
||||
value["status"] = json!("paused_on_exit");
|
||||
}
|
||||
transfer::no_credentials(&value)?;
|
||||
write_json(output, &value)?;
|
||||
@ -367,10 +370,22 @@ pub(super) fn save(
|
||||
}
|
||||
|
||||
pub(super) fn rebase_paths(value: &mut Value, old: &Path, new: &Path) {
|
||||
rebase_project_json(value, old, new, false);
|
||||
}
|
||||
|
||||
pub(super) fn carries_template_bindings(path: &str) -> bool {
|
||||
matches!(path, "canvas-workspace.json" | "template-slots.json" | "template-workflow.json")
|
||||
}
|
||||
|
||||
pub(super) fn rebase_project_json(value: &mut Value, old: &Path, new: &Path, bound: bool) {
|
||||
use super::template_slots::{self, LEGACY_ENTERPRISE_PATHS};
|
||||
let valid_pack = value.get("contentHash").is_some() && template_slots::validate_pack(value).is_ok();
|
||||
let enterprise = (bound && valid_pack).then(|| value["enterprise"].clone());
|
||||
match value {
|
||||
Value::String(text) => {
|
||||
if let Ok(relative) = Path::new(text).strip_prefix(old) {
|
||||
*text = new.join(relative).to_string_lossy().into_owned();
|
||||
*text = if relative.as_os_str().is_empty() { new.to_string_lossy().into_owned() }
|
||||
else { new.join(relative).to_string_lossy().into_owned() };
|
||||
return;
|
||||
}
|
||||
let normalized = text.replace('\\', "/");
|
||||
@ -381,10 +396,24 @@ pub(super) fn rebase_paths(value: &mut Value, old: &Path, new: &Path) {
|
||||
*text = new.join(relative.split('/').collect::<PathBuf>()).to_string_lossy().into_owned();
|
||||
}
|
||||
}
|
||||
Value::Array(items) => items.iter_mut().for_each(|value| rebase_paths(value, old, new)),
|
||||
Value::Object(items) => items.values_mut().for_each(|value| rebase_paths(value, old, new)),
|
||||
Value::Array(items) => items.iter_mut().for_each(|value| rebase_project_json(value, old, new, bound)),
|
||||
Value::Object(items) => {
|
||||
for (key, value) in items {
|
||||
if key != LEGACY_ENTERPRISE_PATHS { rebase_project_json(value, old, new, bound); }
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if valid_pack && let Ok(content_hash) = template_slots::pack_hash(value) {
|
||||
if value["contentHash"] == content_hash { return; }
|
||||
if let Some(enterprise) = enterprise {
|
||||
// Frozen canvas, slot and request IDs still reference the installed hash.
|
||||
if value["enterprise"] != enterprise { template_slots::preserve_legacy_binding(value, &enterprise); }
|
||||
} else {
|
||||
value["contentHash"] = json!(content_hash);
|
||||
value.as_object_mut().unwrap().remove(LEGACY_ENTERPRISE_PATHS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn normal_relative(path: &Path) -> bool {
|
||||
@ -469,6 +498,62 @@ mod tests {
|
||||
use super::*;
|
||||
use photocraft_doc::{Affine, ColorMode, Layer, LayerContent, SampleType, Size, SmartContentsId, SmartObject, SmartSource, Surface};
|
||||
|
||||
#[test]
|
||||
fn saved_production_is_paused_and_resumable_and_settings_are_redacted() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let source = tmp.path().join("source.json");
|
||||
let output = tmp.path().join("output.json");
|
||||
for active in [true, false] {
|
||||
write_json(&source, &json!({"active":active,"phase":"paused","workspaceId":"original"})).unwrap();
|
||||
checkpoint_file(tmp.path(), &source, &output, "production-run.json", None, CheckpointCopy::Save, false).unwrap();
|
||||
let paused = read_json(&output).unwrap();
|
||||
assert_eq!(paused["active"], true);
|
||||
assert_eq!(paused["phase"], "paused");
|
||||
assert_eq!(paused["status"], "paused_on_exit");
|
||||
assert_eq!(paused["workspaceId"], "original");
|
||||
}
|
||||
write_json(&source, &json!({"timeBudgetMinutes":45,"apiKey":"fixture-secret"})).unwrap();
|
||||
checkpoint_file(tmp.path(), &source, &output, "agent/test/project/conversation-v1/production-settings.json",
|
||||
None, CheckpointCopy::Save, false).unwrap();
|
||||
assert_eq!(read_json(&output).unwrap(), json!({"timeBudgetMinutes":45}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebasing_a_valid_legacy_pack_upgrades_its_hash_without_blessing_corruption() {
|
||||
let mut pack: Value = serde_json::from_str(include_str!("../../../../../lib/desktop-client/template-packs/yjd-desk-dnz0385-native-v1.json")).unwrap();
|
||||
pack["enterprise"] = json!({"sourceKind":"xiaoyi-release","snapshotVersion":pack["version"],
|
||||
"manifestRevision":"c".repeat(64),"originalSha256":"d".repeat(64),
|
||||
"mappingPath":"old/mapping.json","inventoryPath":"old/inventory.json"});
|
||||
pack.as_object_mut().unwrap().remove("contentHash");
|
||||
pack["contentHash"] = json!(super::super::hash(&pack.to_string()));
|
||||
super::super::template_slots::validate_pack(&pack).unwrap();
|
||||
let mut corrupted = pack.clone();
|
||||
corrupted["name"] = json!("已被修改");
|
||||
let mut both = json!([pack,corrupted]);
|
||||
rebase_paths(&mut both, Path::new("old"), Path::new("new"));
|
||||
assert_eq!(Path::new(both[0]["enterprise"]["mappingPath"].as_str().unwrap()), Path::new("new").join("mapping.json"));
|
||||
assert_eq!(both[0]["contentHash"], super::super::template_slots::pack_hash(&both[0]).unwrap());
|
||||
assert!(super::super::template_slots::validate_pack(&both[1]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebased_project_preserves_the_hash_used_by_existing_canvas_and_request_bindings() {
|
||||
let mut pack: Value = serde_json::from_str(include_str!("../../../../../lib/desktop-client/template-packs/yjd-desk-dnz0385-native-v1.json")).unwrap();
|
||||
pack["enterprise"] = json!({"sourceKind":"xiaoyi-release","snapshotVersion":pack["version"],
|
||||
"manifestRevision":"c".repeat(64),"originalSha256":"d".repeat(64),"mappingPath":"old/mapping.json"});
|
||||
pack.as_object_mut().unwrap().remove("contentHash");
|
||||
let legacy = super::super::hash(&pack.to_string());
|
||||
pack["contentHash"] = json!(legacy);
|
||||
let mut workspace = json!({"template":pack,"productTemplates":{"detail":pack}});
|
||||
rebase_project_json(&mut workspace, Path::new("old"), Path::new("new"), true);
|
||||
rebase_project_json(&mut workspace, Path::new("new"), Path::new("moved"), true);
|
||||
for pack in [&workspace["template"], &workspace["productTemplates"]["detail"]] {
|
||||
assert_eq!(pack["contentHash"], legacy);
|
||||
assert_eq!(Path::new(pack["enterprise"]["mappingPath"].as_str().unwrap()), Path::new("moved").join("mapping.json"));
|
||||
super::super::template_slots::validate_pack(pack).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_keeps_referenced_candidates_and_discards_the_unreferenced_pool() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
|
||||
@ -218,9 +218,7 @@ impl Backend {
|
||||
continue;
|
||||
};
|
||||
let dir = entry.path();
|
||||
let Ok(c) = creation::load(&dir) else {
|
||||
continue;
|
||||
};
|
||||
let c = creation::load(&dir).unwrap_or_default();
|
||||
let stage = &c["generation"]["recovery"];
|
||||
let eligible_stage = stage.is_object()
|
||||
&& stage["applied"] != true
|
||||
@ -238,7 +236,8 @@ impl Backend {
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if (eligible_stage || eligible_pending) && dir.join("canvas.pcraft").exists() && dir.join("context.json").exists() {
|
||||
if (eligible_stage || eligible_pending || self.production_recovery_status(&dir, &local).is_some())
|
||||
&& dir.join("canvas.pcraft").exists() && dir.join("context.json").exists() {
|
||||
candidates.push(local);
|
||||
}
|
||||
if candidates.len() > 1 {
|
||||
@ -247,6 +246,20 @@ impl Backend {
|
||||
}
|
||||
candidates.first().map_or(Value::Null, |id| json!({"id":id,"source":"native"}))
|
||||
}
|
||||
|
||||
fn production_recovery_status(&self, dir: &Path, local: &str) -> Option<Value> {
|
||||
let checkpoint = read_json(&dir.join("production-run.json")).unwrap_or_default();
|
||||
let paused = checkpoint["phase"] == "paused" || checkpoint["status"] == "paused_on_exit";
|
||||
let resumable = checkpoint["project"] == local && (checkpoint["active"] == true || checkpoint["phase"] == "paused");
|
||||
let pending = super::canvas_workspace::pending_summary(dir).unwrap_or_default();
|
||||
(resumable || !pending.is_empty()).then(|| json!({
|
||||
"accountId":self.auth["account"]["id"],"origin":self.origin,"projectLocalId":local,
|
||||
"productionInterrupted":resumable,"pendingCanvasRequests":pending,
|
||||
"message":if paused && resumable { "上次制作已暂停,打开工程后可继续" }
|
||||
else { "上次制作中断,打开工程后可核查原请求并继续" },
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn scan_recovery(&mut self, tx: &mpsc::Sender<Event>, ctx: &egui::Context) {
|
||||
if self.auth["account"]["id"].as_str().is_none() {
|
||||
return;
|
||||
@ -263,15 +276,16 @@ impl Backend {
|
||||
let Some(local) = entry.file_name().to_str().map(str::to_owned).filter(|id| Uuid::parse_str(id).is_ok()) else {
|
||||
continue;
|
||||
};
|
||||
if !entry.path().join("creation.json").exists() {
|
||||
continue;
|
||||
}
|
||||
match self.auto_recover_project_window(&local, false, budget, tx, ctx) {
|
||||
Ok(value) if !value.is_null() => {
|
||||
let status = match self.auto_recover_project_window(&local, false, budget, tx, ctx) {
|
||||
Ok(value) if !value.is_null() => Some(value),
|
||||
_ => self.production_recovery_status(&entry.path(), &local),
|
||||
};
|
||||
match status {
|
||||
Some(value) => {
|
||||
let _ = tx.send(Event::Json("recovery-status".into(), Ok(value)));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
Err(_) | Ok(_) => {}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -506,6 +520,26 @@ mod tests {
|
||||
use super::*;
|
||||
use super::super::{open_binding_local, HashMap, PathBuf};
|
||||
#[test]
|
||||
fn interrupted_production_is_discoverable_without_a_creation_journal() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut backend = Backend::new(tmp.path().into()).unwrap();
|
||||
backend.auth = json!({"account":{"id":"test-account"}});
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let dir = backend.dir().join("projects").join(&id);
|
||||
write_json(&dir.join("context.json"), &json!({})).unwrap();
|
||||
fs::write(dir.join("canvas.pcraft"), b"fixture").unwrap();
|
||||
for (active, phase) in [(false, "paused"), (true, "running")] {
|
||||
write_json(&dir.join("production-run.json"), &json!({"project":id,"phase":phase,"active":active})).unwrap();
|
||||
assert_eq!(backend.resume_project()["id"], id);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
backend.scan_recovery(&tx, &egui::Context::default());
|
||||
let Event::Json(method, Ok(status)) = rx.try_recv().unwrap() else { panic!("recovery status"); };
|
||||
assert_eq!(method, "recovery-status");
|
||||
assert_eq!(status["productionInterrupted"], true);
|
||||
assert_eq!(status["projectLocalId"], id);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn an_already_applied_creation_repairs_its_original_image_journal_on_restart() {
|
||||
let dir = std::env::temp_dir().join(format!("recovery-applied-repair-{}", Uuid::new_v4()));
|
||||
write_json(&dir.join("context.json"), &json!({})).unwrap();
|
||||
|
||||
@ -113,6 +113,7 @@ fn allowed_file(path: &str) -> bool {
|
||||
"template-slots.json",
|
||||
"template-input.json",
|
||||
"canvas-workspace.json",
|
||||
"production-run.json",
|
||||
];
|
||||
(exact.contains(&path) || path.split_once('/').is_some_and(|(root, _)| BACKUP_ATTACHMENT_DIRS.contains(&root)))
|
||||
&& matches!(Path::new(path).extension().and_then(|e| e.to_str()), Some("json" | "jsonl" | "wasm" | "png" | "jpg" | "jpeg" | "webp" | "pcraft"))
|
||||
@ -214,7 +215,12 @@ fn collect_backup_sources(base: &Path, path: &Path, prefix: &str, files: &mut Ve
|
||||
if !relative.ends_with(".pcraft") {
|
||||
let inline_size = files.iter().filter(|file| file.entry["source"].is_null()).filter_map(|file| file.entry["size"].as_u64()).sum::<u64>();
|
||||
if inline_size.saturating_add(meta.len()) > BACKUP_LIMIT { return Err("会话附件超过256MiB,尚未同步".into()); }
|
||||
let bytes = fs::read(path).map_err(|_| "会话文件无法读取")?;
|
||||
let mut bytes = fs::read(path).map_err(|_| "会话文件无法读取")?;
|
||||
if relative.starts_with("agent/") && relative.ends_with("/production-settings.json") {
|
||||
let mut settings: Value = serde_json::from_slice(&bytes).map_err(|_| "制作设置格式无效")?;
|
||||
transfer::redact(&mut settings);
|
||||
bytes = serde_json::to_vec(&settings).map_err(|_| "制作设置格式无效")?;
|
||||
}
|
||||
transfer::check_file(&logical, &bytes)?;
|
||||
*total = total.saturating_add(bytes.len() as u64);
|
||||
files.push(BackupSource { path: path.to_owned(), entry: json!({"path":logical,"sha256":digest(&bytes),"size":bytes.len(),"data":STANDARD.encode(bytes)}) });
|
||||
@ -287,34 +293,22 @@ fn request_error(code: u16) -> String {
|
||||
_ => format!("云同步未完成(HTTP {code}),本机草稿已保留"),
|
||||
}
|
||||
}
|
||||
fn remap_paths(value: &mut Value, old: &str, new: &str) {
|
||||
match value {
|
||||
Value::String(text) if !old.is_empty() && (text == old || text.strip_prefix(old).is_some_and(|s| s.starts_with(['/', '\\']))) => {
|
||||
*text = format!("{new}{}", text.get(old.len()..).unwrap_or(""))
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for item in items {
|
||||
remap_paths(item, old, new);
|
||||
}
|
||||
}
|
||||
Value::Object(items) => {
|
||||
for item in items.values_mut() {
|
||||
remap_paths(item, old, new);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
fn remap_paths(value: &mut Value, old: &str, new: &str, path: &str) {
|
||||
if !old.is_empty() {
|
||||
super::project_file::rebase_project_json(value, Path::new(old), Path::new(new),
|
||||
super::project_file::carries_template_bindings(path));
|
||||
}
|
||||
}
|
||||
fn restored_bytes(path: &str, bytes: &[u8], old: &str, new: &str) -> R<Vec<u8>> {
|
||||
if path.ends_with(".json") {
|
||||
let mut value: Value = serde_json::from_slice(bytes).map_err(|_| "会话JSON无效")?;
|
||||
remap_paths(&mut value, old, new);
|
||||
remap_paths(&mut value, old, new, path);
|
||||
serde_json::to_vec(&value).map_err(|_| "会话JSON恢复失败".into())
|
||||
} else if path.ends_with(".jsonl") {
|
||||
let mut out = Vec::new();
|
||||
for line in std::str::from_utf8(bytes).map_err(|_| "会话编码无效")?.lines().filter(|s| !s.trim().is_empty()) {
|
||||
let mut value: Value = serde_json::from_str(line).map_err(|_| "会话记录无效")?;
|
||||
remap_paths(&mut value, old, new);
|
||||
remap_paths(&mut value, old, new, path);
|
||||
serde_json::to_writer(&mut out, &value).map_err(|_| "会话恢复失败")?;
|
||||
out.push(b'\n');
|
||||
}
|
||||
@ -1118,7 +1112,7 @@ impl Backend {
|
||||
}
|
||||
let old_root = backup["oldProjectRoot"].as_str().unwrap_or("");
|
||||
let new_root = destination.to_string_lossy();
|
||||
remap_paths(&mut context, old_root, &new_root);
|
||||
remap_paths(&mut context, old_root, &new_root, "context.json");
|
||||
let staging = account.join(format!("restore-{}", Uuid::new_v4()));
|
||||
fs::create_dir_all(&staging).map_err(|_| "无法准备恢复目录")?;
|
||||
let superseded = if existing.is_some() {
|
||||
|
||||
@ -220,13 +220,25 @@ impl Backend {
|
||||
let original = assets.iter().find(|item| item["type"] == "original"
|
||||
&& item["component"] == component && item["sha256"] == source["sha256"])
|
||||
.ok_or("小壹锁定包缺少与模板绑定一致的原稿")?;
|
||||
originals.push(json!({"assetId":source["assetId"],"originalPath":original["localPath"],"canvas":source["canvas"]}));
|
||||
originals.push((source, original));
|
||||
}
|
||||
let fonts: Vec<_> = assets.iter().filter(|item| item["type"] == "font"
|
||||
&& (item["component"] == component || item["component"] == "shared"))
|
||||
.map(|item| &item["localPath"]).collect();
|
||||
&& (item["component"] == component || item["component"] == "shared")).collect();
|
||||
let required: Vec<_> = originals.iter().map(|(_, item)| *item).chain(fonts.iter().copied()).collect();
|
||||
let paths = xiaoyi_asset_paths(&required, || {
|
||||
let session = self.xiaoyi_release_session(&required)?;
|
||||
let version = knowledge["knowledgeVersion"].as_str().ok_or("小壹知识包缺少锁定版本")?;
|
||||
let result = self.enterprise_template_request(json!({"action":"xiaoyi-pack","templateId":knowledge["templateId"],
|
||||
"name":pack["name"],"brandId":pack["brandId"],"categoryId":pack["categoryId"],
|
||||
"projectDir":session,"cache":self.dir().join("xiaoyi-blobs"),"knowledgeVersion":version}))?;
|
||||
let restored = &result["packs"][component]["xiaoyi"];
|
||||
if restored["knowledgeVersion"] != version { return Err("原稿恢复返回了其他知识包版本".into()); }
|
||||
Ok(restored["assets"].clone())
|
||||
})?;
|
||||
let sources: Vec<_> = originals.iter().zip(&paths).map(|((source, _), path)|
|
||||
json!({"assetId":source["assetId"],"originalPath":path,"canvas":source["canvas"]})).collect();
|
||||
progress(json!({"phase":"import"}));
|
||||
return super::slot_canvas::enterprise(pack, &json!({"originals":originals,"fonts":fonts}), component, document, variant);
|
||||
return super::slot_canvas::enterprise(pack, &json!({"originals":sources,"fonts":&paths[sources.len()..]}), component, document, variant);
|
||||
}
|
||||
let mut request = pack["enterprise"].clone();
|
||||
request["action"] = json!("prepare");
|
||||
@ -244,6 +256,19 @@ impl Backend {
|
||||
progress(json!({"phase":"import"}));
|
||||
super::slot_canvas::enterprise(pack, &prepared, component, document, variant)
|
||||
}
|
||||
|
||||
fn xiaoyi_release_session(&self, assets: &[&Value]) -> R<PathBuf> {
|
||||
let scope = self.scope();
|
||||
let id = assets.iter().filter_map(|item| item["localPath"].as_str()).find_map(|path| {
|
||||
let parts: Vec<_> = path.split(['/', '\\']).collect();
|
||||
parts.windows(5).find(|parts| parts[0] == "agent" && parts[1] == scope
|
||||
&& Uuid::parse_str(parts[2]).is_ok() && parts[3] == "conversation-v1"
|
||||
&& parts[4] == "xiaoyi-release").map(|parts| parts[2])
|
||||
}).ok_or("小壹锁定包未绑定到当前账户的工程")?;
|
||||
// During reopen, the saved project is available before its canvas tab receives a document ID.
|
||||
let project = super::projects::local_path(&self.dir().join("projects"), id)?;
|
||||
Ok(project.join("agent").join(scope).join(id).join("conversation-v1"))
|
||||
}
|
||||
/// Caller checks current desktop authority before use (slot-install already
|
||||
/// calls validate). The endpoint independently rechecks every network GET.
|
||||
pub(super) fn template_pack(&self, brand: &str, category: &str, check_updates: bool) -> R<Value> {
|
||||
@ -266,10 +291,61 @@ impl Backend {
|
||||
}
|
||||
}
|
||||
|
||||
fn xiaoyi_asset_paths(required: &[&Value], hydrate: impl FnOnce() -> R<Value>) -> R<Vec<PathBuf>> {
|
||||
fn verified(item: &Value) -> Option<PathBuf> {
|
||||
let path = PathBuf::from(item["localPath"].as_str()?);
|
||||
let expected = item["sha256"].as_str()?;
|
||||
super::canvas_workspace::file_digest(&path).ok().filter(|actual| actual == expected)?;
|
||||
Some(path)
|
||||
}
|
||||
let paths: Vec<_> = required.iter().map(|item| verified(item)).collect();
|
||||
if paths.iter().all(Option::is_some) {
|
||||
return Ok(paths.into_iter().flatten().collect());
|
||||
}
|
||||
let restored = hydrate()?;
|
||||
let assets = restored.as_array().ok_or("小壹锁定包恢复缺少资产清单")?;
|
||||
required.iter().zip(paths).map(|(item, path)| {
|
||||
path.or_else(|| assets.iter().find(|candidate| item["path"].is_string()
|
||||
&& candidate["path"] == item["path"] && candidate["sha256"] == item["sha256"]
|
||||
&& candidate["component"] == item["component"] && candidate["type"] == item["type"])
|
||||
.and_then(verified)).ok_or_else(|| format!("小壹锁定资产缺失或校验失败:{}", item["path"]))
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::super::{fs};
|
||||
|
||||
#[test]
|
||||
fn moved_or_damaged_assets_restore_using_the_pinned_relative_paths_and_digests() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old = dir.path().join("damaged.psd");
|
||||
let current = dir.path().join("restored.psd");
|
||||
fs::write(&old, b"damaged").unwrap();
|
||||
fs::write(¤t, b"pinned original").unwrap();
|
||||
let sha = super::super::canvas_workspace::file_digest(¤t).unwrap();
|
||||
let pinned = json!({"path":"originals/template.psd","localPath":old,"sha256":sha,"type":"original","component":"detail"});
|
||||
let mut restored = pinned.clone();
|
||||
restored["localPath"] = json!(current);
|
||||
assert_eq!(xiaoyi_asset_paths(&[&pinned], || Ok(json!([restored]))).unwrap(), vec![current.clone()]);
|
||||
assert_eq!(xiaoyi_asset_paths(&[&restored], || panic!("valid cached assets need no request")).unwrap(), vec![current]);
|
||||
restored["path"] = json!("originals/different.psd");
|
||||
assert!(xiaoyi_asset_paths(&[&pinned], || Ok(json!([restored]))).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_rehydration_finds_the_local_project_before_a_canvas_tab_is_bound() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let backend = Backend::new(root.path().into()).unwrap();
|
||||
let scope = backend.scope();
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let project = backend.dir().join("projects").join(&id);
|
||||
fs::create_dir_all(&project).unwrap();
|
||||
let old = json!({"localPath":format!("old/profile/agent/{scope}/{id}/conversation-v1/xiaoyi-release/template.psd")});
|
||||
let expected = project.canonicalize().unwrap().join("agent").join(scope).join(id).join("conversation-v1");
|
||||
assert_eq!(backend.xiaoyi_release_session(&[&old]).unwrap(), expected);
|
||||
}
|
||||
struct Temp(PathBuf);
|
||||
impl Drop for Temp {
|
||||
fn drop(&mut self) {
|
||||
|
||||
@ -4,16 +4,48 @@
|
||||
use super::{json, Value, R, hash, Read, Digest, Path, PathBuf, original_project_present, read_json, write_json, sync, Uuid, now, fs, Sha256};
|
||||
|
||||
const FILE: &str = "template-slots.json";
|
||||
pub(super) const LEGACY_ENTERPRISE_PATHS: &str = "legacyEnterprisePaths";
|
||||
|
||||
pub(super) fn pack_hash(pack: &Value) -> R<String> {
|
||||
hash_pack(pack, true)
|
||||
}
|
||||
|
||||
fn pack_hash_legacy(pack: &Value) -> R<String> {
|
||||
hash_pack(pack, false)
|
||||
}
|
||||
|
||||
fn hash_pack(pack: &Value, portable: bool) -> R<String> {
|
||||
let mut pack = pack.clone();
|
||||
let content = pack.as_object_mut().ok_or("模板包格式无效")?;
|
||||
content.remove("contentHash");
|
||||
// 小壹知识包有独立版本,画布仍按原稿与字段映射的模板身份绑定。
|
||||
content.remove("xiaoyi");
|
||||
let legacy_paths = content.remove(LEGACY_ENTERPRISE_PATHS);
|
||||
if let Some(enterprise) = content.get_mut("enterprise").and_then(Value::as_object_mut) {
|
||||
for field in ["mappingPath", "inventoryPath"] {
|
||||
if portable { enterprise.remove(field); }
|
||||
else if let Some(paths) = &legacy_paths {
|
||||
match paths.get(field) {
|
||||
Some(path) => { enterprise.insert(field.into(), path.clone()); }
|
||||
None => { enterprise.remove(field); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(hash(&pack.to_string()))
|
||||
}
|
||||
|
||||
pub(super) fn preserve_legacy_binding(pack: &mut Value, enterprise: &Value) {
|
||||
if pack.get(LEGACY_ENTERPRISE_PATHS).is_some() { return; }
|
||||
let mut paths = serde_json::Map::new();
|
||||
for field in ["mappingPath", "inventoryPath"] {
|
||||
if let Some(path) = enterprise.get(field) {
|
||||
paths.insert(field.into(), path.clone());
|
||||
}
|
||||
}
|
||||
pack[LEGACY_ENTERPRISE_PATHS] = Value::Object(paths);
|
||||
}
|
||||
|
||||
fn short(value: &Value, max: usize, label: &str) -> R<String> {
|
||||
value.as_str().filter(|s| !s.trim().is_empty() && s.chars().count() <= max).map(str::to_owned).ok_or_else(|| format!("{label}无效"))
|
||||
}
|
||||
@ -45,7 +77,8 @@ pub(super) fn validate_pack(pack: &Value) -> R<()> {
|
||||
for (field, max) in [("id", 120), ("version", 80), ("name", 160), ("brandId", 150), ("categoryId", 150)] {
|
||||
short(&pack[field], max, field)?;
|
||||
}
|
||||
if !hex(&pack["contentHash"]) || pack["contentHash"] != pack_hash(pack)? {
|
||||
if !hex(&pack["contentHash"])
|
||||
|| pack["contentHash"] != pack_hash(pack)? && pack["contentHash"] != pack_hash_legacy(pack)? {
|
||||
return Err("模板包校验值不一致,未覆盖项目模板".into());
|
||||
}
|
||||
let enterprise = pack["enterprise"].is_object();
|
||||
@ -654,6 +687,25 @@ mod tests {
|
||||
assert_ne!(slot_id(&p, "S01-I01"), slot_id(&next, "S01-I01"));
|
||||
}
|
||||
#[test]
|
||||
fn legacy_template_identity_validates_but_new_hash_ignores_cache_location() {
|
||||
let mut pack = pack();
|
||||
pack["enterprise"] = json!({"sourceKind":"xiaoyi-release","snapshotVersion":pack["version"],
|
||||
"manifestRevision":"c".repeat(64),"originalSha256":"d".repeat(64),
|
||||
"mappingPath":"old/mapping.json","inventoryPath":"old/inventory.json"});
|
||||
pack["contentHash"] = json!(pack_hash_legacy(&pack).unwrap());
|
||||
validate_pack(&pack).unwrap();
|
||||
let canonical = pack_hash(&pack).unwrap();
|
||||
assert_ne!(pack["contentHash"], canonical);
|
||||
pack["enterprise"]["mappingPath"] = json!("new/mapping.json");
|
||||
pack["enterprise"]["inventoryPath"] = json!("new/inventory.json");
|
||||
assert_eq!(pack_hash(&pack).unwrap(), canonical);
|
||||
assert!(validate_pack(&pack).is_err());
|
||||
pack["contentHash"] = json!(canonical);
|
||||
validate_pack(&pack).unwrap();
|
||||
pack["enterprise"]["originalSha256"] = json!("e".repeat(64));
|
||||
assert!(validate_pack(&pack).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn enterprise_templates_require_a_resource_map_snapshot() {
|
||||
let mut p = pack();
|
||||
p["version"] = json!(format!("map-{}", "a".repeat(64)));
|
||||
|
||||
@ -139,8 +139,9 @@ impl Policy<'_> {
|
||||
pub(super) fn agent_file(&self, path: &str) -> Result<(), &'static str> {
|
||||
let parts: Vec<_> = path.split('/').collect();
|
||||
match parts.as_slice() {
|
||||
["agent", scope, project, "production-settings.json"] if *scope == self.scope && *project == self.project => Ok(()),
|
||||
["agent", scope, project, "conversation-v1", name] if *scope == self.scope && *project == self.project => {
|
||||
if *name == "product-production-strategy.json" || production_journal(name) {
|
||||
if matches!(*name, "production-settings.json" | "product-production-strategy.json") || production_journal(name) {
|
||||
Ok(())
|
||||
} else if *name == "session.json" {
|
||||
if self.chat { Ok(()) } else { Err("chat_history_disabled") }
|
||||
|
||||
@ -399,6 +399,8 @@ fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId, answer: Answe
|
||||
Answer::Cancel => {
|
||||
if app.discard.take().is_some_and(|prompt| prompt.id == EXIT) {
|
||||
app.explicit_exit = false;
|
||||
app.allow_close = false;
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::jiansun::cancel_exit(app);
|
||||
}
|
||||
|
||||
@ -1048,6 +1048,7 @@ pub struct Workspace {
|
||||
draft_changed: bool,
|
||||
product_checkpoint: Value,
|
||||
production_exit: Option<product_production::PendingExit>,
|
||||
production_exit_state: Option<product_production::ExitState>,
|
||||
pub exit_admission_closed: Arc<AtomicBool>,
|
||||
pub prepare_daemon_exit: Option<Box<dyn Fn() -> ExitReceipt>>,
|
||||
pub cancel_daemon_exit: Option<fn()>,
|
||||
@ -1599,6 +1600,7 @@ impl Workspace {
|
||||
draft_changed: false,
|
||||
product_checkpoint: Value::Null,
|
||||
production_exit: None,
|
||||
production_exit_state: None,
|
||||
exit_admission_closed: Arc::new(AtomicBool::new(false)),
|
||||
prepare_daemon_exit: None,
|
||||
cancel_daemon_exit: None,
|
||||
@ -1643,7 +1645,7 @@ impl Workspace {
|
||||
project_list_error: String::new(),
|
||||
pi_run: None,
|
||||
production_stop: json!({"mode":null,"state":"idle","reason":null,"error":null}),
|
||||
production_budget_minutes: 120,
|
||||
production_budget_minutes: 45,
|
||||
pi_ui: pi_ui::State::default(),
|
||||
agent_native: agent_native::State::default(),
|
||||
visual_preview: None,
|
||||
@ -2827,10 +2829,12 @@ impl Workspace {
|
||||
self.ready_image = v.get("imageTask").filter(|task| image_ready_for_canvas(task)).cloned();
|
||||
self.project_context = v["project"].clone();
|
||||
self.product_checkpoint = v["productionRun"].clone();
|
||||
self.production_budget_minutes = v["timeBudgetMinutes"].as_u64().filter(|n| *n > 0).unwrap_or(120);
|
||||
self.production_budget_minutes = v["timeBudgetMinutes"].as_u64().filter(|n| *n > 0).unwrap_or(45);
|
||||
self.production_stop = match self.product_checkpoint["phase"].as_str() {
|
||||
Some("ended") => json!({"mode":"end","state":"ended","reason":"用户手动停止目标","error":null}),
|
||||
Some("paused") => json!({"mode":"pause","state":"paused","reason":self.product_checkpoint["reason"],"error":null}),
|
||||
_ if self.product_checkpoint["active"] == true && (!self.model_ready || !self.image_ready) =>
|
||||
json!({"mode":null,"state":"interrupted","reason":"waiting_for_models","error":null}),
|
||||
_ => json!({"mode":null,"state":"idle","reason":null,"error":null}),
|
||||
};
|
||||
for key in ["cloudLink", "syncedRevision", "status", "materialDelivery"] {
|
||||
@ -3083,6 +3087,9 @@ impl Workspace {
|
||||
Ok(value) if value["doc"].as_u64() == app.session.active().map(|state| state.doc.id.0)
|
||||
&& value["accountId"] == self.account["id"] && value["origin"] == self.origin => {
|
||||
self.template_workflow["productionSettings"] = value["productionSettings"].clone();
|
||||
if let Some(minutes) = value["productionSettings"]["timeBudgetMinutes"].as_f64().filter(|n| *n > 0.0) {
|
||||
self.production_budget_minutes = minutes.round() as u64;
|
||||
}
|
||||
}
|
||||
Err(error) => self.error = error,
|
||||
_ => {}
|
||||
@ -4781,6 +4788,9 @@ pub(crate) fn cancel_exit(app: &mut PhotocraftApp) {
|
||||
workspace.pi_run = None;
|
||||
workspace.pi_native = false;
|
||||
workspace.pi_request_scope = Value::Null;
|
||||
workspace.restore_cancelled_exit();
|
||||
workspace.pi_write_blocked = false;
|
||||
workspace.agent_effects_paused = false;
|
||||
}
|
||||
}
|
||||
|
||||
@ -5759,6 +5769,24 @@ mod tests {
|
||||
(w, app, requests, events)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_settings_receipt_updates_the_live_budget_for_the_current_project() {
|
||||
let (mut w, mut app, _, _) = slot_workspace();
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
let ctx = egui::Context::default();
|
||||
assert_eq!(w.production_budget_minutes, 45);
|
||||
w.receive_json_event(&mut app, &ctx, "production-settings".into(), Ok(json!({
|
||||
"doc":doc,"accountId":"another-account","origin":w.origin,
|
||||
"productionSettings":{"refinement":true,"timeBudgetMinutes":120.0}
|
||||
})));
|
||||
assert_eq!(w.production_budget_minutes, 45);
|
||||
w.receive_json_event(&mut app, &ctx, "production-settings".into(), Ok(json!({
|
||||
"doc":doc,"accountId":w.account["id"],"origin":w.origin,
|
||||
"productionSettings":{"refinement":true,"timeBudgetMinutes":120.0}
|
||||
})));
|
||||
assert_eq!(w.production_budget_minutes, 120);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopening_project_focuses_existing_tab_without_saving_or_reloading_dirty_content() {
|
||||
let (mut w, mut app, requests, _) = slot_workspace();
|
||||
|
||||
@ -802,7 +802,8 @@ pub(super) struct Run {
|
||||
finish_receipt: Value,
|
||||
requested_outputs: Vec<Stage>,
|
||||
deferred_images: HashMap<Stage, Vec<String>>,
|
||||
deferred_image_due: HashMap<String, Instant>,
|
||||
deferred_image_due: HashMap<String, (Instant, u64)>,
|
||||
deferred_image_stopped: HashSet<String>,
|
||||
deferred_image_in_flight: Vec<DeferredImageRecovery>,
|
||||
drafts: Vec<Value>,
|
||||
started_at: u64,
|
||||
@ -840,6 +841,11 @@ pub(super) struct PendingExit {
|
||||
save_requested: bool,
|
||||
}
|
||||
|
||||
pub(super) struct ExitState {
|
||||
run: Option<Run>,
|
||||
checkpoint: Value,
|
||||
}
|
||||
|
||||
impl PendingExit {
|
||||
fn poll_receipts(&mut self) -> Option<Result<(), String>> {
|
||||
let checkpoint = self.checkpoint.clone()?;
|
||||
@ -865,7 +871,8 @@ impl Run {
|
||||
Self { doc, project, workspace, total: stages.len(), requested_outputs: stages.iter().cloned().collect(), stages, completed: 0,
|
||||
goal_user_entry, reset_goal: false, bound: None, opening: None, previous_save: Value::Null, session_epoch: None,
|
||||
finish: None, finish_receipt: Value::Null, phase, drafts: Vec::new(),
|
||||
deferred_images: HashMap::new(), deferred_image_due: HashMap::new(), deferred_image_in_flight: Vec::new(),
|
||||
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, restarted: false,
|
||||
delivery_dir: None, delivery_id: None, published: Vec::new(), delivery_receipt: Value::Null,
|
||||
delivery_cancellation: None, delivery_write_epoch: None }
|
||||
@ -970,7 +977,10 @@ impl Run {
|
||||
|
||||
fn clear_deferred(&mut self, stage: &Stage) {
|
||||
if let Some(ids) = self.deferred_images.remove(stage) {
|
||||
for id in ids { self.deferred_image_due.remove(&id); }
|
||||
for id in ids {
|
||||
self.deferred_image_due.remove(&id);
|
||||
self.deferred_image_stopped.remove(&id);
|
||||
}
|
||||
}
|
||||
self.deferred_image_in_flight.retain(|pending| {
|
||||
if &pending.stage != stage { return true; }
|
||||
@ -990,8 +1000,8 @@ impl Run {
|
||||
fn queued_deferred_images(&self) -> impl Iterator<Item = (Option<Instant>, &Stage, &String)> {
|
||||
self.stages.iter()
|
||||
.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))
|
||||
.map(move |(stage, id)| (self.deferred_image_due.get(id).copied(), stage, id))
|
||||
.filter(move |(_, id)| !self.recovering_deferred_image(id) && !self.deferred_image_stopped.contains(*id))
|
||||
.map(move |(stage, id)| (self.deferred_image_due.get(id).map(|(due, _)| *due), stage, id))
|
||||
}
|
||||
|
||||
fn settle_deferred_image(&mut self, stage: &Stage, id: &str) -> bool {
|
||||
@ -1001,6 +1011,7 @@ impl Run {
|
||||
if ids.len() == before { return false; }
|
||||
if ids.is_empty() { self.deferred_images.remove(stage); }
|
||||
self.deferred_image_due.remove(id);
|
||||
self.deferred_image_stopped.remove(id);
|
||||
true
|
||||
}
|
||||
|
||||
@ -1119,9 +1130,30 @@ impl Workspace {
|
||||
checkpoint["reason"] = pause["reason"].clone();
|
||||
checkpoint["requiredAction"] = pause["requiredAction"].clone();
|
||||
}
|
||||
let waiting = Self::production_waiting_originals(&run.phase);
|
||||
if waiting.is_object() {
|
||||
checkpoint["waitingOriginals"] = waiting;
|
||||
}
|
||||
json!({"doc":run.doc,"checkpoint":checkpoint})
|
||||
}
|
||||
|
||||
fn production_waiting_originals(phase: &Phase) -> Value {
|
||||
match phase {
|
||||
Phase::WaitingOriginals { models, images, goal } => json!({"models":models,"images":images,"goal":goal}),
|
||||
Phase::Paused(pause) => pause["waitingOriginals"].clone(),
|
||||
_ => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
fn production_resume_phase(waiting: &Value) -> Phase {
|
||||
if !waiting.is_object() { return Phase::AwaitingSave; }
|
||||
let ids = |field: &str| waiting[field].as_array().into_iter().flatten()
|
||||
.filter_map(Value::as_str).map(str::to_owned).collect();
|
||||
Phase::WaitingOriginals {
|
||||
models: ids("models"), images: ids("images"), goal: waiting["goal"].as_str().map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_production_checkpoint(&self, run: &Run, active: bool) {
|
||||
let _ = self.tx.send(Request::Action("product-run-checkpoint".into(), Self::production_checkpoint_request(run, active)));
|
||||
}
|
||||
@ -1138,8 +1170,11 @@ impl Workspace {
|
||||
.filter(|state| w.loaded_draft == Some(state.doc.id.0))
|
||||
.map(|state| (state.doc.id.0, w.draft_changed || w.creation_dirty
|
||||
|| w.persisted_revisions.get(&state.doc.id.0) != Some(&state.revision))));
|
||||
let dirty_tabs = app.session.documents().iter().any(|state| state.is_dirty()
|
||||
&& self.open_projects.contains_key(&state.doc.id.0));
|
||||
if self.exit_admission_closed.load(Ordering::Acquire)
|
||||
|| !app.explicit_exit && !(draft.is_some_and(|(_, dirty)| dirty) || self.product_production.is_some()
|
||||
|| dirty_tabs
|
||||
|| self.background_status(app).is_some() || app.services.app_tray.is_some() && (app.saving() || app.exporting()))
|
||||
{
|
||||
return false;
|
||||
@ -1151,10 +1186,7 @@ impl Workspace {
|
||||
let composers = self.save_exit_composers(ctx);
|
||||
let delivering = self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle);
|
||||
let ending = self.busy.as_deref() == Some("product-end-checkpoint");
|
||||
let run = if delivering { None } else { self.product_production.take().map(|mut run| {
|
||||
run.paused_at.get_or_insert_with(production_time);
|
||||
run
|
||||
}) };
|
||||
let run = if delivering { None } else { self.product_production.take() };
|
||||
if !delivering {
|
||||
self.with_product_target(app, |w, _| {
|
||||
w.pi_ui_cancel("客户端正在退出");
|
||||
@ -1164,13 +1196,12 @@ impl Workspace {
|
||||
self.pending_slot_apply = None;
|
||||
self.pi_write_blocked = true;
|
||||
self.agent_effects_paused = true;
|
||||
self.product_checkpoint = Value::Null;
|
||||
|
||||
let input = run.map(|run| {
|
||||
let input = run.as_ref().map(|run| {
|
||||
if ending {
|
||||
json!({"doc":run.doc,"checkpoint":{"active":false,"phase":"ended","project":run.project.rsplit('|').next()}})
|
||||
} else {
|
||||
Self::production_checkpoint_request(&run, true)
|
||||
Self::production_checkpoint_request(run, true)
|
||||
}
|
||||
}).or_else(|| {
|
||||
if delivering { return None; }
|
||||
@ -1179,6 +1210,7 @@ impl Workspace {
|
||||
let project = identity.strip_prefix(&self.local_identity(""))?;
|
||||
Some(json!({"doc":doc,"checkpoint":{"project":project}}))
|
||||
});
|
||||
self.production_exit_state = Some(ExitState { run, checkpoint: std::mem::take(&mut self.product_checkpoint) });
|
||||
let checkpoint = if let Some(mut input) = input {
|
||||
input["checkpoint"]["status"] = json!("paused_on_exit");
|
||||
self.tx.send(Request::Action("product-exit-checkpoint".into(), input)).err()
|
||||
@ -1199,6 +1231,21 @@ impl Workspace {
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn restore_cancelled_exit(&mut self) {
|
||||
self.production_exit = None;
|
||||
let Some(snapshot) = self.production_exit_state.take() else { return; };
|
||||
self.product_checkpoint = snapshot.checkpoint;
|
||||
if let Some(mut run) = snapshot.run {
|
||||
if !matches!(run.phase, Phase::Paused(_) | Phase::WaitingOriginals { .. }) {
|
||||
run.phase = Phase::AwaitingSave;
|
||||
run.opening = None;
|
||||
run.finish = None;
|
||||
}
|
||||
self.write_production_checkpoint(&run, true);
|
||||
self.product_production = Some(run);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn advance_production_exit(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
let Some(exit) = &self.production_exit else { return };
|
||||
if self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle) {
|
||||
@ -1262,6 +1309,33 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.production_exit.as_ref()?.save_error.is_none() {
|
||||
let draft = app.session.documents().iter().find(|state| {
|
||||
let id = state.doc.id.0;
|
||||
state.is_dirty() && self.persisted_revisions.get(&id) != Some(&state.revision)
|
||||
&& self.open_projects.contains_key(&id)
|
||||
});
|
||||
if let Some(state) = draft {
|
||||
let doc = state.doc.id.0;
|
||||
let revision = state.revision;
|
||||
if self.tx.send(Request::Save(state.doc.clone(), revision, json!({"syncDirty":true}))).is_err() {
|
||||
return Some(Err("本机草稿保存服务已断开".into()));
|
||||
}
|
||||
self.saving = Some((doc, revision));
|
||||
return None;
|
||||
}
|
||||
// Save receipts mark the active canvas. Apply the same confirmed
|
||||
// revisions to other tabs before the general discard dialog runs.
|
||||
let active = app.session.active_index();
|
||||
let saved: Vec<_> = app.session.documents().iter().enumerate().filter_map(|(index, state)|
|
||||
(state.is_dirty() && self.persisted_revisions.get(&state.doc.id.0) == Some(&state.revision))
|
||||
.then_some((index, state.revision))).collect();
|
||||
for (index, revision) in saved {
|
||||
app.session.set_active(index);
|
||||
app.session.active_mut().unwrap().saved_revision = revision;
|
||||
}
|
||||
if let Some(active) = active { app.session.set_active(active); }
|
||||
}
|
||||
if self.busy.as_deref() == Some("slot-product-export") || app.exporting()
|
||||
|| self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle)
|
||||
{ return None; }
|
||||
@ -1385,15 +1459,30 @@ impl Workspace {
|
||||
}
|
||||
|
||||
pub(super) fn pause_for_authorization(&mut self, category: &Value) {
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
const REAUTHORIZE: &str = "请重新授权后继续制作";
|
||||
let mut run = self.product_production.take();
|
||||
if let Some(run) = run.as_mut() {
|
||||
run.paused_at.get_or_insert_with(production_time);
|
||||
let mut input = Self::production_checkpoint_request(run, false);
|
||||
input["checkpoint"]["phase"] = json!("paused");
|
||||
input["checkpoint"]["reason"] = category.clone();
|
||||
let _ = self.tx.send(Request::Action("product-run-checkpoint".into(), input));
|
||||
let waiting = Self::production_waiting_originals(&run.phase);
|
||||
run.cancel_deferred_image_recovery();
|
||||
run.phase = Phase::Paused(json!({"reason":category,"requiredAction":REAUTHORIZE,"waitingOriginals":waiting}));
|
||||
self.write_production_checkpoint(run, true);
|
||||
} else if self.product_checkpoint["active"] == true || self.product_checkpoint["phase"] == "paused" {
|
||||
self.product_checkpoint["active"] = json!(true);
|
||||
self.product_checkpoint["phase"] = json!("paused");
|
||||
self.product_checkpoint["reason"] = category.clone();
|
||||
self.product_checkpoint["requiredAction"] = json!(REAUTHORIZE);
|
||||
if let Some(doc) = self.loaded_draft
|
||||
&& self.open_projects.get(&doc) == Some(&self.local_identity(self.product_checkpoint["project"].as_str().unwrap_or(""))) {
|
||||
let _ = self.tx.send(Request::Action("product-run-checkpoint".into(),
|
||||
json!({"doc":doc,"checkpoint":self.product_checkpoint})));
|
||||
}
|
||||
}
|
||||
self.product_checkpoint = Value::Null;
|
||||
self.handover();
|
||||
self.product_production = run;
|
||||
if self.has_paused_production() {
|
||||
self.production_stop = json!({"mode":"pause","state":"paused","reason":category,"error":null});
|
||||
}
|
||||
self.pi_write_blocked = true;
|
||||
self.agent_effects_paused = true;
|
||||
}
|
||||
@ -1424,18 +1513,25 @@ impl Workspace {
|
||||
|
||||
pub(super) fn has_paused_production(&self) -> bool {
|
||||
self.product_production.as_ref().is_some_and(|run| matches!(run.phase, Phase::Paused(_)))
|
||||
|| self.product_checkpoint["active"] == true && self.product_checkpoint["phase"] == "paused"
|
||||
|| self.product_checkpoint["phase"] == "paused"
|
||||
}
|
||||
|
||||
pub(super) fn resume_paused_production(&mut self, app: &PhotocraftApp, text: String) {
|
||||
if !self.model_ready || !self.image_ready { return; }
|
||||
if self.product_production.is_none() {
|
||||
self.restore_production_checkpoint(app);
|
||||
}
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
run.resume_clock();
|
||||
run.goal_user_entry = Some(text.clone());
|
||||
if self.production_stop["state"] == "interrupted" { self.error.clear(); }
|
||||
self.production_stop = json!({"mode":null,"state":"idle","reason":null,"error":null});
|
||||
run.phase = Phase::AwaitingSave;
|
||||
run.phase = match &run.phase {
|
||||
Phase::Paused(pause) => Self::production_resume_phase(&pause["waitingOriginals"]),
|
||||
_ => Phase::AwaitingSave,
|
||||
};
|
||||
self.pi_write_blocked = false;
|
||||
self.agent_effects_paused = false;
|
||||
self.messages.push(json!({"role":"user","text":text}));
|
||||
self.checkpoint_production();
|
||||
self.production_tick(app);
|
||||
@ -1445,34 +1541,50 @@ impl Workspace {
|
||||
}
|
||||
|
||||
pub(super) fn restore_production_checkpoint(&mut self, app: &PhotocraftApp) {
|
||||
if self.product_checkpoint["active"] != true || self.busy.is_some() || self.saving.is_some()
|
||||
|| self.product_checkpoint["deliveryId"].is_null() && self.product_checkpoint["phase"] != "paused"
|
||||
&& (!self.model_ready || !self.image_ready)
|
||||
{ return; }
|
||||
let paused = self.product_checkpoint["phase"] == "paused";
|
||||
if (!paused && self.product_checkpoint["active"] != true) || self.busy.is_some() || self.saving.is_some() { return; }
|
||||
let Some(canvas) = app.session.active() else { return; };
|
||||
let doc = canvas.doc.id.0;
|
||||
let Some(project) = self.open_projects.get(&doc).cloned() else { return; };
|
||||
let workspace = self.template_workflow["workspaceId"].clone();
|
||||
if project != self.local_identity(self.product_checkpoint["project"].as_str().unwrap_or(""))
|
||||
|| workspace.is_null() || workspace != self.product_checkpoint["workspaceId"]
|
||||
|| self.product_checkpoint["phase"] != "paused"
|
||||
|| !paused
|
||||
&& self.persisted_revisions.get(&doc) != Some(&canvas.revision)
|
||||
{ return; }
|
||||
const WAITING_MODELS: &str = "上次制作已中断,连接对话和生图模型后可继续";
|
||||
if self.product_checkpoint["deliveryId"].is_null() && (!self.model_ready || !self.image_ready) {
|
||||
self.production_stop = json!({"mode":null,"state":"interrupted","reason":"waiting_for_models","error":WAITING_MODELS});
|
||||
self.error = WAITING_MODELS.into();
|
||||
if !paused { return; }
|
||||
} else if self.production_stop["state"] == "interrupted" {
|
||||
self.production_stop = json!({"mode":null,"state":"idle","reason":null,"error":null});
|
||||
if self.error == WAITING_MODELS { self.error.clear(); }
|
||||
}
|
||||
let remaining: HashSet<_> = self.template_workflow["productionStages"].as_array()
|
||||
.into_iter().flatten().filter_map(Stage::read).collect();
|
||||
let checkpoint = std::mem::take(&mut self.product_checkpoint);
|
||||
let stages: Vec<_> = checkpoint["stages"].as_array().into_iter().flatten()
|
||||
let mut stages: Vec<_> = checkpoint["stages"].as_array().into_iter().flatten()
|
||||
.filter_map(Stage::read).filter(|stage| remaining.contains(stage)).collect();
|
||||
if checkpoint["status"] == "paused_on_exit" {
|
||||
for stage in self.template_workflow["productionStages"].as_array().into_iter().flatten().filter_map(Stage::read) {
|
||||
if !stages.contains(&stage) && checkpoint["published"].as_array().into_iter().flatten().any(|row|
|
||||
Stage::read(row).as_ref() == Some(&stage)
|
||||
&& row["issues"].as_array().is_some_and(|issues| !issues.is_empty())) {
|
||||
stages.push(stage);
|
||||
}
|
||||
}
|
||||
}
|
||||
let output_selected = checkpoint["outputSelected"].as_bool().unwrap_or_else(||
|
||||
checkpoint["selectFirstOutput"] != true && checkpoint["firstCanvasOpening"] != true);
|
||||
let bound = Stage::read(&checkpoint["boundOutput"])
|
||||
.or_else(|| output_selected.then(|| Stage::read(&self.template_workflow)).flatten())
|
||||
.filter(|stage| canvas_workspace::document_scope_matches(
|
||||
&canvas.doc, &self.template_workflow, &stage.output, &stage.variant));
|
||||
let paused = checkpoint["phase"] == "paused";
|
||||
let phase = if paused {
|
||||
Phase::Paused(json!({"reason":checkpoint["reason"],"requiredAction":checkpoint["requiredAction"]}))
|
||||
} else { Phase::AwaitingSave };
|
||||
Phase::Paused(json!({"reason":checkpoint["reason"],"requiredAction":checkpoint["requiredAction"],
|
||||
"waitingOriginals":checkpoint["waitingOriginals"]}))
|
||||
} else { Self::production_resume_phase(&checkpoint["waitingOriginals"]) };
|
||||
let mut run = Run::new(doc, project, workspace, stages, None, phase);
|
||||
run.bound = bound;
|
||||
run.reset_goal = checkpoint["resetGoal"] == true;
|
||||
@ -1492,6 +1604,7 @@ impl Workspace {
|
||||
}
|
||||
run.delivery_dir = delivery_dir(&checkpoint);
|
||||
run.delivery_id = checkpoint["deliveryId"].as_str().map(str::to_owned);
|
||||
run.delivery_receipt = checkpoint["productionDelivery"].clone();
|
||||
run.finish_receipt["knownIssues"] = checkpoint["knownIssues"].clone();
|
||||
run.finish_receipt["deliveryReason"] = checkpoint["deliveryReason"].clone();
|
||||
run.published = checkpoint["published"].as_array().cloned().unwrap_or_default();
|
||||
@ -1502,7 +1615,13 @@ impl Workspace {
|
||||
run.total = checkpoint["total"].as_u64().unwrap_or(run.total as u64) as usize;
|
||||
run.completed = run.published.len();
|
||||
run.restore_deferred_images(&checkpoint);
|
||||
if !paused && (run.stages.is_empty() || run.finish_receipt["deliveryReason"].is_string()) && run.delivery_id.is_some() {
|
||||
Self::seed_deferred_images(&mut run, &self.template_workflow);
|
||||
if run.stages.is_empty() && run.delivery_id.is_none() {
|
||||
run.phase = Phase::AwaitingSave;
|
||||
self.write_production_checkpoint(&run, false);
|
||||
self.production_stop = json!({"mode":null,"state":"idle","reason":null,"error":null});
|
||||
if self.error == WAITING_MODELS { self.error.clear(); }
|
||||
} else if !paused && (run.stages.is_empty() || run.finish_receipt["deliveryReason"].is_string()) && run.delivery_id.is_some() {
|
||||
if run.finish_receipt["deliveryReason"].is_string() {
|
||||
self.production_stop = json!({"mode":"deliver","state":"delivering","reason":run.finish_receipt["deliveryReason"],"error":null});
|
||||
}
|
||||
@ -2244,9 +2363,21 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
|
||||
fn seed_deferred_images(run: &mut Run, workflow: &Value) {
|
||||
let mut requests = HashSet::new();
|
||||
for row in 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()
|
||||
&& row["requestId"].as_str().is_none_or(|request| requests.insert(request))
|
||||
&& !run.owns_deferred_image(id) {
|
||||
run.defer_images(stage, vec![id.into()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn tick_deferred_image_recovery(&mut self, app: &PhotocraftApp, ctx: &egui::Context, now: Instant) {
|
||||
if !self.authority_active() || self.library_blocked() || self.production_exit.is_some()
|
||||
|| self.product_production.as_ref().is_none_or(|run| !run.current(self, app))
|
||||
|| self.product_production.as_ref().is_none_or(|run| !run.current(self, app) || matches!(run.phase, Phase::Paused(_)))
|
||||
{
|
||||
self.cancel_deferred_image_recovery();
|
||||
return;
|
||||
@ -2254,13 +2385,10 @@ impl Workspace {
|
||||
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()]);
|
||||
}
|
||||
}
|
||||
Self::seed_deferred_images(run, &self.template_workflow);
|
||||
let mut settled = Vec::new();
|
||||
let mut retry = Vec::new();
|
||||
let mut stopped = 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
|
||||
@ -2268,8 +2396,37 @@ impl Workspace {
|
||||
settled.push((pending.stage.clone(), value));
|
||||
false
|
||||
}
|
||||
_ => false,
|
||||
Ok(Ok(value)) if value["id"] == pending.id
|
||||
&& matches!(value["status"].as_str(), Some("unknown" | "running" | "dispatched")) => {
|
||||
retry.push(pending.id.clone());
|
||||
false
|
||||
}
|
||||
Ok(Err(error)) if error == "原候选仍在处理" => {
|
||||
retry.push(pending.id.clone());
|
||||
false
|
||||
}
|
||||
result => {
|
||||
let error = match result {
|
||||
Ok(Err(error)) => error,
|
||||
_ => "原生图核查回执不可用,可手动核查原请求".into(),
|
||||
};
|
||||
stopped.push((pending.id.clone(), error));
|
||||
false
|
||||
}
|
||||
});
|
||||
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));
|
||||
}
|
||||
for (id, error) in stopped {
|
||||
run.deferred_image_stopped.insert(id);
|
||||
self.error = error;
|
||||
}
|
||||
let mut changed = false;
|
||||
for (stage, receipt) in &settled {
|
||||
let id = receipt["id"].as_str().unwrap();
|
||||
@ -2286,16 +2443,14 @@ impl Workspace {
|
||||
let next = run.queued_deferred_images()
|
||||
.filter(|(due, _, _)| due.is_none_or(|due| now >= due))
|
||||
.min_by_key(|(due, _, _)| *due)
|
||||
.map(|(due, stage, id)| (due, stage.clone(), id.clone()));
|
||||
let Some((due, stage, id)) = next else { break; };
|
||||
.map(|(_, stage, id)| (stage.clone(), id.clone()));
|
||||
let Some((stage, id)) = next else { break; };
|
||||
let (reply, receipt) = mpsc::channel();
|
||||
let cancellation = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let input = json!({"doc":run.doc,"project":run.project.rsplit('|').next(),
|
||||
"workspaceId":run.workspace,"outputId":stage.output,"variantId":stage.variant,
|
||||
"taskId":id,"accountId":self.account["id"],"origin":self.origin,
|
||||
"accountEpoch":self.accepted_account_epoch,"writeEpoch":self.write_epoch,"recoveryBudgetMs":9000});
|
||||
let delay = if due.is_some() { 15 } else { 8 };
|
||||
run.deferred_image_due.insert(id.clone(), now + Duration::from_secs(delay));
|
||||
if self.tx.send(Request::RecoverDeferredImage(input, cancellation.clone(), reply)).is_err() {
|
||||
break;
|
||||
}
|
||||
@ -2358,6 +2513,103 @@ mod tests {
|
||||
use std::sync::mpsc;
|
||||
|
||||
use crate::{AppTray, TrayAction};
|
||||
|
||||
#[test]
|
||||
fn legacy_paused_checkpoint_restores_originals_and_requires_model_connection_to_continue() {
|
||||
let (tx, requests) = mpsc::channel();
|
||||
let (_, rx) = mpsc::channel();
|
||||
let mut w = Workspace::new(tx, rx);
|
||||
requests.try_recv().unwrap();
|
||||
w.busy = None;
|
||||
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;
|
||||
w.open_projects.insert(doc, w.local_identity("project"));
|
||||
let stage = json!({"outputId":"detail","variantId":"wood"});
|
||||
w.template_workflow = json!({"workspaceId":"workspace","productionStages":[stage],
|
||||
"pendingImageRequests":[
|
||||
{"outputId":"detail","variantId":"wood","candidateId":"candidate","requestId":"original"},
|
||||
{"outputId":"detail","variantId":"wood","candidateId":"duplicate","requestId":"original"}
|
||||
]});
|
||||
w.product_checkpoint = json!({"active":false,"phase":"paused","project":"project","workspaceId":"workspace",
|
||||
"stages":[stage],"waitingOriginals":{"models":["model-original"],"images":["candidate"],"goal":"model-original"}});
|
||||
assert!(w.has_paused_production());
|
||||
w.restore_production_checkpoint(&app);
|
||||
assert_eq!(w.production_stop["state"], "interrupted");
|
||||
w.model_ready = true;
|
||||
w.image_ready = true;
|
||||
w.resume_paused_production(&app, "继续制作".into());
|
||||
let run = w.product_production.as_ref().unwrap();
|
||||
assert!(matches!(&run.phase, Phase::WaitingOriginals { models, images, goal }
|
||||
if models == &["model-original"] && images == &["candidate"] && goal.as_deref() == Some("model-original")));
|
||||
assert_eq!(run.deferred_images[&Stage::read(&stage).unwrap()], ["candidate"]);
|
||||
assert_eq!(w.production_stop["state"], "idle");
|
||||
let Request::Action(_, checkpoint) = requests.try_recv().unwrap() else { panic!("checkpoint"); };
|
||||
assert_eq!(checkpoint["checkpoint"]["waitingOriginals"]["goal"], "model-original");
|
||||
w.pause_for_authorization(&json!("auth_revoked"));
|
||||
let Request::Action(_, checkpoint) = requests.try_recv().unwrap() else { panic!("paused checkpoint"); };
|
||||
assert_eq!(checkpoint["checkpoint"]["active"], true);
|
||||
assert_eq!(checkpoint["checkpoint"]["phase"], "paused");
|
||||
assert_eq!(checkpoint["checkpoint"]["waitingOriginals"]["images"], json!(["candidate"]));
|
||||
assert!(w.has_paused_production());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_exit_restores_the_run_and_unblocks_effects() {
|
||||
let (tx, requests) = mpsc::channel();
|
||||
let (_, rx) = mpsc::channel();
|
||||
let mut w = Workspace::new(tx, rx);
|
||||
requests.try_recv().unwrap();
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"width":40,"height":50})).unwrap();
|
||||
let mut app = PhotocraftApp::new(session, crate::Services::default());
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
let stage = Stage { output:"detail".into(), variant:"wood".into() };
|
||||
w.product_production = Some(Run::new(doc, w.local_identity("project"), json!("workspace"),
|
||||
vec![stage], None, Phase::Agent));
|
||||
app.jiansun = Some(w);
|
||||
let _ = egui::Context::default().run_logic(&Default::default(), |ctx|
|
||||
assert!(super::super::guard_production_exit(&mut app, ctx)));
|
||||
let Request::Action(method, _) = requests.try_recv().unwrap() else { panic!("exit checkpoint"); };
|
||||
assert_eq!(method, "product-exit-checkpoint");
|
||||
super::super::cancel_exit(&mut app);
|
||||
let w = app.jiansun.as_ref().unwrap();
|
||||
assert!(w.production_exit.is_none());
|
||||
assert!(w.product_production.as_ref().unwrap().awaiting_canvas_save());
|
||||
assert!(!w.pi_write_blocked);
|
||||
assert!(!w.agent_effects_paused);
|
||||
assert!(!w.exit_admission_closed.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_waits_for_dirty_project_tabs_other_than_the_active_canvas() {
|
||||
let (tx, requests) = mpsc::channel();
|
||||
let (events, rx) = mpsc::channel();
|
||||
let mut w = Workspace::new(tx, rx);
|
||||
requests.try_recv().unwrap();
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"width":40,"height":50})).unwrap();
|
||||
session.execute("layer.new.layer", json!({"name":"待保存图层"})).unwrap();
|
||||
let dirty = session.active().unwrap().doc.id.0;
|
||||
w.open_projects.insert(dirty, w.local_identity("dirty-project"));
|
||||
session.execute("file.new", json!({"width":40,"height":50})).unwrap();
|
||||
let active = session.active().unwrap().doc.id.0;
|
||||
let mut app = PhotocraftApp::new(session, crate::Services::default());
|
||||
app.jiansun = Some(w);
|
||||
let ctx = egui::Context::default();
|
||||
let _ = ctx.run_logic(&Default::default(), |ctx|
|
||||
assert!(super::super::guard_production_exit(&mut app, ctx)));
|
||||
let step = |app: &mut PhotocraftApp| ctx.run_logic(&Default::default(), |ctx| super::super::advance(app, ctx))
|
||||
.viewport_commands.remove(&egui::ViewportId::ROOT).unwrap_or_default();
|
||||
assert!(!step(&mut app).contains(&egui::ViewportCommand::Close));
|
||||
let Request::Save(canvas, revision, _) = requests.try_recv().unwrap() else { panic!("save another project"); };
|
||||
assert_eq!(canvas.id.0, dirty);
|
||||
events.send(super::super::Event::Saved(dirty, revision, json!({"localId":"dirty-project"}))).unwrap();
|
||||
assert!(step(&mut app).contains(&egui::ViewportCommand::Close));
|
||||
assert_eq!(app.session.active().unwrap().doc.id.0, active);
|
||||
assert!(!app.session.documents().iter().find(|state| state.doc.id.0 == dirty).unwrap().is_dirty());
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Tray {
|
||||
visible: bool,
|
||||
@ -3282,6 +3534,15 @@ mod tests {
|
||||
w.tick_deferred_image_recovery(&app, &ctx, now + Duration::from_secs(9));
|
||||
assert!(revoked.load(Ordering::Acquire));
|
||||
assert!(requests.try_recv().is_err());
|
||||
w.accepted_account_epoch = 1;
|
||||
w.tick_deferred_image_recovery(&app, &ctx, now + Duration::from_secs(10));
|
||||
let Request::RecoverDeferredImage(_, _, reply) = requests.try_recv().unwrap() else { panic!("original query"); };
|
||||
reply.send(Err("个人Key校验失败(HTTP 401)".into())).unwrap();
|
||||
w.tick_deferred_image_recovery(&app, &ctx, now + Duration::from_secs(19));
|
||||
w.tick_deferred_image_recovery(&app, &ctx, now + Duration::from_secs(100));
|
||||
assert!(requests.try_recv().is_err());
|
||||
assert!(w.product_production.as_ref().unwrap().owns_deferred_image("second"));
|
||||
assert!(w.error.contains("HTTP 401"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -3318,7 +3579,7 @@ mod tests {
|
||||
workers.push((cancellation, reply));
|
||||
}
|
||||
assert!(requests.try_recv().is_err());
|
||||
assert_eq!(w.product_production.as_ref().unwrap().deferred_image_due["detail-0"], now + Duration::from_secs(8));
|
||||
assert!(w.product_production.as_ref().unwrap().deferred_image_due.is_empty());
|
||||
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");
|
||||
|
||||
@ -3384,13 +3645,13 @@ mod tests {
|
||||
let (repaint, delay) = mpsc::channel();
|
||||
ctx.set_repaint_observer(move |info| { let _ = repaint.send(info.delay); });
|
||||
w.tick_deferred_image_recovery(&app, &ctx, now + Duration::from_secs(1));
|
||||
assert_eq!(delay.try_recv().unwrap(), Duration::from_secs(7));
|
||||
assert_eq!(delay.try_recv().unwrap(), Duration::from_secs(8));
|
||||
assert!(requests.try_recv().is_err());
|
||||
let retry_at = now + Duration::from_secs(8);
|
||||
let retry_at = now + Duration::from_secs(9);
|
||||
w.tick_deferred_image_recovery(&app, &ctx, retry_at);
|
||||
let Request::RecoverDeferredImage(_, _, reply) = requests.try_recv().unwrap() else { panic!("second probe") };
|
||||
let run = w.product_production.as_mut().unwrap();
|
||||
assert_eq!(run.deferred_image_due["background"], retry_at + Duration::from_secs(15));
|
||||
assert_eq!(run.deferred_image_due["background"].0, retry_at);
|
||||
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"] {
|
||||
@ -4182,12 +4443,14 @@ mod tests {
|
||||
assert!(!cancellation.load(Ordering::Acquire));
|
||||
first_probe.send(Ok(json!({"id":"detail-original","status":"running"}))).unwrap();
|
||||
w.tick_deferred_image_recovery(app, &ctx, now + Duration::from_secs(8));
|
||||
assert!(requests.try_recv().is_err());
|
||||
w.tick_deferred_image_recovery(app, &ctx, now + Duration::from_secs(16));
|
||||
let Request::RecoverDeferredImage(original, _, final_probe) = requests.try_recv().unwrap()
|
||||
else { panic!("recover the old output while the new canvas saves"); };
|
||||
assert_eq!(original["outputId"], "detail");
|
||||
assert_eq!(original["taskId"], "detail-original");
|
||||
final_probe.send(Ok(json!({"id":"detail-original","status":"complete"}))).unwrap();
|
||||
w.tick_deferred_image_recovery(app, &ctx, now + Duration::from_secs(8));
|
||||
w.tick_deferred_image_recovery(app, &ctx, now + Duration::from_secs(16));
|
||||
let Request::Action(_, checkpoint) = requests.try_recv().unwrap() else { panic!("checkpoint settlement"); };
|
||||
assert_eq!(checkpoint["checkpoint"]["deferredImages"], json!([]));
|
||||
assert!(w.production_canvas_opening(app));
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user