diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs index 8f0c66f5..8f998878 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs @@ -1,9 +1,10 @@ //! A single GUI-owned Node daemon. Messages remain scoped to one run. use photocraft_ui_egui::jiansun::BridgeFailure; use super::{json, R, Value, PathBuf, Arc, Path}; +use std::collections::HashMap; use std::io::{BufRead, BufReader, Read, Write}; use std::process::{Child, ChildStdin, Command, Stdio}; -use std::sync::{Mutex, OnceLock, mpsc}; +use std::sync::{Mutex, OnceLock, mpsc, atomic::{AtomicBool, Ordering}}; use std::time::{Duration, Instant}; enum KnowledgeEvent { Progress(Value), Result(R) } @@ -12,8 +13,8 @@ type ExitReceipt = Box) + Send>; type PendingAcks = std::collections::HashMap)>; struct ActiveRun { - id: String, target: Value, + cancellation: Arc, events: mpsc::Sender>, } @@ -26,7 +27,7 @@ impl ActiveRun { struct State { alive: bool, ready: bool, - active: Option, + active: HashMap, steer_acks: PendingAcks, clear_queue_acks: PendingAcks, knowledge: std::collections::HashMap>, @@ -44,9 +45,9 @@ pub(super) struct Daemon { state: Mutex, pid: u32, } -struct Registry { service: Option>, shutting_down: bool, spawn_count: u64, production_pause: Option } +struct Registry { service: Option>, shutting_down: bool, spawn_count: u64, production_pauses: HashMap<(String, String), Value> } impl Registry { - fn new() -> Self { Self { service: None, shutting_down: false, spawn_count: 0, production_pause: None } } + fn new() -> Self { Self { service: None, shutting_down: false, spawn_count: 0, production_pauses: HashMap::new() } } fn ensure_start_allowed(&self) -> R<()> { if self.shutting_down { return Err("本机Agent正在关闭,未启动新进程".into()); } Ok(()) @@ -70,7 +71,10 @@ impl Daemon { for (_, sender) in state.knowledge.drain() { let _ = sender.send(KnowledgeEvent::Result(Err("企业知识库连接中断".into()))); } state.steer_acks.clear(); state.clear_queue_acks.clear(); - if let Some(run) = state.active.take() { let _ = run.events.send(Err(BridgeFailure::interrupted("本机Agent连接中断,原请求需核查", true))); } + for (_, run) in state.active.drain() { + run.cancellation.store(true, Ordering::SeqCst); + let _ = run.events.send(Err(BridgeFailure::interrupted("本机Agent连接中断,原请求需核查", true))); + } } if let Ok(mut output) = self.outbound.lock() { output.take(); } self.wait_for_exit(); @@ -106,17 +110,37 @@ impl Daemon { number => Some(u32::try_from(number.as_u64().ok_or("模型桥身份无效")?).map_err(|_| "模型桥身份无效")?), }; } + Some("close_session_ack") if state.ready => { + if !value["runId"].is_string() { return Err("关闭会话回执缺少回合编号".into()); } + if value["closed"] != true { + log::warn!("本机Agent会话关闭未确认"); + } + } Some("exit_ready") if state.exiting => { if let Some(receipt) = state.exit_receipt.take() { receipt(Ok(())); } } Some("canvas" | "presentation" | "complete" | "auth_failure") if state.ready => { - if state.exiting && state.active.is_none() { return Ok(()); } - let run = state.active.as_ref().ok_or("本机Agent收到无主回合消息")?; - if value["runId"].as_str() != Some(run.id.as_str()) { return Err("本机Agent回合身份不一致".into()); } - if run.events.send(Ok(value)).is_err() && !state.exiting { return Err("原回合已关闭".into()); } + let id = value["runId"].as_str().ok_or("本机Agent回合身份无效")?; + if let Some(run) = state.active.get(id) { + let _ = run.events.send(Ok(value)); + } else { + log::debug!("忽略已关闭回合的迟到消息"); + } } - Some(kind @ ("steer_ack" | "clear_queue_ack")) if state.ready => { - let pending = if kind == "steer_ack" { &mut state.steer_acks } else { &mut state.clear_queue_acks }; + Some("fatal") => { + // Neither a daemon exception nor stderr is safe to relay verbatim. + let message = "本机Agent报告致命错误,请核查原操作"; + if let Some(id) = value["runId"].as_str() { + if let Some(run) = state.active.remove(id) { + run.cancellation.store(true, Ordering::SeqCst); + let _ = run.events.send(Err(BridgeFailure::interrupted(message, true))); + } + } else { + return Err(message.into()); + } + } + Some(kind @ ("steer_ack" | "follow_up_ack" | "clear_queue_ack")) if state.ready => { + let pending = if kind != "clear_queue_ack" { &mut state.steer_acks } else { &mut state.clear_queue_acks }; if let Some(id) = value["id"].as_str() && pending.get(id).is_some_and(|(run, _)| value["runId"] == *run) && let Some((_, sender)) = pending.remove(id) @@ -151,27 +175,33 @@ impl Daemon { } } pub(super) fn begin(&self, run: &str, config: &Value) -> Result>, BridgeFailure> { - let mut registry = registry().lock().map_err(|_| "本机Agent状态不可用")?; - if config["productProduction"] == true - && let Some(pause) = registry.production_pause.take() - && ["scope", "project", "documentId", "writeEpoch"].iter().all(|key| pause[*key] == config[*key]) - { - return Err(BridgeFailure::new("cancelled", false, false, "本轮制作已停止,未派发模型")); - } + let mut registry = registry().lock().map_err(|_| "本机Agent状态不可用")?; + let target = (config["scope"].as_str().unwrap_or_default().to_owned(), + config["project"].as_str().unwrap_or_default().to_owned()); + if config["productProduction"] == true + && registry.production_pauses.remove(&target).is_some_and(|pause| + ["documentId", "writeEpoch"].iter().all(|key| pause[*key] == config[*key])) + { + return Err(BridgeFailure::new("cancelled", false, false, "本轮制作已停止,未派发模型")); + } let (sender, receiver) = mpsc::channel(); let sent = { let mut state = self.state.lock().map_err(|_| "本机Agent状态不可用")?; if state.exiting { return Err(BridgeFailure::new("cancelled", false, false, "客户端正在退出,未派发新任务")); } if !state.alive || !state.ready { return Err(BridgeFailure::interrupted("本机Agent不可用,未重发", false)); } - if state.active.is_some() { return Err("原Agent回合仍在处理".into()); } - state.active = Some(ActiveRun { - id: run.to_owned(), - target: json!({"scope":config["scope"],"project":config["project"],"documentId":config["documentId"]}), + if state.active.contains_key(run) || state.active.values().any(|active| + active.target["scope"] == config["scope"] && active.target["project"] == config["project"]) { + return Err("本项目原Agent回合仍在处理".into()); + } + state.active.insert(run.to_owned(), ActiveRun { + target: json!({"scope":config["scope"],"project":config["project"],"documentId":config["documentId"], + "writeEpoch":config["writeEpoch"]}), + cancellation: Arc::new(AtomicBool::new(false)), events: sender, }); self.send(&json!({"type":"run","runId":run,"config":config})) }; - drop(registry); + drop(registry); if let Err(error) = sent { self.fail(); return Err(BridgeFailure::interrupted(error, false)); } Ok(receiver) } @@ -220,23 +250,25 @@ impl Daemon { } pub(super) fn steer(&self, scope: &str, project: &str, doc: u64, input: &Value) -> R { self.queue_control(json!({ - "type":"steer","runId":input["runId"],"scope":scope,"project":project,"documentId":doc, + "type":if input["behavior"] == "followUp" { "follow_up" } else { "steer" }, + "runId":input["runId"],"scope":scope,"project":project,"documentId":doc, "text":input["text"],"behavior":input["behavior"],"referenceContent":input["referenceContent"], + "messageId":input["messageId"], })) } - pub(super) fn clear_queue(&self, scope: &str, project: &str, doc: u64, run_id: &Value) -> R { - self.queue_control(json!({"type":"clear_queue","runId":run_id,"scope":scope,"project":project,"documentId":doc})) + pub(super) fn clear_queue(&self, scope: &str, project: &str, doc: u64, run_id: &Value) -> R { + self.queue_control(json!({"type":"clear_queue","runId":run_id,"scope":scope,"project":project,"documentId":doc})) } fn queue_control(&self, mut request: Value) -> R { - let steering = request["type"] == "steer"; + let steering = request["type"] != "clear_queue"; let id = uuid::Uuid::new_v4().to_string(); let (sender, receiver) = mpsc::channel(); { let mut state = self.state.lock().map_err(|_| "本机连接不可用")?; if !state.alive || state.exiting { return Err("本机连接已关闭".into()); } - let Some(run) = state.active.as_ref().filter(|run| request["runId"] == run.id) else { + let Some(run) = request["runId"].as_str().and_then(|id| state.active.get(id)) else { return if steering { Ok(json!({"accepted":false,"reason":"no_active_run"})) } else { Ok(json!({"steering":[],"followUp":[]})) }; }; @@ -244,9 +276,13 @@ impl Daemon { return if steering { Ok(json!({"accepted":false,"reason":"scope_mismatch"})) } else { Err("当前项目的消息队列已切换".into()) }; } - let run = run.id.clone(); + let run = request["runId"].as_str().unwrap().to_owned(); request["id"] = json!(id); + if steering { request["messageId"] = json!(id); } let pending = if steering { &mut state.steer_acks } else { &mut state.clear_queue_acks }; + if pending.contains_key(&id) { + return Err("原消息回执仍待确认".into()); + } pending.insert(id.clone(), (run, sender)); if let Err(error) = self.send(&request) { pending.remove(&id); @@ -268,22 +304,35 @@ impl Daemon { } } - pub(super) fn abort_run(&self, scope: &str, project: &str, doc: u64, run_id: &Value) -> R<()> { + pub(super) fn abort_run(&self, scope: &str, project: &str, doc: u64, run_id: &Value) -> R<()> { + self.run_control("abort_run", scope, project, doc, run_id) + } + + pub(super) fn run_control(&self, method: &str, scope: &str, project: &str, doc: u64, run_id: &Value) -> R<()> { let state = self.state.lock().map_err(|_| "本机连接不可用")?; - let request = json!({"type":"abort_run","runId":run_id,"scope":scope,"project":project,"documentId":doc}); - if state.active.as_ref().is_some_and(|run| request["runId"] == run.id && run.matches(&request)) { + let request = json!({"type":method,"runId":run_id,"scope":scope,"project":project,"documentId":doc}); + let id = run_id.as_str().ok_or("回合编号缺失")?; + if let Some(run) = state.active.get(id).filter(|run| run.matches(&request)) { + run.cancellation.store(true, Ordering::SeqCst); + self.send(&request)?; + } else if method == "close_session" && !state.active.values().any(|run| run.matches(&request)) { self.send(&request)?; } Ok(()) } + pub(super) fn cancellation(&self, run_id: &str) -> R> { + self.state.lock().map_err(|_| "本机Agent状态不可用")?.active.get(run_id) + .map(|run| run.cancellation.clone()).ok_or_else(|| "原回合已关闭".into()) + } + pub(super) fn canvas_accepted(&self, run: &str, id: &Value) -> R<()> { self.send(&json!({"type":"canvas_accepted","runId":run,"id":id})) } pub(super) fn reply(&self, run: &str, id: &Value, reply: &Value) -> R<()> { let state = self.state.lock().map_err(|_| "本机Agent状态不可用")?; - if !state.alive || state.active.as_ref().is_none_or(|current| current.id != run) { return Err("原Agent回合已关闭".into()); } + if !state.alive || !state.active.contains_key(run) { return Err("原Agent回合已关闭".into()); } drop(state); let mut frame = json!({"type":"canvas_result","runId":run,"id":id}); if let Some(error) = reply.get("error") { frame["error"] = error.clone(); } else { frame["value"] = reply["value"].clone(); } @@ -291,15 +340,28 @@ impl Daemon { Ok(()) } pub(super) fn end(&self, run: &str) { - if let Ok(mut state) = self.state.lock() && state.active.as_ref().is_some_and(|current| current.id == run) { state.active = None; } + if let Ok(mut state) = self.state.lock() { state.active.remove(run); } } - fn prepare_exit(&self, receipt: ExitReceipt) { + fn prepare_exit(self: &Arc, receipt: ExitReceipt) { match self.state.lock() { Ok(mut state) if state.alive => { state.exiting = true; + for run in state.active.values() { + run.cancellation.store(true, Ordering::SeqCst); + } match self.send(&json!({"type":"prepare_exit"})) { - Ok(()) => state.exit_receipt = Some(receipt), + Ok(()) => { + state.exit_receipt = Some(receipt); + let daemon = self.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_secs(5)); + let receipt = daemon.state.lock().ok().and_then(|mut state| state.exit_receipt.take()); + if let Some(receipt) = receipt { + receipt(Err("本机Agent退出回执超时,原操作待核查".into())); + } + }); + } Err(error) => receipt(Err(error)), } } @@ -351,7 +413,7 @@ pub(super) fn service(node: &Path, script: &Path, binary: &Path, profile: &Path) } let mut command = Command::new(node); super::knowledge_http::configure_daemon(&mut command)?; - command.arg(script).arg("--daemon").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).env_remove("NODE_OPTIONS").env_remove("NODE_PATH"); + command.arg(script).arg("--daemon").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).env_remove("NODE_OPTIONS").env_remove("NODE_PATH"); command.env("PHOTOCRAFT_KNOWLEDGE_HOST", binary); if let Some(path) = super::knowledge_http::config_path().filter(|_| std::env::var_os("PHOTOCRAFT_KNOWLEDGE_ORIGIN_FILE").is_none()) { command.env("PHOTOCRAFT_KNOWLEDGE_ORIGIN_FILE", path); @@ -374,7 +436,7 @@ pub(super) fn service(node: &Path, script: &Path, binary: &Path, profile: &Path) }; let (output, messages) = mpsc::channel(); let daemon = Arc::new(Daemon { identity, child: Mutex::new(child), outbound: Mutex::new(Some(output)), pid, - state: Mutex::new(State { alive:true, ready:false, active:None, steer_acks:Default::default(), clear_queue_acks:Default::default(), knowledge:Default::default(), broker_pid:None, last_ack:None, last_sent:0, last_acked:0, + state: Mutex::new(State { alive:true, ready:false, active:HashMap::new(), steer_acks:Default::default(), clear_queue_acks:Default::default(), knowledge:Default::default(), broker_pid:None, last_ack:None, last_sent:0, last_acked:0, exiting:false, exit_receipt:None }) }); spawn_writer(&daemon, stdin, messages); let reader_daemon = daemon.clone(); @@ -411,12 +473,6 @@ pub(super) fn service(node: &Path, script: &Path, binary: &Path, profile: &Path) } pub(super) fn current() -> R>> { Ok(registry().lock().map_err(|_| "本机连接不可用")?.service.clone()) -} - -pub(super) fn active_run_id() -> Option { - let daemon = current().ok()??; - let state = daemon.state.lock().ok()?; - Some(state.active.as_ref()?.id.clone()) } pub(super) fn status() -> Value { @@ -424,17 +480,26 @@ pub(super) fn status() -> Value { let Some(service) = ®istry.service else { return json!({"available":false,"pid":null,"brokerPid":null,"spawnCount":registry.spawn_count,"activeRun":null,"heartbeatAgeMs":null}) }; let Ok(state) = service.state.lock() else { return json!({"available":false}) }; json!({"available":state.alive && state.ready,"pid":service.pid,"brokerPid":state.broker_pid,"spawnCount":registry.spawn_count, - "activeRun":state.active.as_ref().map(|run| &run.id),"heartbeatAgeMs":state.last_ack.map(|at|at.elapsed().as_millis().min(u64::MAX as u128) as u64)}) + "activeRun":(state.active.len() == 1).then(|| state.active.keys().next()).flatten(),"activeRuns":state.active.keys().collect::>(),"heartbeatAgeMs":state.last_ack.map(|at|at.elapsed().as_millis().min(u64::MAX as u128) as u64)}) } pub(super) fn pause_production(doc: u64, project_identity: &str, write_epoch: Option) { let Some((account_identity, project)) = project_identity.rsplit_once('|') else { return; }; - if write_epoch.is_none() { return; } - if let Ok(mut registry) = registry().lock() { - let pause = json!({"type":"production_pause","documentId":doc,"project":project, - "scope":super::hash(account_identity),"writeEpoch":write_epoch}); - if let Some(service) = ®istry.service { let _ = service.send(&pause); } - registry.production_pause = Some(pause); + if write_epoch.is_none() { return; } + if let Ok(mut registry) = registry().lock() { + let scope = super::hash(account_identity); + let pause = json!({"type":"production_pause","documentId":doc,"project":project, + "scope":scope,"writeEpoch":write_epoch}); + if let Some(service) = ®istry.service + && let Ok(state) = service.state.lock() + && let Some((id, run)) = state.active.iter() + .find(|(_, run)| run.matches(&pause) && run.target["writeEpoch"] == pause["writeEpoch"]) { + run.cancellation.store(true, Ordering::SeqCst); + let mut frame = pause.clone(); + frame["runId"] = json!(id); + let _ = service.send(&frame); + } + registry.production_pauses.insert((scope, project.to_owned()), pause); } } @@ -458,6 +523,11 @@ pub(super) fn cancel_exit() { pub(super) fn revoke_scope(scope: &str, category: &str) { let service = registry().lock().ok().and_then(|registry| registry.service.clone()); if let Some(service) = service { + if let Ok(state) = service.state.lock() { + for run in state.active.values().filter(|run| run.target["scope"] == scope) { + run.cancellation.store(true, Ordering::SeqCst); + } + } let _ = service.send(&json!({"type":"auth_revoke","scope":scope,"category":category})); } } @@ -527,7 +597,7 @@ rl.on('line',line=>{ let (output, messages) = mpsc::channel(); let daemon = Arc::new(Daemon { identity:(PathBuf::new(),PathBuf::new(),PathBuf::new(),PathBuf::new(),0), child:Mutex::new(child),outbound:Mutex::new(Some(output)),pid, - state:Mutex::new(State { alive:true,ready:false,active:None,steer_acks:Default::default(),clear_queue_acks:Default::default(),knowledge:Default::default(),broker_pid:None,last_ack:None,last_sent:0,last_acked:0, + state:Mutex::new(State { alive:true,ready:false,active:HashMap::new(),steer_acks:Default::default(),clear_queue_acks:Default::default(),knowledge:Default::default(),broker_pid:None,last_ack:None,last_sent:0,last_acked:0, exiting:false,exit_receipt:None }) }); spawn_writer(&daemon, stdin, messages); let handle = daemon.clone(); @@ -548,7 +618,7 @@ rl.on('line',line=>{ for run in ["run-one", "run-two"] { let receiver = daemon.begin(run, &json!({"mode":"fixture"})).unwrap(); assert!(daemon.begin("overlap", &json!({})).is_err()); - assert!(daemon.handle(json!({"type":"complete","runId":"foreign","value":{}})).is_err()); + daemon.handle(json!({"type":"complete","runId":"foreign","value":{}})).unwrap(); let frame = receiver.recv_timeout(Duration::from_secs(5)).unwrap().unwrap(); assert_eq!((frame["type"].as_str(), frame["runId"].as_str()), (Some("presentation"), Some(run))); let frame = receiver.recv_timeout(Duration::from_secs(5)).unwrap().unwrap(); @@ -556,21 +626,34 @@ rl.on('line',line=>{ assert_eq!(daemon.pid, pid); daemon.end(run); } + let first = json!({"mode":"live","scope":"account","project":"one","documentId":42}); + let second = json!({"mode":"live","scope":"account","project":"two","documentId":43}); + let a = daemon.begin("run-a", &first).unwrap(); + let b = daemon.begin("run-b", &second).unwrap(); + assert!(daemon.begin("run-duplicate", &first).is_err()); + daemon.abort_run("account", "two", 43, &json!("run-a")).unwrap(); + daemon.abort_run("account", "two", 43, &json!("run-b")).unwrap(); + assert_eq!(b.recv_timeout(Duration::from_secs(5)).unwrap().unwrap()["runId"], "run-b"); + assert!(a.try_recv().is_err()); + daemon.handle(json!({"type":"fatal","runId":"run-a","error":"untrusted text"})).unwrap(); + assert!(a.recv_timeout(Duration::from_secs(5)).unwrap().is_err()); + daemon.end("run-b"); + for production in [false, true] { let run = uuid::Uuid::new_v4().to_string(); let receiver = daemon.begin(&run, &json!({ "mode":"live","scope":"account","project":"project","documentId":42,"productProduction":production, })).unwrap(); - let input = json!({"runId":run,"text":"补充","behavior":"steer","referenceContent":[]}); + let input = json!({"runId":run,"text":"补充","behavior":"steer","referenceContent":[]}); assert_eq!(daemon.steer("another", "project", 42, &input).unwrap()["reason"], "scope_mismatch"); let ack = daemon.steer("account", "project", 42, &input).unwrap(); assert_eq!(ack["runId"], run); assert_eq!(ack["accepted"], true); assert_eq!(ack["disposition"], "queued"); - let ack = daemon.clear_queue("account", "project", 42, &input["runId"]).unwrap(); + let ack = daemon.clear_queue("account", "project", 42, &input["runId"]).unwrap(); assert_eq!(ack["steering"], json!(["补充"])); assert_eq!(ack["followUp"], json!([])); - daemon.abort_run("account", "project", 42, &input["runId"]).unwrap(); + daemon.abort_run("account", "project", 42, &input["runId"]).unwrap(); let frame = receiver.recv_timeout(Duration::from_secs(5)).unwrap().unwrap(); assert_eq!(frame["value"], json!({"aborted":true,"scope":"account","project":"project","documentId":42})); daemon.end(&run); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 91ca2ee5..9092b5d0 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -1,5 +1,4 @@ //! Native reuse of the existing /api/desktop and 98k public execution contracts. -//! The native client uses public HTTP contracts. Text requests can switch routes before response headers. use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; use photocraft_doc::Document; use photocraft_ui_egui::jiansun::{Edit, Event, Request, Workspace}; @@ -12,7 +11,7 @@ use std::{ io::{self, ErrorKind, Read, Write}, net::{Shutdown, TcpListener, TcpStream}, path::{Path, PathBuf}, - sync::{Arc, mpsc}, + sync::{Arc, Mutex, mpsc}, time::{Duration, Instant, SystemTime, UNIX_EPOCH}, }; use uuid::Uuid; @@ -471,10 +470,93 @@ fn original_project_present(dir: &Path) -> R<()> { } /// The slow open owns no receive-loop state. Its completion is queued behind /// ordinary Save requests, and only that loop may adopt the stable binding. +type ProjectKey = (String, String); +type ProjectWork = Box; +struct QueuedProjectWork { + key: ProjectKey, + run_id: Option, + work: ProjectWork, +} + +struct ProjectSlots { + limit: usize, + active: std::collections::HashSet, + restoring: std::collections::HashSet, + queued: std::collections::VecDeque, +} + +impl ProjectSlots { + fn new(limit: usize) -> Self { + Self { limit, active: Default::default(), restoring: Default::default(), queued: Default::default() } + } + + fn contains(&self, key: &ProjectKey) -> bool { + self.active.contains(key) || self.restoring.contains(key) || self.queued.iter().any(|pending| &pending.key == key) + } + + fn next(&mut self) -> Option<(ProjectKey, ProjectWork)> { + if self.active.len() >= self.limit { + return None; + } + let pending = self.queued.pop_front()?; + self.active.insert(pending.key.clone()); + Some((pending.key, pending.work)) + } + + fn cancel_queued(&mut self, key: &ProjectKey, run_id: &str) -> bool { + let index = self.queued.iter().position(|pending| + &pending.key == key && pending.run_id.as_deref() == Some(run_id)); + index.and_then(|index| self.queued.remove(index)).is_some() + } + + fn submit(pool: &Arc>, key: ProjectKey, run_id: Option, work: ProjectWork) { + let mut slots = pool.lock().expect("project slots"); + debug_assert!(!slots.contains(&key)); + slots.queued.push_back(QueuedProjectWork { key, run_id, work }); + Self::start(pool, &mut slots); + } + + fn start(pool: &Arc>, slots: &mut Self) { + if let Some((key, work)) = slots.next() { + let pool = pool.clone(); + std::thread::spawn(move || { + let _slot = ProjectSlot { pool, key }; + work(); + }); + } + } +} + +struct ProjectSlot { + pool: Arc>, + key: ProjectKey, +} + +impl Drop for ProjectSlot { + fn drop(&mut self) { + let mut slots = self.pool.lock().expect("project slots"); + slots.active.remove(&self.key); + ProjectSlots::start(&self.pool, &mut slots); + } +} + +fn project_slot_key(backend: &Backend, input: &Value, doc: Option) -> ProjectKey { + let doc = doc.or_else(|| input["context"]["id"].as_u64()).or_else(|| input["doc"].as_u64()) + .or_else(|| input["draftDoc"].as_u64()); + let project = doc.and_then(|doc| backend.locations.get(&doc)).cloned() + .or_else(|| ["localId", "projectId", "id"].iter() + .find_map(|key| input[*key].as_str().map(str::to_owned))) + .unwrap_or_else(|| doc.map_or_else(String::new, |doc| format!("doc:{doc}"))); + (backend.scope(), project) +} + fn enqueue_open(requests: mpsc::Sender, open: impl FnOnce() -> T + Send + 'static) { - std::thread::spawn(move || { + static OPEN_WORKERS: std::sync::OnceLock = std::sync::OnceLock::new(); + if let Err(error) = OPEN_WORKERS.get_or_init(reads::QueuedReads::detail_review).submit(move || { let _ = requests.send(open()); - }); + }) { + log::warn!("画布读取队列不可用:{error}"); + } } fn open_binding_local(binding: &Value, scope: &str, origin: &str, account: &Value) -> R { if binding["accountScope"] != scope || binding["origin"] != origin || binding["accountId"] != account["id"] { @@ -2250,7 +2332,8 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { ctx.request_repaint_of(egui::ViewportId::ROOT); return; } - let model_busy = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let parallel_projects = if std::env::var("JIANSUN_PARALLEL_PROJECTS").as_deref() == Ok("3") { 3 } else { 2 }; + let project_slots = Arc::new(Mutex::new(ProjectSlots::new(parallel_projects))); let project_busy = Arc::new(std::sync::atomic::AtomicBool::new(false)); let catalog_reads = reads::ReadPool::catalog(); let image_reads = reads::ReadPool::images(); @@ -2298,8 +2381,9 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { Request::OpenedResult { binding, result } => { let label = if binding["autoResume"] == true { "startup-open" } else { "open" }; let adopted = result.and_then(|(doc, meta)| backend.accept_opened(&binding, doc, meta)); - if binding["updateBusy"] == true { - model_busy.store(false, std::sync::atomic::Ordering::Release); + if let Ok(key) = serde_json::from_value::(binding["projectSlot"].clone()) { + let mut slots = project_slots.lock().expect("project slots"); + slots.restoring.remove(&key); } match adopted { Ok((doc, meta)) => { @@ -2323,21 +2407,19 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { }); } Request::Generate(doc, input) => { - use std::sync::atomic::Ordering; backend.bind_new(doc.id.0); - if model_busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { + let key = project_slot_key(&backend, &input, Some(doc.id.0)); + if project_slots.lock().expect("project slots").contains(&key) { let _ = events.send(Event::Json("image".into(), Err("原请求仍在处理,未重复提交".into()))); } else { let mut b = backend.clone(); let events = events.clone(); let ctx = ctx.clone(); - let busy = model_busy.clone(); - std::thread::spawn(move || { + ProjectSlots::submit(&project_slots, key, None, Box::new(move || { let result = b.image_job(Some(doc), &input, false, &events, &ctx); let _ = events.send(Event::Json("image".into(), result)); - busy.store(false, Ordering::Release); ctx.request_repaint_of(egui::ViewportId::ROOT); - }); + })); } } Request::Save(doc, revision, meta) if meta["metadataOnly"] == true => { @@ -2414,10 +2496,19 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let _ = events.send(event); } Request::Action(method, input) => { - if matches!(method.as_str(), "agent-steer" | "agent-clear-queue" | "agent-abort") { - let mut input = input; - // Pin to the current daemon run before a worker waits for references or an ACK. - input["runId"] = json!(agent_daemon::active_run_id()); + if matches!(method.as_str(), "agent-steer" | "agent-follow-up" | "agent-clear-queue" | "agent-abort" | "agent-pause" | "agent-close-session") { + if matches!(method.as_str(), "agent-abort" | "agent-pause" | "agent-close-session") + && let Some(run_id) = input["runId"].as_str() + && project_slots.lock().expect("project slots") + .cancel_queued(&project_slot_key(&backend, &input, None), run_id) + { + let _ = events.send(Event::Json("agent".into(), Ok(json!({"runId":run_id, + "doc":input["draftDoc"],"phase":"paused","engine":"pi", + "accountId":backend.auth["account"]["id"],"origin":backend.origin,"failure": + {"category":"cancelled","dispatched":false,"message":"排队中的回合已停止"}})))); + ctx.request_repaint_of(egui::ViewportId::ROOT); + continue; + } let reference = json!({ "accountId":backend.auth["account"]["id"],"origin":backend.origin,"doc":input["draftDoc"], }); @@ -2431,7 +2522,14 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let task = move || { let result = match task_method.as_str() { "agent-steer" => pi_runtime::steer(&worker, &input, &task_events, &task_ctx), + "agent-follow-up" => { + let mut input = input; + input["behavior"] = json!("followUp"); + pi_runtime::steer(&worker, &input, &task_events, &task_ctx) + } "agent-clear-queue" => pi_runtime::clear_queue(&worker, &input), + "agent-pause" => pi_runtime::control_run(&worker, &input, "pause"), + "agent-close-session" => pi_runtime::control_run(&worker, &input, "close_session"), _ => pi_runtime::abort_run(&worker, &input), }; let mut receipt = bound_material_read(result, &task_reference); @@ -2439,8 +2537,8 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let _ = task_events.send(Event::Json(task_method, Ok(receipt))); task_ctx.request_repaint_of(egui::ViewportId::ROOT); }; - if method == "agent-abort" { - std::thread::spawn(task); + if matches!(method.as_str(), "agent-abort" | "agent-pause" | "agent-close-session") { + task(); } else if agent_queue_ops.submit(task).is_err() { let mut receipt = bound_material_read(Err("本机消息队列繁忙,请稍后发送".into()), &reference); receipt["text"] = text; @@ -2625,7 +2723,9 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { } return true; } - if matches!(method.as_str(), "project-sync" | "project-state" | "project-delete") && model_busy.load(std::sync::atomic::Ordering::Acquire) { + if matches!(method.as_str(), "project-sync" | "project-state" | "project-delete") + && project_slots.lock().expect("project slots").contains(&project_slot_key(&backend, &input, None)) + { let _ = events.send(Event::Json(method, Err("任务仍在运行,请等待完成或接手后再保存云端状态".into()))); ctx.request_repaint_of(egui::ViewportId::ROOT); return true; @@ -2640,20 +2740,18 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { let _ = events.send(Event::Json(method, result)); ctx.request_repaint_of(egui::ViewportId::ROOT); } else if method == "project-sync" && input["status"] == "completed" { - use std::sync::atomic::Ordering; - if model_busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { + let key = project_slot_key(&backend, &input, None); + if project_slots.lock().expect("project slots").contains(&key) { let _ = events.send(Event::Json(method, Err("原任务仍在处理,未重复提交成品".into()))); } else { let mut b = backend.clone(); let events = events.clone(); let ctx = ctx.clone(); - let busy = model_busy.clone(); - std::thread::spawn(move || { + ProjectSlots::submit(&project_slots, key, None, Box::new(move || { let result = b.sync_project(&input); let _ = events.send(Event::Json(method, result)); - busy.store(false, Ordering::Release); ctx.request_repaint_of(egui::ViewportId::ROOT); - }); + })); } } else if method.starts_with("slot-") || method == "agent" @@ -2663,18 +2761,18 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { { // Slow model calls never block local saving. The task owns its account // snapshot; the GUI also checks that identity before applying a result. - use std::sync::atomic::Ordering; if let Some(id) = input["context"]["id"].as_u64().or_else(|| input["doc"].as_u64()) { backend.bind_new(id); } - if model_busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { + let key = project_slot_key(&backend, &input, None); + if project_slots.lock().expect("project slots").contains(&key) { let _ = events.send(Event::Json(method, Err("原请求仍在处理,不会重复提交".into()))); } else { let mut task_backend = backend.clone(); let task_events = events.clone(); let task_ctx = ctx.clone(); - let busy = model_busy.clone(); - std::thread::spawn(move || { + let run_id = (method == "agent").then(|| input["runId"].as_str().map(str::to_owned)).flatten(); + ProjectSlots::submit(&project_slots, key, run_id, Box::new(move || { let recover = method == "recover"; let result = if method.starts_with("slot-") { task_backend.slot_action(&method, &input, &task_events, &task_ctx) @@ -2689,10 +2787,9 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { task_backend.agent(&input, recover, &task_events, &task_ctx) } }; - busy.store(false, Ordering::Release); let _ = task_events.send(Event::Json(method, result)); task_ctx.request_repaint_of(egui::ViewportId::ROOT); - }); + })); } } else if method.starts_with("creation-") { let result = backend.creation_action(&method, &input, None, &events, &ctx); @@ -2737,17 +2834,20 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { } } } else if method == "open" { - use std::sync::atomic::Ordering; let updating = input["updateExisting"] == true; - if updating && model_busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { + let project_slot = updating.then(|| project_slot_key(&backend, &input, None)); + if project_slot.as_ref().is_some_and(|key| project_slots.lock().expect("project slots").contains(key)) { let _ = events.send(Event::Json(method, Err("任务仍在处理,请先保留原请求后读取新版".into()))); ctx.request_repaint_of(egui::ViewportId::ROOT); return true; } + if let Some(key) = &project_slot { + project_slots.lock().expect("project slots").restoring.insert(key.clone()); + } let mut b = backend.clone(); let events = events.clone(); let ctx = ctx.clone(); - let mut binding = json!({"accountScope":b.scope(),"origin":b.origin,"accountId":b.auth["account"]["id"],"autoResume":input["autoResume"],"updateBusy":updating,"requireCopyIdentity":updating || input["source"] == "native"}); + let mut binding = json!({"accountScope":b.scope(),"origin":b.origin,"accountId":b.auth["account"]["id"],"autoResume":input["autoResume"],"projectSlot":project_slot,"requireCopyIdentity":updating || input["source"] == "native"}); enqueue_open(internal_requests.clone(), move || { let result = b.open_with_recovery(&input, &events, &ctx).map(|(doc, meta)| { binding["localId"] = json!(b.locations.get(&doc.id.0)); @@ -2788,6 +2888,31 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { mod tests { use super::*; + #[test] + fn project_slots_limit_parallel_runs_and_admit_distinct_projects_in_fifo_order() { + let key = |account: &str, project: &str| (account.to_owned(), project.to_owned()); + let a = key("one", "a"); + let b = key("one", "b"); + let c = key("two", "a"); + let d = key("one", "c"); + let mut slots = ProjectSlots::new(2); + for key in [&a, &b, &c, &d] { + slots.queued.push_back(QueuedProjectWork { + key:key.clone(), run_id:Some(key.1.clone()), work:Box::new(|| {}), + }); + } + assert_eq!(slots.next().map(|(key, _)| key), Some(a.clone())); + assert_eq!(slots.next().map(|(key, _)| key), Some(b.clone())); + assert!(slots.contains(&c)); + assert!(slots.next().is_none()); + assert!(!slots.cancel_queued(&d, "wrong run")); + assert!(slots.cancel_queued(&d, "c")); + slots.active.remove(&b); + assert_eq!(slots.next().map(|(key, _)| key), Some(c)); + slots.active.remove(&a); + assert!(slots.next().is_none()); + } + #[test] fn native_project_listing_skips_corrupt_and_stray_entries() { let tmp = tempfile::tempdir().unwrap(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index b0a3d113..acd8e983 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -825,7 +825,7 @@ fn candidate_uses_current_inputs(dir: &Path, state: &Value, record: &Value, vari } fn read_candidate(dir: &Path, id: &str) -> R { let path = candidate_path(dir, id)?; - let record = read_json_with_missing(&path, "文件缺失") + let mut record = read_json_with_missing(&path, "文件缺失") .map_err(|error| format!("候选 {id}({CANDIDATE}):{error}"))?; if record["version"] != 2 || record["id"] != id @@ -835,6 +835,7 @@ fn read_candidate(dir: &Path, id: &str) -> R { { return Err("候选记录或原请求身份无效".into()); } + super::images::reopen_ambiguous_expiry(&mut record); Ok(record) } pub(super) fn retired_archive(dir: &Path, id: &str) -> bool { @@ -1236,6 +1237,13 @@ fn candidate_receipt(record: &Value) -> Value { if record["origin"] == "human" { receipt["origin"] = json!("human"); } if record["phase"] == "complete" { receipt["materialTaskId"] = material_task_id(record).clone(); } if record["generationEvidence"].is_object() { receipt["generationEvidence"] = record["generationEvidence"].clone(); } + if matches!(record["phase"].as_str(), Some("dispatched" | "running" | "unknown")) { + receipt["dispatchState"] = json!("outcome_unknown"); + receipt["originalRequestId"] = record.get("requestId").filter(|id| id.is_string()) + .unwrap_or(&record["id"]).clone(); + } else if record["notDispatched"] == true { + receipt["dispatchState"] = json!("not_dispatched"); + } if record["phase"] == "expired" { receipt["requestId"] = record["requestId"].clone(); receipt["retryable"] = json!(false); @@ -1347,7 +1355,13 @@ fn candidate_projection_task(dir: &Path, record: &Value) -> R> { return Ok(None); } let task = dir.join("image-jobs").join(uuid(&record["id"], "候选")?).join("task.json"); - if task.is_file() { read_json(&task).map(Some) } else { Ok(None) } + if task.is_file() { + let mut task = read_json(&task)?; + super::images::reopen_ambiguous_expiry(&mut task); + Ok(Some(task)) + } else { + Ok(None) + } } // A prepared task must be durably replaced by a dispatched task before POST. @@ -1955,6 +1969,9 @@ fn project_candidate(dir: &Path, record: &Value, journal: &Value) -> R { }); } record["phase"] = json!(phase); + if journal["notDispatched"] == true { + record["notDispatched"] = json!(true); + } if phase == "expired" { record["resultExpiry"] = journal["resultExpiry"].clone(); } let preflight_retry = journal["phase"] == "prepared" && journal["notDispatched"] == true && journal["requestId"].is_null() && record["requestId"].is_null() @@ -2187,6 +2204,7 @@ impl Backend { Some(dispatch) } else { None }; let mut original = read_json(&file)?; + super::images::reopen_ambiguous_expiry(&mut original); if original["id"] != candidate { return Err("原候选任务身份已变化".into()); } @@ -2704,12 +2722,25 @@ pub(super) fn published_receipt(path: &Path) -> R { { return Err("交付指针无效".into()); } - let manifest = read_json(&path.parent().ok_or("交付目录缺失")?.join(manifest))?; + let mut manifest = read_json(&path.parent().ok_or("交付目录缺失")?.join(manifest))?; if ["generationId", "workspaceId", "outputId", "variantId"].iter() .any(|field| manifest[*field] != pointer[*field]) { return Err("交付清单与发布指针不一致".into()); } + if pointer["reusedGeneration"] == true { + for field in ["documentKey", "canvasRevision", "operationId", "deliveryInputHash", "briefRevision", + "productionProfile", "fidelityReport", "knownIssues", "issues", "slotCoverage", "missingImages", + "missingSlots", "unreviewedScreens", "missingVisibleText", "visibleSampleLayer", + "unapprovedFixedTextLayer", "unverifiedCopy", "unverifiedFacts", "blankCopyReasons", + "warnings", "allOutputsCompleted", "deliveryStatus"] { + if let Some(value) = pointer.get(field) { + manifest[field] = value.clone(); + } else { + manifest.as_object_mut().unwrap().remove(field); + } + } + } Ok(manifest) } @@ -4028,11 +4059,56 @@ fn export_layered_document(dir: &Path, component: &str, generation: &str, doc: & "sha256":format!("{:x}",Sha256::digest(&saved))})) } +fn reusable_product_generation(receipt: &Path, result: &Value, + regions: &[(u64, u64, u64)], screens: &[(u64, u64, u64)]) -> Option { + let old = published_receipt(receipt).ok()?; + let generation = old["generationId"].as_str().filter(|id| id.strip_prefix("generation-") + .is_some_and(|suffix| !suffix.is_empty() && suffix.bytes().all(|byte| byte.is_ascii_alphanumeric())))?; + let manifest = receipt.parent()?.join(manifest_path(generation)); + let folder = manifest.parent()?; + if !result["workingSha256"].is_string() || result["workingSha256"] != old["sourceDocument"]["workingSha256"] + || !result["stageInputHash"].is_string() + || old["validation"]["mode"] != "full" + || ["templateHash", "stageInputHash", "variantId", "outputId", "workspaceId", "imageSources"] + .iter().any(|key| old[*key] != result[*key]) + || !export_records_match(&old["files"], regions, Some(generation)) + || !screens.is_empty() && !export_records_match(&old["screenFiles"], screens, Some(generation)) + || screens.is_empty() && old["screenFiles"].as_array().is_some_and(|files| !files.is_empty()) + { + return None; + } + let intact = [&old["sourceDocument"], &old["layeredDocument"]].into_iter() + .chain(old["files"].as_array()?.iter()) + .chain(old["screenFiles"].as_array().into_iter().flatten()) + .all(|artifact| artifact["generationId"] == generation && artifact["path"].as_str() + .is_some_and(|path| Path::new(path).parent() == Some(folder)) && artifact_matches(artifact, true)); + intact.then_some(old) +} + +fn set_delivery_status(receipt: &mut Value, completed: bool) { + receipt["allOutputsCompleted"] = json!(completed); + receipt["deliveryStatus"] = json!(if completed { "completed" } else { "partial_delivered" }); +} + pub(super) fn publish_product_generation( receipt: &Path, native: &Document, document_revision: &Value, result: &mut Value, regions: &[(u64, u64, u64)], screens: &[(u64, u64, u64)], ) -> R<()> { let component = result["outputId"].as_str().ok_or("制作输出缺失")?; + if let Some(old) = reusable_product_generation(receipt, result, regions, screens) { + for field in ["reopenVerification", "generationId", "sourceDocument", "layeredDocument", + "files", "screenFiles", "editable", "productionDelivery", "validation"] { + if let Some(value) = old.get(field) { + result[field] = value.clone(); + } + } + result.as_object_mut().unwrap().remove("workingSha256"); + result["publishedPointer"] = json!(manifest_path(old["generationId"].as_str().unwrap())); + result["reusedGeneration"] = json!(true); + let _guard = sync::context_guard(); + write_json(receipt, result)?; + return Ok(()); + } let root = receipt.with_file_name("generations"); fs::create_dir_all(&root).map_err(|error| format!("无法创建成品目录:{error}"))?; let generation = tempfile::Builder::new().prefix("generation-").tempdir_in(&root) @@ -4179,7 +4255,8 @@ fn export_product_stage_with_source( &scoped } else { state }; let mut result = json!({"doc":doc,"workspaceId":state["id"],"outputId":component,"variantId":variant_id, - "canvasRevision":input["baseRevision"],"documentKey":input["documentKey"],"operationId":input["operationId"],"files":[]}); + "canvasRevision":input["baseRevision"],"documentKey":input["documentKey"],"operationId":input["operationId"],"files":[], + "allOutputsCompleted":false,"missingSlots":[],"unreviewedScreens":[],"deliveryStatus":"failed"}); if let Some(version) = state["template"]["xiaoyi"]["knowledgeVersion"].as_str().or_else(|| input["knowledgeVersion"].as_str()) { result["knowledgeVersion"] = json!(version); } @@ -4253,7 +4330,8 @@ fn export_product_stage_with_source( "outputId":component,"variantId":variant_id,"field":field,"reason":"图位尚未采用图片" })).collect(); result["knownIssues"] = json!(missing_issues); - result["allOutputsCompleted"] = json!(false); + result["missingSlots"] = json!(missing); + set_delivery_status(&mut result, false); if !missing.is_empty() { result["missingImages"] = json!(missing); } @@ -4316,6 +4394,10 @@ fn export_product_stage_with_source( } screens } else { Vec::new() }; + let reviewed = &journal["screenReviews"]; + result["unreviewedScreens"] = json!((0..screens.len()).filter(|index| + !reviewed.as_array().into_iter().flatten().any(|review| review[0].as_u64() == Some(*index as u64))) + .map(|index| index + 1).collect::>()); let creation = creation::load(dir)?; result["briefRevision"] = creation["revision"].clone(); result["stageInputHash"] = json!(stage_input_hash(state, &creation, &variant_id, component)?); @@ -4329,10 +4411,13 @@ fn export_product_stage_with_source( let output = stage["outputId"].as_str().unwrap_or_default(); (variant == variant_id && output == component) || published_receipt(&receipt_path(dir, variant, output)).is_ok_and(|receipt| - receipt["missingImages"].as_array().is_none_or(Vec::is_empty)) + receipt["missingImages"].as_array().is_none_or(Vec::is_empty) + && receipt["unreviewedScreens"].as_array().is_none_or(Vec::is_empty)) }); - result["allOutputsCompleted"] = json!(all_filled && remaining_stages(dir, state, &result["briefRevision"], false) - .iter().all(|stage| stage["variantId"] == variant_id && stage["outputId"] == component)); + let reviewed = result["unreviewedScreens"].as_array().is_some_and(Vec::is_empty); + let complete = reviewed && all_filled && remaining_stages(dir, state, &result["briefRevision"], false) + .iter().all(|stage| stage["variantId"] == variant_id && stage["outputId"] == component); + set_delivery_status(&mut result, complete); let blank_reasons: serde_json::Map = journal["copyEvidence"].as_object().into_iter().flatten() .filter(|(_, row)| row["text"].as_str().is_some_and(|text| text.trim().is_empty())) .filter_map(|(id, row)| { @@ -4347,14 +4432,14 @@ fn export_product_stage_with_source( if remaining.is_empty() { remaining = remaining_stages(dir, state, &result["briefRevision"], true); } - result["allOutputsCompleted"] = json!(remaining.is_empty() && all_filled); - if remaining.is_empty() && all_filled + set_delivery_status(&mut result, remaining.is_empty() && all_filled && reviewed); + if result["allOutputsCompleted"] == true && let Some(goal) = input["piGoalId"].as_str() && let Err(error) = super::pi_runtime::record_product_export(dir, scope, goal) { result["goalSyncError"] = json!(error); } - result["productionDelivery"] = json!({"state":if remaining.is_empty() && all_filled {"completed"} else {"in_progress"}, + result["productionDelivery"] = json!({"state":if result["allOutputsCompleted"] == true {"completed"} else {"in_progress"}, "outputState":"exported","outputId":component,"generationId":result["generationId"]}); result["productionStages"] = json!(runnable_stages(state, remaining)); Ok(result) @@ -4842,8 +4927,14 @@ impl Backend { if let Some((_, presentation)) = production { input["productionImage"] = presentation.clone(); } - let call = self.image_job(None, &input, false, events, ctx); - let dispatch_error = |error, backend: &Self| BridgeFailure::new("image_request_failed", false, backend.image_dispatch_may_have_started(doc, &id), error); + let call = self.dispatch_frozen_image(&input, events, ctx, cancellation); + let dispatch_error = |error, backend: &Self| { + let dispatched = backend.image_dispatch_may_have_started(doc, &id); + let category = if !dispatched && check_image_dispatch_cancelled(cancellation).is_err() { + "cancelled" + } else { "image_request_failed" }; + BridgeFailure::new(category, false, dispatched, error) + }; let result = self.settle_image_candidate(dir, doc, &id, slot, call, events, ctx, !admitted) .map_err(|error| dispatch_error(error, self)) .and_then(|(mut receipt, failure)| { @@ -4920,7 +5011,8 @@ impl Backend { return Err("原候选仍在处理".into()); }; let file = dir.join("image-jobs").join(&id).join("task.json"); - let task = read_json(&file)?; + let mut task = read_json(&file)?; + super::images::reopen_ambiguous_expiry(&mut task); if task["id"] != id || task["slotBinding"] != record["binding"] || task["outputScope"] != input["outputId"] || task["slotBinding"]["detailBatch"] != true || task["origin"] != self.origin || task["accountScope"] != self.scope() || task["localProjectId"] != input["project"] @@ -4932,7 +5024,8 @@ impl Backend { self.recover_archived_image(input, &check)?; } check()?; - let journal = read_json(&file)?; + let mut journal = read_json(&file)?; + super::images::reopen_ambiguous_expiry(&mut journal); let status = if journal["phase"] == "applied" { json!("complete") } else { journal["phase"].clone() }; let mut receipt = json!({"id":id,"status":status,"variantId":input["variantId"]}); if matches!(status.as_str(), Some("complete" | "failed" | "expired")) { @@ -5629,6 +5722,33 @@ mod screen_tests; mod tests { use super::*; + #[test] + fn product_generation_reuses_complete_files_and_regenerates_after_damage_or_source_change() { + use photocraft_doc::{ColorMode, SampleType, Size}; + let temp = tempfile::tempdir().unwrap(); + let receipt = temp.path().join("main_images.json"); + let doc = Document::new("输出", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let regions = [(0, 8, 8)]; + let metadata = || json!({"outputId":"main_images","workingSha256":"working","stageInputHash":"inputs"}); + let mut initial = metadata(); + publish_product_generation(&receipt, &doc, &json!(1), &mut initial, ®ions, &[]).unwrap(); + let mut unchanged = metadata(); + unchanged["unreviewedScreens"] = json!([]); + publish_product_generation(&receipt, &doc, &json!(1), &mut unchanged, ®ions, &[]).unwrap(); + assert_eq!(initial["generationId"], unchanged["generationId"]); + assert_eq!(published_receipt(&receipt).unwrap()["unreviewedScreens"], json!([])); + let manifest = receipt.with_file_name(manifest_path(initial["generationId"].as_str().unwrap())); + assert!(read_json(&manifest).unwrap()["unreviewedScreens"].is_null()); + fs::write(unchanged["files"][0]["path"].as_str().unwrap(), b"broken").unwrap(); + let mut repaired = metadata(); + publish_product_generation(&receipt, &doc, &json!(1), &mut repaired, ®ions, &[]).unwrap(); + assert_ne!(repaired["generationId"], unchanged["generationId"]); + let mut changed = metadata(); + changed["workingSha256"] = json!("changed"); + publish_product_generation(&receipt, &doc, &json!(2), &mut changed, ®ions, &[]).unwrap(); + assert_ne!(changed["generationId"], repaired["generationId"]); + } + #[test] fn pending_production_reads_legacy_tasks_on_their_original_output() { let fixture = fixture(); @@ -8082,11 +8202,8 @@ mod tests { super::super::images::settle_unresolved(&mut task, 100); super::super::images::settle_unresolved(&mut task, 280); write_json(&file, &task).unwrap(); - let receipt = backend.detail_archive(doc, &target, &events, &ctx).unwrap(); - assert_eq!(receipt["id"], id); - assert_eq!(receipt["status"], "expired"); - assert_eq!(receipt["resultExpiry"], task["resultExpiry"]); - assert!(pending_summary(&dir).unwrap().is_empty()); + assert_eq!(task["phase"], "unknown"); + assert!(!pending_summary(&dir).unwrap().is_empty()); assert_eq!(read_candidate(&dir, id).unwrap(), archived_record); assert_eq!(read_json(&file).unwrap(), task); assert!(receiver.try_recv().is_err()); @@ -8321,46 +8438,27 @@ mod tests { } #[test] - fn lookup_not_found_releases_the_slot_without_charging_a_generation_attempt() { - let fixture = fixture(); - let original = candidate(&fixture.dir, "dispatched"); - let next = candidate(&fixture.dir, "dispatched"); - reserve(&fixture.dir, load(&fixture.dir).unwrap(), &original).unwrap(); - let mut task = json!({"id":original["id"],"slotBinding":original["binding"],"phase":"unknown"}); - let pending = reconcile_candidate(&fixture.dir, &task).unwrap(); - assert!(generation_was_dispatched(&pending, Some(&task))); - assert!(reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).is_err()); - - task["phase"] = json!("expired"); - task["resultExpiry"] = json!({"source":"request_not_found","httpStatus":404}); - let record = reconcile_candidate(&fixture.dir, &task).unwrap(); - assert!(!generation_was_dispatched(&record, Some(&task))); - assert!(!generation_was_dispatched(&record, None)); - assert!(pending_summary(&fixture.dir).unwrap().is_empty()); - reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).unwrap(); - } - - #[test] - fn unresolved_original_releases_its_slot_once_the_recovery_budget_is_spent() { - let fixture = fixture(); - let original = candidate(&fixture.dir, "dispatched"); - let next = candidate(&fixture.dir, "dispatched"); - reserve(&fixture.dir, load(&fixture.dir).unwrap(), &original).unwrap(); - let request_id = Uuid::new_v4().to_string(); - let mut task = json!({"id":original["id"],"slotBinding":original["binding"],"phase":"unknown","requestId":request_id}); - let first = 1_795_781_555; - super::super::images::settle_unresolved(&mut task, first); - reconcile_candidate(&fixture.dir, &task).unwrap(); - assert!(reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).is_err(), "inside its budget the original keeps the slot"); - super::super::images::settle_unresolved(&mut task, first + super::super::images::IMAGE_REQUEST_TIMEOUT.as_secs()); - assert_eq!(reconcile_candidate(&fixture.dir, &task).unwrap()["phase"], "expired"); - assert!(pending_summary(&fixture.dir).unwrap().is_empty()); - reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).unwrap(); - let receipt = candidate_receipt(&read_candidate(&fixture.dir, original["id"].as_str().unwrap()).unwrap()); - assert_eq!(receipt["status"], "expired"); - assert_eq!(receipt["retryable"], false); - assert_eq!(receipt["requestId"], request_id); - assert_eq!(receipt["resultExpiry"]["source"], "unresolved"); + fn ambiguous_original_keeps_its_slot_and_generation_attempt() { + for source in ["unresolved", "request_not_found"] { + let fixture = fixture(); + let original = candidate(&fixture.dir, "dispatched"); + let next = candidate(&fixture.dir, "dispatched"); + reserve(&fixture.dir, load(&fixture.dir).unwrap(), &original).unwrap(); + let id = original["id"].as_str().unwrap(); + let mut expired = original.clone(); + expired["phase"] = json!("expired"); + expired["resultExpiry"] = json!({"source":source}); + let path = candidate_path(&fixture.dir, id).unwrap(); + write_json(&path, &expired).unwrap(); + let mut task = json!({"id":id,"phase":"expired","slotBinding":original["binding"], + "resultExpiry":expired["resultExpiry"]}); + write_json(&path.with_file_name("task.json"), &task).unwrap(); + super::super::images::reopen_ambiguous_expiry(&mut task); + let record = read_candidate(&fixture.dir, id).unwrap(); + assert_eq!(record["phase"], "unknown"); + assert!(generation_was_dispatched(&record, Some(&task))); + assert!(reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).is_err()); + } } #[test] diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs index ab460a53..e54a2ced 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs @@ -138,7 +138,10 @@ pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output let receipt = canvas_workspace::receipt_path(project, variant, component); let manifest = receipt.with_file_name(canvas_workspace::manifest_path(id)); let generation = manifest.parent().ok_or("成品版本目录无效")?; - let data = read_json(&manifest)?; + let data = match canvas_workspace::published_receipt(&receipt) { + Ok(current) if current["generationId"] == id && current["validation"]["mode"] == "full" => current, + _ => read_json(&manifest)?, + }; if data["workspaceId"] != input["workspaceId"] || data["outputId"] != component || data["variantId"] != variant @@ -210,6 +213,7 @@ pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output Ok(json!({"variantId":variant,"outputId":component,"generationId":id, "unverifiedCopy":data["unverifiedCopy"],"unverifiedFacts":data["unverifiedFacts"].as_array().map_or(&[][..], Vec::as_slice), "slotCoverage":data["slotCoverage"],"missingImages":data["missingImages"],"missingVisibleText":data["missingVisibleText"], + "missingSlots":data.get("missingSlots").unwrap_or(&data["missingImages"]),"unreviewedScreens":data["unreviewedScreens"], "visibleSampleLayer":data["visibleSampleLayer"],"unapprovedFixedTextLayer":data["unapprovedFixedTextLayer"], "adoptedImages":adopted,"fidelityReport":data["fidelityReport"],"reopenVerification":data["reopenVerification"]})) } @@ -294,7 +298,9 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu .ok() .filter(|saved| saved["deliveryId"] == delivery_id) .map(|saved| json!({"state":"bundle_saved","path":target,"allOutputsCompleted":saved["allOutputsCompleted"],"completedOutputs":saved["completedOutputs"],"counts":saved["counts"], - "slotCoverage":saved["slotCoverage"],"deliveryReason":saved["deliveryReason"],"missingOutputs":saved["missingOutputs"],"missing":saved["missing"],"knownIssues":saved["knownIssues"],"unverifiedCopy":saved["unverifiedCopy"]})) + "slotCoverage":saved["slotCoverage"],"missingSlots":saved["missingSlots"].as_array().map_or(&[][..], Vec::as_slice), + "unreviewedScreens":saved["unreviewedScreens"].as_array().map_or(&[][..], Vec::as_slice), + "deliveryStatus":if saved["allOutputsCompleted"] == true { "completed" } else { "partial_delivered" },"deliveryReason":saved["deliveryReason"],"missingOutputs":saved["missingOutputs"],"missing":saved["missing"],"knownIssues":saved["knownIssues"],"unverifiedCopy":saved["unverifiedCopy"]})) }; // Recover a committed directory if the client lost the completion event. for number in 1.. { @@ -401,7 +407,13 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu let total = input["total"].as_u64().ok_or("本轮计划输出数无效")?; let missing_outputs = total.checked_sub(outputs.len() as u64).ok_or("本轮已导出数量超过计划")?; - let all_outputs_completed = missing_outputs == 0 && !missing_images + let output_items = |field: &str| output_evidence.iter().flat_map(|output| { + output[field].as_array().into_iter().flatten().map(move |item| + json!({"variantId":output["variantId"],"outputId":output["outputId"],"item":item})) + }).collect::>(); + let missing_slots = output_items("missingSlots"); + let unreviewed_screens = output_items("unreviewedScreens"); + let all_outputs_completed = missing_outputs == 0 && !missing_images && missing_slots.is_empty() && unreviewed_screens.is_empty() && (!input["deliveryReason"].is_string() || known_issues.is_empty()); let mut missing = Vec::new(); if missing_outputs > 0 @@ -423,10 +435,12 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu for category in files.iter().filter_map(|file| file["category"].as_str()) { *counts.entry(category.to_owned()).or_insert(0) += 1; } + let delivery_status = if all_outputs_completed { "completed" } else { "partial_delivered" }; let mut manifest = json!({"version":1,"deliveryId":delivery_id,"allOutputsCompleted":all_outputs_completed, "completedOutputs":outputs.len(),"totalOutputs":total,"missingOutputs":missing_outputs,"missing":missing, "counts":counts,"files":files,"deliveryReason":input["deliveryReason"],"knownIssues":known_issues,"unverifiedCopy":unverified_copy, - "slotCoverage":coverage,"outputEvidence":output_evidence}); + "slotCoverage":coverage,"outputEvidence":output_evidence,"deliveryStatus":delivery_status, + "missingSlots":missing_slots,"unreviewedScreens":unreviewed_screens}); if let Some(version) = input["knowledgeVersion"].as_str() { manifest["knowledgeVersion"] = json!(version); } @@ -447,7 +461,8 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu Ok(()) => { let flush = RealFs.sync_dir(&dir).err().map(|error| disk(error)); return Ok(json!({"state":"bundle_saved","path":target,"allOutputsCompleted":all_outputs_completed,"completedOutputs":outputs.len(), - "counts":counts,"slotCoverage":coverage,"missingOutputs":missing_outputs,"missing":missing, + "counts":counts,"slotCoverage":coverage,"deliveryStatus":delivery_status, + "missingSlots":missing_slots,"unreviewedScreens":unreviewed_screens,"missingOutputs":missing_outputs,"missing":missing, "deliveryReason":input["deliveryReason"],"knownIssues":known_issues,"unverifiedCopy":unverified_copy,"durabilityWarning":flush})); } Err(_) if target.exists() => continue, @@ -490,9 +505,12 @@ impl Backend { let (status, progress) = match &result { Ok(receipt) => { let status = if receipt["durabilityWarning"].is_string() { "unconfirmed" } else { "completed" }; - (status, json!({"counts":receipt["counts"],"allOutputsCompleted":receipt["allOutputsCompleted"]})) + (status, json!({"counts":receipt["counts"],"allOutputsCompleted":receipt["allOutputsCompleted"], + "deliveryStatus":receipt["deliveryStatus"],"missingSlots":receipt["missingSlots"], + "unreviewedScreens":receipt["unreviewedScreens"]})) } - Err(_) => ("failed", Value::Null), + Err(_) => ("failed", json!({"allOutputsCompleted":false,"deliveryStatus":"failed", + "missingSlots":[],"unreviewedScreens":[]})), }; pi_runtime::record_export_event(self, doc, &input, "export", "deliver_bundle", status, progress); result @@ -709,11 +727,19 @@ mod tests { let mut receipt = read_json(&generation).unwrap(); receipt["slotCoverage"] = json!({"adopted":0,"manual":1,"unadoptedWithCandidates":0,"empty":1,"skipped":1,"total":3}); receipt["missingImages"] = json!(["I02"]); + receipt["unreviewedScreens"] = json!([2]); receipt["imageSources"] = json!([{"origin":"human","kind":"local-import","slotId":"I01","sha256":"manual"}]); write_json(&generation, &receipt).unwrap(); let policy = transfer::Policy { scope:"owner", project:&local, chat:false }; let done = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap(); assert_eq!(done["allOutputsCompleted"], false); + assert_eq!(done["deliveryStatus"], "partial_delivered"); + assert_eq!(done["missingSlots"][0]["item"], "I02"); + assert_eq!(done["unreviewedScreens"][0]["item"], 2); + let recovered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap(); + for key in ["path", "deliveryStatus", "missingSlots", "unreviewedScreens"] { + assert_eq!(recovered[key], done[key]); + } assert_eq!(done["slotCoverage"]["manual"], 1); assert_eq!(done["slotCoverage"]["skipped"], 1); assert_eq!(done["knownIssues"][0]["field"], "I02"); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs index c3765379..5deca52d 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs @@ -226,7 +226,10 @@ fn read_reference_thumbnail(file: &Path) -> R> { pub(super) fn pending(dir: &Path) -> R { let file = dir.join("image-task.json"); - Ok(file.exists() && matches!(read_json(&file)?["phase"].as_str(), Some("dispatched" | "unknown" | "running"))) + if !file.exists() { return Ok(false); } + let mut task = read_json(&file)?; + reopen_ambiguous_expiry(&mut task); + Ok(matches!(task["phase"].as_str(), Some("dispatched" | "unknown" | "running"))) } /// The only transport continuation for a new image POST. Canvas-first admission /// is an exact durable v2 binding, never a global exemption from the old plan. @@ -333,7 +336,8 @@ fn job_save_locked(dir: &Path, t: &Value, current_only: bool) -> R<()> { let mut settled = t.clone(); transfer::redact(&mut settled); if archive.exists() { - let existing = read_json(&archive)?; + let mut existing = read_json(&archive)?; + reopen_ambiguous_expiry(&mut existing); if existing["id"] != t["id"] || existing["keyFingerprint"].is_string() && existing["keyFingerprint"] != t["keyFingerprint"] || existing["requestId"].is_string() && existing["requestId"] != t["requestId"] @@ -751,37 +755,76 @@ fn observed_wait(kind: &str, code: u16, body: &Value) -> Option { } } -/// An `unresolved` lookup has no confirmed result. Once it stays unresolved for -/// the whole recovery budget, the original is settled as expired and its slot -/// may prepare a new request. The first observation is kept durably, so every -/// recovery path measures the same budget. +/// A lookup window can end while a charged request is still pending. pub(super) fn settle_unresolved(task: &mut Value, now: u64) { - let since = match task["unresolvedSince"].as_u64() { - Some(since) => since, - None => { - task["unresolvedSince"] = json!(now); - now - } - }; - if now.saturating_sub(since) >= IMAGE_REQUEST_TIMEOUT.as_secs() { - task["phase"] = json!("expired"); - task["resultExpiry"] = json!({"source":"unresolved","unresolvedSince":since,"observedAt":now, - "requestId":task["requestId"],"upstreamTaskId":task["upstreamTaskId"]}); - task["message"] = json!("原请求在恢复预算内始终未确认结果(unresolved),按已过期处理;可为此图位准备新请求"); + if task["unresolvedSince"].is_null() { + task["unresolvedSince"] = json!(now); } } fn settle_request_not_found(task: &mut Value, now: u64) { - let Some(since) = task["requestNotFoundSince"].as_u64() else { return }; - if now.saturating_sub(since) >= IMAGE_REQUEST_TIMEOUT.as_secs() { - task["phase"] = json!("expired"); - task["resultExpiry"] = json!({"source":"request_not_found","httpStatus":404, - "requestNotFoundSince":since,"observedAt":now, - "requestId":task["requestId"],"upstreamTaskId":task["upstreamTaskId"]}); - task["message"] = json!("网关没有这笔请求的记录,按未发起处理;可为此图位准备新请求"); + if task["requestNotFoundSince"].is_null() { + task["requestNotFoundSince"] = json!(now); } } +/// Older clients expired ambiguous requests on a local timer. They still +/// require a GET against the original idempotency key. +pub(super) fn reopen_ambiguous_expiry(task: &mut Value) { + if task["phase"] == "expired" + && matches!(task["resultExpiry"]["source"].as_str(), Some("unresolved" | "request_not_found")) + { + task["phase"] = json!("unknown"); + task["recoveryWait"] = task["resultExpiry"]["source"].clone(); + task["resultExpiry"] = Value::Null; + task["message"] = json!("原请求仍待核查;不会重发"); + } +} + +static IMAGE_WORK: (std::sync::Mutex, std::sync::Condvar) = + (std::sync::Mutex::new(0), std::sync::Condvar::new()); + +struct ImageWorkPermit; +impl ImageWorkPermit { + fn acquire() -> Self { + let mut active = IMAGE_WORK.1.wait_while(IMAGE_WORK.0.lock().expect("image work quota"), |count| *count >= 3) + .expect("image work quota"); + *active += 1; + Self + } +} +impl Drop for ImageWorkPermit { + fn drop(&mut self) { + *IMAGE_WORK.0.lock().expect("image work quota") -= 1; + IMAGE_WORK.1.notify_one(); + } +} + +thread_local! { + static RUN_CANCELLATION: std::cell::RefCell>> = const { + std::cell::RefCell::new(None) + }; +} + +pub(super) fn with_run_cancellation(token: Arc, action: impl FnOnce() -> T) -> T { + struct Reset(Option>); + impl Drop for Reset { + fn drop(&mut self) { RUN_CANCELLATION.with(|slot| slot.replace(self.0.take())); } + } + let _reset = Reset(RUN_CANCELLATION.with(|slot| slot.replace(Some(token)))); + action() +} + +fn claim_image_dispatch(cancellation: Option<&std::sync::atomic::AtomicBool>) -> R<()> { + use std::sync::atomic::Ordering::SeqCst; + // The compare-exchange orders the claim against the run's cancellation + // store. After the claim the original stays recoverable even on a timeout. + if cancellation.is_some_and(|token| token.compare_exchange(false, false, SeqCst, SeqCst).is_err()) { + return Err("原制作回合已停止,生图未派发".into()); + } + Ok(()) +} + pub(super) fn retry_original_queries( mut query: impl FnMut(Duration) -> R, mut wait: impl FnMut(Duration), @@ -811,6 +854,11 @@ pub(super) fn retry_original_queries( } pub(super) fn public(t: &Value, doc: u64, account: &Value, origin: &str) -> Value { let mut receipt = json!({"doc":doc,"revision":t["revision"],"accountId":account["id"],"origin":origin,"projectId":t["localProjectId"],"artifactSha256":t["sha256"],"image":true,"isSlotCandidate":t["slotBinding"].is_object(),"taskId":t["id"],"requestId":t["requestId"],"upstreamTaskId":t["upstreamTaskId"],"unknown":matches!(t["phase"].as_str(),Some("dispatched"|"unknown"|"running")),"phase":t["phase"],"path":t["artifact"],"target":t["target"],"mode":t["mode"],"referenceCount":t["references"].as_array().map_or(0,Vec::len),"modelId":t["modelId"],"reply":t["message"],"center":t["center"]}); + if receipt["unknown"] == true { + receipt["dispatchState"] = json!("outcome_unknown"); + receipt["originalRequestId"] = t.get("requestId").filter(|id| id.is_string()) + .unwrap_or(&t["id"]).clone(); + } if t["phase"] == "expired" { receipt["retryable"] = json!(false); receipt["resultExpiry"] = t["resultExpiry"].clone(); @@ -965,17 +1013,24 @@ impl Backend { pub(super) fn image_job_with_scene(&mut self, doc: Option>, input: &Value, recover: bool, tx: &mpsc::Sender, ctx: &egui::Context, scene: Option<(super::scene_composite::Recipe, Vec)>) -> R { - self.run_image_job(doc, input, recover, scene, Some((tx, ctx)), None) + self.run_image_job(doc, input, recover, scene, Some((tx, ctx)), None, None) + } + + pub(super) fn dispatch_frozen_image(&mut self, input: &Value, tx: &mpsc::Sender, + ctx: &egui::Context, cancellation: Option<&std::sync::atomic::AtomicBool>) -> R { + self.run_image_job(None, input, false, None, Some((tx, ctx)), None, cancellation) } pub(super) fn recover_archived_image(&mut self, input: &Value, check: &dyn Fn() -> R<()>) -> R { - self.run_image_job(None, input, true, None, None, Some(check)) + self.run_image_job(None, input, true, None, None, Some(check), None) } fn run_image_job(&mut self, doc: Option>, input: &Value, recover: bool, scene: Option<(super::scene_composite::Recipe, Vec)>, progress: Option<(&mpsc::Sender, &egui::Context)>, - archive_check: Option<&dyn Fn() -> R<()>>) -> R { + archive_check: Option<&dyn Fn() -> R<()>>, + cancellation: Option<&std::sync::atomic::AtomicBool>) -> R { + let _permit = ImageWorkPermit::acquire(); let check = || archive_check.map_or(Ok(()), |check| check()); check()?; let deadline = if recover { input["recoveryBudgetMs"].as_u64().map(|ms| Instant::now() + Duration::from_millis(ms.min(180_000))) } else { None }; @@ -1157,6 +1212,7 @@ impl Backend { if t["keyFingerprint"] != hash(key) { return Err("请切回原个人Key,只读核查原请求;不会重发".into()); } + if recover { reopen_ambiguous_expiry(&mut t); } if recover && bind_recovery_request_id(&mut t, input)? { // Persist only the supplied original identity before the GET-only path. persist(&t)?; @@ -1184,6 +1240,7 @@ impl Backend { }; // The structured reason this attempt leaves the original pending, if any. let wait = std::cell::Cell::new(None::); + let mut dispatch_claimed = false; let result = (|| -> R<()> { let raw_file = taskdir.join("response.json"); let image_file = taskdir.join("response-image.bin"); @@ -1309,9 +1366,12 @@ impl Backend { let response = slot_post(&dir, &t, || { if self.exiting() { return Err("客户端正在退出,未提交生图请求".into()); } self.check_dispatch()?; - progress("98k 正在生成图片…", true); + claim_image_dispatch(cancellation)?; + RUN_CANCELLATION.with(|slot| claim_image_dispatch(slot.borrow().as_deref()))?; + dispatch_claimed = true; client.execute(request).map_err(|error| stream::transport_error(&error)) })?; + progress("98k 正在生成图片…", true); if let Some(seconds) = response.headers().get(reqwest::header::RETRY_AFTER).and_then(|value| value.to_str().ok()).and_then(|value| value.parse::().ok()) { t["retryAfterSeconds"] = json!(seconds); job_save(&dir, &t)?; @@ -1453,6 +1513,14 @@ impl Backend { })(); match result { Err(reason) => { + if !recover && !dispatch_claimed && t["phase"] == "dispatched" { + t["phase"] = json!("prepared"); + t["notDispatched"] = json!(true); + t["dispatchState"] = json!("not_dispatched"); + t["message"] = json!(reason); + persist(&t)?; + return Err(reason); + } if t["phase"] == "prepared" { return Err(reason); } @@ -2652,9 +2720,8 @@ mod tests { panic!("a repeated missing lookup must keep the original timestamp"); }).is_err()); settle_request_not_found(&mut stored, deadline); - assert_eq!(stored["phase"], "expired"); - assert_eq!(stored["resultExpiry"]["source"], "request_not_found"); - assert_eq!(stored["resultExpiry"]["requestNotFoundSince"], first); + assert_eq!(stored["phase"], "unknown"); + assert_eq!(stored["requestNotFoundSince"], first); } #[test] @@ -2737,8 +2804,7 @@ mod tests { assert!(outcome.is_err()); let since = task["requestNotFoundSince"].as_u64().unwrap(); settle_request_not_found(&mut task, since + IMAGE_REQUEST_TIMEOUT.as_secs()); - assert_eq!(task["phase"], "expired"); - assert_eq!(task["resultExpiry"]["source"], "request_not_found"); + assert_eq!(task["phase"], "unknown"); } _ => assert!(outcome.is_err()), } @@ -2857,74 +2923,47 @@ mod tests { } #[test] - fn unresolved_original_expires_once_it_outlasts_the_recovery_budget() { - let dir = tempfile::tempdir().unwrap(); - write_json(&dir.path().join("context.json"), &json!({})).unwrap(); - let mut task = unknown_image(); - task["requestId"] = json!(FAILURE_REQUEST); - let original = task.clone(); - let first = 1_795_781_555; - let budget = IMAGE_REQUEST_TIMEOUT.as_secs(); - settle_unresolved(&mut task, first); - settle_unresolved(&mut task, first + budget - 1); - assert_eq!(task["phase"], "unknown", "the budget counts from the first unresolved observation"); - assert_eq!(task["unresolvedSince"], first); - job_save(dir.path(), &task).unwrap(); - assert!(pending(dir.path()).unwrap(), "an unresolved original inside its budget is still checked by its original ID"); - - settle_unresolved(&mut task, first + budget); - assert_eq!(task["phase"], "expired"); - assert_eq!(task["resultExpiry"], json!({"source":"unresolved","unresolvedSince":first,"observedAt":first + budget, - "requestId":FAILURE_REQUEST,"upstreamTaskId":null})); - for key in ["id", "requestId", "slotBinding", "prompt", "references", "modelId", "keyFingerprint"] { - assert_eq!(task[key], original[key], "expiry changed {key}"); + fn recovery_budget_preserves_original_and_historical_uncertainty() { + for source in ["unresolved", "request_not_found"] { + let mut task = unknown_image(); + let original = task["id"].clone(); + task["phase"] = json!("expired"); + task["resultExpiry"] = json!({"source":source}); + reopen_ambiguous_expiry(&mut task); + let elapsed = std::cell::Cell::new(Duration::ZERO); + let receipt = retry_original_queries( + |_| { + settle_unresolved(&mut task, elapsed.get().as_secs()); + Ok(public(&task, 1, &json!({}), "origin")) + }, + |delay| elapsed.set(elapsed.get() + delay), + || elapsed.get(), + ).unwrap(); + assert_eq!(elapsed.get(), IMAGE_REQUEST_TIMEOUT); + assert_eq!(receipt["originalRequestId"], original); + assert_eq!(receipt["phase"], "unknown"); + assert!(settled_recovery(&task, 1, &json!({}), "origin").is_none()); } - job_save(dir.path(), &task).unwrap(); - assert!(!pending(dir.path()).unwrap()); - let mut late = original.clone(); - late["message"] = json!("late unresolved GET"); - job_save(dir.path(), &late).unwrap(); - let stored = read_json(&dir.path().join("image-task.json")).unwrap(); - assert_eq!(stored, task, "a late unknown copy cannot reopen the expired original"); - let receipt = settled_recovery(&stored, 1, &json!({"id":"owner"}), "origin").unwrap(); - assert_eq!(receipt["phase"], "expired"); - assert_eq!(receipt["unknown"], false); - assert_eq!(receipt["retryable"], false); - assert_eq!(receipt["resultExpiry"]["source"], "unresolved"); - assert!(receipt.get("recoveryWait").is_none()); } #[test] - fn a_later_recovery_round_settles_the_original_that_stayed_unresolved_for_the_budget() { - // The first round starts at the first unresolved lookup and ends with the - // original still unknown; the next round finds the budget spent. - let first = 1_795_781_555; - let clock = std::cell::Cell::new(Duration::ZERO); - let mut task = unknown_image(); - task["requestId"] = json!(FAILURE_REQUEST); - let first_round = retry_original_queries( - |_| { - settle_unresolved(&mut task, first + clock.get().as_secs()); - Ok(json!({"phase":task["phase"],"recoveryWait":"unresolved"})) - }, - |delay| clock.set(clock.get() + delay), - || clock.get(), - ); - assert_eq!(first_round.unwrap()["phase"], "unknown"); - assert_eq!(clock.get(), IMAGE_REQUEST_TIMEOUT); - assert_eq!(task["unresolvedSince"], first); - clock.set(IMAGE_REQUEST_TIMEOUT + Duration::from_secs(8)); - let settled = retry_original_queries( - |_| { - settle_unresolved(&mut task, first + clock.get().as_secs()); - Ok(json!({"phase":task["phase"],"recoveryWait":"unresolved"})) - }, - |_| panic!("an expired original is not polled again"), - || Duration::ZERO, - ).unwrap(); - assert_eq!(settled["phase"], "expired"); - assert_eq!(task["resultExpiry"]["source"], "unresolved"); + fn stop_before_the_slot_post_claim_skips_transport() { + use std::sync::atomic::{AtomicBool, Ordering}; + let stop = AtomicBool::new(false); + let task = json!({}); + let calls = std::cell::Cell::new(0); + let post = || { + claim_image_dispatch(Some(&stop))?; + calls.set(calls.get() + 1); + Ok(()) + }; + let dir = tempfile::tempdir().unwrap(); + slot_post(dir.path(), &task, post).unwrap(); + stop.store(true, Ordering::SeqCst); + assert!(slot_post(dir.path(), &task, post).is_err()); + assert_eq!(calls.get(), 1); } + #[test] fn image_recovery_binds_original_request_without_changing_task_or_phase() { let dir = std::env::temp_dir().join(format!("jiansun-image-bind-{}", Uuid::new_v4())); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_models.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_models.rs index fe4e5e31..12a7e651 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_models.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_models.rs @@ -100,14 +100,14 @@ fn model_with_candidates(id: &str, key: Option<&str>, candidates: Vec, fo Some(model) } -fn add_openai_alternate(candidates: &mut Vec, image_input: bool) { - let chat = candidates.iter().any(|candidate| candidate["protocol"] == "openai-chat"); - let responses = candidates.iter().any(|candidate| candidate["protocol"] == "openai-responses"); - if chat && !responses { - candidates.push(standard_candidate("/v1/responses", "openai-responses", image_input)); - } else if responses && !chat { - candidates.push(standard_candidate("/v1/chat/completions", "openai-chat", image_input)); +pub(super) fn google_text_path(path: &str, id: &str) -> Option { + if id.is_empty() || !id.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte)) { + return None; } + let path = path.strip_suffix("?alt=sse").unwrap_or(path); + let model = path.strip_prefix("/v1beta/models/")?.strip_suffix(":streamGenerateContent")?; + matches!(model, "{model}" | "{model_id}").then_some(()).or_else(|| (model == id).then_some(()))?; + Some(format!("/v1beta/models/{id}:streamGenerateContent?alt=sse")) } fn text_protocol(invocation: &Value, responses: bool) -> Option<&'static str> { @@ -116,7 +116,14 @@ fn text_protocol(invocation: &Value, responses: bool) -> Option<&'static str> { } let auth = &invocation["authentication"]; let bearer = auth["type"] == "bearer" && auth["header"] == "Authorization"; - let (protocol, input) = match invocation["path"].as_str()? { + let path = invocation["path"].as_str()?; + if responses && path.starts_with("/v1beta/models/") && path.split('?').next()?.ends_with(":streamGenerateContent") + && auth["type"] == "api_key" && auth["header"].as_str().is_some_and(|header| header.eq_ignore_ascii_case("x-goog-api-key")) + && invocation["input_schema"]["properties"]["contents"].is_object() + { + return Some("google-generative-ai"); + } + let (protocol, input) = match path { "/v1/chat/completions" if bearer => ("openai-chat", "messages"), "/v1/messages" if auth["type"] == "api_key" && auth["header"] == "X-Api-Key" => ("anthropic-messages", "messages"), "/v1/responses" if responses && bearer => ("openai-responses", "input"), @@ -194,15 +201,10 @@ pub(super) fn text_model(row: &Value, key: Option<&str>) -> Option { pub(super) fn text_model_for(row: &Value, key: Option<&str>, responses: bool) -> Option { let id = row["id"].as_str().filter(|id| !id.is_empty() && id.len() <= 200)?; if row["catalogFormat"] == "newapi-pricing" { - let mut candidates: Vec<_> = row["endpoints"].as_array()?.iter().filter_map(|path| { + let candidates = row["endpoints"].as_array()?.iter().filter_map(|path| { let path = path.as_str()?; Some(standard_candidate(path, chat_protocol(path, responses)?, true)) }).collect(); - if responses { - add_openai_alternate(&mut candidates, true); - } else if candidates.is_empty() && row["endpoints"].as_array()?.iter().any(|path| path == "/v1/responses") { - candidates.push(standard_candidate("/v1/chat/completions", "openai-chat", true)); - } return model_with_candidates(id, key, candidates, "newapi-pricing"); } if row["status"] != "available" || row["available"] != true @@ -231,31 +233,18 @@ pub(super) fn text_model_for(row: &Value, key: Option<&str>, responses: bool) -> .then_with(|| preferred(b).cmp(&preferred(a))) }); let mut candidates: Vec<_> = routes.into_iter().filter_map(|(route, protocol)| { - typed_candidate(route, protocol, route["id"].as_str(), image_input) + typed_candidate(route, id, protocol, route["id"].as_str(), image_input) }).collect(); if candidates.is_empty() && row["service_offers"].is_null() && allows_streaming_tools(row) { - candidates.push(typed_candidate(row, text_protocol(&row["invocation"], responses)?, None, image_input)?); - } - let mut unpinned = Vec::new(); - for candidate in &candidates { - if candidate["headers"] != json!({}) && !unpinned.iter().any(|other: &Value| other["path"] == candidate["path"]) { - let mut fallback = candidate.clone(); - fallback["routeId"] = Value::Null; - fallback["headers"] = json!({}); - fallback["productionVerified"] = json!(false); - unpinned.push(fallback); - } - } - candidates.extend(unpinned); - if responses { - let image_ready = candidates.iter().any(|candidate| candidate["supportsImageInput"] == true); - add_openai_alternate(&mut candidates, image_ready); + candidates.push(typed_candidate(row, id, text_protocol(&row["invocation"], responses)?, None, image_input)?); } model_with_candidates(id, key, candidates, "v2") } -fn typed_candidate(contract: &Value, protocol: &str, route_id: Option<&str>, image_input: bool) -> Option { - let path = contract["invocation"]["path"].as_str()?; +fn typed_candidate(contract: &Value, id: &str, protocol: &str, route_id: Option<&str>, image_input: bool) -> Option { + let declared_path = contract["invocation"]["path"].as_str()?; + let path = if protocol == "google-generative-ai" { google_text_path(declared_path, id)? } + else { declared_path.to_owned() }; let properties = &contract["invocation"]["input_schema"]["properties"]; let (reasoning, reasoning_efforts) = reasoning_options(protocol, properties); let tool_choice = &properties["tool_choice"]; @@ -431,6 +420,7 @@ pub(super) fn apply_pi_capacity(model: &mut Value, catalog: &[Value]) { Some("openai-chat") => "openai-completions", Some("openai-responses") => "openai-responses", Some("anthropic-messages") => "anthropic-messages", + Some("google-generative-ai") => "google-generative-ai", _ => "", }; let matching_api = || matches().filter(|entry| { @@ -472,6 +462,26 @@ pub(super) fn apply_pi_capacity(model: &mut Value, catalog: &[Value]) { mod tests { use super::*; + #[test] + fn catalog_uses_only_the_declared_streaming_protocol_and_route() { + let route = "0dc244a0-c68a-4756-a785-ec6a1721c1d4"; + let row = json!({"id":"gemini-example","available":true,"status":"available","modality":"multimodal", + "input_modes":["image"],"service_offers":[{"route_options":[{"id":route,"available":true, + "invocation":{"method":"POST","path":"/v1beta/models/{model}:streamGenerateContent","content_type":"application/json", + "authentication":{"type":"api_key","header":"X-Goog-Api-Key"}, + "headers":{"X-Relay-Route-Option":route},"input_schema":{"properties":{"contents":{"type":"array"}}}}}]}]}); + let model = text_model(&row, None).unwrap(); + assert_eq!(model["protocol"], "google-generative-ai"); + assert_eq!(model["path"], "/v1beta/models/gemini-example:streamGenerateContent?alt=sse"); + assert_eq!(model["routeId"], route); + assert_eq!(model["candidates"].as_array().unwrap().len(), 1); + assert!(google_text_path("/v1beta/models/other:streamGenerateContent", "gemini-example").is_none()); + let legacy = json!({"id":"chat","catalogFormat":"newapi-pricing","endpoints":["/v1/chat/completions"]}); + let model = text_model(&legacy, None).unwrap(); + assert_eq!(model["candidates"].as_array().unwrap().len(), 1); + assert_eq!(model["protocol"], "openai-chat"); + } + #[test] fn pricing_uses_key_endpoints_and_keeps_private_models() { let pricing = json!({"success":true,"supported_endpoint":{"vip-messages":{"method":"POST","path":"/v1/messages"}}, diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs index 622e3305..c5eee8f5 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs @@ -93,6 +93,19 @@ fn scope_matches(method: &str, input: &Value, actual: &str) -> bool { } } fn validate_provider_payload(value: &Value, model: &Value) -> R<()> { + if model["protocol"] == "google-generative-ai" { + let contents = value["contents"].as_array().filter(|items| !items.is_empty() && items.len() <= 2000) + .ok_or("会话条数无效")?; + if contents.iter().any(|message| !matches!(message["role"].as_str(), Some("user" | "model"))) { + return Err("会话角色无效".into()); + } + if let Some(limit) = value["generationConfig"].get("maxOutputTokens") + && limit.as_u64().is_none_or(|limit| limit == 0 || model["maxTokens"].as_u64().is_some_and(|max| limit > max)) + { + return Err("输出长度或候选数量超限".into()); + } + return Ok(()); + } if value["model"] != model["id"] || value["stream"] != true { return Err("只能调用当前账户已选择的流式对话模型".into()); } @@ -159,55 +172,32 @@ fn authorized_candidate(model: &Value, legacy_headers: &Value, input: &Value) -> Some(candidate) } -fn same_protocol_attempts(model: &Value, requested: &Value, mut compatible: impl FnMut(&Value) -> bool) -> Vec { - let mut attempts = vec![requested.clone()]; - let candidates = model["candidates"].as_array().into_iter().flatten().filter(|candidate| { - candidate["protocol"] == requested["protocol"] && candidate["path"] == requested["path"] - && candidate["headers"] != requested["headers"] - }); - if let Some(route) = candidates.clone().find(|candidate| candidate["routeId"].is_string() && compatible(candidate)) { - attempts.push(route.clone()); - } - if let Some(unpinned) = candidates.filter(|candidate| candidate["headers"] == json!({})).find(|candidate| compatible(candidate)) { - attempts.push(unpinned.clone()); - } - attempts -} - pub(super) fn send_text( backend: &Backend, model: &Value, requested: &Value, key: &str, id: &str, timeout: Duration, - compatible: impl FnMut(&Value) -> bool, + _compatible: impl FnMut(&Value) -> bool, mut send: impl FnMut(reqwest::blocking::RequestBuilder, &Value, &str) -> R, ) -> R { - let attempts = same_protocol_attempts(model, requested, compatible); - let mut attempts = attempts.iter().peekable(); - let mut request_id = id.to_owned(); - while let Some(candidate) = attempts.next() { - let path = candidate["path"].as_str().ok_or("模型路径无效")?; - if !matches!(path, "/v1/chat/completions" | "/v1/responses" | "/v1/messages") { - return Err("模型路径无效".into()); - } - let mut request = backend.http.post(format!("{UPSTREAM}{path}")).timeout(timeout) - .bearer_auth(key).header("Idempotency-Key", &request_id); - for (name, value) in invocation_headers(&json!({"invocationHeaders":candidate["headers"]}))? { - request = request.header(name, value); - } - if path == "/v1/messages" { - request = request.header("Anthropic-Version", "2023-06-01").header("X-Api-Key", key); - } - let response = send(request, candidate, &request_id)?; - if !matches!(response.status().as_u16(), 502 | 503) { - return Ok(response); - } - let mut failed = candidate.clone(); + let path = requested["path"].as_str().ok_or("模型路径无效")?; + let google = requested["protocol"] == "google-generative-ai" + && model["id"].as_str().and_then(|id| crate::jiansun_models::google_text_path(path, id)).as_deref() == Some(path); + if !google && !matches!(path, "/v1/chat/completions" | "/v1/responses" | "/v1/messages") { + return Err("模型路径无效".into()); + } + let request = backend.http.post(format!("{UPSTREAM}{path}")).timeout(timeout).header("Idempotency-Key", id); + let mut request = if google { request.header("x-goog-api-key", key) } else { request.bearer_auth(key) }; + for (name, value) in invocation_headers(&json!({"invocationHeaders":requested["headers"]}))? { + request = request.header(name, value); + } + if path == "/v1/messages" { + request = request.header("Anthropic-Version", "2023-06-01").header("X-Api-Key", key); + } + let response = send(request, requested, id)?; + if matches!(response.status().as_u16(), 502 | 503) { + let mut failed = requested.clone(); failed["id"] = model["id"].clone(); pi_runtime::invalidate_invocation(backend, &failed); - if attempts.peek().is_none() { - return Ok(response); - } - request_id = Uuid::new_v4().to_string(); } - Err("没有可用的对话线路".into()) + Ok(response) } fn selected(backend: &mut Backend, role: &str) -> R<(Value, Value, Value, Value)> { @@ -302,7 +292,7 @@ pub(super) fn run() -> R<()> { return Err("SDK输入过大".into()); } let input: Value = serde_json::from_slice(&bytes).map_err(|_| "SDK输入无效")?; - dispatch(input, &mut None, &mut None, &mut false) + dispatch(input, &mut None, &mut None, &mut false, &mut Value::Null) } // Read each line without ever allocating more than the request limit. Oversized @@ -349,7 +339,7 @@ fn rpc_error_frame(error: &str, new_request_preflight: bool) -> Value { "98k暂时无法连接(域名解析失败);个人Key已保留" => "98k暂时无法连接(域名解析失败);个人Key已保留", "98k暂时无法连接(连接失败);个人Key已保留" => "98k暂时无法连接(连接失败);个人Key已保留", "98k暂时无法连接(网络请求失败);个人Key已保留" => "98k暂时无法连接(网络请求失败);个人Key已保留", - "98k公开调用目录暂时不可用,未派发模型" => "98k公开调用目录暂时不可用,未派发模型", + "98k公开调用目录暂时不可用,未派发模型" | "模型调用路由已更新,本次尚未提交" => error, "请在小壹设置中选择对话模型" | "当前对话模型不在可用目录,请在小壹设置中重新选择" | "当前对话模型已停用,请在小壹设置中重新选择" @@ -387,17 +377,28 @@ pub(super) fn run_rpc() -> R<()> { let mut selection = None; while let Some(line) = bounded_line(&mut reader)? { let mut new_request_preflight = false; + let mut outcome = Value::Null; let result = line.map_err(|_| "SDK输入过大".to_owned()) .and_then(|bytes| serde_json::from_slice::(&bytes).map_err(|_| "SDK输入无效".to_owned())) .and_then(|input| { if input["method"] == "knowledge-http" { super::knowledge_http::exchange(&input, emit) } else { - dispatch(input, &mut shared_http, &mut selection, &mut new_request_preflight) + if input["method"] == "request" { + new_request_preflight = true; + outcome = json!({"dispatchState":"not_dispatched", + "originalRequestId":uuid(&input, "id").ok(), + "actualRouteId":null,"actualProtocol":null}); + } + dispatch(input, &mut shared_http, &mut selection, &mut new_request_preflight, &mut outcome) } }); if let Err(error) = result { - emit(rpc_error_frame(&error, new_request_preflight))?; + let mut frame = rpc_error_frame(&error, new_request_preflight); + if let Some(fields) = outcome.as_object() { + frame.as_object_mut().unwrap().extend(fields.clone()); + } + emit(frame)?; } } Ok(()) @@ -417,21 +418,54 @@ fn verified_detail_model(record: &Value, input: &Value, settings: &Value, scope: let key = settings["key"].as_str()?; let model = &record["model"]; (input["modelRole"] == "detail" && record["id"] == id && record["scope"] == scope - && record["keyFingerprint"] == hash(key) && record["choice"] == settings["model"] + && record["keyFingerprint"] == hash(key) && authorized_candidate(model, &record["headers"], input).is_some()) .then(|| model.clone()) } fn continue_detail_selection(current: Option<&Selection>, record: &Value, settings: &Value, scope: &str) -> Option<(Value, Value, String)> { let (selected_scope, role, selected_settings, model, invocation) = current?; - if selected_scope != scope || role != "detail" || selected_settings != settings + if selected_scope != scope || role != "detail" || selected_settings["key"] != settings["key"] || record["scope"] != scope || record["model"] != *model || record["headers"] != invocation["headers"] { return None; } Some((model.clone(), invocation.clone(), uuid(record, "id").ok()?)) } -fn dispatch(input: Value, shared_http: &mut Option, selection: &mut Option, new_request_preflight: &mut bool) -> R<()> { +fn ambiguous_gateway_result(bytes: &[u8]) -> bool { + serde_json::from_slice::(bytes).is_ok_and(|error| + error["code"] == "request_outcome_unknown" || error["error"]["code"] == "request_outcome_unknown") +} + +#[derive(Default)] +struct SseDispatchStatus { + line: Vec, + oversized: bool, +} + +impl SseDispatchStatus { + fn observe(&mut self, bytes: &[u8]) -> bool { + for part in bytes.split_inclusive(|&byte| byte == b'\n') { + if !self.oversized && self.line.len() + part.len() <= 64 * 1024 { + self.line.extend_from_slice(part); + } else { + self.oversized = true; + } + if part.ends_with(b"\n") { + if self.unknown() { return true; } + self.line.clear(); + self.oversized = false; + } + } + false + } + + fn unknown(&self) -> bool { + !self.oversized && self.line.strip_prefix(b"data:").is_some_and(ambiguous_gateway_result) + } +} + +fn dispatch(input: Value, shared_http: &mut Option, selection: &mut Option, new_request_preflight: &mut bool, outcome: &mut Value) -> R<()> { let project = uuid(&input, "project")?; let root = crate::services::config_dir().ok_or("本机配置目录不可用")?.join("jiansun"); let mut backend = Backend::new(root)?; @@ -501,7 +535,7 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m read_task(&selection_file).ok().and_then(|record| verified_detail_model(&record, &input, &settings, &backend.scope())) } else { selection.as_ref().filter(|(scope, cached_role, cached, model, invocation)| - scope == &backend.scope() && cached_role == role && cached == &settings + scope == &backend.scope() && cached_role == role && cached["key"] == settings["key"] && authorized_candidate(model, &invocation["headers"], &input).is_some()) .map(|(_, _, _, model, _)| model.clone()) }; @@ -509,6 +543,9 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m backend.validate()?; (settings, model) } else { + if input["selectionId"].is_string() || selection.is_some() { + return Err("模型调用路由已更新,本次尚未提交".into()); + } let (settings, mut model, invocation, _) = selected(&mut backend, role)?; pi_runtime::apply_invocation_capacity(&mut model, &invocation)?; if authorized_candidate(&model, &invocation["headers"], &input).is_none() { @@ -526,14 +563,31 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m .ok_or("模型调用路由已更新,本次尚未提交")?; requested["id"] = model["id"].clone(); validate_provider_payload(&value, &requested)?; + outcome["actualRouteId"] = requested["routeId"].clone(); + outcome["actualProtocol"] = requested["protocol"].clone(); let mut response = send_text(&backend, &model, &requested, key, &id, Duration::from_secs(600), |candidate| validate_provider_payload(&value, candidate).is_ok(), |request, _, _| { check_dispatch_lease(&input["dispatchLease"])?; *new_request_preflight = false; + outcome["dispatchState"] = json!("outcome_unknown"); request.header("Content-Type", "application/json").body(payload.to_owned()).send().map_err(|_| "98k连接中断".into()) })?; let status = response.status().as_u16(); + if let Some(id) = response.headers().get("x-request-id").and_then(|id| id.to_str().ok()) + .and_then(|id| Uuid::parse_str(id).ok()) { + outcome["originalRequestId"] = json!(id); + } + if let Some(id) = response.headers().get("x-relay-route-option").and_then(|id| id.to_str().ok()) + .and_then(|id| Uuid::parse_str(id).ok()) { + outcome["actualRouteId"] = json!(id); + } + outcome["dispatchState"] = json!(match status { + 200..=299 | 408 | 504 | 524 => "outcome_unknown", + 429 | 502 | 503 => "retryable_error", + _ => "committed_error", + }); + if matches!(status, 401 | 403) { *selection = None; if input["selectionId"].is_string() @@ -541,20 +595,51 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m let _ = fs::remove_file(&selection_file); } } + let mut error_body = Vec::new(); + if !(200..300).contains(&status) { + (&mut response).take(1_048_577).read_to_end(&mut error_body).map_err(|_| { + outcome["dispatchState"] = json!("outcome_unknown"); + "98k响应中断" + })?; + if error_body.len() > 1_048_576 || ambiguous_gateway_result(&error_body) + { + outcome["dispatchState"] = json!("outcome_unknown"); + return Err("98k响应中断".into()); + } + } let content_type = response.headers().get("content-type").and_then(|value| value.to_str().ok()) .unwrap_or("application/octet-stream"); let retry_after = response.headers().get("retry-after").and_then(|value| value.to_str().ok()); let mut headers = json!({"content-type":content_type}); if let Some(retry_after) = retry_after { headers["retry-after"] = json!(retry_after); } - emit(json!({"type":"headers","status":status,"headers":headers}))?; - backend.check_model_authority(&response, key)?; - let mut chunk = [0u8; 8192]; - loop { - let count = response.read(&mut chunk).map_err(|_| "98k响应中断")?; - if count == 0 { break; } - emit(json!({"type":"chunk","data":STANDARD.encode(&chunk[..count])}))?; + let mut identity = outcome.clone(); + if (200..300).contains(&status) { + identity.as_object_mut().unwrap().remove("dispatchState"); } - emit(json!({"type":"result","value":{}})) + let mut frame = identity.clone(); + frame["type"] = json!("headers"); + frame["status"] = json!(status); + frame["headers"] = headers; + emit(frame)?; + backend.check_model_authority(&response, key)?; + if (200..300).contains(&status) { + let mut dispatch_status = SseDispatchStatus::default(); + let mut chunk = [0u8; 8192]; + loop { + let count = response.read(&mut chunk).map_err(|_| "98k响应中断")?; + if count == 0 { + if dispatch_status.unknown() { return Err("98k响应中断".into()); } + break; + } + if dispatch_status.observe(&chunk[..count]) { return Err("98k响应中断".into()); } + emit(json!({"type":"chunk","data":STANDARD.encode(&chunk[..count])}))?; + } + } else if !error_body.is_empty() { + for chunk in error_body.chunks(8192) { + emit(json!({"type":"chunk","data":STANDARD.encode(chunk)}))?; + } + } + emit(json!({"type":"result","value":identity})) } #[cfg(test)] @@ -562,7 +647,16 @@ mod tests { use super::*; #[test] - fn model_alternates_are_authorized_by_path_and_headers_but_failover_stays_on_protocol() { + fn unknown_gateway_sse_is_detected_across_chunks_without_matching_model_text() { + let mut status = SseDispatchStatus::default(); + assert!(!status.observe(b"data: {\"content\":\"request_outcome_unknown\"}\n\n")); + assert!(!status.observe(b"data: {\"error\":{\"code\":\"request_")); + assert!(status.observe(b"outcome_unknown\"}}\r\n\n")); + assert!(!ambiguous_gateway_result(br#"{"error":{"code":"route_unavailable"}}"#)); + } + + #[test] + fn model_routes_are_authorized_by_path_and_headers() { let chat = |route: Option<&str>| json!({"protocol":"openai-chat","path":"/v1/chat/completions", "routeId":route,"headers":route.map_or_else(|| json!({}), |id| json!({"X-Relay-Route-Option":id}))}); let pinned = chat(Some("6db9b40d-ad0d-4dd1-b7b9-bb0b3cf8040a")); @@ -574,11 +668,10 @@ mod tests { assert_eq!(authorized_candidate(&model, &Value::Null, &requested), Some(alternate)); let invalid = json!({"invocationPath":"/v1/responses","invocationHeaders":pinned["headers"]}); assert!(authorized_candidate(&model, &Value::Null, &invalid).is_none()); - assert_eq!(same_protocol_attempts(&model, &pinned, |_| true), vec![pinned, backup, unpinned]); } #[test] - fn text_failover_uses_new_keys_only_for_gateway_failures_before_headers() { + fn text_dispatch_preserves_exactly_one_route_and_id_on_every_status() { let temp = tempfile::tempdir().unwrap(); let backend = Backend::new(temp.path().to_owned()).unwrap(); let route = |id: Option<&str>| json!({"id":"chat","protocol":"openai-chat","path":"/v1/chat/completions", @@ -587,7 +680,7 @@ mod tests { let backup = route(Some("bc5fa545-59d5-4b95-b4df-bd9b53b37906")); let model = json!({"id":"chat","candidates":[primary,backup,route(None)]}); let client = reqwest::blocking::Client::builder().no_proxy().build().unwrap(); - for (statuses, expected) in [(vec![502, 503, 200], 200), (vec![429], 429), (vec![200], 200), (vec![502, 503, 502], 502)] { + for (statuses, expected) in [(vec![503], 503), (vec![429], 429), (vec![200], 200), (vec![502], 502)] { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let count = statuses.len(); @@ -633,7 +726,8 @@ mod tests { for (field, value) in [("key","new-key"),("model","another-model")] { let mut changed = settings.clone(); changed[field] = json!(value); - assert!(verified_detail_model(&record, &input, &changed, "account-scope").is_none()); + assert_eq!(verified_detail_model(&record, &input, &changed, "account-scope").is_some(), + field == "model"); } for (field, value) in [("selectionId",json!(Uuid::new_v4().to_string())),("modelRole",json!("chat")), ("invocationHeaders",json!({})),("invocationPath",json!("/v1/chat/completions"))] { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs index 110fded0..53081352 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -184,7 +184,11 @@ pub(super) fn invocation_from(catalog: &Value, model: &Value) -> R { .ok_or("当前模型线路不可用,未派发模型") }).transpose()?; let invocation = &route.unwrap_or(found)["invocation"]; - if invocation["method"] != "POST" || invocation["path"] != model["path"] || invocation["content_type"] != "application/json" { + let path = if model["protocol"] == "google-generative-ai" { + invocation["path"].as_str().zip(model["id"].as_str()) + .and_then(|(path, id)| crate::jiansun_models::google_text_path(path, id)).map_or(Value::Null, Value::String) + } else { invocation["path"].clone() }; + if invocation["method"] != "POST" || path != model["path"] || invocation["content_type"] != "application/json" { return Err("当前模型公开契约与已选协议不一致,未调用".into()); } let headers = crate::jiansun_models::text_catalog_headers(invocation, model["protocol"].as_str().unwrap_or_default())?; @@ -522,7 +526,7 @@ pub(super) fn record_export_event( /// Pi journals affect template capabilities without incrementing the template /// revision. Read the canonical state after the SDK durably finishes, while the -/// existing worker still owns model_busy; an eager second UI request can race +/// existing worker still owns the project slot; an eager second UI request can race /// that worker's release and must not be used to manufacture fresh permissions. fn canonical_pi_result(b: &Backend, mut value: Value) -> R { let refresh = (|| -> R<(String, Value)> { @@ -582,11 +586,11 @@ fn workflow_receipt(delegation: &Value, result: R) -> R { #[derive(Default)] struct WorkflowChildren { - workers: Vec>, + workers: Vec>, seen: std::collections::HashSet, } impl WorkflowChildren { - fn start(&mut self, b: &Backend, delegation: &Value, scope: (&str, &str, u64), events: &mpsc::Sender, ctx: &egui::Context) -> R<()> { + fn start(&mut self, b: &Backend, delegation: &Value, scope: (&str, &str, u64), cancellation: Arc, events: &mpsc::Sender, ctx: &egui::Context) -> R<()> { let (run, project, doc) = scope; let (method, input) = workflow_delegation(delegation, run, &b.origin, &b.auth["account"]["id"], project, doc)?; // A new delegation is issued only after the GUI consumes the previous @@ -595,9 +599,18 @@ impl WorkflowChildren { let batch = input["detailBatch"] == true; let mut index = 0; while index < self.workers.len() { - if !batch || self.workers[index].is_finished() { - self.workers.swap_remove(index).join().map_err(|_| "原工作流线程异常,结果需核查")?; - } else { index += 1; } + if !batch { + self.workers.swap_remove(index).recv().map_err(|_| "原工作流线程异常,结果需核查")?; + } else { + match self.workers[index].try_recv() { + Ok(()) => { self.workers.swap_remove(index); } + Err(mpsc::TryRecvError::Disconnected) => { + self.workers.swap_remove(index); + return Err("原工作流线程异常,结果需核查".into()); + } + Err(mpsc::TryRecvError::Empty) => index += 1, + } + } } let operation = delegation["operationId"].as_str().ok_or("操作身份缺失")?.to_owned(); if !self.seen.insert(operation) { return Err("原工作流操作已登记,不会重发".into()); } @@ -605,34 +618,96 @@ impl WorkflowChildren { let child_events = events.clone(); let child_ctx = ctx.clone(); let receipt_identity = delegation.clone(); - self.workers.push(std::thread::Builder::new().name("pi-workflow-operation".into()).spawn(move || { + static WORKFLOWS: std::sync::OnceLock = std::sync::OnceLock::new(); + let (finished, completion) = mpsc::channel(); + WORKFLOWS.get_or_init(|| super::reads::ReadPool::with_limits(3, 24)).submit(move || { // The existing business dispatcher retains its journals, reference // ownership checks and final single-POST barrier. The parent keeps - // model_busy throughout; no global model lock is bypassed. - let result = child_backend.slot_action(&method, &input, &child_events, &child_ctx); + // the project slot throughout. + let result = super::images::with_run_cancellation(cancellation, || + child_backend.slot_action(&method, &input, &child_events, &child_ctx)); let _ = child_events.send(Event::Json(method, workflow_receipt(&receipt_identity, result))); child_ctx.request_repaint_of(egui::ViewportId::ROOT); - }).map_err(|_| "本机工作流线程无法启动,未派发模型")?); + let _ = finished.send(()); + }).map_err(|_| "本机工作流队列已满,未派发模型")?; + self.workers.push(completion); Ok(()) } } impl Drop for WorkflowChildren { fn drop(&mut self) { - // Do not release the parent's global model lease while a stopped or - // disconnected turn still has an original business request in flight. - for worker in self.workers.drain(..) { let _ = worker.join(); } + for worker in self.workers.drain(..) { let _ = worker.recv(); } } } struct DaemonTurnGuard { daemon: Arc, + run_id: String, + scope: String, + project: String, + doc: u64, complete: bool, } impl Drop for DaemonTurnGuard { fn drop(&mut self) { - // An interrupted protocol cannot be reused or silently replayed. - if !self.complete { self.daemon.fail(); } + if !self.complete { + let _ = self.daemon.abort_run(&self.scope, &self.project, self.doc, &json!(self.run_id)); + self.daemon.end(&self.run_id); + } } } + +fn native_operation_path(dir: &Path, input: &Value) -> R> { + input["clientOperationId"].as_str().map(|id| { + let id = Uuid::parse_str(id).map_err(|_| "原生操作编号无效")?; + Ok(dir.join("native-operations").join(format!("{id}.json"))) + }).transpose() +} + +fn retained_native_reply(record: &Value, input: &Value) -> Value { + if record["terminal"].is_object() { + return record["terminal"].clone(); + } + json!({"run":input["run"],"documentId":input["documentId"],"job":record["job"], + "clientOperationId":input["clientOperationId"],"state":"outcome_unknown","completed":false, + "source":"retained-native-receipt"}) +} + +fn save_native_operation(path: &Path, reply: &Result<(Value, Option), BridgeFailure>) -> R<()> { + let _guard = super::sync::context_guard(); + let mut record = read_json(path)?; + if record["terminal"].is_object() { return Ok(()); } + match reply { + Ok((value, _)) => { + if value["job"].is_number() { + if record["job"].is_number() && record["job"] != value["job"] { + return Err("原生任务编号已变化,保留原回执".into()); + } + record["job"] = value["job"].clone(); + record["phase"] = json!("accepted"); + } + if value["completed"] == true && !matches!(value["state"].as_str(), Some("outcome_unknown")) { + let applied = value["applied"] == true && value["applicationVerified"] == true && value["executed"] == true; + let rejected = value["executed"] == false && value["applied"] != true; + if applied || rejected || value["job"].is_null() && value["executed"] == true { + record["terminal"] = json!({"run":record["run"],"documentId":record["documentId"], + "job":record["job"],"clientOperationId":record["clientOperationId"], + "state":if rejected { "failed" } else { "done" },"completed":true, + "executed":!rejected,"applied":!rejected,"applicationVerified":!rejected, + "source":"retained-native-receipt"}); + } + } + } + Err(error) if !error.dispatched => { + record["terminal"] = json!({"run":record["run"],"documentId":record["documentId"], + "job":record["job"],"clientOperationId":record["clientOperationId"],"state":"failed", + "completed":true,"executed":false,"applied":false,"source":"retained-native-receipt"}); + } + Err(_) => return Ok(()), + } + if record["terminal"].is_object() { record["phase"] = json!("terminal"); } + write_json(path, &record) +} + fn allowed_canvas_action(action: &str) -> bool { matches!(action, "pi-begin" | "pi-state" | "pi-production-open" | "pi-production-finish" | "pi-production-finish-status" | "pi-ui-request" | "pi-ui-poll" | "pi-ui-cancel" | "pi-canvas-read" | "pi-template-image" | "pi-detail-images" | "pi-detail-archive" | "pi-detail-copy-fields" | "pi-detail-copy-apply" | "pi-product-screen" | "pi-image-request" | "pi-preview" | "pi-copy-options" | "pi-copy-fields" | "pi-native-catalog" | "pi-native-call" | "pi-native-poll" | "pi-reply" | "pi-context-usage" | "pi-write-request" | "pi-edit" | "pi-end" | "pi-workflow-read" @@ -675,6 +750,13 @@ fn take_late_workflow_delegations(replies: &mut Vec> ready } +fn apply_run_authority_failure(backend: &Backend, category: &str) { + // An old native canvas lease can change while the account is still valid. + if category == "auth_revoked" || backend.check_dispatch().is_err() { + backend.revoke_access(category); + } +} + fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: &egui::Context) -> Result { b.check_dispatch().map_err(|message| BridgeFailure::new("auth_revoked", false, false, message))?; let doc = input["context"]["id"].as_u64().or_else(|| input["doc"].as_u64()).ok_or("请先打开项目")?; @@ -719,23 +801,30 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: let mut config = config; config["referenceContent"] = json!(resolve_references(b, doc, &dir, &input["context"]["requestScope"]["references"], &input["referenceContent"], events, ctx)?); let daemon = agent_daemon::service(&node, &script, &binary, profile)?; - let daemon_run = Uuid::new_v4().to_string(); + let daemon_run = input["runId"].as_str().map(Uuid::parse_str).transpose() + .map_err(|_| "制作回合编号无效")?.unwrap_or_else(Uuid::new_v4).to_string(); + config["runId"] = json!(daemon_run); let receiver = daemon.begin(&daemon_run, &config)?; + let cancellation = daemon.cancellation(&daemon_run)?; if product_prompt { log::info!("小壹启动 doc={doc} prepare_native_ms={}", begin.elapsed().as_millis()); } - let mut turn_guard = DaemonTurnGuard { daemon:daemon.clone(), complete:false }; + let mut workflow_children = WorkflowChildren::default(); + let mut turn_guard = DaemonTurnGuard { daemon:daemon.clone(), run_id:daemon_run.clone(), + scope:b.scope(), project:project.clone(), doc, complete:false }; + let startup_deadline = std::time::Instant::now() + Duration::from_secs(90); + let mut native_jobs = std::collections::HashMap::::new(); let mut bound_run: Option = None; let mut request_ids = std::collections::HashSet::new(); - let mut workflow_children = WorkflowChildren::default(); - let mut detail_image_reads = None; - let mut canvas_screen_reads = None; + static DETAIL_IMAGE_READS: std::sync::OnceLock = std::sync::OnceLock::new(); + static CANVAS_SCREEN_READS: std::sync::OnceLock = std::sync::OnceLock::new(); + static IMAGE_JOBS: std::sync::OnceLock = std::sync::OnceLock::new(); let screen_reader = Arc::new(super::canvas_workspace::ScreenReader::default()); let mut late_workflow_replies = Vec::new(); let start_workflow = |children: &mut WorkflowChildren, delegation: &Value, run: Option<&str>| { if b.exiting() { return Err("客户端正在退出,未派发工作流".into()); } let start = b.check_dispatch().and_then(|()| run.ok_or_else(|| "原对话尚未连接到当前项目".to_owned())) - .and_then(|run| children.start(b, delegation, (run, &project, doc), events, ctx)); + .and_then(|run| children.start(b, delegation, (run, &project, doc), cancellation.clone(), events, ctx)); if let Err(error) = &start && let Some(method) = delegation["method"].as_str().filter(|method| matches!(*method, "slot-append" | "slot-adopt-prep")) { @@ -748,7 +837,13 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: for delegation in take_late_workflow_delegations(&mut late_workflow_replies) { let _ = start_workflow(&mut workflow_children, &delegation, bound_run.as_deref()); } - let value = if late_workflow_replies.is_empty() { + let value = if bound_run.is_none() && late_workflow_replies.is_empty() { + receiver.recv_timeout(startup_deadline.saturating_duration_since(std::time::Instant::now())) + .map_err(|error| match error { + mpsc::RecvTimeoutError::Timeout => BridgeFailure::interrupted("小壹启动会话超时,原请求需核查", true), + mpsc::RecvTimeoutError::Disconnected => BridgeFailure::interrupted("小壹的本机连接中断,原请求需核查", true), + })?? + } else if late_workflow_replies.is_empty() { receiver.recv().map_err(|_| BridgeFailure::interrupted("小壹的本机连接中断,原请求需核查", true))?? } else { match receiver.recv_timeout(Duration::from_millis(100)) { @@ -761,7 +856,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: if value["type"] == "auth_failure" { let category = value["category"].as_str().filter(|category| matches!(*category, "auth_revoked" | "scope_changed")) .ok_or("小壹授权状态无效")?; - b.revoke_access(category); + apply_run_authority_failure(b, category); } else if value["type"] == "presentation" && b.check_dispatch().is_ok() { let action = value["action"].as_str().filter(|action| matches!(*action, "pi-delta" | "pi-activity" | "pi-queue-update" | "pi-user-delivered")) .ok_or("Agent展示动作未授权")?; @@ -791,6 +886,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: // Only the trusted native owner establishes product evidence scope. fields.insert("accountScope".into(), json!(b.scope())); fields.insert("project".into(), json!(project)); + fields.insert("runId".into(), json!(daemon_run)); if product_prompt { fields.insert("timeBudgetMinutes".into(), json!(b.production_budget_minutes(&dir, &project))); } @@ -800,6 +896,43 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: fields.insert("requestScope".into(), input["context"]["requestScope"].clone()); } } + let mut operation = None; + if matches!(action, "pi-native-call" | "pi-native-reconcile") { + operation = native_operation_path(&dir, &native_input)?; + if let Some(path) = &operation { + let _guard = super::sync::context_guard(); + let existing = if path.try_exists().map_err(|_| "原生操作记录不可读")? { + Some(read_json(path)?) + } else { None }; + if action == "pi-native-call" { + let fingerprint = hash(&native_input.to_string()); + if let Some(record) = existing { + if record["fingerprint"] != fingerprint { + daemon.reply(&daemon_run, &value["id"], &json!({"error": + BridgeFailure::new("local_precondition_failed", false, false, "原生操作编号已绑定其他请求").wire()}))?; + } else { + daemon.reply(&daemon_run, &value["id"], &json!({"value":retained_native_reply(&record, &native_input)}))?; + } + continue; + } + write_json(path, &json!({"clientOperationId":native_input["clientOperationId"], + "fingerprint":fingerprint,"run":native_input["run"],"documentId":native_input["documentId"], + "phase":"received"}))?; + } else { + let record = existing.unwrap_or(Value::Null); + if record.is_object() && (record["run"] != native_input["run"] || record["documentId"] != native_input["documentId"]) { + return Err("原生操作回执不属于本回合或文档".into()); + } + if record["terminal"].is_object() || !record["job"].is_number() { + daemon.reply(&daemon_run, &value["id"], &json!({"value":retained_native_reply(&record, &native_input)}))?; + continue; + } + native_input["job"] = record["job"].clone(); + } + } + } else if action == "pi-native-poll" { + operation = native_input["job"].as_u64().and_then(|job| native_jobs.get(&job)).cloned(); + } let requested_run = native_input["run"].as_str().map(str::to_owned); if product_prompt && action == "pi-begin" { log::info!("小壹启动 doc={doc} canvas_bind_ms={}", begin.elapsed().as_millis()); @@ -811,6 +944,26 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: let _timing = photocraft_ui_egui::operation_timer::OperationTimer::new(action, None, false).waiting(); rx.recv_timeout(Duration::from_secs(12)) }; + if let Some(path) = &operation { + if let Ok(reply) = &receipt { + save_native_operation(path, reply)?; + if let Ok((result, _)) = reply + && let Some(job) = result["job"].as_u64() { + native_jobs.insert(job, path.clone()); + } + } else if action == "pi-native-call" { + let path = path.clone(); + std::thread::spawn(move || { + if let Ok(reply) = rx.recv_timeout(Duration::from_secs(120)) + && let Err(error) = save_native_operation(&path, &reply) { + log::warn!("原生操作迟到回执保存失败:{error}"); + } + }); + daemon.reply(&daemon_run, &value["id"], &json!({"error": + BridgeFailure::interrupted("原生操作待核查", true).wire()}))?; + continue; + } + } let send_receipt = { let transport = daemon.clone(); let run = daemon_run.clone(); @@ -844,19 +997,27 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: }; let reply = match receipt { Ok(Ok((mut v, snapshot))) => { + if action == "pi-native-reconcile" && value["input"]["clientOperationId"].is_string() && v.is_object() { + v["clientOperationId"] = value["input"]["clientOperationId"].clone(); + } daemon.canvas_accepted(&daemon_run, &value["id"])?; if action == "pi-image-request" { let mut worker = b.clone(); let task_events = events.clone(); let task_ctx = ctx.clone(); - std::thread::spawn(move || { - let result = worker.production_image_request(doc, &v, &task_events, &task_ctx, snapshot.as_ref()); + let image_receipt = send_receipt.clone(); + let cancellation = cancellation.clone(); + if let Err(message) = IMAGE_JOBS.get_or_init(|| super::reads::ReadPool::with_limits(3, 24)).submit(move || { + let result = super::images::with_run_cancellation(cancellation, || + worker.production_image_request(doc, &v, &task_events, &task_ctx, snapshot.as_ref())); let reply = match result { Ok(value) => json!({"value":value}), Err(error) => json!({"error":error.wire()}), }; - let _ = send_receipt(reply); - }); + let _ = image_receipt(reply); + }) { + send_receipt(json!({"error":BridgeFailure::new("local_precondition_failed", true, false, message).wire()}))?; + } // Candidate operations own their local receipts. The original // output keeps them even if the Pi turn releases its lease. continue; @@ -866,7 +1027,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: let queued = if archive && config["productProduction"] != true && !config["productionTemplate"].is_object() { Err("当前回合没有整套详情页的授权".into()) } else { - let pool = detail_image_reads.get_or_insert_with(super::reads::QueuedReads::detail_review); + let pool = DETAIL_IMAGE_READS.get_or_init(super::reads::QueuedReads::detail_review); let mut reader = b.clone(); let archive_events = events.clone(); let archive_ctx = ctx.clone(); @@ -888,7 +1049,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: } if action == "pi-product-screen" { let queued = if let Some(PiCanvasSnapshot { document, cancellation, slot_source }) = snapshot { - let pool = canvas_screen_reads.get_or_insert_with(super::reads::QueuedReads::canvas_screens); + let pool = CANVAS_SCREEN_READS.get_or_init(super::reads::QueuedReads::canvas_screens); let reader = screen_reader.clone(); let backend = b.clone(); let send_receipt = send_receipt.clone(); @@ -984,6 +1145,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: result["failure"] = BridgeFailure::new("auth_revoked", false, false, super::AUTH_REVOKED).wire(); } result["engine"] = json!("pi"); + result["runId"] = json!(daemon_run); result["doc"] = json!(doc); result["accountId"] = b.auth["account"]["id"].clone(); result["origin"] = json!(b.origin); @@ -1048,7 +1210,7 @@ pub(super) fn steer(b: &Backend, input: &Value, events: &mpsc::Sender, ct let Some(daemon) = agent_daemon::current()? else { return Ok(json!({"accepted":false,"reason":"no_active_run"})); }; - let mut request = json!({"runId":input["runId"],"text":input["text"],"behavior":input["behavior"],"referenceContent":[]}); + let mut request = json!({"runId":input["runId"],"text":input["text"],"behavior":input["behavior"],"messageId":input["messageId"],"referenceContent":[]}); if input["references"].as_array().is_some_and(|items| !items.is_empty()) { request["referenceContent"] = json!(resolve_references(b, doc, &b.project_dir(doc)?, &input["references"], &input["referenceContent"], events, ctx)?); } @@ -1083,6 +1245,14 @@ pub(super) fn abort_run(b: &Backend, input: &Value) -> R { Ok(json!({})) } +pub(super) fn control_run(b: &Backend, input: &Value, action: &str) -> R { + let (scope, project, doc) = live_target(b, input)?; + if let Some(daemon) = agent_daemon::current()? { + daemon.run_control(action, &scope, project, doc, &input["runId"])?; + } + Ok(json!({})) +} + fn merge_reference_identity(item: &mut Value, reference: &Value) { for key in ["kind", "label", "nativeLayerId", "component", "layerKind", "slotId", "fieldId", "candidateId", "taskId", "outputId", "productVariantId", "pageId", "documentId", "source", "status"] { @@ -1096,6 +1266,35 @@ fn merge_reference_identity(item: &mut Value, reference: &Value) { #[cfg(test)] mod tests { + #[test] + fn stale_canvas_scope_keeps_account_admission_while_auth_revocation_closes_it() { + let temp = tempfile::tempdir().unwrap(); + let backend = Backend::new(temp.path().to_owned()).unwrap(); + assert!(backend.check_dispatch().is_ok()); + apply_run_authority_failure(&backend, "scope_changed"); + assert!(backend.check_dispatch().is_ok()); + apply_run_authority_failure(&backend, "auth_revoked"); + assert!(backend.check_dispatch().is_err()); + } + + #[test] + fn native_operation_receipt_recovers_the_original_job_and_terminal_state() { + let temp = tempfile::tempdir().unwrap(); + let input = json!({"clientOperationId":Uuid::new_v4(),"run":"run","documentId":"doc"}); + let path = native_operation_path(temp.path(), &input).unwrap().unwrap(); + write_json(&path, &input).unwrap(); + save_native_operation(&path, &Ok((json!({"job":19,"pending":true}), None))).unwrap(); + let record = read_json(&path).unwrap(); + assert_eq!(record["job"], 19); + assert_eq!(retained_native_reply(&record, &input)["state"], "outcome_unknown"); + save_native_operation(&path, &Ok((json!({"job":19,"state":"done","completed":true, + "executed":true,"applied":true,"applicationVerified":true}), None))).unwrap(); + let reply = retained_native_reply(&read_json(&path).unwrap(), &input); + assert_eq!(reply["clientOperationId"], input["clientOperationId"]); + assert_eq!(reply["source"], "retained-native-receipt"); + assert_eq!(reply["applicationVerified"], true); + } + #[test] fn reference_metadata_preserves_objects_without_media() { let reference = serde_json::json!({"kind":"layer","label":"文字蒙版","nativeLayerId":13, diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_recovery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_recovery.rs index 9337f956..b7b48c39 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_recovery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_recovery.rs @@ -327,6 +327,7 @@ impl Backend { if !task["creationBinding"].is_object() { task["creationBinding"] = legacy_binding(&dir, &c, &task, local, &self.scope(), &self.origin)?; } + super::images::reopen_ambiguous_expiry(&mut task); association(&c, &task, local, &self.scope(), &self.origin)?; let task_id = uuid(&task["id"])?.to_owned(); let screen = uuid(&pending["screenId"])?.to_owned();