дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 03:14:38 +02:00
perf(agents): send a running tool's output as the text it grew by (#5476)
A running tool's output was resent whole on every flush, so long outputs sent megabytes to the UI. The backend now sends a toolOutput event with only the appended text when the new output starts with everything already sent (checked by the sent length and a hash of the sent text); any replacement or other change goes out as a whole Entry. Agent and thought messages use the same check. PROTOCOL_VERSION is bumped to 4 so an older app refuses a newer server instead of showing stale output. Co-authored-by: Mr0Bread <[email protected]>
Цей коміт міститься в:
1 джерело
c5f7b3ae98
коміт
40c616e46d
8 files changed
+556
-65
No files matched your search
@@ -44,7 +44,9 @@ use ide_vcs::Repo;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
|
||||
use std::hash::Hasher;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
@@ -570,8 +572,8 @@ struct Task {
|
||||
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
|
||||
config_sent: Mutex<HashSet<(String, String)>>,
|
||||
dirty: Mutex<BTreeSet<(Session, usize)>>,
|
||||
/// How much of each session's streaming message was last sent, so the next flush sends the rest.
|
||||
streamed: Mutex<HashMap<Session, Sent>>,
|
||||
/// What was last sent of the entries that stream, so the next flush sends the rest.
|
||||
streamed: Mutex<Streamed>,
|
||||
flush_scheduled: AtomicBool,
|
||||
stderr: Mutex<VecDeque<String>>,
|
||||
/// Saves asked for (see `persist`); the file holds those up to `file.saved`.
|
||||
@@ -2266,7 +2268,7 @@ impl Task {
|
||||
skills_reload_pending: AtomicBool::new(false),
|
||||
config_sent: Mutex::new(HashSet::new()),
|
||||
dirty: Mutex::new(BTreeSet::new()),
|
||||
streamed: Mutex::new(HashMap::new()),
|
||||
streamed: Mutex::new(Streamed::default()),
|
||||
flush_scheduled: AtomicBool::new(false),
|
||||
stderr: Mutex::new(VecDeque::new()),
|
||||
saves_asked: AtomicU64::new(0),
|
||||
@@ -2531,7 +2533,7 @@ impl Task {
|
||||
.into_iter()
|
||||
.filter_map(|(subagent, i)| {
|
||||
let entry = s.conversation.timeline(&subagent)?.entries.get(i)?;
|
||||
Some(entry_event(&self.id, &mut streamed, subagent, i, entry))
|
||||
entry_event(&self.id, &mut streamed, subagent, i, entry)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
@@ -4402,80 +4404,160 @@ fn stdio_mcp_servers(executable: Option<&std::path::Path>, supported: bool, root
|
||||
vec![json!({ "name": BUILTIN_SERVER, "command": command[0], "args": command[1..], "env": env })]
|
||||
}
|
||||
|
||||
/// What was sent of a streaming message: its first `bytes` (`utf16` UTF-16 units), which
|
||||
/// ended with `tail`. A message only grows while it streams, so its tail tells a message
|
||||
/// that went on from one that was replaced without comparing (or keeping) all of it.
|
||||
/// What was sent of a streaming text: its first `bytes` (`utf16` UTF-16 units), hashed. The
|
||||
/// text only grows while it streams; the hash tells one that went on from one that was replaced
|
||||
/// (at its end or anywhere before) without keeping a copy of it.
|
||||
struct Sent {
|
||||
index: usize,
|
||||
bytes: usize,
|
||||
utf16: usize,
|
||||
tail: String,
|
||||
hash: u64,
|
||||
}
|
||||
|
||||
const SENT_TAIL: usize = 64;
|
||||
|
||||
impl Sent {
|
||||
fn new(index: usize, text: &str) -> Self {
|
||||
Self::after(index, text, 0, 0)
|
||||
Self { index, bytes: text.len(), utf16: text.encode_utf16().count(), hash: Self::digest(text) }
|
||||
}
|
||||
|
||||
/// `text` as sent, of which the first `bytes` (`utf16` units) were sent before.
|
||||
fn after(index: usize, text: &str, bytes: usize, utf16: usize) -> Self {
|
||||
let mut start = text.len().saturating_sub(SENT_TAIL);
|
||||
while !text.is_char_boundary(start) {
|
||||
start -= 1;
|
||||
fn digest(text: &str) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
hasher.write(text.as_bytes());
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// `text` at `index` as sent after this, when it is this text with more at the end.
|
||||
fn extended(&self, index: usize, text: &str) -> Option<Self> {
|
||||
if self.index != index || text.len() <= self.bytes || !text.is_char_boundary(self.bytes) {
|
||||
return None;
|
||||
}
|
||||
let utf16 = utf16 + text[bytes..].encode_utf16().count();
|
||||
Self { index, bytes: text.len(), utf16, tail: text[start..].to_owned() }
|
||||
let mut hasher = DefaultHasher::new();
|
||||
hasher.write(&text.as_bytes()[..self.bytes]);
|
||||
if hasher.finish() != self.hash {
|
||||
return None;
|
||||
}
|
||||
let more = &text[self.bytes..];
|
||||
hasher.write(more.as_bytes());
|
||||
Some(Self { index, bytes: text.len(), utf16: self.utf16 + more.encode_utf16().count(), hash: hasher.finish() })
|
||||
}
|
||||
|
||||
/// Whether `text` at `index` is this message, gone on.
|
||||
fn extended_by(&self, index: usize, text: &str) -> bool {
|
||||
self.index == index
|
||||
&& text.len() > self.bytes
|
||||
&& text.is_char_boundary(self.bytes)
|
||||
&& text[..self.bytes].ends_with(&self.tail)
|
||||
/// Whether `text` is exactly what was sent.
|
||||
fn is(&self, text: &str) -> bool {
|
||||
text.len() == self.bytes && Self::digest(text) == self.hash
|
||||
}
|
||||
}
|
||||
|
||||
/// A running tool call as last sent: the entry without its output, and what was sent of that.
|
||||
struct SentTool {
|
||||
call: AgentEntry,
|
||||
output: Sent,
|
||||
}
|
||||
|
||||
/// What each window was last sent of the entries that stream, so the next flush sends the rest.
|
||||
#[derive(Default)]
|
||||
struct Streamed {
|
||||
/// The message each session streams now.
|
||||
messages: HashMap<Session, Sent>,
|
||||
/// The tool calls still running, by session and entry index.
|
||||
tools: HashMap<(Session, usize), SentTool>,
|
||||
}
|
||||
|
||||
impl Streamed {
|
||||
fn clear(&mut self) {
|
||||
self.messages.clear();
|
||||
self.tools.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// The event that brings the UI's copy of entry `i` up to date: only the new text when
|
||||
/// it extends the message last sent for the session, else the whole entry.
|
||||
/// it extends the message (or the tool output) last sent, else the whole entry; `None`
|
||||
/// when the UI's copy of a tool already is the entry.
|
||||
fn entry_event(
|
||||
task: &str,
|
||||
streamed: &mut HashMap<Session, Sent>,
|
||||
streamed: &mut Streamed,
|
||||
subagent: Session,
|
||||
i: usize,
|
||||
entry: &AgentEntry,
|
||||
) -> AgentEvent {
|
||||
) -> Option<AgentEvent> {
|
||||
let whole = |subagent| AgentEvent::Entry { task: task.to_owned(), subagent, index: i as u32, entry: entry.clone() };
|
||||
let text = match entry {
|
||||
AgentEntry::Agent { text } | AgentEntry::Thought { text, .. } => Some(text),
|
||||
AgentEntry::Tool { .. } => return tool_event(task, streamed, subagent, i, entry),
|
||||
_ => None,
|
||||
};
|
||||
let Some(text) = text else {
|
||||
if streamed.get(&subagent).is_some_and(|sent| sent.index == i) {
|
||||
streamed.remove(&subagent);
|
||||
if streamed.messages.get(&subagent).is_some_and(|sent| sent.index == i) {
|
||||
streamed.messages.remove(&subagent);
|
||||
}
|
||||
return AgentEvent::Entry { task: task.to_owned(), subagent, index: i as u32, entry: entry.clone() };
|
||||
return Some(whole(subagent));
|
||||
};
|
||||
match streamed.get(&subagent).filter(|sent| sent.extended_by(i, text)) {
|
||||
Some(sent) => {
|
||||
let (bytes, from) = (sent.bytes, sent.utf16);
|
||||
streamed.insert(subagent.clone(), Sent::after(i, text, bytes, from));
|
||||
AgentEvent::Append {
|
||||
match streamed.messages.get(&subagent).and_then(|sent| Some((sent.bytes, sent.utf16, sent.extended(i, text)?))) {
|
||||
Some((bytes, from, sent)) => {
|
||||
streamed.messages.insert(subagent.clone(), sent);
|
||||
Some(AgentEvent::Append {
|
||||
task: task.to_owned(),
|
||||
subagent,
|
||||
index: i as u32,
|
||||
from: from as u32,
|
||||
text: text[bytes..].to_owned(),
|
||||
}
|
||||
})
|
||||
}
|
||||
None => {
|
||||
streamed.insert(subagent.clone(), Sent::new(i, text));
|
||||
AgentEvent::Entry { task: task.to_owned(), subagent, index: i as u32, entry: entry.clone() }
|
||||
streamed.messages.insert(subagent.clone(), Sent::new(i, text));
|
||||
Some(whole(subagent))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`entry_event`] for a tool call: the output it grew by while the rest of it is unchanged.
|
||||
fn tool_event(
|
||||
task: &str,
|
||||
streamed: &mut Streamed,
|
||||
subagent: Session,
|
||||
i: usize,
|
||||
entry: &AgentEntry,
|
||||
) -> Option<AgentEvent> {
|
||||
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms } = entry
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let call = AgentEntry::Tool {
|
||||
id: id.clone(),
|
||||
title: title.clone(),
|
||||
kind: kind.clone(),
|
||||
status: *status,
|
||||
locations: locations.clone(),
|
||||
images: images.clone(),
|
||||
output: None,
|
||||
diffs: diffs.clone(),
|
||||
started_ms: *started_ms,
|
||||
ended_ms: *ended_ms,
|
||||
};
|
||||
let text = output.as_deref().unwrap_or_default();
|
||||
let key = (subagent, i);
|
||||
if let Some(sent) = streamed.tools.get_mut(&key).filter(|sent| sent.call == call) {
|
||||
if let Some(output) = sent.output.extended(i, text) {
|
||||
let (bytes, from) = (sent.output.bytes, sent.output.utf16);
|
||||
sent.output = output;
|
||||
return Some(AgentEvent::ToolOutput {
|
||||
task: task.to_owned(),
|
||||
subagent: key.0,
|
||||
index: i as u32,
|
||||
from: from as u32,
|
||||
text: text[bytes..].to_owned(),
|
||||
});
|
||||
}
|
||||
if sent.output.is(text) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if matches!(status, AgentToolStatus::Pending | AgentToolStatus::Running) {
|
||||
streamed.tools.insert(key.clone(), SentTool { call, output: Sent::new(i, text) });
|
||||
} else {
|
||||
streamed.tools.remove(&key);
|
||||
}
|
||||
Some(AgentEvent::Entry { task: task.to_owned(), subagent: key.0, index: i as u32, entry: entry.clone() })
|
||||
}
|
||||
|
||||
struct SessionOpenError {
|
||||
message: String,
|
||||
allow_acp_fallback: bool,
|
||||
|
||||
@@ -801,6 +801,16 @@ pub enum AgentEvent {
|
||||
from: u32,
|
||||
text: String,
|
||||
},
|
||||
/// Text was appended to the output of tool entry `index`: it read the first `from` UTF-16
|
||||
/// units of its output when the previous event for it was sent. Any other change of the
|
||||
/// tool (status, title, diffs…) arrives as an `Entry`.
|
||||
ToolOutput {
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
index: u32,
|
||||
from: u32,
|
||||
text: String,
|
||||
},
|
||||
/// An agent reported the usage limits of its account (shared by every task of `provider`).
|
||||
Limits {
|
||||
provider: String,
|
||||
|
||||
@@ -282,6 +282,24 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, "running it in the background");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "stream tool output" {
|
||||
// A long command whose output grows: every update carries all of it so far.
|
||||
let update = |kind: &str, status: &str, output: &str| {
|
||||
json!({"sessionUpdate": kind, "toolCallId": "build", "title": "cargo build",
|
||||
"kind": "execute", "status": status,
|
||||
"content": [{"type": "content", "content": {"type": "text", "text": output}}]})
|
||||
};
|
||||
self.update(&session, update("tool_call", "in_progress", "$ cargo build"));
|
||||
let mut output = String::from("$ cargo build");
|
||||
for i in 0..40 {
|
||||
output.push_str(&format!("\n{i:04} {}", "x".repeat(1500)));
|
||||
self.update(&session, update("tool_call_update", "in_progress", &output));
|
||||
// Longer than the flush interval: every update reaches the window on its own.
|
||||
std::thread::sleep(FLUSH_DELAY + Duration::from_millis(30));
|
||||
}
|
||||
self.update(&session, update("tool_call_update", "completed", &output));
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "delegate" {
|
||||
self.delegate(&session);
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
@@ -3935,42 +3953,256 @@ async fn discovery_times_out_when_session_new_hangs() {
|
||||
assert!(!cursor.config.iter().any(|o| o.category.as_deref() == Some("model")));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_growing_tool_output_is_not_sent_whole_on_every_flush() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
// What a window receives of the tool's entry: events, and the bytes they take.
|
||||
let sent = Arc::new(Mutex::new((0usize, Vec::<AgentEvent>::new())));
|
||||
let sink = sent.clone();
|
||||
mgr.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |e| {
|
||||
let json = serde_json::to_value(&e).unwrap();
|
||||
if json["entry"]["type"] == "tool" || json["type"] == "toolOutput" {
|
||||
let mut sent = sink.lock();
|
||||
sent.0 += json.to_string().len();
|
||||
sent.1.push(e);
|
||||
}
|
||||
}),
|
||||
);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("stream tool output"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// The turn takes a few seconds: the agent paces its updates by the flush interval.
|
||||
let finished = |mgr: &AgentManager| {
|
||||
mgr.entries(&task.id, None).unwrap().into_iter().find_map(|e| match e {
|
||||
AgentEntry::Tool { output, status: AgentToolStatus::Completed, .. } => output,
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
for _ in 0..6000 {
|
||||
if finished(&mgr).is_some() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
tokio::time::sleep(FLUSH_DELAY * 3).await;
|
||||
|
||||
let output = finished(&mgr).expect("the command's output was kept");
|
||||
assert!(output.len() > 60_000, "a long output that the timeline keeps whole: {}", output.len());
|
||||
let (bytes, events) = {
|
||||
let sent = sent.lock();
|
||||
(sent.0, sent.1.len())
|
||||
};
|
||||
assert!(events >= 30, "the output reached the window in many flushes: {events}");
|
||||
assert!(bytes < 3 * output.len(), "{bytes} bytes sent for {} bytes of output over {events} events", output.len());
|
||||
|
||||
// The window's copy, built as the UI does, ends as the conversation holds it.
|
||||
let mut shown: Option<String> = None;
|
||||
for e in &sent.lock().1 {
|
||||
match e {
|
||||
AgentEvent::Entry { entry: AgentEntry::Tool { output, .. }, .. } => shown = output.clone(),
|
||||
AgentEvent::ToolOutput { from, text, .. } => {
|
||||
let have = shown.get_or_insert_default();
|
||||
assert_eq!(*from as usize, have.encode_utf16().count(), "a delta goes on where the last one ended");
|
||||
have.push_str(text);
|
||||
}
|
||||
_ => unreachable!("{e:?}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(shown, Some(output));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_text_is_sent_as_appends() {
|
||||
let mut streamed = HashMap::new();
|
||||
let mut streamed = Streamed::default();
|
||||
let agent = |t: &str| AgentEntry::Agent { text: t.into() };
|
||||
let first = entry_event("t", &mut streamed, None, 3, &agent("Hé"));
|
||||
let first = entry_event("t", &mut streamed, None, 3, &agent("Hé")).unwrap();
|
||||
assert!(matches!(first, AgentEvent::Entry { index: 3, .. }), "the first sight of a message is whole");
|
||||
let next = entry_event("t", &mut streamed, None, 3, &agent("Hé 👋 there"));
|
||||
let next = entry_event("t", &mut streamed, None, 3, &agent("Hé 👋 there")).unwrap();
|
||||
assert!(
|
||||
matches!(&next, AgentEvent::Append { subagent: None, index: 3, from: 2, text, .. } if text == " 👋 there"),
|
||||
"{next:?}"
|
||||
);
|
||||
let sub = entry_event("t", &mut streamed, Some("s".into()), 3, &agent("Hé 👋 there!"));
|
||||
let sub = entry_event("t", &mut streamed, Some("s".into()), 3, &agent("Hé 👋 there!")).unwrap();
|
||||
assert!(matches!(sub, AgentEvent::Entry { .. }), "each session streams on its own");
|
||||
let after = entry_event("t", &mut streamed, None, 3, &agent("Hé 👋 there."));
|
||||
let after = entry_event("t", &mut streamed, None, 3, &agent("Hé 👋 there.")).unwrap();
|
||||
assert!(
|
||||
matches!(&after, AgentEvent::Append { from: 11, text, .. } if text == "."),
|
||||
"from counts UTF-16 units: {after:?}"
|
||||
);
|
||||
let replaced = entry_event("t", &mut streamed, None, 3, &agent("Other"));
|
||||
let replaced = entry_event("t", &mut streamed, None, 3, &agent("Other")).unwrap();
|
||||
assert!(matches!(replaced, AgentEvent::Entry { .. }), "text that doesn't extend the sent text is sent whole");
|
||||
let thought = AgentEntry::Thought { text: "hmm…".into(), started_ms: None };
|
||||
let thought = entry_event("t", &mut streamed, None, 4, &thought);
|
||||
let thought = entry_event("t", &mut streamed, None, 4, &thought).unwrap();
|
||||
assert!(matches!(thought, AgentEvent::Entry { index: 4, .. }), "a new message starts whole");
|
||||
let tool = AgentEntry::Error { message: "x".into() };
|
||||
entry_event("t", &mut streamed, None, 4, &tool);
|
||||
entry_event("t", &mut streamed, None, 4, &tool).unwrap();
|
||||
let again = AgentEntry::Thought { text: "hmm… ok".into(), started_ms: None };
|
||||
let again = entry_event("t", &mut streamed, None, 4, &again);
|
||||
let again = entry_event("t", &mut streamed, None, 4, &again).unwrap();
|
||||
assert!(matches!(again, AgentEvent::Entry { .. }), "an entry replaced by another kind forgets its text");
|
||||
|
||||
let long = "é".repeat(5000);
|
||||
entry_event("t", &mut streamed, None, 5, &agent(&long));
|
||||
assert!(streamed[&None].tail.len() <= 64, "only the end of what was sent is kept");
|
||||
let on = entry_event("t", &mut streamed, None, 5, &agent(&format!("{long}!")));
|
||||
entry_event("t", &mut streamed, None, 5, &agent(&long)).unwrap();
|
||||
let on = entry_event("t", &mut streamed, None, 5, &agent(&format!("{long}!"))).unwrap();
|
||||
assert!(matches!(&on, AgentEvent::Append { from: 5000, text, .. } if text == "!"), "{on:?}");
|
||||
let rewritten = entry_event("t", &mut streamed, None, 5, &agent(&format!("{}x!??", "é".repeat(4999))));
|
||||
let rewritten = entry_event("t", &mut streamed, None, 5, &agent(&format!("{}x!??", "é".repeat(4999)))).unwrap();
|
||||
assert!(matches!(rewritten, AgentEvent::Entry { .. }), "a rewritten end is sent whole");
|
||||
// A text that goes on with its end as sent but an edited start is not an append.
|
||||
let kept_end =
|
||||
entry_event("t", &mut streamed, None, 5, &agent(&format!("{}{}", "e".repeat(5000), "é".repeat(5000))));
|
||||
assert!(matches!(kept_end, Some(AgentEvent::Entry { .. })), "{kept_end:?}");
|
||||
let edited_start =
|
||||
entry_event("t", &mut streamed, None, 5, &agent(&format!("{}{}!", "x".repeat(5000), "é".repeat(5000))));
|
||||
assert!(
|
||||
matches!(edited_start, Some(AgentEvent::Entry { .. })),
|
||||
"a rewritten start is sent whole even when the end is as sent: {edited_start:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_running_tools_output_is_sent_as_appends() {
|
||||
let mut streamed = Streamed::default();
|
||||
let call = |status, output: Option<&str>| AgentEntry::Tool {
|
||||
id: "t1".into(),
|
||||
title: "cargo build".into(),
|
||||
kind: "execute".into(),
|
||||
status,
|
||||
locations: Vec::new(),
|
||||
images: Vec::new(),
|
||||
output: output.map(str::to_owned),
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(1.0),
|
||||
ended_ms: None,
|
||||
};
|
||||
let running = |output| call(AgentToolStatus::Running, output);
|
||||
let event = |streamed: &mut Streamed, session: Session, i, entry: &AgentEntry| {
|
||||
entry_event("t", streamed, session, i, entry)
|
||||
};
|
||||
|
||||
let first = event(&mut streamed, None, 2, &running(None)).unwrap();
|
||||
assert!(matches!(first, AgentEvent::Entry { index: 2, .. }), "the first sight of a call is whole");
|
||||
let output = event(&mut streamed, None, 2, &running(Some("$ make"))).unwrap();
|
||||
assert!(
|
||||
matches!(&output, AgentEvent::ToolOutput { subagent: None, index: 2, from: 0, text, .. } if text == "$ make"),
|
||||
"{output:?}"
|
||||
);
|
||||
let next = event(&mut streamed, None, 2, &running(Some("$ make\ncc é.c 👋"))).unwrap();
|
||||
assert!(
|
||||
matches!(&next, AgentEvent::ToolOutput { from: 6, text, .. } if text == "\ncc é.c 👋"),
|
||||
"from counts UTF-16 units: {next:?}"
|
||||
);
|
||||
let after = event(&mut streamed, None, 2, &running(Some("$ make\ncc é.c 👋\nok"))).unwrap();
|
||||
assert!(matches!(&after, AgentEvent::ToolOutput { from: 16, text, .. } if text == "\nok"), "{after:?}");
|
||||
assert!(
|
||||
event(&mut streamed, None, 2, &running(Some("$ make\ncc é.c 👋\nok"))).is_none(),
|
||||
"what the window has is not sent again"
|
||||
);
|
||||
|
||||
// Anything else about the call goes whole, output included.
|
||||
let mut titled = running(Some("$ make\ncc é.c 👋\nok\n"));
|
||||
if let AgentEntry::Tool { title, .. } = &mut titled {
|
||||
*title = "make".into();
|
||||
}
|
||||
let renamed = event(&mut streamed, None, 2, &titled).unwrap();
|
||||
assert!(
|
||||
matches!(&renamed, AgentEvent::Entry { entry: AgentEntry::Tool { output: Some(o), .. }, .. } if o.ends_with("ok\n")),
|
||||
"{renamed:?}"
|
||||
);
|
||||
let on = event(&mut streamed, None, 2, &titled);
|
||||
assert!(on.is_none(), "the entry the window holds now is this one");
|
||||
if let AgentEntry::Tool { output, .. } = &mut titled {
|
||||
output.as_mut().unwrap().push_str("more");
|
||||
}
|
||||
let on = event(&mut streamed, None, 2, &titled).unwrap();
|
||||
assert!(matches!(&on, AgentEvent::ToolOutput { from: 20, text, .. } if text == "more"), "{on:?}");
|
||||
|
||||
// An image the tool returned is not part of the appended text: it goes with the whole entry.
|
||||
let mut shown = titled.clone();
|
||||
if let AgentEntry::Tool { images, output, .. } = &mut shown {
|
||||
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None });
|
||||
output.as_mut().unwrap().push('!');
|
||||
}
|
||||
let imaged = event(&mut streamed, None, 2, &shown).unwrap();
|
||||
assert!(
|
||||
matches!(&imaged, AgentEvent::Entry { entry: AgentEntry::Tool { images, .. }, .. } if images.len() == 1),
|
||||
"{imaged:?}"
|
||||
);
|
||||
titled = shown;
|
||||
|
||||
// Output the call replaced rather than extended goes whole.
|
||||
let make = |output: &str| {
|
||||
let mut entry = titled.clone();
|
||||
if let AgentEntry::Tool { output: o, .. } = &mut entry {
|
||||
*o = Some(output.to_owned());
|
||||
}
|
||||
entry
|
||||
};
|
||||
let replaced = event(&mut streamed, None, 2, &make("$ make\nother")).unwrap();
|
||||
assert!(matches!(replaced, AgentEvent::Entry { .. }), "a rewritten output is sent whole");
|
||||
let on = event(&mut streamed, None, 2, &make("$ make\nother, but longer")).unwrap();
|
||||
assert!(matches!(on, AgentEvent::ToolOutput { from: 12, .. }), "and the next growth is appended to it: {on:?}");
|
||||
|
||||
// A replacement that keeps the old end, or the old length, is not mistaken for growth.
|
||||
let mut kept = make("$ make\nother, but longer");
|
||||
let swap = |entry: &mut AgentEntry, output: String| {
|
||||
if let AgentEntry::Tool { output: o, .. } = entry {
|
||||
*o = Some(output);
|
||||
}
|
||||
};
|
||||
let (long_tail, same_length) =
|
||||
(format!("{}{}", "X".repeat(100), "z".repeat(100)), "Y".repeat(100) + &"z".repeat(100));
|
||||
swap(&mut kept, long_tail.clone());
|
||||
event(&mut streamed, None, 2, &kept).unwrap();
|
||||
swap(&mut kept, same_length);
|
||||
let same = event(&mut streamed, None, 2, &kept).unwrap();
|
||||
assert!(
|
||||
matches!(&same, AgentEvent::Entry { entry: AgentEntry::Tool { output: Some(o), .. }, .. } if o.starts_with('Y')),
|
||||
"same length, same end, different start is sent whole: {same:?}"
|
||||
);
|
||||
swap(&mut kept, format!("{}{}!", "W".repeat(100), "z".repeat(100)));
|
||||
let grown = event(&mut streamed, None, 2, &kept).unwrap();
|
||||
assert!(
|
||||
matches!(grown, AgentEvent::Entry { .. }),
|
||||
"a replacement that also grows, with the old end, is sent whole: {grown:?}"
|
||||
);
|
||||
|
||||
// Calls run side by side, each in its own session.
|
||||
let whole = |e: &AgentEvent| matches!(e, AgentEvent::Entry { .. });
|
||||
let (a, b) = (
|
||||
event(&mut streamed, None, 3, &running(Some("a"))),
|
||||
event(&mut streamed, Some("s".into()), 3, &running(Some("b"))),
|
||||
);
|
||||
let c = event(&mut streamed, None, 4, &running(Some("c")));
|
||||
assert!([&a, &b, &c].into_iter().all(|e| whole(e.as_ref().unwrap())), "each call starts whole");
|
||||
let a = event(&mut streamed, None, 3, &running(Some("ab"))).unwrap();
|
||||
let c = event(&mut streamed, None, 4, &running(Some("cd"))).unwrap();
|
||||
let b = event(&mut streamed, Some("s".into()), 3, &running(Some("bc"))).unwrap();
|
||||
assert!(
|
||||
[&a, &b, &c].into_iter().all(|e| matches!(e, AgentEvent::ToolOutput { from: 1, .. })),
|
||||
"one call's flush does not end another's: {a:?} {b:?} {c:?}"
|
||||
);
|
||||
|
||||
// A call that ended is sent whole, and forgotten.
|
||||
let done = call(AgentToolStatus::Completed, Some("ab\ndone"));
|
||||
let done_event = event(&mut streamed, None, 3, &done).unwrap();
|
||||
assert!(matches!(done_event, AgentEvent::Entry { .. }));
|
||||
assert!(!streamed.tools.contains_key(&(None, 3)));
|
||||
let late = event(&mut streamed, None, 3, &call(AgentToolStatus::Completed, Some("ab\ndone\nlate"))).unwrap();
|
||||
assert!(matches!(late, AgentEvent::Entry { .. }), "an ended call's output is not appended to");
|
||||
|
||||
// A rollback forgets what was sent.
|
||||
streamed.clear();
|
||||
let again = event(&mut streamed, None, 4, &running(Some("cdef"))).unwrap();
|
||||
assert!(matches!(again, AgentEvent::Entry { .. }), "after the conversation was cut, calls start whole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -28,7 +28,9 @@ use std::pin::Pin;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// 3: binary arguments (`IpcBytes`) are base64 strings, not arrays of numbers.
|
||||
pub const PROTOCOL_VERSION: u32 = 3;
|
||||
/// 4: a running tool's output arrives as `AgentEvent::ToolOutput` appends; a client that
|
||||
/// doesn't know the event would show stale output.
|
||||
pub const PROTOCOL_VERSION: u32 = 4;
|
||||
pub const SESSION_REPLACED: &str = "session_replaced";
|
||||
pub const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90);
|
||||
|
||||
|
||||
@@ -2664,6 +2664,12 @@ export type AgentEvent_Deserialize =
|
||||
* `from` UTF-16 units of its text when the previous event for it was sent.
|
||||
*/
|
||||
({ type: "append"; task: string; subagent: string | null; index: number; from: number; text: string }) & { catalog?: never; entry?: never; eventId?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never } |
|
||||
/**
|
||||
* Text was appended to the output of tool entry `index`: it read the first `from` UTF-16
|
||||
* units of its output when the previous event for it was sent. Any other change of the
|
||||
* tool (status, title, diffs…) arrives as an `Entry`.
|
||||
*/
|
||||
({ type: "toolOutput"; task: string; subagent: string | null; index: number; from: number; text: string }) & { catalog?: never; entry?: never; eventId?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never } |
|
||||
/** An agent reported the usage limits of its account (shared by every task of `provider`). */
|
||||
({ type: "limits"; provider: string; limits: AgentLimit[] }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; reason?: never; subagent?: never; task?: never; text?: never } |
|
||||
/** A model lookup started or completed, including unsuccessful lookups. */
|
||||
@@ -2686,6 +2692,12 @@ export type AgentEvent_Serialize =
|
||||
* `from` UTF-16 units of its text when the previous event for it was sent.
|
||||
*/
|
||||
({ type: "append"; task: string; subagent: string | null; index: number; from: number; text: string }) & { catalog?: never; entry?: never; eventId?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never } |
|
||||
/**
|
||||
* Text was appended to the output of tool entry `index`: it read the first `from` UTF-16
|
||||
* units of its output when the previous event for it was sent. Any other change of the
|
||||
* tool (status, title, diffs…) arrives as an `Entry`.
|
||||
*/
|
||||
({ type: "toolOutput"; task: string; subagent: string | null; index: number; from: number; text: string }) & { catalog?: never; entry?: never; eventId?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never } |
|
||||
/** An agent reported the usage limits of its account (shared by every task of `provider`). */
|
||||
({ type: "limits"; provider: string; limits: AgentLimit[] }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; reason?: never; subagent?: never; task?: never; text?: never } |
|
||||
/** A model lookup started or completed, including unsuccessful lookups. */
|
||||
|
||||
@@ -136,21 +136,37 @@ export function upsertEntry(entries: AgentEntry[], index: number, entry: AgentEn
|
||||
return next;
|
||||
}
|
||||
|
||||
/** `shown` with `text`, which follows its first `from` units, added; `null` when `shown` is too short to take it. */
|
||||
function grown(shown: string, from: number, text: string): string | null {
|
||||
if (shown.length < from) return null;
|
||||
return shown.length >= from + text.length ? shown : shown + text.slice(shown.length - from);
|
||||
}
|
||||
|
||||
/**
|
||||
* `entries` with `text` appended to the message at `index`, which read its first `from`
|
||||
* UTF-16 units when the backend last sent it; `null` when the copy here can't take it (a
|
||||
* gap, or another kind of entry), so the conversation is loaded again. A copy loaded while
|
||||
* the text streamed may already hold some of it.
|
||||
* `entries` with `text` appended to the message at `index` (or to the output of the tool call
|
||||
* there), which read its first `from` UTF-16 units when the backend last sent it; `null` when
|
||||
* the copy here can't take it (a gap, or another kind of entry), so the conversation is
|
||||
* loaded again. A copy loaded while the text streamed may already hold some of it.
|
||||
*/
|
||||
export function appendEntry(entries: AgentEntry[], index: number, from: number, text: string): AgentEntry[] | null {
|
||||
const entry = entries[index];
|
||||
if (!entry || (entry.type !== "agent" && entry.type !== "thought")) return null;
|
||||
const have = entry.text.length;
|
||||
if (have < from) return null;
|
||||
if (have >= from + text.length) return entries;
|
||||
const next = entries.slice();
|
||||
next[index] = { ...entry, text: entry.text + text.slice(have - from) };
|
||||
return next;
|
||||
let next: AgentEntry;
|
||||
if (entry?.type === "tool") {
|
||||
const output = grown(entry.output ?? "", from, text);
|
||||
if (output === null) return null;
|
||||
if (output === entry.output) return entries;
|
||||
next = { ...entry, output };
|
||||
} else if (entry?.type === "agent" || entry?.type === "thought") {
|
||||
const added = grown(entry.text, from, text);
|
||||
if (added === null) return null;
|
||||
if (added === entry.text) return entries;
|
||||
next = { ...entry, text: added };
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
const copy = entries.slice();
|
||||
copy[index] = next;
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** "agent/fix-lexer" → "fix-lexer". */
|
||||
|
||||
@@ -584,7 +584,7 @@ export async function connect(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
type EntryEvent = Extract<AgentEvent, { type: "entry" | "append" }>;
|
||||
type EntryEvent = Extract<AgentEvent, { type: "entry" | "append" | "toolOutput" }>;
|
||||
|
||||
/** Entry events that arrived while their conversation loaded, applied on top of the copy it loads. */
|
||||
const arrivedWhileLoading = new Map<string, EntryEvent[]>();
|
||||
@@ -593,7 +593,7 @@ const streamingReply = new Map<string, { index: number; reply: boolean }>();
|
||||
|
||||
/** `entries` with the event applied; `null` when the copy can't take it. */
|
||||
function applyEntryEvent(entries: AgentEntry[], e: EntryEvent): AgentEntry[] | null {
|
||||
if (e.type === "append") return appendEntry(entries, e.index, e.from, e.text);
|
||||
if (e.type === "append" || e.type === "toolOutput") return appendEntry(entries, e.index, e.from, e.text);
|
||||
const have = entries[e.index];
|
||||
// Sent before the loaded copy was read: that copy already holds more of the message.
|
||||
if (
|
||||
@@ -851,6 +851,10 @@ function onEvent(e: AgentEvent) {
|
||||
onEntryEvent(s, e);
|
||||
break;
|
||||
}
|
||||
case "toolOutput": {
|
||||
onEntryEvent(s, e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings";
|
||||
import { deferred } from "@/test/deferred";
|
||||
import { entriesKey } from "./model";
|
||||
import { connect, disconnect, loadEntries, useAgents } from "./store";
|
||||
|
||||
const backend = vi.hoisted(() => ({
|
||||
channel: null as { onmessage: (event: AgentEvent) => void } | null,
|
||||
entries: vi.fn(),
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/core", async (original) => ({
|
||||
...(await original<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage = () => {};
|
||||
},
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (original) => ({
|
||||
...(await original<typeof import("@/platform/ipc")>()),
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
agentSubscribe: async (channel: typeof backend.channel) => {
|
||||
backend.channel = channel;
|
||||
return { status: "ok", data: [task] };
|
||||
},
|
||||
agentProviders: async () => ({ status: "ok", data: [] }),
|
||||
agentEntries: async () => ({ status: "ok", data: await backend.entries() }),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
editorService: () => ({ openTabs: () => [] }),
|
||||
}));
|
||||
|
||||
const task: AgentTask = {
|
||||
id: "one",
|
||||
title: "one",
|
||||
status: "running",
|
||||
provider: "codex",
|
||||
isolation: "local",
|
||||
model: null,
|
||||
cwd: "/project",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
};
|
||||
const call = (output: string | null, status: "running" | "completed" = "running"): AgentEntry => ({
|
||||
type: "tool",
|
||||
id: "build",
|
||||
title: "cargo build",
|
||||
kind: "execute",
|
||||
status,
|
||||
locations: [],
|
||||
output,
|
||||
diffs: [],
|
||||
startedMs: 1,
|
||||
endedMs: null,
|
||||
});
|
||||
const emit = (event: AgentEvent) => backend.channel!.onmessage(event);
|
||||
const entry = (index: number, e: AgentEntry): AgentEvent => ({
|
||||
type: "entry",
|
||||
task: "one",
|
||||
subagent: null,
|
||||
index,
|
||||
entry: e,
|
||||
});
|
||||
const more = (index: number, from: number, text: string): AgentEvent => ({
|
||||
type: "toolOutput",
|
||||
task: "one",
|
||||
subagent: null,
|
||||
index,
|
||||
from,
|
||||
text,
|
||||
});
|
||||
const shown = () => useAgents.getState().entries.get(entriesKey("one", null));
|
||||
const output = () => {
|
||||
const tool = shown()?.[1];
|
||||
return tool?.type === "tool" ? tool.output : undefined;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
disconnect();
|
||||
backend.entries.mockReset();
|
||||
backend.entries.mockResolvedValue([{ type: "user", text: "build it", attachments: [] }]);
|
||||
await connect();
|
||||
await loadEntries("one");
|
||||
});
|
||||
|
||||
describe("a running tool's output", () => {
|
||||
it("grows by what each event adds, and the last entry settles it", () => {
|
||||
emit(entry(1, call("$ cargo build")));
|
||||
emit(more(1, 13, "\nCompiling é"));
|
||||
emit(more(1, 25, " 👋\nDone"));
|
||||
expect(shown()![1]).toEqual(call("$ cargo build\nCompiling é 👋\nDone"));
|
||||
emit(entry(1, call("$ cargo build\nCompiling é 👋\nDone\n", "completed")));
|
||||
expect(shown()![1]).toEqual(call("$ cargo build\nCompiling é 👋\nDone\n", "completed"));
|
||||
});
|
||||
|
||||
it("starts from nothing when the call had no output yet", () => {
|
||||
emit(entry(1, call(null)));
|
||||
emit(more(1, 0, "first"));
|
||||
expect(output()).toBe("first");
|
||||
});
|
||||
|
||||
it("takes text it already holds once, and loads the conversation again when it misses some", async () => {
|
||||
emit(entry(1, call("abc")));
|
||||
emit(more(1, 0, "abc"));
|
||||
expect(output()).toBe("abc");
|
||||
backend.entries.mockResolvedValue([{ type: "user", text: "build it", attachments: [] }, call("abcdef")]);
|
||||
emit(more(1, 5, "g"));
|
||||
await vi.waitFor(() => expect(output()).toBe("abcdef"));
|
||||
expect(backend.entries).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("lands on a copy that loads while the output streams", async () => {
|
||||
const read = deferred<AgentEntry[]>();
|
||||
backend.entries.mockReturnValue(read.promise);
|
||||
useAgents.setState({ entries: new Map(), entryLoads: new Map() });
|
||||
const loading = loadEntries("one");
|
||||
emit(more(1, 3, "def"));
|
||||
emit(more(1, 6, "ghi"));
|
||||
read.resolve([{ type: "user", text: "build it", attachments: [] }, call("abcdef")]);
|
||||
await loading;
|
||||
expect(output()).toBe("abcdefghi");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Заблокувати користувача