Merge T3: Rust host and UI mid-turn steer and chat abort
This commit is contained in:
commit
16be0ddf8a
@ -9,10 +9,26 @@ use std::time::{Duration, Instant};
|
||||
enum KnowledgeEvent { Progress(Value), Result(R<Value>) }
|
||||
type ExitReceipt = Box<dyn FnOnce(R<()>) + Send>;
|
||||
|
||||
type PendingAcks = std::collections::HashMap<String, (String, mpsc::Sender<Value>)>;
|
||||
|
||||
struct ActiveRun {
|
||||
id: String,
|
||||
target: Value,
|
||||
events: mpsc::Sender<Result<Value, BridgeFailure>>,
|
||||
}
|
||||
|
||||
impl ActiveRun {
|
||||
fn matches(&self, request: &Value) -> bool {
|
||||
["scope", "project", "documentId"].iter().all(|key| self.target[*key] == request[*key])
|
||||
}
|
||||
}
|
||||
|
||||
struct State {
|
||||
alive: bool,
|
||||
ready: bool,
|
||||
active: Option<(String, mpsc::Sender<Result<Value, BridgeFailure>>)>,
|
||||
active: Option<ActiveRun>,
|
||||
steer_acks: PendingAcks,
|
||||
clear_queue_acks: PendingAcks,
|
||||
knowledge: std::collections::HashMap<String, mpsc::Sender<KnowledgeEvent>>,
|
||||
broker_pid: Option<u32>,
|
||||
last_ack: Option<Instant>,
|
||||
@ -52,7 +68,9 @@ impl Daemon {
|
||||
state.alive = false;
|
||||
if let Some(receipt) = state.exit_receipt.take() { receipt(Err("本机Agent退出回执未确认".into())); }
|
||||
for (_, sender) in state.knowledge.drain() { let _ = sender.send(KnowledgeEvent::Result(Err("企业知识库连接中断".into()))); }
|
||||
if let Some((_, sender)) = state.active.take() { let _ = sender.send(Err(BridgeFailure::interrupted("本机Agent连接中断,原请求需核查", true))); }
|
||||
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))); }
|
||||
}
|
||||
if let Ok(mut output) = self.outbound.lock() { output.take(); }
|
||||
self.wait_for_exit();
|
||||
@ -93,9 +111,18 @@ impl Daemon {
|
||||
}
|
||||
Some("canvas" | "presentation" | "complete" | "auth_failure") if state.ready => {
|
||||
if state.exiting && state.active.is_none() { return Ok(()); }
|
||||
let (run, sender) = state.active.as_ref().ok_or("本机Agent收到无主回合消息")?;
|
||||
if value["runId"].as_str() != Some(run.as_str()) { return Err("本机Agent回合身份不一致".into()); }
|
||||
if sender.send(Ok(value)).is_err() && !state.exiting { return Err("原回合已关闭".into()); }
|
||||
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()); }
|
||||
}
|
||||
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 };
|
||||
if let Some(id) = value["id"].as_str()
|
||||
&& pending.get(id).is_some_and(|(run, _)| value["runId"] == *run)
|
||||
&& let Some((_, sender)) = pending.remove(id)
|
||||
{
|
||||
let _ = sender.send(value);
|
||||
}
|
||||
}
|
||||
Some("knowledge_progress") if state.ready => {
|
||||
if let Some(sender) = value["id"].as_str().and_then(|id| state.knowledge.get(id)) {
|
||||
@ -137,7 +164,11 @@ impl Daemon {
|
||||
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((run.to_owned(), sender));
|
||||
state.active = Some(ActiveRun {
|
||||
id: run.to_owned(),
|
||||
target: json!({"scope":config["scope"],"project":config["project"],"documentId":config["documentId"]}),
|
||||
events: sender,
|
||||
});
|
||||
self.send(&json!({"type":"run","runId":run,"config":config}))
|
||||
};
|
||||
drop(registry);
|
||||
@ -187,13 +218,72 @@ impl Daemon {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn steer(&self, scope: &str, project: &str, doc: u64, input: &Value) -> R<Value> {
|
||||
self.queue_control(json!({
|
||||
"type":"steer","runId":input["runId"],"scope":scope,"project":project,"documentId":doc,
|
||||
"text":input["text"],"behavior":input["behavior"],"referenceContent":input["referenceContent"],
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn clear_queue(&self, scope: &str, project: &str, doc: u64, run_id: &Value) -> R<Value> {
|
||||
self.queue_control(json!({"type":"clear_queue","runId":run_id,"scope":scope,"project":project,"documentId":doc}))
|
||||
}
|
||||
|
||||
fn queue_control(&self, mut request: Value) -> R<Value> {
|
||||
let steering = request["type"] == "steer";
|
||||
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 {
|
||||
return if steering { Ok(json!({"accepted":false,"reason":"no_active_run"})) }
|
||||
else { Ok(json!({"steering":[],"followUp":[]})) };
|
||||
};
|
||||
if !run.matches(&request) {
|
||||
return if steering { Ok(json!({"accepted":false,"reason":"scope_mismatch"})) }
|
||||
else { Err("当前项目的消息队列已切换".into()) };
|
||||
}
|
||||
let run = run.id.clone();
|
||||
request["id"] = json!(id);
|
||||
let pending = if steering { &mut state.steer_acks } else { &mut state.clear_queue_acks };
|
||||
pending.insert(id.clone(), (run, sender));
|
||||
if let Err(error) = self.send(&request) {
|
||||
pending.remove(&id);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
match receiver.recv_timeout(Duration::from_secs(5)) {
|
||||
Ok(value) => Ok(value),
|
||||
Err(error) => {
|
||||
if let Ok(mut state) = self.state.lock() {
|
||||
let pending = if steering { &mut state.steer_acks } else { &mut state.clear_queue_acks };
|
||||
pending.remove(&id);
|
||||
}
|
||||
Err(match error {
|
||||
mpsc::RecvTimeoutError::Timeout => "消息队列回执超时,请核对当前队列",
|
||||
mpsc::RecvTimeoutError::Disconnected => "本机连接已中断,请核对当前队列",
|
||||
}.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn abort_run(&self, 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)) {
|
||||
self.send(&request)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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 != run) { return Err("原Agent回合已关闭".into()); }
|
||||
if !state.alive || state.active.as_ref().is_none_or(|current| current.id != 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(); }
|
||||
@ -201,7 +291,7 @@ 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 == run) { state.active = None; }
|
||||
if let Ok(mut state) = self.state.lock() && state.active.as_ref().is_some_and(|current| current.id == run) { state.active = None; }
|
||||
}
|
||||
|
||||
fn prepare_exit(&self, receipt: ExitReceipt) {
|
||||
@ -284,7 +374,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, knowledge:Default::default(), broker_pid:None, last_ack:None, last_sent:0, last_acked:0,
|
||||
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,
|
||||
exiting:false, exit_receipt:None }) });
|
||||
spawn_writer(&daemon, stdin, messages);
|
||||
let reader_daemon = daemon.clone();
|
||||
@ -319,12 +409,22 @@ pub(super) fn service(node: &Path, script: &Path, binary: &Path, profile: &Path)
|
||||
daemon.wait_ready()?;
|
||||
Ok(daemon)
|
||||
}
|
||||
pub(super) fn current() -> R<Option<Arc<Daemon>>> {
|
||||
Ok(registry().lock().map_err(|_| "本机连接不可用")?.service.clone())
|
||||
}
|
||||
|
||||
pub(super) fn active_run_id() -> Option<String> {
|
||||
let daemon = current().ok()??;
|
||||
let state = daemon.state.lock().ok()?;
|
||||
Some(state.active.as_ref()?.id.clone())
|
||||
}
|
||||
|
||||
pub(super) fn status() -> Value {
|
||||
let Ok(registry) = registry().lock() else { return json!({"available":false}) };
|
||||
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),"heartbeatAgeMs":state.last_ack.map(|at|at.elapsed().as_millis().min(u64::MAX as u128) as u64)})
|
||||
"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)})
|
||||
}
|
||||
|
||||
pub(super) fn pause_production(doc: u64, project_identity: &str, write_epoch: Option<u64>) {
|
||||
@ -394,7 +494,28 @@ mod tests {
|
||||
let script = r#"const rl=require('node:readline').createInterface({input:process.stdin});
|
||||
console.log(JSON.stringify({type:'ready'}));
|
||||
rl.on('line',line=>{if(JSON.parse(line).type==='prepare_exit')console.log(JSON.stringify({type:'exit_ready'}));});
|
||||
rl.on('line',line=>{const x=JSON.parse(line);if(x.type==='run'){console.log(JSON.stringify({type:'presentation',runId:x.runId,action:'pi-delta'}));console.log(JSON.stringify({type:'complete',runId:x.runId,value:{ok:true}}));}if(x.type==='knowledge'){console.log(JSON.stringify({type:'knowledge_progress',id:x.id,value:{phase:'download',completed:1,fileCount:2}}));if(!x.input.slow)console.log(JSON.stringify({type:'knowledge_result',id:x.id,value:{ok:true}}));}});"#;
|
||||
rl.on('line',line=>{
|
||||
const x=JSON.parse(line);
|
||||
const send=(type, fields) => console.log(JSON.stringify({type,...fields}));
|
||||
if(x.type==='run' && x.config.mode==='fixture'){
|
||||
send('presentation',{runId:x.runId,action:'pi-delta'});
|
||||
send('complete',{runId:x.runId,value:{ok:true}});
|
||||
}
|
||||
if(x.type==='knowledge'){
|
||||
send('knowledge_progress',{id:x.id,value:{phase:'download',completed:1,fileCount:2}});
|
||||
if(!x.input.slow)send('knowledge_result',{id:x.id,value:{ok:true}});
|
||||
}
|
||||
if(x.type==='steer'){
|
||||
send('steer_ack',{id:x.id,runId:'foreign',accepted:false});
|
||||
send('steer_ack',{id:x.id,runId:x.runId,accepted:true,behavior:x.behavior,disposition:'queued',reason:null,error:null});
|
||||
}
|
||||
if(x.type==='clear_queue'){
|
||||
send('clear_queue_ack',{id:x.id,runId:x.runId,steering:['补充'],followUp:[],error:null});
|
||||
}
|
||||
if(x.type==='abort_run'){
|
||||
send('complete',{runId:x.runId,value:{aborted:true,scope:x.scope,project:x.project,documentId:x.documentId}});
|
||||
}
|
||||
});"#;
|
||||
let mut command = Command::new("node");
|
||||
command.args(["-e", script]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null());
|
||||
#[cfg(windows)]
|
||||
@ -406,7 +527,7 @@ rl.on('line',line=>{const x=JSON.parse(line);if(x.type==='run'){console.log(JSON
|
||||
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,knowledge:Default::default(),broker_pid:None,last_ack:None,last_sent:0,last_acked:0,
|
||||
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,
|
||||
exiting:false,exit_receipt:None }) });
|
||||
spawn_writer(&daemon, stdin, messages);
|
||||
let handle = daemon.clone();
|
||||
@ -435,6 +556,28 @@ rl.on('line',line=>{const x=JSON.parse(line);if(x.type==='run'){console.log(JSON
|
||||
assert_eq!(daemon.pid, pid);
|
||||
daemon.end(run);
|
||||
}
|
||||
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":[]});
|
||||
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();
|
||||
assert_eq!(ack["steering"], json!(["补充"]));
|
||||
assert_eq!(ack["followUp"], json!([]));
|
||||
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);
|
||||
}
|
||||
let state = daemon.state.lock().unwrap();
|
||||
assert!(state.steer_acks.is_empty() && state.clear_queue_acks.is_empty());
|
||||
drop(state);
|
||||
let mut progress = Vec::new();
|
||||
assert_eq!(daemon.knowledge_with_progress(json!({}), |value| progress.push(value)).unwrap()["ok"], true);
|
||||
assert_eq!(progress.len(), 2);
|
||||
|
||||
@ -2201,6 +2201,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
let image_reads = reads::ReadPool::images();
|
||||
let project_reads = reads::ReadPool::catalog();
|
||||
let prompt_ops = reads::ReadPool::catalog();
|
||||
let agent_queue_ops = reads::ReadPool::catalog();
|
||||
let updates = reads::ReadPool::with_limits(1, 1);
|
||||
let mut recovery_scope = String::new();
|
||||
if !backend.auth.is_null() {
|
||||
@ -2358,6 +2359,41 @@ 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());
|
||||
let reference = json!({
|
||||
"accountId":backend.auth["account"]["id"],"origin":backend.origin,"doc":input["draftDoc"],
|
||||
});
|
||||
let text = input["text"].clone();
|
||||
let worker = backend.clone();
|
||||
let task_events = events.clone();
|
||||
let task_ctx = ctx.clone();
|
||||
let task_method = method.clone();
|
||||
let task_reference = reference.clone();
|
||||
let task_text = text.clone();
|
||||
let task = move || {
|
||||
let result = match task_method.as_str() {
|
||||
"agent-steer" => pi_runtime::steer(&worker, &input, &task_events, &task_ctx),
|
||||
"agent-clear-queue" => pi_runtime::clear_queue(&worker, &input),
|
||||
_ => pi_runtime::abort_run(&worker, &input),
|
||||
};
|
||||
let mut receipt = bound_material_read(result, &task_reference);
|
||||
receipt["text"] = task_text;
|
||||
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);
|
||||
} else if agent_queue_ops.submit(task).is_err() {
|
||||
let mut receipt = bound_material_read(Err("本机消息队列繁忙,请稍后发送".into()), &reference);
|
||||
receipt["text"] = text;
|
||||
let _ = events.send(Event::Json(method, Ok(receipt)));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if matches!(method.as_str(), "desktop-feedback" | "workbench-knowledge") {
|
||||
let mut worker = backend.clone();
|
||||
let task_events = events.clone();
|
||||
|
||||
@ -704,46 +704,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx:
|
||||
"productionSettings":scope["productionSettings"],"productionClock":scope["productionClock"],
|
||||
"productionTemplate":scope["productionTemplate"]});
|
||||
let mut config = config;
|
||||
{
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
let mut content = Vec::new();
|
||||
for (index, reference) in input["context"]["requestScope"]["references"].as_array().into_iter().flatten().enumerate() {
|
||||
let captured = &input["referenceContent"][index];
|
||||
let mut item = if captured.is_object() { captured.clone() } else { json!({}) };
|
||||
if matches!(reference["kind"].as_str(), Some("candidate" | "template-image" | "image"))
|
||||
&& let Some(task) = reference["taskId"].as_str().filter(|id| !id.trim().is_empty())
|
||||
&& item["image"].as_str().is_none_or(str::is_empty)
|
||||
{
|
||||
let request = json!({"doc":doc,"taskId":task});
|
||||
let preview = if super::images::reference_preview_id(task) {
|
||||
b.reference_image_preview(&request)?
|
||||
} else {
|
||||
b.agent_image_preview(&request).ok()
|
||||
};
|
||||
if let Some((_, image)) = preview {
|
||||
item["image"] = json!(photocraft_ui_egui::jiansun::reference_jpeg(&image, 768)?);
|
||||
}
|
||||
} else if let Some((data, id)) = item["image"].as_str().zip(item["imageId"].as_str()) {
|
||||
if !super::images::reference_preview_id(id) { return Err("引用预览身份无效".into()); }
|
||||
let path = dir.join("reference-previews").join(format!("{id}.jpg"));
|
||||
if !path.exists() {
|
||||
let bytes = STANDARD.decode(data).map_err(|_| "引用图片格式无效")?;
|
||||
std::fs::create_dir_all(dir.join("reference-previews")).map_err(|_| "无法保存引用图片")?;
|
||||
photocraft_format::atomic_write(&path, &bytes).map_err(|_| "无法保存引用图片")?;
|
||||
}
|
||||
if let Ok(Some((meta, image))) = b.reference_image_preview(&json!({"doc":doc,"taskId":id})) {
|
||||
let _ = events.send(Event::Preview(meta, image));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
}
|
||||
merge_reference_identity(&mut item, reference);
|
||||
content.push(item);
|
||||
}
|
||||
if serde_json::to_vec(&content).map_err(|_| "引用内容无法读取")?.len() > 1024 * 1024 {
|
||||
return Err("图片引用较多,请减少本轮引用后再发送".into());
|
||||
}
|
||||
config["referenceContent"] = json!(content);
|
||||
}
|
||||
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 receiver = daemon.begin(&daemon_run, &config)?;
|
||||
@ -789,11 +750,15 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx:
|
||||
.ok_or("小壹授权状态无效")?;
|
||||
b.revoke_access(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"))
|
||||
let action = value["action"].as_str().filter(|action| matches!(*action, "pi-delta" | "pi-activity" | "pi-queue-update" | "pi-user-delivered"))
|
||||
.ok_or("Agent展示动作未授权")?;
|
||||
let (reply, _) = mpsc::channel();
|
||||
let mut presentation = value["input"].clone();
|
||||
presentation.as_object_mut().ok_or("Agent展示参数无效")?.insert("accountEpoch".into(), json!(b.access.epoch));
|
||||
let fields = presentation.as_object_mut().ok_or("Agent展示参数无效")?;
|
||||
fields.insert("accountEpoch".into(), json!(b.access.epoch));
|
||||
if matches!(action, "pi-queue-update" | "pi-user-delivered") {
|
||||
fields.insert("run".into(), json!(bound_run));
|
||||
}
|
||||
let _ = events.send(Event::PiAction(action.into(), presentation, reply));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
} else if value["type"] == "canvas" {
|
||||
@ -1013,6 +978,98 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx:
|
||||
result["contextUsage"] = super::context_usage::read(b, &dir, &project);
|
||||
Ok(result)
|
||||
}
|
||||
fn resolve_references(
|
||||
b: &Backend, doc: u64, dir: &Path, references: &Value, captured_content: &Value,
|
||||
events: &mpsc::Sender<Event>, ctx: &egui::Context,
|
||||
) -> R<Vec<Value>> {
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
let mut content = Vec::new();
|
||||
for (index, reference) in references.as_array().into_iter().flatten().enumerate() {
|
||||
let captured = &captured_content[index];
|
||||
let mut item = if captured.is_object() { captured.clone() } else { json!({}) };
|
||||
if matches!(reference["kind"].as_str(), Some("candidate" | "template-image" | "image"))
|
||||
&& let Some(task) = reference["taskId"].as_str().filter(|id| !id.trim().is_empty())
|
||||
&& item["image"].as_str().is_none_or(str::is_empty)
|
||||
{
|
||||
let request = json!({"doc":doc,"taskId":task});
|
||||
let preview = if super::images::reference_preview_id(task) {
|
||||
b.reference_image_preview(&request)?
|
||||
} else {
|
||||
b.agent_image_preview(&request).ok()
|
||||
};
|
||||
if let Some((_, image)) = preview {
|
||||
item["image"] = json!(photocraft_ui_egui::jiansun::reference_jpeg(&image, 768)?);
|
||||
}
|
||||
} else if let Some((data, id)) = item["image"].as_str().zip(item["imageId"].as_str()) {
|
||||
if !super::images::reference_preview_id(id) { return Err("引用预览身份无效".into()); }
|
||||
let path = dir.join("reference-previews").join(format!("{id}.jpg"));
|
||||
if !path.exists() {
|
||||
let bytes = STANDARD.decode(data).map_err(|_| "引用图片格式无效")?;
|
||||
std::fs::create_dir_all(dir.join("reference-previews")).map_err(|_| "无法保存引用图片")?;
|
||||
photocraft_format::atomic_write(&path, &bytes).map_err(|_| "无法保存引用图片")?;
|
||||
}
|
||||
if let Ok(Some((meta, image))) = b.reference_image_preview(&json!({"doc":doc,"taskId":id})) {
|
||||
let _ = events.send(Event::Preview(meta, image));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
}
|
||||
merge_reference_identity(&mut item, reference);
|
||||
content.push(item);
|
||||
}
|
||||
if serde_json::to_vec(&content).map_err(|_| "引用内容无法读取")?.len() > 1024 * 1024 {
|
||||
return Err("图片引用较多,请减少本轮引用后再发送".into());
|
||||
}
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
fn live_target<'a>(b: &'a Backend, input: &Value) -> R<(String, &'a str, u64)> {
|
||||
b.check_dispatch()?;
|
||||
let doc = input["doc"].as_u64().ok_or("请先打开项目")?;
|
||||
b.ensure_owner(doc)?;
|
||||
let project = b.locations.get(&doc).ok_or("项目身份尚未绑定")?;
|
||||
Ok((b.scope(), project, doc))
|
||||
}
|
||||
|
||||
pub(super) fn steer(b: &Backend, input: &Value, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<Value> {
|
||||
let (scope, project, doc) = live_target(b, input)?;
|
||||
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":[]});
|
||||
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)?);
|
||||
}
|
||||
b.check_dispatch()?;
|
||||
daemon.steer(&scope, project, doc, &request)
|
||||
}
|
||||
|
||||
pub(super) fn clear_queue(b: &Backend, input: &Value) -> R<Value> {
|
||||
let (scope, project, doc) = live_target(b, input)?;
|
||||
match agent_daemon::current()? {
|
||||
Some(daemon) => {
|
||||
let mut ack = daemon.clear_queue(&scope, project, doc, &input["runId"])?;
|
||||
if let Some(message) = match ack["error"].as_str() {
|
||||
Some("starting") => Some("小壹正在启动,请稍后清空队列"),
|
||||
Some("scope_mismatch") => Some("本轮对话的项目已切换"),
|
||||
Some("no_active_run") => Some("本轮对话已结束"),
|
||||
_ => None,
|
||||
} {
|
||||
ack["error"] = json!(message);
|
||||
}
|
||||
Ok(ack)
|
||||
},
|
||||
None => Ok(json!({"steering":[],"followUp":[]})),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn abort_run(b: &Backend, input: &Value) -> R<Value> {
|
||||
let (scope, project, doc) = live_target(b, input)?;
|
||||
if let Some(daemon) = agent_daemon::current()? {
|
||||
daemon.abort_run(&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"] {
|
||||
|
||||
@ -1091,6 +1091,8 @@ pub struct Workspace {
|
||||
project_tombstones: Vec<Value>,
|
||||
project_list_error: String,
|
||||
pi_run: Option<String>,
|
||||
pi_queued_steering: Vec<String>,
|
||||
pi_queued_followup: Vec<String>,
|
||||
production_stop: Value,
|
||||
production_budget_minutes: u64,
|
||||
pi_ui: pi_ui::State,
|
||||
@ -1642,6 +1644,8 @@ impl Workspace {
|
||||
project_tombstones: vec![],
|
||||
project_list_error: String::new(),
|
||||
pi_run: None,
|
||||
pi_queued_steering: Vec::new(),
|
||||
pi_queued_followup: Vec::new(),
|
||||
production_stop: json!({"mode":null,"state":"idle","reason":null,"error":null}),
|
||||
production_budget_minutes: 120,
|
||||
pi_ui: pi_ui::State::default(),
|
||||
@ -2434,6 +2438,66 @@ impl Workspace {
|
||||
"selected":request_scope["selected"],"subject":request_scope["subject"],"references":request_scope["references"],"requestScope":request_scope,
|
||||
"product":self.creation["brief"],"facts":self.creation["facts"],"sellingPoints":self.creation["sellingPoints"],"plan":self.creation["plan"]})
|
||||
}
|
||||
fn steering_available(&self, app: &PhotocraftApp) -> bool {
|
||||
(self.pi_run.is_some() || matches!(self.busy.as_deref(), Some("agent" | "pi-agent"))
|
||||
|| self.product_production.as_ref().is_some_and(product_production::Run::showing_agent_progress))
|
||||
&& !matches!(self.production_stop["state"].as_str(), Some("stopping" | "delivering"))
|
||||
&& self.production_exit.is_none()
|
||||
&& !self.agent_effects_paused && !self.pi_ui_waiting()
|
||||
&& self.composer_draft_ready(app) && !self.library_blocked()
|
||||
}
|
||||
|
||||
fn can_steer(&self, app: &PhotocraftApp) -> bool {
|
||||
self.steering_available(app) && !self.composer.trim().is_empty()
|
||||
}
|
||||
|
||||
fn steer(&mut self, app: &PhotocraftApp, text: String, behavior: &str) -> bool {
|
||||
let Some(draft_doc) = app.session.active().map(|state| state.doc.id.0) else { return false; };
|
||||
let Some(doc) = self.pi_request_scope["project"]["documentId"].as_u64().or(self.owner_doc) else {
|
||||
self.error = "本轮对话尚未绑定项目,请稍后发送".into();
|
||||
return false;
|
||||
};
|
||||
let result = (|| -> Result<(), String> {
|
||||
self.composer_reference_sync(app);
|
||||
let references = self.composer_reference_snapshot(app)?;
|
||||
let content = reference_media::capture(app, &references)?;
|
||||
self.tx.send(Request::Action("agent-steer".into(), json!({
|
||||
"doc":doc,"draftDoc":draft_doc,"text":text,"behavior":behavior,
|
||||
"references":references,"referenceContent":content,
|
||||
}))).map_err(|_| "本机服务已停止,请保留作品后重启".to_owned())
|
||||
})();
|
||||
match result {
|
||||
Ok(()) => { self.error.clear(); true }
|
||||
Err(error) => { self.error = error; false }
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_steer_queue(&mut self) {
|
||||
if let Some(doc) = self.pi_request_scope["project"]["documentId"].as_u64().or(self.owner_doc)
|
||||
&& self.tx.send(Request::Action("agent-clear-queue".into(), json!({"doc":doc}))).is_err()
|
||||
{
|
||||
self.error = "本机服务已停止,消息队列未清空".into();
|
||||
}
|
||||
}
|
||||
|
||||
fn abort_chat_run(&mut self) {
|
||||
self.pi_queued_steering.clear();
|
||||
self.pi_queued_followup.clear();
|
||||
if self.product_production.is_none()
|
||||
&& (self.pi_run.is_some() || matches!(self.busy.as_deref(), Some("agent" | "pi-agent")))
|
||||
&& let Some(doc) = self.pi_request_scope["project"]["documentId"].as_u64().or(self.owner_doc)
|
||||
&& self.tx.send(Request::Action("agent-abort".into(), json!({"doc":doc}))).is_err()
|
||||
{
|
||||
self.error = "本机服务已停止,原请求需核查".into();
|
||||
}
|
||||
self.stop_production();
|
||||
if self.pi_run.is_none() && self.busy.as_deref() == Some("agent")
|
||||
&& self.pi_request_scope["productProduction"] != true
|
||||
{
|
||||
self.busy = Some("agent-stopping".into());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn submit(&mut self, app: &PhotocraftApp, text: String) {
|
||||
self.submit_turn(app, text, false);
|
||||
}
|
||||
@ -2991,6 +3055,40 @@ impl Workspace {
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if matches!(method.as_str(), "agent-steer" | "agent-clear-queue" | "agent-abort") {
|
||||
match result {
|
||||
Ok(value) if value["accountId"] == self.account["id"] && value["origin"] == self.origin => {
|
||||
if method == "agent-steer" && value["accepted"] != true {
|
||||
if value["doc"].as_u64() != self.loaded_draft || !self.composer_draft_ready(app) { return; }
|
||||
let text = value["text"].as_str().unwrap_or_default();
|
||||
if value["reason"] == "not_streaming" && self.turn_idle() && !self.agent_effects_paused {
|
||||
self.submit(app, text.to_owned());
|
||||
if self.busy.as_deref() == Some("agent") { return; }
|
||||
}
|
||||
if self.composer.is_empty() {
|
||||
self.composer = text.to_owned();
|
||||
self.draft_changed = true;
|
||||
}
|
||||
self.error = value["error"].as_str().unwrap_or(match value["reason"].as_str() {
|
||||
Some("starting") => "小壹正在启动,请稍后发送",
|
||||
Some("scope_mismatch") => "本轮对话的项目已切换,请确认后发送",
|
||||
_ => "本轮已停止接收补充消息,请重新发送",
|
||||
}).to_owned();
|
||||
} else if let Some(error) = value["error"].as_str() {
|
||||
self.error = error.to_owned();
|
||||
}
|
||||
}
|
||||
Err(error) => self.error = error,
|
||||
_ => {}
|
||||
}
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
|
||||
if method == "agent" && self.busy.as_deref() == Some("agent-stopping") {
|
||||
self.busy = Some("agent".into());
|
||||
}
|
||||
|
||||
if method == "client-update" {
|
||||
if let Ok(receipt) = result {
|
||||
self.client_update.receive(receipt);
|
||||
|
||||
@ -1672,7 +1672,7 @@ impl Workspace {
|
||||
if active {
|
||||
let stop = super::stitch_ui::icon_button(ui, "square", 26.0, false, "停止本地自动操作,保留原请求");
|
||||
self.panel_geometry["taskStop"] = rect_value(stop.rect);
|
||||
if stop.clicked() { self.stop_production(); }
|
||||
if stop.clicked() { self.abort_chat_run(); }
|
||||
}
|
||||
});
|
||||
if let Some(ms) = elapsed_ms {
|
||||
@ -1731,7 +1731,7 @@ impl Workspace {
|
||||
if running && !preparing {
|
||||
let stop = super::stitch_ui::icon_button(ui, "square", 26.0, false, "停止本地自动操作,保留原请求");
|
||||
self.panel_geometry["taskStop"] = rect_value(stop.rect);
|
||||
if stop.clicked() { self.stop_production(); }
|
||||
if stop.clicked() { self.abort_chat_run(); }
|
||||
}
|
||||
ui.allocate_ui_with_layout(vec2(ui.available_width(), 26.0), Layout::left_to_right(Align::Center), |ui| {
|
||||
super::stitch_ui::ai_loader(ui, id.with("loader"), running, true);
|
||||
@ -1939,6 +1939,11 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
user_bubble_with_reveal(ui, text, started, self.reduce_motion);
|
||||
if turn.user_index.is_some_and(|index| self.messages[index]["kind"] == "steer" && self.messages[index]["delivered"] == true) {
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
ui.label(RichText::new("已插话").size(11.0).color(t.text_dim));
|
||||
});
|
||||
}
|
||||
});
|
||||
agent_motion::message_repaint(ui, response.response.rect, enter);
|
||||
ui.add_space(18.0);
|
||||
@ -2603,6 +2608,7 @@ impl Workspace {
|
||||
self.busy.as_deref(),
|
||||
Some(
|
||||
"agent"
|
||||
| "agent-stopping"
|
||||
| "pi-agent"
|
||||
| "recover"
|
||||
| "image"
|
||||
@ -2821,7 +2827,7 @@ impl Workspace {
|
||||
if let Some(target) = located { self.canvas_locate(target); }
|
||||
if let Some(stop) = result.stop {
|
||||
self.panel_geometry["taskStop"] = rect_value(stop.rect);
|
||||
if stop.clicked() { self.stop_production(); }
|
||||
if stop.clicked() { self.abort_chat_run(); }
|
||||
}
|
||||
if let Some(controls) = &result.controls {
|
||||
use timeline::StopMode;
|
||||
@ -2904,7 +2910,35 @@ impl Workspace {
|
||||
if self.result_needs_check() || (!self.pending() && self.ready_image.is_some()) { height += button + 16.0 + gap; }
|
||||
if !self.error.is_empty() && self.error != self.library_message { height += super::operation_error::inline_height(ui,&self.error,(ui.available_width()-20.0).max(1.0)) + gap; }
|
||||
if !self.needs_library_login() && !self.library_blocked() && !self.key_saved { height += button + gap; }
|
||||
height
|
||||
height + self.steering_queue_height()
|
||||
}
|
||||
|
||||
fn steering_queue_height(&self) -> f32 {
|
||||
if self.pi_run.is_none() || self.agent_effects_paused || self.loaded_draft != self.owner_doc { return 0.0; }
|
||||
let groups = usize::from(!self.pi_queued_steering.is_empty()) + usize::from(!self.pi_queued_followup.is_empty());
|
||||
if groups == 0 { 0.0 } else { (groups as f32 * 19.0).max(26.0) + 6.0 }
|
||||
}
|
||||
|
||||
fn steering_queue_ui(&mut self, ui: &mut Ui) {
|
||||
let height = self.steering_queue_height();
|
||||
if height == 0.0 { return; }
|
||||
let tint = Tokens::get(ui.ctx()).agent().text_dim;
|
||||
ui.allocate_ui_with_layout(vec2(ui.available_width(), height - 6.0), Layout::right_to_left(Align::Center), |ui| {
|
||||
let clear = super::stitch_ui::icon_button(ui, "x", 26.0, false, "清空待发送消息");
|
||||
if clear.clicked() { self.clear_steer_queue(); }
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 0.0;
|
||||
for (title, messages) in [
|
||||
("待插话 · 当前步骤后注入", &self.pi_queued_steering),
|
||||
("已排队 · 本轮结束后发送", &self.pi_queued_followup),
|
||||
] {
|
||||
if messages.is_empty() { continue; }
|
||||
let preview = messages.join(" / ").replace('\n', " ");
|
||||
ui.add(egui::Label::new(RichText::new(format!("{title} {preview}")).size(12.0).color(tint)).truncate())
|
||||
.on_hover_text(format!("{title}\n{}", messages.join("\n")));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn can_send(&self, app: &PhotocraftApp) -> bool {
|
||||
@ -2912,6 +2946,11 @@ impl Workspace {
|
||||
}
|
||||
|
||||
fn can_send_with(&self, app: &PhotocraftApp, image: bool) -> bool {
|
||||
if !image && self.can_steer(app) { return true; }
|
||||
if !image && self.has_paused_production() && self.turn_idle() {
|
||||
return self.can_resume_product() && self.composer_draft_ready(app)
|
||||
&& !self.library_blocked() && !self.composer.trim().is_empty();
|
||||
}
|
||||
let target_ready = !image
|
||||
|| self.template_workflow["canvasFirst"] != true
|
||||
|| (self.template_workflow["capabilities"]["imageDispatchAllowed"] == true
|
||||
@ -2934,7 +2973,7 @@ impl Workspace {
|
||||
}
|
||||
|
||||
fn send_discussion(&mut self, app: &PhotocraftApp) {
|
||||
if !self.composer_text_send_allowed_for(app) {
|
||||
if !self.can_steer(app) && !self.has_paused_production() && !self.composer_text_send_allowed_for(app) {
|
||||
self.error = "当前对话模型暂不支持图片,请先移除附件或使用生图".into();
|
||||
return;
|
||||
}
|
||||
@ -2971,6 +3010,21 @@ impl Workspace {
|
||||
}
|
||||
let text = self.composer.clone();
|
||||
if self.image_mode == "chat" {
|
||||
if self.can_steer(app) {
|
||||
if self.steer(app, text, "steer") {
|
||||
self.composer.clear();
|
||||
self.draft_changed = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.has_paused_production() && self.turn_idle() {
|
||||
self.resume_product_production_with(app, Some(text));
|
||||
if !self.has_paused_production() {
|
||||
self.composer.clear();
|
||||
self.draft_changed = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.submit(app, text);
|
||||
} else {
|
||||
self.generate(app, text, &self.image_mode.clone());
|
||||
@ -3069,6 +3123,9 @@ impl Workspace {
|
||||
}
|
||||
self.panel_geometry["reconnect"] = Value::Null;
|
||||
self.error_notice_ui(ui);
|
||||
self.steering_queue_ui(ui);
|
||||
self.panel_geometry["send"] = Value::Null;
|
||||
self.panel_geometry["stop"] = Value::Null;
|
||||
let shortcut = composer_enter(ui, input_id);
|
||||
let morph = self.panel_geometry["composerMorph"].as_f64().unwrap_or(1.0) as f32;
|
||||
let can_stop = self.pending() && !self.batch_progress_visible() && !self.agent_effects_paused;
|
||||
@ -3132,7 +3189,10 @@ impl Workspace {
|
||||
.max_height(input_rect.height().max(24.0)).min_scrolled_height(input_rect.height().max(24.0))
|
||||
.content_margin(egui::Margin::ZERO).auto_shrink([false, false])
|
||||
.show(&mut input_ui, |ui| {
|
||||
let editor=super::stitch_ui::text_input(&mut self.composer, if !draft_ready { "正在加载项目草稿…" } else { "告诉小壹,你想怎么改…" }, true)
|
||||
let hint = if !draft_ready { "正在加载项目草稿…" }
|
||||
else if self.steering_available(app) { "继续补充要求,将在当前步骤后插话…" }
|
||||
else { "告诉小壹,你想怎么改…" };
|
||||
let editor=super::stitch_ui::text_input(&mut self.composer, hint, true)
|
||||
.layouter(&mut layouter).id(input_id).return_key(egui::KeyboardShortcut::new(egui::Modifiers::SHIFT, egui::Key::Enter))
|
||||
.font(FontId::proportional(14.0)).desired_rows(1).desired_width(f32::INFINITY)
|
||||
.min_size(vec2(0.0, input_rect.height().max(24.0))).margin(egui::Margin::ZERO).frame(Frame::NONE).show(ui);
|
||||
@ -3184,17 +3244,23 @@ impl Workspace {
|
||||
let mut toolbar = ui.new_child(egui::UiBuilder::new().id_salt("composer-toolbar").max_rect(toolbar_rect));
|
||||
toolbar.set_opacity(((morph - 0.3) / 0.7).clamp(0.0, 1.0));
|
||||
if morph < 0.95 { toolbar.disable(); }
|
||||
let can = self.can_send_with(app, false);
|
||||
let connect = (self.needs_library_login() || self.library_blocked())
|
||||
&& draft_ready && self.busy.is_none() && !self.composer.trim().is_empty();
|
||||
let mut send_clicked = false;
|
||||
if morph > 0.3 {
|
||||
let ui = &mut toolbar;
|
||||
// One responsive toolbar. Narrow docks retain every action with
|
||||
// an accessible icon; only labels collapse, never controls.
|
||||
ui.horizontal(|ui| {
|
||||
let narrow = ui.available_width() < 260.0;
|
||||
let ultra = ui.available_width() < 145.0;
|
||||
let ultra = ui.available_width() < if can_stop { 175.0 } else { 145.0 };
|
||||
let action_size = if narrow { 24.0 } else { 28.0 };
|
||||
ui.spacing_mut().item_spacing.x = if narrow { 1.0 } else { 3.0 };
|
||||
ui.spacing_mut().button_padding.x = 4.0;
|
||||
let right_width = 30.0 + if ultra { 0.0 } else { action_size + ui.spacing().item_spacing.x };
|
||||
let right_width = 30.0
|
||||
+ if can_stop { 30.0 + ui.spacing().item_spacing.x } else { 0.0 }
|
||||
+ if ultra { 0.0 } else { action_size + ui.spacing().item_spacing.x };
|
||||
let left_width = (ui.available_width() - right_width - ui.spacing().item_spacing.x).max(1.0);
|
||||
let mut compact_settings_anchor = None;
|
||||
ui.allocate_ui_with_layout(vec2(left_width, 42.0), Layout::left_to_right(Align::Center), |ui| {
|
||||
@ -3244,28 +3310,23 @@ impl Workspace {
|
||||
}
|
||||
});
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
let response = ui
|
||||
.add_enabled_ui(can || connect, |ui| super::stitch_ui::send_action_button(ui, Id::unique("composer-send"), self.reduce_motion))
|
||||
.inner
|
||||
.on_hover_text(if connect { "连接素材库后发送" }
|
||||
else if self.can_steer(app) { "Enter 插话 · Shift+Enter 换行" }
|
||||
else { "Enter 发送 · Shift+Enter 换行" })
|
||||
.on_disabled_hover_text(if self.unknown { "先核查原请求结果" }
|
||||
else if !self.composer_text_send_allowed_for(app) { "当前对话模型暂不支持图片,请先移除附件或使用生图" }
|
||||
else { "打开项目、连接模型并输入要求后发送" });
|
||||
self.panel_geometry["send"] = rect_value(response.rect);
|
||||
send_clicked = response.clicked();
|
||||
if compact_stop {
|
||||
ui.allocate_exact_size(vec2(30.0,30.0), Sense::hover());
|
||||
} else if can_stop {
|
||||
let stop = super::stitch_ui::icon_button(ui, "square", 30.0, false, "停止小壹,保留原请求");
|
||||
self.panel_geometry["stop"] = rect_value(stop.rect);
|
||||
if stop.clicked() { self.stop_production(); }
|
||||
} else {
|
||||
let can = self.can_send_with(app, false);
|
||||
let connect = (self.needs_library_login() || self.library_blocked())
|
||||
&& self.composer_draft_ready(app) && self.busy.is_none() && !self.composer.trim().is_empty();
|
||||
let response = ui
|
||||
.add_enabled_ui(can || connect, |ui| super::stitch_ui::send_action_button(ui, Id::unique("composer-send"), self.reduce_motion))
|
||||
.inner
|
||||
.on_hover_text(if connect { "连接素材库后发送" } else { "Enter 发送 · Shift+Enter 换行" })
|
||||
.on_disabled_hover_text(if self.unknown { "先核查原请求结果" }
|
||||
else if !self.composer_text_send_allowed_for(app) { "当前对话模型暂不支持图片,请先移除附件或使用生图" }
|
||||
else { "打开项目、连接模型并输入要求后发送" });
|
||||
self.panel_geometry["send"] = rect_value(response.rect);
|
||||
if response.clicked() || (shortcut && (can || connect)) {
|
||||
if connect { self.open_library_login(); }
|
||||
else { self.send_discussion(app); }
|
||||
}
|
||||
if stop.clicked() { self.abort_chat_run(); }
|
||||
}
|
||||
if !ultra {
|
||||
let response = super::stitch_ui::icon_button(ui, "sliders-horizontal", action_size, self.model_settings, "连接设置、通知与警告");
|
||||
@ -3292,18 +3353,22 @@ impl Workspace {
|
||||
if let Some(anchor) = compact_settings_anchor { self.settings_popup(ui, &anchor); }
|
||||
});
|
||||
}
|
||||
if send_clicked || (shortcut && (can || connect)) {
|
||||
if connect { self.open_library_login(); }
|
||||
else { self.send_discussion(app); }
|
||||
}
|
||||
// 设置浮层里点的"检查更新"在这里派发:浮层本身拿不到 app。
|
||||
self.flush_client_update_request(app);
|
||||
let compact_stop_rect = Id::unique("jiansun-composer-compact-stop-rect");
|
||||
if compact_stop {
|
||||
let compact_center = egui::pos2(surface_rect.right() - 27.0, mini_input.center().y);
|
||||
let expanded_center = egui::pos2(toolbar_rect.right() - 15.0, toolbar_rect.center().y);
|
||||
let expanded_center = egui::pos2(toolbar_rect.right() - 48.0, toolbar_rect.center().y);
|
||||
let rect = Rect::from_center_size(compact_center.lerp(expanded_center,morph),vec2(30.0,30.0));
|
||||
let mut control = ui.new_child(egui::UiBuilder::new().id_salt("composer-compact-stop").max_rect(rect));
|
||||
let stop = super::stitch_ui::icon_button(&mut control, "square", 30.0, false, "停止小壹,保留原请求");
|
||||
self.panel_geometry["stop"] = rect_value(stop.rect);
|
||||
ui.data_mut(|data| data.insert_temp(compact_stop_rect, stop.rect));
|
||||
if stop.clicked() { self.stop_production(); }
|
||||
if stop.clicked() { self.abort_chat_run(); }
|
||||
} else {
|
||||
ui.data_mut(|data| data.remove::<Rect>(compact_stop_rect));
|
||||
}
|
||||
@ -8852,27 +8917,180 @@ mod tests {
|
||||
assert!(!w.error.is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn composer_keeps_the_draft_and_disables_both_send_modes_until_the_pi_run_ends() {
|
||||
fn composer_steers_an_active_chat_and_keeps_image_generation_disabled() {
|
||||
let (mut app,requests) = dock_fixture();
|
||||
let mut w = app.jiansun.take().unwrap();
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
let draft = w.composer.clone();
|
||||
let messages = w.messages.clone();
|
||||
w.pi_run = Some("12345678-1234-1234-1234-123456789012".into());
|
||||
w.busy = None;
|
||||
assert!(w.pending());
|
||||
assert!(!w.can_send_with(&app,false));
|
||||
w.busy = Some("agent".into());
|
||||
w.owner_doc = Some(doc);
|
||||
w.pi_request_scope = json!({"project":{"documentId":doc},"subject":{"kind":"project"}});
|
||||
w.stream_reply = "未结束的回复".into();
|
||||
let scope = w.pi_request_scope.clone();
|
||||
assert!(w.can_send_with(&app,false));
|
||||
assert!(!w.can_send_with(&app,true));
|
||||
w.send_composer(&app);
|
||||
assert_eq!(w.composer,draft);
|
||||
let Request::Action(method,input) = requests.try_recv().unwrap() else { panic!("expected an action") };
|
||||
assert_eq!(method, "agent-steer");
|
||||
assert_eq!(input["text"], draft);
|
||||
assert_eq!(input["behavior"], "steer");
|
||||
assert_eq!(input["doc"], doc);
|
||||
assert!(w.composer.is_empty());
|
||||
assert_eq!(w.messages,messages);
|
||||
assert_eq!(w.pi_request_scope,scope);
|
||||
assert_eq!(w.busy.as_deref(),Some("agent"));
|
||||
assert!(w.pi_run.is_some());
|
||||
assert_eq!(w.stream_reply,"未结束的回复");
|
||||
assert!(requests.try_recv().is_err());
|
||||
w.pi_run = None;
|
||||
assert!(w.can_send(&app));
|
||||
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
w.pi_request_scope["outputId"] = json!("detail");
|
||||
w.canvas_workspace.output = "sku".into();
|
||||
w.composer = "补充详情页的安排".into();
|
||||
assert!(w.can_steer(&app));
|
||||
w.send_composer(&app);
|
||||
assert!(matches!(requests.try_recv().unwrap(),Request::Action(method,_) if method=="agent"));
|
||||
assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent-steer" && input["doc"] == doc));
|
||||
assert_eq!(w.pi_request_scope["outputId"], "detail");
|
||||
assert_eq!(w.canvas_workspace.output, "sku");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_composer_renders_stop_beside_send_and_accepts_enter() {
|
||||
let (mut app, requests) = dock_fixture();
|
||||
let ctx = egui::Context::default();
|
||||
PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium);
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
let w = app.jiansun.as_mut().unwrap();
|
||||
w.reduce_motion = true;
|
||||
w.owner_doc = Some(doc);
|
||||
w.busy = Some("agent".into());
|
||||
w.pi_run = Some("12345678-1234-1234-1234-123456789012".into());
|
||||
w.pi_queued_steering = vec!["保留高光".into()];
|
||||
w.pi_queued_followup = vec!["说明用色".into()];
|
||||
for _ in 0..3 { dock_frame(&ctx, &mut app, vec![]); }
|
||||
let w = app.jiansun.as_ref().unwrap();
|
||||
let send = geometry(w, "send");
|
||||
let stop = geometry(w, "stop");
|
||||
assert!(!send.intersects(stop));
|
||||
assert!(geometry(w, "composer").contains_rect(send.union(stop)));
|
||||
ctx.memory_mut(|memory| memory.request_focus(super::super::composer_input_id()));
|
||||
dock_frame(&ctx, &mut app, vec![egui::Event::Key {
|
||||
key:egui::Key::Enter,physical_key:None,pressed:true,repeat:false,modifiers:egui::Modifiers::NONE,
|
||||
}]);
|
||||
assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent-steer" && input["doc"] == doc));
|
||||
app.jiansun.as_mut().unwrap().composer = "保留草稿".into();
|
||||
let center = stop.center();
|
||||
for pressed in [true, false] {
|
||||
dock_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(center), egui::Event::PointerButton {
|
||||
pos:center,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE,
|
||||
}]);
|
||||
}
|
||||
assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent-abort" && input["doc"] == doc));
|
||||
assert!(app.jiansun.as_ref().unwrap().pi_queued_steering.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_steering_and_followup_render_above_the_composer_and_can_be_cleared() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let (mut app, requests) = dock_fixture();
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
let mut w = app.jiansun.take().unwrap();
|
||||
w.owner_doc = Some(doc);
|
||||
w.pi_run = Some("12345678-1234-1234-1234-123456789012".into());
|
||||
w.pi_queued_steering = vec!["保留高光".into()];
|
||||
w.pi_queued_followup = vec!["说明用色".into()];
|
||||
let mut harness = egui_kittest::Harness::builder()
|
||||
.with_context_setup(crate::cjk_fonts::install_system_provider_for_tests)
|
||||
.with_size(vec2(520.0, 300.0))
|
||||
.build_ui_state(|ui, (w, app): &mut (Workspace, PhotocraftApp)| w.composer_ui(app, ui), (w, app));
|
||||
harness.run_steps(3);
|
||||
assert_eq!(harness.query_all_by_label("待插话 · 当前步骤后注入 保留高光").count(), 1);
|
||||
assert_eq!(harness.query_all_by_label("已排队 · 本轮结束后发送 说明用色").count(), 1);
|
||||
let clear = harness.get_by_role_and_label(egui::accesskit::Role::Button, "清空待发送消息");
|
||||
assert!(clear.rect().bottom() <= geometry(&harness.state().0, "composer").top());
|
||||
clear.click();
|
||||
harness.run_steps(2);
|
||||
assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent-clear-queue" && input["doc"] == doc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Offscreen composer evidence; writes to PHOTOCRAFT_AGENT_QA_OUT"]
|
||||
fn gpu_steering_composer_at_desktop_and_narrow_widths() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let _guard = photocraft_testkit::gpu_lock();
|
||||
let directory = std::path::PathBuf::from(std::env::var("PHOTOCRAFT_AGENT_QA_OUT").unwrap());
|
||||
for width in [520.0, 260.0] {
|
||||
let (mut app, requests) = dock_fixture();
|
||||
let mut w = app.jiansun.take().unwrap();
|
||||
w.reduce_motion = true;
|
||||
w.busy = Some("agent".into());
|
||||
w.pi_run = Some("12345678-1234-1234-1234-123456789012".into());
|
||||
w.owner_doc = w.loaded_draft;
|
||||
w.pi_queued_steering = vec!["保留高光与木纹细节".into()];
|
||||
w.pi_queued_followup = vec!["说明本轮用色".into()];
|
||||
let mut harness = egui_kittest::Harness::builder()
|
||||
.with_context_setup(|ctx| {
|
||||
PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium);
|
||||
crate::cjk_fonts::install_system_provider_for_tests(ctx);
|
||||
})
|
||||
.with_size(vec2(width, 300.0))
|
||||
.wgpu()
|
||||
.build_ui_state(|ui, (w, app): &mut (Workspace, PhotocraftApp)| w.composer_ui(app, ui), (w, app));
|
||||
harness.run_steps(3);
|
||||
let w = &harness.state().0;
|
||||
let composer = geometry(w, "composer");
|
||||
let stop = geometry(w, "stop");
|
||||
let send = geometry(w, "send");
|
||||
assert!(composer.contains_rect(stop.union(send)));
|
||||
assert!(!stop.intersects(send));
|
||||
let clear = harness.get_by_role_and_label(egui::accesskit::Role::Button, "清空待发送消息");
|
||||
assert!(clear.rect().bottom() <= composer.top());
|
||||
assert!(requests.try_recv().is_err());
|
||||
harness.render().unwrap().save(directory.join(format!("steering-composer-{width}.png"))).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_steering_resubmits_when_idle_and_preserves_an_unsent_draft_on_error() {
|
||||
let (mut app, requests) = dock_fixture();
|
||||
let mut w = app.jiansun.take().unwrap();
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
let ctx = egui::Context::default();
|
||||
w.composer.clear();
|
||||
let mut receipt = json!({"accountId":w.account["id"],"origin":w.origin,"doc":doc,
|
||||
"accepted":false,"reason":"not_streaming","text":"补充一下排版"});
|
||||
w.receive_json_event(&mut app, &ctx, "agent-steer".into(), Ok(receipt.clone()));
|
||||
assert!(matches!(requests.try_recv().unwrap(), Request::Action(method,input) if method == "agent" && input["text"] == receipt["text"]));
|
||||
receipt["reason"] = json!("starting");
|
||||
receipt["error"] = json!("本轮正在连接");
|
||||
w.receive_json_event(&mut app, &ctx, "agent-steer".into(), Ok(receipt));
|
||||
assert_eq!(w.composer, "补充一下排版");
|
||||
assert_eq!(w.error, "本轮正在连接");
|
||||
assert!(requests.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_delivered_steering_has_the_timeline_tag() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let (mut app, _) = dock_fixture();
|
||||
let mut w = app.jiansun.take().unwrap();
|
||||
w.reduce_motion = true;
|
||||
w.messages = vec![
|
||||
json!({"role":"user","text":"普通消息"}),
|
||||
json!({"role":"user","kind":"steer","delivered":true,"text":"保留高光"}),
|
||||
];
|
||||
let h = egui_kittest::Harness::builder().with_context_setup(crate::cjk_fonts::install_system_provider_for_tests)
|
||||
.with_size(vec2(300.0, 260.0)).build_ui_state(
|
||||
|ui, w: &mut Workspace| {
|
||||
for turn in turns(&w.messages) {
|
||||
w.turn_ui(ui, turn, Id::NULL, w.messages.len(), false, false, None);
|
||||
}
|
||||
}, w);
|
||||
assert_eq!(h.query_all_by_label("已插话").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_discussion_needs_a_model_but_no_brand_rules_or_canvas_write_grant() {
|
||||
let (tx, requests) = mpsc::channel();
|
||||
|
||||
@ -288,6 +288,9 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
return Err("画布与模型账户不一致".into());
|
||||
}
|
||||
let own_submit = w.busy.as_deref() == Some("agent") && w.pi_run.is_none() && input["documentId"].as_u64() == w.owner_doc;
|
||||
if w.busy.as_deref() == Some("agent-stopping") {
|
||||
return Err(BridgeFailure::new("cancelled", false, false, "本轮已停止"));
|
||||
}
|
||||
let scoped_production = private && own_submit && w.pi_request_scope["productProduction"] == true
|
||||
&& w.production_can_use_scoped_pending();
|
||||
if (w.busy.is_some() && !own_submit) || w.pi_run.is_some() || (w.unknown && !scoped_production && !w.scoped_production_pending()) || !w.queue.is_empty() || w.pending_image.is_some() {
|
||||
@ -333,6 +336,8 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
}
|
||||
w.owner_doc = Some(st.doc.id.0);
|
||||
w.expected_revision = st.revision;
|
||||
w.pi_queued_steering.clear();
|
||||
w.pi_queued_followup.clear();
|
||||
w.pi_run = Some(run.to_owned());
|
||||
// A visual choice belongs to one explicit turn; a new run cannot
|
||||
// restore permission. Keep its same-scope images as a read-only receipt.
|
||||
@ -371,6 +376,26 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
if method == "pi-edit-reconcile" { return super::agent_native::reconcile_edit(w, app, input).map_err(BridgeFailure::from); }
|
||||
if method == "pi-workflow-reconcile" { return workflow_bridge::reconcile(w, app, input).map_err(BridgeFailure::from); }
|
||||
identity(w, input)?;
|
||||
if private && matches!(method, "pi-queue-update" | "pi-user-delivered") {
|
||||
if !app.session.active().is_some_and(|state| Some(state.doc.id.0) == w.owner_doc) {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
if method == "pi-queue-update" {
|
||||
if w.agent_effects_paused { return Ok(Value::Null); }
|
||||
let messages = |key: &str| -> Vec<String> {
|
||||
input[key].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect()
|
||||
};
|
||||
w.pi_queued_steering = messages("steering");
|
||||
w.pi_queued_followup = messages("followUp");
|
||||
} else {
|
||||
let text = input["text"].as_str().filter(|text| !text.trim().is_empty()).ok_or("补充消息为空")?;
|
||||
w.messages.push(json!({"role":"user","kind":"steer","delivered":true,"text":text,
|
||||
"run":w.pi_run,"target":w.pi_request_scope["subject"],"behavior":input["behavior"],"timestamp":input["timestamp"]}));
|
||||
w.draft_changed = true;
|
||||
}
|
||||
if let Some(ctx) = ctx { ctx.request_repaint(); }
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
let key = &w.pi_request_scope["documentKey"];
|
||||
let opening = w.production_canvas_opening(app);
|
||||
let clean_input;
|
||||
@ -401,7 +426,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
&& (input["action"] == "pending" || input["targetOutput"].is_object()
|
||||
&& matches!(input["action"].as_str(), Some("read" | "prepare" | "dispatch" | "transform" | "product_reference")));
|
||||
if w.production_boundary_pending() && !scoped_read && !(opening && scoped_image) && !matches!(method,
|
||||
"pi-state" | "pi-activity" | "pi-delta" | "pi-context-usage" | "pi-production-open"
|
||||
"pi-state" | "pi-activity" | "pi-delta" | "pi-reply" | "pi-context-usage" | "pi-production-open"
|
||||
| "pi-production-finish" | "pi-production-finish-status" | "pi-workflow-poll" | "pi-native-poll" | "pi-write-request" | "pi-end") {
|
||||
return Err(BridgeFailure::new("production_canvas_pending", true, false, "请等待画布保存或交付回执"));
|
||||
}
|
||||
@ -420,6 +445,8 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
// Release only the old run; never append its text to the new canvas.
|
||||
w.allow_apply = false;
|
||||
w.pi_write_blocked = true;
|
||||
w.pi_queued_steering.clear();
|
||||
w.pi_queued_followup.clear();
|
||||
w.pi_run = None;
|
||||
w.pi_request_scope = Value::Null;
|
||||
w.pi_native = false;
|
||||
@ -953,6 +980,8 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
Ok(status(w, app))
|
||||
}
|
||||
"pi-end" => {
|
||||
w.pi_queued_steering.clear();
|
||||
w.pi_queued_followup.clear();
|
||||
w.pi_ui_cancel("回合已结束");
|
||||
if !w.queue.is_empty() {
|
||||
return Err("画布操作尚未落定".into());
|
||||
@ -1001,6 +1030,8 @@ impl Workspace {
|
||||
if self.pi_run.as_deref().is_some_and(|run| self.workflow.operation_in_flight(run)) { self.handover(); }
|
||||
if !slot_running { self.busy = None; }
|
||||
self.allow_apply = false;
|
||||
self.pi_queued_steering.clear();
|
||||
self.pi_queued_followup.clear();
|
||||
self.pi_run = None;
|
||||
self.pi_native = false;
|
||||
self.unknown = slot_running;
|
||||
@ -1054,6 +1085,31 @@ mod tests {
|
||||
(w, app, input)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steering_queue_and_delivered_user_message_follow_live_reply_order() {
|
||||
let (mut w, mut app, input) = activity_fixture();
|
||||
let run = &input["run"];
|
||||
let queued = json!({"run":run,"steering":["补充颜色"],"followUp":["解释排版"]});
|
||||
let ctx = egui::Context::default();
|
||||
let before = w.messages.len();
|
||||
private_action_in_ui(&mut w, &mut app, &ctx, "pi-queue-update", &queued).unwrap();
|
||||
assert_eq!(w.pi_queued_steering, ["补充颜色"]);
|
||||
assert_eq!(w.pi_queued_followup, ["解释排版"]);
|
||||
assert_eq!(w.messages.len(), before);
|
||||
|
||||
let target = w.pi_request_scope["subject"].clone();
|
||||
private_action_in_ui(&mut w, &mut app, &ctx, "pi-reply", &json!({"run":run,"text":"先说明当前步骤"})).unwrap();
|
||||
let delivered = json!({"run":run,"text":"补充颜色","behavior":"steer","timestamp":123});
|
||||
private_action_in_ui(&mut w, &mut app, &ctx, "pi-user-delivered", &delivered).unwrap();
|
||||
assert_eq!(w.messages[before]["text"], "先说明当前步骤");
|
||||
assert_eq!(w.messages[before + 1], json!({"role":"user","kind":"steer","delivered":true,
|
||||
"text":"补充颜色","run":run,"target":target,"behavior":"steer","timestamp":123}));
|
||||
|
||||
private_action_in_ui(&mut w, &mut app, &ctx, "pi-end", &json!({"run":run,"text":"完成"})).unwrap();
|
||||
assert!(w.pi_queued_steering.is_empty() && w.pi_queued_followup.is_empty());
|
||||
assert!(private_action_in_ui(&mut w, &mut app, &ctx, "pi-user-delivered", &delivered).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_auth_epoch_change_rejects_a_queued_write_before_the_account_event() {
|
||||
use std::sync::{Arc, atomic::{AtomicU64, Ordering}};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user