Skip to main content

vtcode_core/core/agent/events/
lifecycle.rs

1use crate::exec::events::{
2    AgentMessageItem, ErrorItem, ItemCompletedEvent, ItemStartedEvent, ItemUpdatedEvent, ReasoningItem, ThreadEvent,
3    ThreadItem, ThreadItemDetails, ToolCallStatus, ToolInvocationItem, ToolOutcome, ToolOutputItem,
4    tool_outcome_from_status,
5};
6use crate::tools::file_ops::{canonical_diff_previews, diff_preview_user_message};
7use serde_json::Value;
8use std::collections::HashMap;
9use std::fmt::Write;
10
11#[derive(Debug, Clone, Default)]
12struct StreamingTextState {
13    item_id: Option<String>,
14    text: String,
15    started: bool,
16}
17
18#[derive(Debug, Clone)]
19struct ToolCallStreamState {
20    item_id: String,
21    name: Option<String>,
22    arguments: String,
23    started: bool,
24    /// Bytes of `arguments` included in the last emitted `item.updated` event.
25    /// Used to throttle per-token delta emissions — see `MIN_TOOL_ARG_UPDATE_BYTES`.
26    last_emitted_args_len: usize,
27    /// Number of intermediate `item.updated` events emitted for this tool call.
28    /// Capped at `MAX_TOOL_ARG_UPDATE_EVENTS` to bound log growth for large arguments.
29    update_events: usize,
30}
31
32/// Minimum accumulated bytes of tool-call arguments between two `item.updated`
33/// events. Without this, every streaming argument delta (one per token) emits a
34/// full-arguments update, producing ~30+ events per tool call and bloating the
35/// session log (observed 3069 `item.updated` events for 98 tool outputs in a
36/// single 3-turn session). The final `complete_tool_call` always emits the full
37/// arguments, so intermediate updates are progress hints only.
38const MIN_TOOL_ARG_UPDATE_BYTES: usize = 512;
39
40/// Maximum intermediate `item.updated` events per tool call. Once reached, no
41/// further streaming updates are emitted until the tool call completes.
42const MAX_TOOL_ARG_UPDATE_EVENTS: usize = 8;
43
44#[derive(Debug, Clone, PartialEq, Eq)]
45/// Aggregated output from a tool execution, containing either inline text or a
46/// spool file reference.
47pub struct ToolOutputPayload {
48    /// Combined output text from the tool execution.
49    pub aggregated_output: String,
50    /// Optional path to a spool file containing the full output.
51    pub spool_path: Option<String>,
52}
53
54fn pluralize<'a>(count: u64, singular: &'a str, plural: &'a str) -> &'a str {
55    if count == 1 { singular } else { plural }
56}
57
58/// Attribute only a successful file tool's recorded result, never current Git state.
59pub fn file_change_completed_event(
60    call_id: &str,
61    tool_name: &str,
62    args: &Value,
63    output: &Value,
64) -> Option<ThreadEvent> {
65    use crate::exec::events::{FileChangeItem, FileUpdateChange, PatchApplyStatus, PatchChangeKind};
66    let file_tool =
67        matches!(tool_name, "apply_patch" | "write_file" | "edit_file" | "create_file" | "delete_file" | "file")
68            || tool_name == crate::config::constants::tools::UNIFIED_FILE;
69    if !file_tool
70        || !crate::tools::tool_intent::classify_tool_intent(tool_name, args).mutating
71        || output.get("success").and_then(Value::as_bool) == Some(false)
72        || output.get("skipped").and_then(Value::as_bool) == Some(true)
73        || output.get("conflict").and_then(Value::as_bool) == Some(true)
74        || crate::tools::file_ops::diff_output_has_effective_change(output) == Some(false)
75    {
76        return None;
77    }
78    let previews = canonical_diff_previews(output);
79    let mut changes = Vec::new();
80    let mut diffs = Vec::new();
81    let mut additions = 0u64;
82    let mut deletions = 0u64;
83    let mut counts_available = true;
84    let mut diff_incomplete = previews.is_empty();
85    for preview in &previews {
86        if preview.get("is_empty").and_then(Value::as_bool) == Some(true)
87            && !matches!(preview.get("operation").and_then(Value::as_str), Some("created" | "deleted"))
88        {
89            continue;
90        }
91        let Some(path) = preview.get("path").and_then(Value::as_str) else {
92            continue;
93        };
94        let kind = match preview.get("operation").and_then(Value::as_str) {
95            Some("created" | "added") => PatchChangeKind::Add,
96            Some("deleted" | "removed") => PatchChangeKind::Delete,
97            _ => PatchChangeKind::Update,
98        };
99        changes.push(FileUpdateChange { path: path.to_owned(), kind });
100        diff_incomplete |= preview.get("truncated").and_then(Value::as_bool) == Some(true)
101            || preview.get("skipped").and_then(Value::as_bool) == Some(true)
102            || preview.get("content").and_then(Value::as_str).is_none();
103        if let Some(content) = preview.get("content").and_then(Value::as_str) {
104            diffs.push(content.to_owned());
105        }
106        if let (Some(a), Some(d)) = (
107            preview
108                .get("additions")
109                .or_else(|| preview.get("summary").and_then(|s| s.get("additions")))
110                .and_then(Value::as_u64),
111            preview
112                .get("deletions")
113                .or_else(|| preview.get("summary").and_then(|s| s.get("deletions")))
114                .and_then(Value::as_u64),
115        ) {
116            additions = additions.saturating_add(a);
117            deletions = deletions.saturating_add(d);
118        } else {
119            counts_available = false;
120        }
121    }
122    if changes.is_empty()
123        && let Some(paths) = output.get("modified_files").and_then(Value::as_array)
124    {
125        counts_available = false;
126        for path in paths.iter().filter_map(Value::as_str) {
127            changes.push(FileUpdateChange {
128                path: path.to_owned(),
129                kind: PatchChangeKind::Update,
130            });
131        }
132    }
133    if changes.is_empty() {
134        return None;
135    }
136    Some(ThreadEvent::ItemCompleted(ItemCompletedEvent {
137        item: ThreadItem {
138            id: format!("{call_id}:changes"),
139            context: None,
140            details: ThreadItemDetails::FileChange(Box::new(FileChangeItem {
141                diff_incomplete: diff_incomplete.then_some(true),
142                changes,
143                status: PatchApplyStatus::Completed,
144                unified_diff: (!diffs.is_empty()).then(|| diffs.join("\n")),
145                additions: counts_available.then_some(additions),
146                deletions: counts_available.then_some(deletions),
147            })),
148        },
149    }))
150}
151
152fn trimmed_string_field<'a>(output: &'a Value, key: &str) -> Option<&'a str> {
153    output
154        .get(key)
155        .and_then(Value::as_str)
156        .map(str::trim)
157        .filter(|text| !text.is_empty())
158}
159
160fn diff_preview_output(output: &Value) -> Option<String> {
161    let diffs = canonical_diff_previews(output);
162    if diffs.is_empty() {
163        return None;
164    }
165    let mut sections = Vec::new();
166
167    for diff in &diffs {
168        let path = diff.get("path").and_then(Value::as_str).unwrap_or("file");
169        let operation = diff
170            .get("operation")
171            .and_then(Value::as_str)
172            .map(|operation| format!(" ({operation})"))
173            .unwrap_or_default();
174        let counts =
175            match (diff.get("additions").and_then(Value::as_u64), diff.get("deletions").and_then(Value::as_u64)) {
176                (Some(additions), Some(deletions)) if additions > 0 || deletions > 0 => {
177                    format!(" (+{additions} -{deletions})")
178                }
179                _ => String::new(),
180            };
181        if let Some(content) = diff
182            .get("content")
183            .and_then(Value::as_str)
184            .map(str::trim)
185            .filter(|content| !content.is_empty())
186        {
187            sections.push(format!("diff preview for {path}{operation}{counts}:\n{content}"));
188            continue;
189        }
190
191        if diff.get("skipped").and_then(Value::as_bool) == Some(true) {
192            let reason = diff_preview_user_message(diff);
193            sections.push(format!("diff preview for {path}{operation}{counts}: {reason}"));
194            continue;
195        }
196
197        if diff.get("is_empty").and_then(Value::as_bool) == Some(true) {
198            sections.push(format!("diff preview for {path}{operation}: no changes"));
199        }
200    }
201
202    (!sections.is_empty()).then(|| sections.join("\n"))
203}
204
205#[cold]
206fn trimmed_error_message(output: &Value) -> Option<&str> {
207    match output.get("error") {
208        Some(Value::String(message)) => Some(message.as_str()),
209        Some(Value::Object(error)) => error.get("message").and_then(Value::as_str),
210        _ => None,
211    }
212    .map(str::trim)
213    .filter(|text| !text.is_empty())
214}
215
216fn sample_strings_from_objects(items: &[Value], keys: &[&str], limit: usize) -> Vec<String> {
217    let mut samples = Vec::new();
218
219    for item in items {
220        let Some(value) = keys
221            .iter()
222            .find_map(|key| item.get(*key).and_then(Value::as_str))
223            .map(str::trim)
224            .filter(|text| !text.is_empty())
225        else {
226            continue;
227        };
228
229        if samples.iter().any(|sample| sample == value) {
230            continue;
231        }
232
233        samples.push(value.to_string());
234        if samples.len() >= limit {
235            break;
236        }
237    }
238
239    samples
240}
241
242fn match_path_text(item: &Value) -> Option<&str> {
243    item.get("path")
244        .and_then(Value::as_str)
245        .map(str::trim)
246        .filter(|text| !text.is_empty())
247        .or_else(|| {
248            item.get("file")
249                .and_then(Value::as_str)
250                .map(str::trim)
251                .filter(|text| !text.is_empty())
252        })
253        .or_else(|| {
254            item.get("data")
255                .and_then(Value::as_object)
256                .and_then(|data| data.get("path"))
257                .and_then(Value::as_object)
258                .and_then(|path| path.get("text"))
259                .and_then(Value::as_str)
260                .map(str::trim)
261                .filter(|text| !text.is_empty())
262        })
263}
264
265fn sample_match_paths(matches: &[Value], limit: usize) -> Vec<String> {
266    let mut samples = Vec::new();
267
268    for item in matches {
269        let Some(path) = match_path_text(item) else {
270            continue;
271        };
272
273        if samples.iter().any(|sample| sample == path) {
274            continue;
275        }
276
277        samples.push(path.to_string());
278        if samples.len() >= limit {
279            break;
280        }
281    }
282
283    samples
284}
285
286fn summarize_list_items(output: &Value, items: &[Value]) -> String {
287    let total = output
288        .get("total")
289        .or_else(|| output.get("count"))
290        .and_then(Value::as_u64)
291        .unwrap_or(items.len() as u64);
292
293    let (files, directories) =
294        items
295            .iter()
296            .fold((0u64, 0u64), |(files, directories), item| match item.get("type").and_then(Value::as_str) {
297                Some("file") => (files + 1, directories),
298                Some("directory") => (files, directories + 1),
299                _ => (files, directories),
300            });
301
302    let mut summary = format!("Listed {total} {}", pluralize(total, "item", "items"));
303    if files > 0 || directories > 0 {
304        let _ = write!(
305            summary,
306            " ({} {}, {} {})",
307            files,
308            pluralize(files, "file", "files"),
309            directories,
310            pluralize(directories, "directory", "directories"),
311        );
312    }
313
314    let samples = sample_strings_from_objects(items, &["path", "name"], 3);
315    if !samples.is_empty() {
316        let _ = write!(summary, ": {}", samples.join(", "));
317    }
318
319    summary
320}
321
322fn summarize_file_list(output: &Value, files: &[Value]) -> String {
323    let total = output.get("total").and_then(Value::as_u64).unwrap_or(files.len() as u64);
324    let mut summary = format!("Listed {total} {}", pluralize(total, "file", "files"));
325
326    let samples = files
327        .iter()
328        .filter_map(Value::as_str)
329        .map(str::trim)
330        .filter(|text| !text.is_empty())
331        .take(3)
332        .map(str::to_string)
333        .collect::<Vec<_>>();
334    if !samples.is_empty() {
335        let _ = write!(summary, ": {}", samples.join(", "));
336    }
337
338    summary
339}
340
341fn summarize_search_results(output: &Value, results: &[Value]) -> String {
342    let returned = output
343        .get("returned")
344        .or_else(|| output.get("total"))
345        .or_else(|| output.get("count"))
346        .and_then(Value::as_u64)
347        .unwrap_or(results.len() as u64);
348
349    let mut summary = if returned == 0 {
350        "No results found".to_string()
351    } else {
352        format!("Returned {returned} {}", pluralize(returned, "result", "results"))
353    };
354    if let Some(query) = trimmed_string_field(output, "query") {
355        let _ = write!(summary, " for `{query}`");
356    }
357
358    // Sample a few hits as `path:line` so archives stay legible without
359    // embedding full snippets.
360    let mut samples = Vec::new();
361    for item in results {
362        let Some(path) = match_path_text(item) else { continue };
363        let sample = match item.get("line").and_then(Value::as_u64) {
364            Some(line) => format!("{path}:{line}"),
365            None => path.to_string(),
366        };
367        if samples.iter().any(|existing: &String| existing == &sample) {
368            continue;
369        }
370        samples.push(sample);
371        if samples.len() >= 3 {
372            break;
373        }
374    }
375    if !samples.is_empty() {
376        let _ = write!(summary, ": {}", samples.join(", "));
377    }
378
379    summary
380}
381
382fn summarize_matches(output: &Value, matches: &[Value]) -> String {
383    let total = output
384        .get("total_match_count")
385        .or_else(|| output.get("matched_count"))
386        .or_else(|| output.get("count"))
387        .and_then(Value::as_u64)
388        .unwrap_or(matches.len() as u64);
389
390    if total == 0 {
391        return "No matches found".to_string();
392    }
393
394    let mut summary = format!("Found {total} {}", pluralize(total, "match", "matches"));
395
396    let samples = sample_match_paths(matches, 3);
397    if !samples.is_empty() {
398        let _ = write!(summary, " in {}", samples.join(", "));
399    } else if let Some(path) = trimmed_string_field(output, "path") {
400        let _ = write!(summary, " in {path}");
401    }
402
403    summary
404}
405
406fn append_unique_line(lines: &mut Vec<String>, line: &str) {
407    if !lines.iter().any(|existing| existing == line) {
408        lines.push(line.to_string());
409    }
410}
411
412fn contains_line_block(container: &str, candidate: &str) -> bool {
413    !line_block_ranges(container, candidate).is_empty()
414}
415
416fn line_block_ranges(container: &str, candidate: &str) -> Vec<(usize, usize)> {
417    let container_lines = container.lines().collect::<Vec<_>>();
418    let candidate_lines = candidate.lines().collect::<Vec<_>>();
419    if candidate_lines.is_empty() || candidate_lines.len() > container_lines.len() {
420        return Vec::new();
421    }
422
423    container_lines
424        .windows(candidate_lines.len())
425        .enumerate()
426        .filter_map(|(start, window)| {
427            (window == candidate_lines.as_slice()).then_some((start, start + candidate_lines.len()))
428        })
429        .collect()
430}
431
432fn contains_distinct_line_blocks(container: &str, first: &str, second: &str) -> bool {
433    let first_ranges = line_block_ranges(container, first);
434    let second_ranges = line_block_ranges(container, second);
435    first_ranges.iter().any(|&(first_start, first_end)| {
436        second_ranges
437            .iter()
438            .any(|&(second_start, second_end)| first_end <= second_start || second_end <= first_start)
439    })
440}
441
442fn append_labeled_stream_text(lines: &mut Vec<String>, label: &str, text: &str) {
443    lines.push(format!("[{label}]\n{text}"));
444}
445
446fn append_unrepresented_stream_text(lines: &mut Vec<String>, text: &str) {
447    if !lines.iter().any(|existing| contains_line_block(existing, text)) {
448        lines.push(text.to_string());
449    }
450}
451
452fn aggregate_primary_streams(output: &Value) -> Vec<String> {
453    let merged = trimmed_string_field(output, "output");
454    let stdout = trimmed_string_field(output, "stdout");
455    let stderr = trimmed_string_field(output, "stderr");
456    let mut parts = Vec::new();
457
458    match (merged, stdout, stderr) {
459        (None, Some(stdout), Some(stderr)) => {
460            // Without an authoritative merged field, stdout and stderr are
461            // separate pipes. Keep both labels even when their bytes happen
462            // to be identical or one is contained by the other.
463            append_labeled_stream_text(&mut parts, "stdout", stdout);
464            append_labeled_stream_text(&mut parts, "stderr", stderr);
465        }
466        (None, Some(stdout), None) | (None, None, Some(stdout)) => parts.push(stdout.to_string()),
467        (None, None, None) => {}
468        (Some(merged), Some(stdout), Some(stderr)) if contains_distinct_line_blocks(merged, stdout, stderr) => {
469            // The merged field proves that it contains both named streams as
470            // distinct blocks, so it is safe to emit once without duplicates.
471            parts.push(merged.to_string());
472        }
473        (Some(merged), Some(stdout), Some(stderr)) => {
474            let stdout_is_in_merged = contains_line_block(merged, stdout);
475            let stderr_is_in_merged = contains_line_block(merged, stderr);
476            let stdout_contains_merged = contains_line_block(stdout, merged);
477            let stderr_contains_merged = contains_line_block(stderr, merged);
478
479            if stdout_is_in_merged && !stderr_is_in_merged {
480                parts.push(merged.to_string());
481                append_labeled_stream_text(&mut parts, "stderr", stderr);
482            } else if stderr_is_in_merged && !stdout_is_in_merged {
483                parts.push(merged.to_string());
484                append_labeled_stream_text(&mut parts, "stdout", stdout);
485            } else {
486                // Equal or overlapping named streams cannot be deduplicated
487                // from one occurrence in `output`; retain both labels. Keep
488                // the merged value too when neither named stream covers it
489                // completely.
490                append_labeled_stream_text(&mut parts, "stdout", stdout);
491                append_labeled_stream_text(&mut parts, "stderr", stderr);
492                if !stdout_contains_merged && !stderr_contains_merged {
493                    append_unrepresented_stream_text(&mut parts, merged);
494                }
495            }
496        }
497        (Some(merged), Some(named), None) | (Some(merged), None, Some(named)) => {
498            if contains_line_block(merged, named) {
499                // The merged value contains the complete named stream and is
500                // the least lossy representation of the result.
501                parts.push(merged.to_string());
502            } else if contains_line_block(named, merged) {
503                // The named stream is the complete value and `output` is a
504                // bounded preview.
505                parts.push(named.to_string());
506            } else {
507                parts.push(merged.to_string());
508                append_unrepresented_stream_text(&mut parts, named);
509            }
510        }
511        (Some(merged), None, None) => parts.push(merged.to_string()),
512    }
513
514    if let Some(content) = trimmed_string_field(output, "content") {
515        // `content` is an independent payload field. Never replace a labeled
516        // pipe stream with it merely because one contains the other.
517        append_unrepresented_stream_text(&mut parts, content);
518    }
519
520    parts
521}
522
523const STREAM_OUTPUT_METADATA_FIELDS: &[&str] = &[
524    "output",
525    "stdout",
526    "stderr",
527    "content",
528    "success",
529    "status",
530    "exit_code",
531    "command",
532    "working_directory",
533    "session_id",
534    "process_id",
535    "id",
536    "is_exited",
537    "rows",
538    "cols",
539    "wall_time",
540    "duration_ms",
541    "spool_path",
542    "critical_note",
543    "hint",
544    "message",
545    "next_action",
546    "error_message",
547];
548
549fn structured_stream_metadata(output: &Value, additional_excluded_fields: &[&str]) -> Option<String> {
550    let object = output.as_object()?;
551    let metadata = object
552        .iter()
553        .filter(|(key, value)| {
554            // A string error is rendered below as its user-facing text;
555            // retain structured errors so codes, retry state, and other
556            // diagnostic fields remain available to event consumers.
557            !(STREAM_OUTPUT_METADATA_FIELDS.contains(&key.as_str())
558                || additional_excluded_fields.contains(&key.as_str())
559                || matches!(value, Value::Null)
560                || (key.as_str() == "error" && value.is_string()))
561        })
562        .map(|(key, value)| (key.clone(), value.clone()))
563        .collect::<serde_json::Map<_, _>>();
564
565    if metadata.is_empty() {
566        return None;
567    }
568
569    serde_json::to_string_pretty(&Value::Object(metadata))
570        .ok()
571        .map(|metadata| format!("Structured output:\n{metadata}"))
572}
573
574fn append_primary_output_context_with_exclusions(
575    parts: &mut Vec<String>,
576    output: &Value,
577    additional_excluded_fields: &[&str],
578) {
579    if let Some(metadata) = structured_stream_metadata(output, additional_excluded_fields) {
580        append_unique_line(parts, &metadata);
581    }
582    if let Some(text) = trimmed_error_message(output) {
583        append_unique_line(parts, text);
584    }
585    for key in ["message", "critical_note", "hint", "next_action", "error_message"] {
586        if let Some(text) = trimmed_string_field(output, key) {
587            append_unique_line(parts, text);
588        }
589    }
590}
591
592fn append_primary_output_context(parts: &mut Vec<String>, output: &Value) {
593    append_primary_output_context_with_exclusions(parts, output, &[]);
594}
595
596const LIST_RESULT_SUMMARY_FIELDS: &[&str] = &["items", "count", "total"];
597const FILE_RESULT_SUMMARY_FIELDS: &[&str] = &["files", "total"];
598const MATCH_RESULT_SUMMARY_FIELDS: &[&str] = &["matches", "total_match_count", "matched_count", "count", "path"];
599const SEARCH_RESULT_SUMMARY_FIELDS: &[&str] = &["results", "returned", "total", "count", "query"];
600const EMPTY_RESULT_SUMMARY_FIELDS: &[&str] = &[];
601
602fn append_structured_result_metadata(parts: &mut Vec<String>, output: &Value, summary_fields: &[&str]) {
603    if let Some(metadata) = structured_stream_metadata(output, summary_fields) {
604        append_unique_line(parts, &metadata);
605    }
606}
607
608fn append_diff_stream_context(parts: &mut Vec<String>, output: &Value) {
609    for stream in aggregate_primary_streams(output) {
610        let stream_text = stream
611            .strip_prefix("[stdout]\n")
612            .or_else(|| stream.strip_prefix("[stderr]\n"))
613            .unwrap_or(&stream);
614        let already_in_diff = canonical_diff_previews(output).iter().any(|diff| {
615            diff.get("content")
616                .and_then(Value::as_str)
617                .is_some_and(|content| content.trim() == stream_text.trim())
618        });
619        if !already_in_diff {
620            append_unique_line(parts, &stream);
621        }
622    }
623}
624
625/// Extract a [`ToolOutputPayload`] from a tool result JSON value, preserving
626/// bounded metadata alongside a spool reference and falling back to inline
627/// text aggregation otherwise.
628pub fn tool_output_payload_from_value(output: &Value) -> ToolOutputPayload {
629    if !output.is_object() {
630        let aggregated_output = match output {
631            Value::Null => String::new(),
632            Value::String(text) => text.to_string(),
633            _ => serde_json::to_string(output).unwrap_or_default(),
634        };
635        return ToolOutputPayload { aggregated_output, spool_path: None };
636    }
637
638    if let Some(spool_path) = output.get("spool_path").and_then(Value::as_str) {
639        let mut parts = Vec::new();
640        append_primary_output_context(&mut parts, output);
641        return ToolOutputPayload {
642            aggregated_output: parts.join("\n"),
643            spool_path: Some(spool_path.to_string()),
644        };
645    }
646
647    if let Some(diff) = diff_preview_output(output) {
648        let mut parts = vec![diff];
649        append_diff_stream_context(&mut parts, output);
650        append_primary_output_context_with_exclusions(&mut parts, output, &["diff", "diff_preview"]);
651        return ToolOutputPayload {
652            aggregated_output: parts.join("\n"),
653            spool_path: None,
654        };
655    }
656
657    let mut primary_text = aggregate_primary_streams(output);
658
659    if !primary_text.is_empty() {
660        append_primary_output_context(&mut primary_text, output);
661        return ToolOutputPayload {
662            aggregated_output: primary_text.join("\n"),
663            spool_path: None,
664        };
665    }
666
667    let (structured_summary, summary_fields) = if let Some(items) = output.get("items").and_then(Value::as_array) {
668        (Some(summarize_list_items(output, items)), LIST_RESULT_SUMMARY_FIELDS)
669    } else if let Some(files) = output.get("files").and_then(Value::as_array) {
670        (Some(summarize_file_list(output, files)), FILE_RESULT_SUMMARY_FIELDS)
671    } else if let Some(matches) = output.get("matches").and_then(Value::as_array) {
672        (Some(summarize_matches(output, matches)), MATCH_RESULT_SUMMARY_FIELDS)
673    } else if let Some(results) = output.get("results").and_then(Value::as_array) {
674        // `code_search`-style outputs: without this branch the archive only
675        // records "Structured result with fields: query, filters, results,
676        // returned", which made the turn_912/913 planning trajectories (54
677        // searches) illegible in session archives and ATIF exports.
678        (Some(summarize_search_results(output, results)), SEARCH_RESULT_SUMMARY_FIELDS)
679    } else {
680        (
681            output
682                .as_object()
683                .map(|obj| {
684                    obj.keys()
685                        .filter(|key| key.as_str() != "success")
686                        .take(4)
687                        .cloned()
688                        .collect::<Vec<_>>()
689                })
690                .filter(|keys| !keys.is_empty())
691                .map(|keys| format!("Structured result with fields: {}", keys.join(", "))),
692            EMPTY_RESULT_SUMMARY_FIELDS,
693        )
694    };
695
696    let mut parts = Vec::new();
697    if let Some(summary) = structured_summary.as_deref() {
698        append_unique_line(&mut parts, summary);
699    }
700    if let Some(text) = trimmed_error_message(output) {
701        append_unique_line(&mut parts, text);
702    }
703    for key in ["message", "critical_note", "hint", "next_action", "error_message"] {
704        if let Some(text) = trimmed_string_field(output, key) {
705            append_unique_line(&mut parts, text);
706        }
707    }
708    append_structured_result_metadata(&mut parts, output, summary_fields);
709
710    ToolOutputPayload {
711        aggregated_output: parts.join("\n"),
712        spool_path: None,
713    }
714}
715
716/// Shared lifecycle state for assistant text, reasoning, and model-emitted tool calls.
717#[derive(Debug, Default)]
718pub struct SharedLifecycleEmitter {
719    next_item_index: u64,
720    assistant: StreamingTextState,
721    reasoning: StreamingTextState,
722    reasoning_stage: Option<String>,
723    tool_calls: HashMap<String, ToolCallStreamState>,
724    pending_events: Vec<ThreadEvent>,
725}
726
727impl SharedLifecycleEmitter {
728    /// Generate the next unique item ID for lifecycle events.
729    #[must_use]
730    pub fn next_item_id(&mut self) -> String {
731        let id = self.next_item_index;
732        self.next_item_index += 1;
733        format!("item_{id}")
734    }
735
736    /// Emit a completed agent message event with the full text.
737    pub fn emit_completed_agent_message(&mut self, text: &str) {
738        if text.trim().is_empty() {
739            return;
740        }
741        let item_id = self.next_item_id();
742        self.pending_events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
743            item: ThreadItem {
744                context: None,
745                id: item_id,
746                details: ThreadItemDetails::AgentMessage(AgentMessageItem { text: text.to_string() }),
747            },
748        }));
749    }
750
751    /// Replace the current assistant streaming text. Returns `true` if the text changed.
752    pub fn replace_assistant_text(&mut self, text: &str) -> bool {
753        replace_stream_text(&mut self.assistant, text)
754    }
755
756    /// Whether the assistant text stream has been started.
757    #[must_use]
758    pub fn assistant_started(&self) -> bool {
759        self.assistant.started
760    }
761
762    /// Length of the accumulated assistant text in bytes.
763    #[must_use]
764    pub fn assistant_len(&self) -> usize {
765        self.assistant.text.len()
766    }
767
768    /// Append a delta to the assistant text stream. Returns `true` if content was added.
769    pub fn append_assistant_delta(&mut self, delta: &str) -> bool {
770        append_stream_delta(&mut self.assistant, delta)
771    }
772
773    /// Emit a snapshot of the current assistant text as an item event.
774    pub fn emit_assistant_snapshot(&mut self, item_id: Option<String>) -> bool {
775        let item_id = item_id.unwrap_or_else(|| self.next_item_id());
776        emit_text_snapshot(&mut self.pending_events, &mut self.assistant, item_id, |text| {
777            ThreadItemDetails::AgentMessage(AgentMessageItem { text })
778        })
779    }
780
781    /// Complete the assistant text stream, emitting a final completed event.
782    pub fn complete_assistant_stream(&mut self) -> bool {
783        complete_text_stream(&mut self.pending_events, &mut self.assistant, |text| {
784            ThreadItemDetails::AgentMessage(AgentMessageItem { text })
785        })
786    }
787
788    /// Emit a completed reasoning event with the full text.
789    pub fn emit_completed_reasoning(&mut self, text: &str) {
790        if text.trim().is_empty() {
791            return;
792        }
793        let item_id = self.next_item_id();
794        self.pending_events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
795            item: ThreadItem {
796                context: None,
797                id: item_id,
798                details: ThreadItemDetails::Reasoning(Box::new(ReasoningItem {
799                    diagnostic: None,
800                    text: text.to_string(),
801                    stage: self.reasoning_stage.clone(),
802                })),
803            },
804        }));
805    }
806
807    /// Replace the current reasoning streaming text. Returns `true` if the text changed.
808    pub fn replace_reasoning_text(&mut self, text: &str) -> bool {
809        replace_stream_text(&mut self.reasoning, text)
810    }
811
812    /// Append a delta to the reasoning text stream. Returns `true` if content was added.
813    pub fn append_reasoning_delta(&mut self, delta: &str) -> bool {
814        append_stream_delta(&mut self.reasoning, delta)
815    }
816
817    /// Update the reasoning stage label. Returns `true` if the stage changed.
818    pub fn set_reasoning_stage(&mut self, stage: Option<String>) -> bool {
819        if self.reasoning_stage == stage {
820            return false;
821        }
822        self.reasoning_stage = stage;
823        true
824    }
825
826    /// Length of the accumulated reasoning text in bytes.
827    #[must_use]
828    pub fn reasoning_len(&self) -> usize {
829        self.reasoning.text.len()
830    }
831
832    /// Whether the reasoning text stream has been started.
833    #[must_use]
834    pub fn reasoning_started(&self) -> bool {
835        self.reasoning.started
836    }
837
838    /// Emit a snapshot of the current reasoning text as an item event.
839    pub fn emit_reasoning_snapshot(&mut self, item_id: Option<String>) -> bool {
840        let item_id = item_id.unwrap_or_else(|| self.next_item_id());
841        let stage = self.reasoning_stage.clone();
842        emit_text_snapshot(&mut self.pending_events, &mut self.reasoning, item_id, move |text| {
843            ThreadItemDetails::Reasoning(Box::new(ReasoningItem { diagnostic: None, text, stage: stage.clone() }))
844        })
845    }
846
847    /// Emit an update event reflecting the current reasoning stage.
848    pub fn emit_reasoning_stage_update(&mut self) -> bool {
849        if !self.reasoning.started {
850            return false;
851        }
852        let Some(item_id) = self.reasoning.item_id.clone() else {
853            return false;
854        };
855        self.pending_events.push(ThreadEvent::ItemUpdated(ItemUpdatedEvent {
856            item: ThreadItem {
857                context: None,
858                id: item_id,
859                details: ThreadItemDetails::Reasoning(Box::new(ReasoningItem {
860                    diagnostic: None,
861                    text: self.reasoning.text.clone(),
862                    stage: self.reasoning_stage.clone(),
863                })),
864            },
865        }));
866        true
867    }
868
869    /// Complete the reasoning text stream, emitting a final completed event.
870    pub fn complete_reasoning_stream(&mut self) -> bool {
871        let stage = self.reasoning_stage.clone();
872        complete_text_stream(&mut self.pending_events, &mut self.reasoning, move |text| {
873            ThreadItemDetails::Reasoning(Box::new(ReasoningItem { diagnostic: None, text, stage: stage.clone() }))
874        })
875    }
876
877    /// Start tracking a tool call, emitting an item-started event.
878    pub fn start_tool_call(&mut self, call_id: &str, tool_name: Option<String>, item_id: Option<String>) -> bool {
879        let generated_item_id = item_id.unwrap_or_else(|| self.next_item_id());
880        let buffer = self
881            .tool_calls
882            .entry(call_id.to_string())
883            .or_insert_with(|| ToolCallStreamState {
884                item_id: generated_item_id,
885                name: None,
886                arguments: String::new(),
887                started: false,
888                last_emitted_args_len: 0,
889                update_events: 0,
890            });
891
892        if buffer.name.is_none() {
893            buffer.name = tool_name;
894        }
895        if buffer.started {
896            return false;
897        }
898
899        buffer.started = true;
900        self.pending_events.push(tool_started_event(
901            buffer.item_id.clone(),
902            buffer.name.as_deref().unwrap_or_default(),
903            None,
904            Some(call_id),
905        ));
906        true
907    }
908
909    /// Append an argument delta to an in-progress tool call.
910    pub fn append_tool_call_delta(
911        &mut self,
912        call_id: &str,
913        delta: &str,
914        tool_name: Option<String>,
915        item_id: Option<String>,
916    ) -> bool {
917        if delta.is_empty() {
918            return false;
919        }
920
921        let generated_item_id = item_id.unwrap_or_else(|| self.next_item_id());
922        let buffer = self
923            .tool_calls
924            .entry(call_id.to_string())
925            .or_insert_with(|| ToolCallStreamState {
926                item_id: generated_item_id,
927                name: None,
928                arguments: String::new(),
929                started: false,
930                last_emitted_args_len: 0,
931                update_events: 0,
932            });
933
934        if !buffer.started {
935            buffer.started = true;
936            if buffer.name.is_none() {
937                buffer.name = tool_name;
938            }
939            self.pending_events.push(tool_started_event(
940                buffer.item_id.clone(),
941                buffer.name.as_deref().unwrap_or_default(),
942                None,
943                Some(call_id),
944            ));
945        } else if buffer.name.is_none() {
946            buffer.name = tool_name;
947        }
948
949        buffer.arguments.push_str(delta);
950        // Throttle intermediate `item.updated` events: emit the first delta
951        // eagerly (so the UI shows progress), then only when enough new bytes
952        // have accumulated and the per-call cap hasn't been reached. The final
953        // `complete_tool_call` always emits the full arguments regardless.
954        let new_len = buffer.arguments.len();
955        let should_emit = buffer.update_events == 0
956            || (buffer.update_events < MAX_TOOL_ARG_UPDATE_EVENTS
957                && new_len.saturating_sub(buffer.last_emitted_args_len) >= MIN_TOOL_ARG_UPDATE_BYTES);
958        if should_emit {
959            buffer.last_emitted_args_len = new_len;
960            buffer.update_events += 1;
961            let arguments = progress_tool_arguments(&buffer.arguments);
962            self.pending_events.push(tool_invocation_updated_event(
963                buffer.item_id.clone(),
964                buffer.name.as_deref().unwrap_or_default(),
965                Some(&arguments),
966                Some(call_id),
967                ToolCallStatus::InProgress,
968            ));
969        }
970        true
971    }
972
973    pub fn complete_tool_call(&mut self, call_id: &str, status: ToolCallStatus, outcome: Option<ToolOutcome>) -> bool {
974        let Some(buffer) = self.tool_calls.remove(call_id) else {
975            return false;
976        };
977        if !buffer.started {
978            return false;
979        }
980
981        let arguments = if buffer.arguments.is_empty() {
982            None
983        } else {
984            Some(progress_tool_arguments(&buffer.arguments))
985        };
986        let resolved_outcome = outcome.unwrap_or_else(|| tool_outcome_from_status(&status));
987        self.pending_events.push(tool_invocation_completed_event(
988            buffer.item_id,
989            buffer.name.as_deref().unwrap_or_default(),
990            arguments.as_ref(),
991            Some(call_id),
992            status,
993            resolved_outcome,
994        ));
995        true
996    }
997
998    #[must_use]
999    pub fn tool_call_item_id(&self, call_id: &str) -> Option<&str> {
1000        self.tool_calls.get(call_id).map(|buffer| buffer.item_id.as_str())
1001    }
1002
1003    pub fn sync_tool_call_arguments(
1004        &mut self,
1005        call_id: &str,
1006        arguments: &str,
1007        tool_name: Option<String>,
1008        item_id: Option<String>,
1009    ) -> bool {
1010        let generated_item_id = item_id.unwrap_or_else(|| self.next_item_id());
1011        let buffer = self
1012            .tool_calls
1013            .entry(call_id.to_string())
1014            .or_insert_with(|| ToolCallStreamState {
1015                item_id: generated_item_id,
1016                name: None,
1017                arguments: String::new(),
1018                started: false,
1019                last_emitted_args_len: 0,
1020                update_events: 0,
1021            });
1022
1023        if buffer.name.is_none() {
1024            buffer.name = tool_name;
1025        }
1026
1027        if !buffer.started {
1028            buffer.started = true;
1029            self.pending_events.push(tool_started_event(
1030                buffer.item_id.clone(),
1031                buffer.name.as_deref().unwrap_or_default(),
1032                None,
1033                Some(call_id),
1034            ));
1035        }
1036
1037        if buffer.arguments == arguments {
1038            return false;
1039        }
1040
1041        buffer.arguments.clear();
1042        buffer.arguments.push_str(arguments);
1043        let args = progress_tool_arguments(&buffer.arguments);
1044        self.pending_events.push(tool_invocation_updated_event(
1045            buffer.item_id.clone(),
1046            buffer.name.as_deref().unwrap_or_default(),
1047            Some(&args),
1048            Some(call_id),
1049            ToolCallStatus::InProgress,
1050        ));
1051        buffer.last_emitted_args_len = buffer.arguments.len();
1052        buffer.update_events = buffer.update_events.saturating_add(1);
1053        true
1054    }
1055
1056    pub fn complete_open_items(&mut self) {
1057        self.complete_open_text_items();
1058        self.complete_open_tool_calls_with_status(ToolCallStatus::Completed);
1059    }
1060
1061    pub fn complete_open_text_items(&mut self) {
1062        let _ = self.complete_assistant_stream();
1063        let _ = self.complete_reasoning_stream();
1064    }
1065
1066    pub fn complete_open_items_with_tool_status(&mut self, status: ToolCallStatus) {
1067        self.complete_open_text_items();
1068        self.complete_open_tool_calls_with_status(status);
1069    }
1070
1071    pub fn complete_open_tool_calls_with_status(&mut self, status: ToolCallStatus) {
1072        let call_ids = self.tool_calls.keys().cloned().collect::<Vec<_>>();
1073        for call_id in call_ids {
1074            let _ = self.complete_tool_call(&call_id, status.clone(), None);
1075        }
1076    }
1077
1078    /// Emit a final `item.updated` carrying the full accumulated arguments for
1079    /// each open tool call, bypassing the intermediate-update throttle.
1080    ///
1081    /// Tool calls remain open (not completed); callers complete them via
1082    /// [`Self::complete_tool_call`] when execution finishes. This guarantees
1083    /// the authoritative streamed arguments are visible after streaming ends
1084    /// even when intermediate deltas were throttled (e.g. small tool calls
1085    /// whose completing delta fell below the byte threshold). Updates that
1086    /// would carry the same length as the last emitted snapshot are skipped
1087    /// to avoid redundant events for large tool calls whose last intermediate
1088    /// update already captured the full arguments.
1089    pub fn flush_open_tool_call_arguments(&mut self) {
1090        let call_ids: Vec<String> = self.tool_calls.keys().cloned().collect();
1091        for call_id in call_ids {
1092            let Some(buffer) = self.tool_calls.get_mut(&call_id) else {
1093                continue;
1094            };
1095            if buffer.arguments.is_empty() || buffer.last_emitted_args_len == buffer.arguments.len() {
1096                continue;
1097            }
1098            let arguments = progress_tool_arguments(&buffer.arguments);
1099            self.pending_events.push(tool_invocation_updated_event(
1100                buffer.item_id.clone(),
1101                buffer.name.as_deref().unwrap_or_default(),
1102                Some(&arguments),
1103                Some(&call_id),
1104                ToolCallStatus::InProgress,
1105            ));
1106            buffer.last_emitted_args_len = buffer.arguments.len();
1107        }
1108    }
1109
1110    #[must_use]
1111    pub fn drain_events(&mut self) -> Vec<ThreadEvent> {
1112        std::mem::take(&mut self.pending_events)
1113    }
1114}
1115
1116fn replace_stream_text(state: &mut StreamingTextState, text: &str) -> bool {
1117    if state.text == text {
1118        return false;
1119    }
1120    state.text.clear();
1121    state.text.push_str(text);
1122    true
1123}
1124
1125fn append_stream_delta(state: &mut StreamingTextState, delta: &str) -> bool {
1126    if delta.is_empty() {
1127        return false;
1128    }
1129    state.text.push_str(delta);
1130    true
1131}
1132
1133fn emit_text_snapshot(
1134    pending_events: &mut Vec<ThreadEvent>,
1135    state: &mut StreamingTextState,
1136    item_id: String,
1137    build_details: impl FnOnce(String) -> ThreadItemDetails,
1138) -> bool {
1139    if state.text.trim().is_empty() {
1140        return false;
1141    }
1142
1143    let item_id = state.item_id.get_or_insert(item_id).clone();
1144    let item = ThreadItem {
1145        context: None,
1146        id: item_id,
1147        details: build_details(state.text.clone()),
1148    };
1149
1150    if state.started {
1151        pending_events.push(ThreadEvent::ItemUpdated(ItemUpdatedEvent { item }));
1152    } else {
1153        state.started = true;
1154        pending_events.push(ThreadEvent::ItemStarted(ItemStartedEvent { item }));
1155    }
1156    true
1157}
1158
1159fn complete_text_stream(
1160    pending_events: &mut Vec<ThreadEvent>,
1161    state: &mut StreamingTextState,
1162    build_details: impl FnOnce(String) -> ThreadItemDetails,
1163) -> bool {
1164    if !state.started {
1165        return false;
1166    }
1167
1168    let Some(item_id) = state.item_id.take() else {
1169        state.started = false;
1170        state.text.clear();
1171        return false;
1172    };
1173
1174    state.started = false;
1175    let text = std::mem::take(&mut state.text);
1176    pending_events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
1177        item: ThreadItem {
1178            context: None,
1179            id: item_id,
1180            details: build_details(text),
1181        },
1182    }));
1183    true
1184}
1185
1186#[must_use]
1187pub fn tool_output_item_id(call_item_id: &str) -> String {
1188    format!("{call_item_id}:output")
1189}
1190
1191fn tool_invocation_item(
1192    item_id: String,
1193    tool_name: &str,
1194    arguments: Option<&Value>,
1195    tool_call_id: Option<&str>,
1196    status: ToolCallStatus,
1197    outcome: Option<ToolOutcome>,
1198) -> ThreadItem {
1199    ThreadItem {
1200        context: None,
1201        id: item_id,
1202        details: ThreadItemDetails::ToolInvocation(Box::new(ToolInvocationItem {
1203            tool_name: tool_name.to_string(),
1204            arguments: arguments.cloned(),
1205            tool_call_id: tool_call_id.map(str::to_string),
1206            status,
1207            outcome,
1208        })),
1209    }
1210}
1211
1212fn tool_output_item(
1213    call_item_id: &str,
1214    tool_call_id: Option<&str>,
1215    status: ToolCallStatus,
1216    exit_code: Option<i32>,
1217    spool_path: Option<&str>,
1218    output: impl Into<String>,
1219) -> ThreadItem {
1220    ThreadItem {
1221        context: None,
1222        id: tool_output_item_id(call_item_id),
1223        details: ThreadItemDetails::ToolOutput(Box::new(ToolOutputItem {
1224            call_id: call_item_id.to_string(),
1225            tool_call_id: tool_call_id.map(str::to_string),
1226            spool_path: spool_path.map(str::to_string),
1227            output: output.into(),
1228            exit_code,
1229            status,
1230        })),
1231    }
1232}
1233
1234#[must_use]
1235pub fn tool_started_event(
1236    item_id: String,
1237    tool_name: &str,
1238    arguments: Option<&Value>,
1239    tool_call_id: Option<&str>,
1240) -> ThreadEvent {
1241    ThreadEvent::ItemStarted(ItemStartedEvent {
1242        item: tool_invocation_item(item_id, tool_name, arguments, tool_call_id, ToolCallStatus::InProgress, None),
1243    })
1244}
1245
1246#[must_use]
1247pub fn tool_invocation_updated_event(
1248    item_id: String,
1249    tool_name: &str,
1250    arguments: Option<&Value>,
1251    tool_call_id: Option<&str>,
1252    status: ToolCallStatus,
1253) -> ThreadEvent {
1254    ThreadEvent::ItemUpdated(ItemUpdatedEvent {
1255        item: tool_invocation_item(item_id, tool_name, arguments, tool_call_id, status, None),
1256    })
1257}
1258
1259#[must_use]
1260pub fn tool_invocation_completed_event(
1261    item_id: String,
1262    tool_name: &str,
1263    arguments: Option<&Value>,
1264    tool_call_id: Option<&str>,
1265    status: ToolCallStatus,
1266    outcome: ToolOutcome,
1267) -> ThreadEvent {
1268    ThreadEvent::ItemCompleted(ItemCompletedEvent {
1269        item: tool_invocation_item(item_id, tool_name, arguments, tool_call_id, status, Some(outcome)),
1270    })
1271}
1272
1273#[must_use]
1274pub fn tool_output_started_event(call_item_id: String, tool_call_id: Option<&str>) -> ThreadEvent {
1275    ThreadEvent::ItemStarted(ItemStartedEvent {
1276        item: tool_output_item(&call_item_id, tool_call_id, ToolCallStatus::InProgress, None, None, String::new()),
1277    })
1278}
1279
1280#[must_use]
1281pub fn tool_output_updated_event(
1282    call_item_id: String,
1283    tool_call_id: Option<&str>,
1284    output: impl Into<String>,
1285) -> ThreadEvent {
1286    ThreadEvent::ItemUpdated(ItemUpdatedEvent {
1287        item: tool_output_item(&call_item_id, tool_call_id, ToolCallStatus::InProgress, None, None, output),
1288    })
1289}
1290
1291#[must_use]
1292pub fn tool_output_completed_event(
1293    call_item_id: String,
1294    tool_call_id: Option<&str>,
1295    status: ToolCallStatus,
1296    exit_code: Option<i32>,
1297    spool_path: Option<&str>,
1298    output: impl Into<String>,
1299) -> ThreadEvent {
1300    ThreadEvent::ItemCompleted(ItemCompletedEvent {
1301        item: tool_output_item(&call_item_id, tool_call_id, status, exit_code, spool_path, output),
1302    })
1303}
1304
1305#[must_use]
1306#[cold]
1307pub fn error_item_completed_event(item_id: String, message: impl Into<String>) -> ThreadEvent {
1308    ThreadEvent::ItemCompleted(ItemCompletedEvent {
1309        item: ThreadItem {
1310            context: None,
1311            id: item_id,
1312            details: ThreadItemDetails::Error(ErrorItem { message: message.into() }),
1313        },
1314    })
1315}
1316
1317fn progress_tool_arguments(arguments: &str) -> Value {
1318    serde_json::from_str(arguments).unwrap_or_else(|_| Value::String(arguments.to_string()))
1319}
1320
1321#[cfg(test)]
1322mod tests {
1323    #[test]
1324    fn explanation_file_attribution_ignores_noops_failures_and_unrelated_reads() {
1325        let args = serde_json::json!({"path":"a.rs", "content":"same"});
1326        let noop = serde_json::json!({"success":true,"diff":[{"path":"a.rs","operation":"updated","is_empty":true,"content":""}]});
1327        assert!(file_change_completed_event("call", "write_file", &args, &noop).is_none());
1328        let changed = serde_json::json!({"success":true,"diff":[{"path":"a.rs","operation":"updated","content":"--- a/a.rs\n+++ b/a.rs\n@@ -1 +1 @@\n-old\n+new","additions":1,"deletions":1},{"path":"b.rs","operation":"updated","is_empty":true}]});
1329        let event = file_change_completed_event("call", "write_file", &args, &changed).unwrap();
1330        let ThreadEvent::ItemCompleted(e) = event else {
1331            panic!("expected completed file change")
1332        };
1333        let ThreadItemDetails::FileChange(change) = e.item.details else {
1334            panic!("expected file change")
1335        };
1336        assert_eq!(change.changes.len(), 1);
1337        assert_eq!(change.changes[0].path, "a.rs");
1338        assert_eq!(change.additions, Some(1));
1339        assert_eq!(change.diff_incomplete, None);
1340        let incomplete = serde_json::json!({"success":true,"diff":[{"path":"a.rs","operation":"updated","content":"+new","additions":1,"deletions":0,"truncated":true},{"path":"b.rs","operation":"updated","skipped":true}]});
1341        let ThreadEvent::ItemCompleted(event) =
1342            file_change_completed_event("second", "write_file", &args, &incomplete).unwrap()
1343        else {
1344            panic!("file event")
1345        };
1346        let ThreadItemDetails::FileChange(change) = event.item.details else {
1347            panic!("file details")
1348        };
1349        assert_eq!(change.diff_incomplete, Some(true));
1350        assert_eq!(change.additions, None, "partial totals must remain unavailable");
1351        assert!(file_change_completed_event("call", "read_file", &args, &changed).is_none());
1352        assert!(
1353            file_change_completed_event(
1354                "call",
1355                "write_file",
1356                &args,
1357                &serde_json::json!({"success":false,"modified_files":["a.rs"]})
1358            )
1359            .is_none()
1360        );
1361    }
1362    use serde_json::json;
1363
1364    use super::*;
1365
1366    #[test]
1367    fn tool_started_event_omits_arguments_when_absent() {
1368        let event = tool_started_event("item".to_string(), "shell", None, Some("call_1"));
1369        let ThreadEvent::ItemStarted(ItemStartedEvent { item }) = event else {
1370            panic!("expected started item");
1371        };
1372        let ThreadItemDetails::ToolInvocation(details) = item.details else {
1373            panic!("expected tool invocation");
1374        };
1375        assert!(details.arguments.is_none());
1376        assert_eq!(details.tool_name, "shell");
1377    }
1378
1379    #[test]
1380    fn tool_output_updated_event_streams_in_progress_output() {
1381        let event = tool_output_updated_event("item".to_string(), Some("call_1"), "abc");
1382        let ThreadEvent::ItemUpdated(ItemUpdatedEvent { item }) = event else {
1383            panic!("expected updated item");
1384        };
1385        let ThreadItemDetails::ToolOutput(details) = item.details else {
1386            panic!("expected tool output");
1387        };
1388        assert_eq!(details.call_id, "item");
1389        assert_eq!(details.tool_call_id.as_deref(), Some("call_1"));
1390        assert_eq!(details.output, "abc");
1391        assert_eq!(details.status, ToolCallStatus::InProgress);
1392    }
1393
1394    #[test]
1395    fn tool_output_payload_preserves_spool_reference() {
1396        let payload = tool_output_payload_from_value(&json!({
1397            "spool_path": ".vtcode/context/tool_outputs/run-1.txt",
1398            "output": "ignored"
1399        }));
1400
1401        assert_eq!(payload.aggregated_output, "");
1402        assert_eq!(payload.spool_path.as_deref(), Some(".vtcode/context/tool_outputs/run-1.txt"));
1403    }
1404
1405    #[test]
1406    fn tool_output_payload_preserves_spooled_metadata_with_reference() {
1407        let payload = tool_output_payload_from_value(&json!({
1408            "spool_path": ".vtcode/context/tool_outputs/run-1.txt",
1409            "preview": "bounded preview",
1410            "spooled_bytes": 42,
1411            "stderr_preview": "diagnostic preview",
1412            "generated_files": ["src/generated.rs"],
1413            "next_action": "Inspect the generated file."
1414        }));
1415
1416        assert_eq!(payload.spool_path.as_deref(), Some(".vtcode/context/tool_outputs/run-1.txt"));
1417        assert!(payload.aggregated_output.contains("bounded preview"));
1418        assert!(payload.aggregated_output.contains("\"spooled_bytes\": 42"));
1419        assert!(payload.aggregated_output.contains("diagnostic preview"));
1420        assert!(payload.aggregated_output.contains("src/generated.rs"));
1421        assert!(payload.aggregated_output.contains("Inspect the generated file."));
1422    }
1423
1424    #[test]
1425    fn tool_output_payload_includes_apply_patch_diff_content() {
1426        let payload = tool_output_payload_from_value(&json!({
1427            "success": true,
1428            "applied": ["[1/1] Updated file: README.md (1 chunk)"],
1429            "modified_files": ["README.md"],
1430            "diff": [{
1431                "path": "README.md",
1432                "content": "diff --git a/README.md b/README.md\n-before\n+after\n",
1433                "skipped": false
1434            }]
1435        }));
1436
1437        assert!(payload.aggregated_output.contains("diff --git a/README.md b/README.md"));
1438        assert!(payload.aggregated_output.contains("-before"));
1439        assert!(payload.aggregated_output.contains("+after"));
1440    }
1441
1442    #[test]
1443    fn tool_output_payload_normalizes_legacy_write_diff_preview() {
1444        let payload = tool_output_payload_from_value(&json!({
1445            "success": true,
1446            "path": "README.md",
1447            "diff_preview": {
1448                "content": "diff --git a/README.md b/README.md\n-before\n+after\n",
1449                "skipped": false
1450            }
1451        }));
1452
1453        assert!(payload.aggregated_output.contains("diff preview for README.md"));
1454        assert!(payload.aggregated_output.contains("-before"));
1455        assert!(payload.aggregated_output.contains("+after"));
1456    }
1457
1458    #[test]
1459    fn tool_output_payload_preserves_diff_metadata_without_repeating_preview() {
1460        let payload = tool_output_payload_from_value(&json!({
1461            "success": true,
1462            "applied": ["Updated README.md"],
1463            "modified_files": ["README.md"],
1464            "diff": [{
1465                "path": "README.md",
1466                "content": "diff --git a/README.md b/README.md\n-before\n+after\n",
1467                "skipped": false
1468            }],
1469            "next_action": "Run the documentation checks."
1470        }));
1471
1472        assert!(payload.aggregated_output.contains("Updated README.md"));
1473        assert!(payload.aggregated_output.contains("README.md"));
1474        assert!(payload.aggregated_output.contains("Run the documentation checks."));
1475        assert_eq!(payload.aggregated_output.matches("diff --git a/README.md b/README.md").count(), 1);
1476    }
1477
1478    #[test]
1479    fn tool_output_payload_summarizes_list_results() {
1480        let payload = tool_output_payload_from_value(&json!({
1481            "items": [
1482                {"name": "app.rs", "path": "vtcode-tui/src/app.rs", "type": "file"},
1483                {"name": "core_tui", "path": "vtcode-tui/src/core_tui", "type": "directory"},
1484                {"name": "lib.rs", "path": "vtcode-tui/src/lib.rs", "type": "file"}
1485            ],
1486            "count": 3,
1487            "total": 11
1488        }));
1489
1490        assert_eq!(payload.spool_path, None);
1491        assert!(payload.aggregated_output.contains("Listed 11 items"));
1492        assert!(payload.aggregated_output.contains("2 files, 1 directory"));
1493        assert!(payload.aggregated_output.contains("vtcode-tui/src/app.rs"));
1494    }
1495
1496    #[test]
1497    fn tool_output_payload_combines_list_summary_with_message() {
1498        let payload = tool_output_payload_from_value(&json!({
1499            "items": [
1500                {"name": "app.rs", "path": "vtcode-tui/src/app.rs", "type": "file"},
1501                {"name": "core_tui", "path": "vtcode-tui/src/core_tui", "type": "directory"}
1502            ],
1503            "count": 2,
1504            "total": 2,
1505            "message": "[+3 more items]"
1506        }));
1507
1508        assert!(payload.aggregated_output.contains("Listed 2 items"));
1509        assert!(payload.aggregated_output.contains("[+3 more items]"));
1510    }
1511
1512    #[test]
1513    fn tool_output_payload_summarizes_match_results() {
1514        let payload = tool_output_payload_from_value(&json!({
1515            "matches": [
1516                {"path": "src/main.rs", "line_number": 12},
1517                {"file": "src/lib.rs", "line_number": 9}
1518            ],
1519            "total_match_count": 7
1520        }));
1521
1522        assert_eq!(payload.spool_path, None);
1523        assert!(payload.aggregated_output.contains("Found 7 matches"));
1524        assert!(payload.aggregated_output.contains("src/main.rs"));
1525        assert!(payload.aggregated_output.contains("src/lib.rs"));
1526    }
1527
1528    #[test]
1529    fn tool_output_payload_summarizes_nested_match_paths() {
1530        let payload = tool_output_payload_from_value(&json!({
1531            "matches": [
1532                {
1533                    "type": "match",
1534                    "data": {
1535                        "path": {"text": "vtcode-tui/src/core_tui/runner/mod.rs"},
1536                        "line_number": 27,
1537                        "lines": {"text": "runloop\n"}
1538                    }
1539                }
1540            ],
1541            "total_match_count": 1
1542        }));
1543
1544        assert!(payload.aggregated_output.contains("Found 1 match"));
1545        assert!(payload.aggregated_output.contains("vtcode-tui/src/core_tui/runner/mod.rs"));
1546    }
1547
1548    #[test]
1549    fn tool_output_payload_reports_empty_match_set() {
1550        let payload = tool_output_payload_from_value(&json!({
1551            "matches": [],
1552            "path": "crates/codegen/vtcode-core/src"
1553        }));
1554
1555        assert_eq!(payload.aggregated_output, "No matches found");
1556        assert_eq!(payload.spool_path, None);
1557    }
1558
1559    #[test]
1560    fn tool_output_payload_summarizes_code_search_results() {
1561        // Shape produced by the `code_search` tool (`CodeSearchResult`).
1562        let payload = tool_output_payload_from_value(&json!({
1563            "query": "startup timing",
1564            "filters": {"path": "src", "file_types": null, "result_types": null, "max_results": 10},
1565            "results": [
1566                {"result_type": "definition", "path": "src/main.rs", "line": 42},
1567                {"result_type": "usage", "path": "src/startup/mod.rs", "line": 7},
1568                {"result_type": "usage", "path": "src/main.rs", "line": 42}
1569            ],
1570            "returned": 3
1571        }));
1572
1573        assert_eq!(payload.spool_path, None);
1574        assert!(payload.aggregated_output.contains("Returned 3 results"));
1575        assert!(payload.aggregated_output.contains("for `startup timing`"));
1576        assert!(payload.aggregated_output.contains("src/main.rs:42"));
1577        assert!(payload.aggregated_output.contains("src/startup/mod.rs:7"));
1578        // Duplicated path:line sampled once only.
1579        assert_eq!(payload.aggregated_output.matches("src/main.rs:42").count(), 1);
1580    }
1581
1582    #[test]
1583    fn tool_output_payload_reports_empty_code_search_results() {
1584        let payload = tool_output_payload_from_value(&json!({
1585            "query": "nonexistent_symbol",
1586            "results": [],
1587            "returned": 0
1588        }));
1589
1590        assert_eq!(payload.aggregated_output, "No results found for `nonexistent_symbol`");
1591    }
1592
1593    #[test]
1594    fn tool_output_payload_includes_structured_recovery_guidance() {
1595        let payload = tool_output_payload_from_value(&json!({
1596            "matches": [],
1597            "path": "src/agent",
1598            "hint": "Pattern looks like a code fragment.",
1599            "next_action": "Retry with a larger parseable pattern."
1600        }));
1601
1602        assert!(payload.aggregated_output.contains("No matches found"));
1603        assert!(payload.aggregated_output.contains("Pattern looks like a code fragment."));
1604        assert!(payload.aggregated_output.contains("Retry with a larger parseable pattern."));
1605    }
1606
1607    #[test]
1608    fn tool_output_payload_preserves_distinct_stream_aliases_once() {
1609        let payload = tool_output_payload_from_value(&json!({
1610            "output": "merged stdout\nmerged stderr",
1611            "stdout": "merged stdout",
1612            "stderr": "merged stderr"
1613        }));
1614
1615        assert_eq!(payload.aggregated_output, "merged stdout\nmerged stderr");
1616    }
1617
1618    #[test]
1619    fn tool_output_payload_preserves_equal_named_streams_without_merged_output() {
1620        let payload = tool_output_payload_from_value(&json!({
1621            "stdout": "same output",
1622            "stderr": "same output"
1623        }));
1624
1625        assert!(payload.aggregated_output.contains("[stdout]\nsame output"));
1626        assert!(payload.aggregated_output.contains("[stderr]\nsame output"));
1627        assert_eq!(payload.aggregated_output.matches("same output").count(), 2);
1628    }
1629
1630    #[test]
1631    fn tool_output_payload_preserves_subset_named_streams_without_merged_output() {
1632        let payload = tool_output_payload_from_value(&json!({
1633            "stdout": "shared line\nstdout only",
1634            "stderr": "shared line"
1635        }));
1636
1637        assert!(payload.aggregated_output.contains("[stdout]\nshared line\nstdout only"));
1638        assert!(payload.aggregated_output.contains("[stderr]\nshared line"));
1639        assert_eq!(payload.aggregated_output.matches("shared line").count(), 2);
1640    }
1641
1642    #[test]
1643    fn tool_output_payload_preserves_overlapping_named_streams_with_merged_output() {
1644        let payload = tool_output_payload_from_value(&json!({
1645            "output": "shared line\nmerged only",
1646            "stdout": "shared line",
1647            "stderr": "shared line"
1648        }));
1649
1650        assert!(payload.aggregated_output.contains("[stdout]\nshared line"));
1651        assert!(payload.aggregated_output.contains("[stderr]\nshared line"));
1652        assert!(payload.aggregated_output.contains("shared line\nmerged only"));
1653    }
1654
1655    #[test]
1656    fn tool_output_payload_preserves_structured_metadata_with_streams() {
1657        let payload = tool_output_payload_from_value(&json!({
1658            "stdout": "command output",
1659            "json_result": {"answer": 42},
1660            "generated_files": {"files": ["src/generated.rs"]},
1661            "next_action": "Review the generated file."
1662        }));
1663
1664        assert!(payload.aggregated_output.contains("command output"));
1665        assert!(payload.aggregated_output.contains("Structured output:"));
1666        assert!(payload.aggregated_output.contains("src/generated.rs"));
1667        assert!(payload.aggregated_output.contains("\"answer\": 42"));
1668        assert!(payload.aggregated_output.contains("Review the generated file."));
1669    }
1670
1671    #[test]
1672    fn tool_output_payload_preserves_structured_only_result_metadata() {
1673        let payload = tool_output_payload_from_value(&json!({
1674            "json_result": {"answer": 42},
1675            "metadata_flag": false,
1676            "metadata_count": 0,
1677        }));
1678
1679        assert!(payload.aggregated_output.contains("Structured output:"));
1680        assert!(payload.aggregated_output.contains("\"answer\": 42"));
1681        assert!(payload.aggregated_output.contains("\"metadata_flag\": false"));
1682        assert!(payload.aggregated_output.contains("\"metadata_count\": 0"));
1683    }
1684
1685    #[test]
1686    fn tool_output_payload_preserves_structured_error_details() {
1687        let payload = tool_output_payload_from_value(&json!({
1688            "error": {
1689                "message": "command failed",
1690                "code": "E_COMMAND",
1691                "retryable": true,
1692            }
1693        }));
1694
1695        assert!(payload.aggregated_output.contains("command failed"));
1696        assert!(payload.aggregated_output.contains("\"code\": \"E_COMMAND\""));
1697        assert!(payload.aggregated_output.contains("\"retryable\": true"));
1698    }
1699
1700    #[test]
1701    fn tool_output_payload_preserves_streams_alongside_diff_preview() {
1702        let payload = tool_output_payload_from_value(&json!({
1703            "stdout": "apply completed",
1704            "stderr": "warning: generated file was already present",
1705            "diff": [{
1706                "path": "README.md",
1707                "content": "diff --git a/README.md b/README.md\n-before\n+after\n",
1708                "skipped": false,
1709            }]
1710        }));
1711
1712        assert!(payload.aggregated_output.contains("diff --git a/README.md b/README.md"));
1713        assert!(payload.aggregated_output.contains("[stdout]\napply completed"));
1714        assert!(
1715            payload
1716                .aggregated_output
1717                .contains("[stderr]\nwarning: generated file was already present")
1718        );
1719    }
1720
1721    #[test]
1722    fn tool_output_payload_preserves_non_object_results() {
1723        assert_eq!(tool_output_payload_from_value(&json!("  plain result\n")).aggregated_output, "  plain result\n");
1724        assert_eq!(tool_output_payload_from_value(&json!(42)).aggregated_output, "42");
1725        assert_eq!(tool_output_payload_from_value(&json!(null)).aggregated_output, "");
1726    }
1727
1728    #[test]
1729    fn tool_invocation_completed_event_embeds_outcome() {
1730        let event = tool_invocation_completed_event(
1731            "tool_1".to_string(),
1732            "exec_command",
1733            Some(&json!({"cmd": "pwd"})),
1734            Some("call_1"),
1735            ToolCallStatus::Failed,
1736            ToolOutcome::HookDenied,
1737        );
1738        let ThreadEvent::ItemCompleted(ItemCompletedEvent { item }) = event else {
1739            panic!("expected completed item");
1740        };
1741        let ThreadItemDetails::ToolInvocation(details) = item.details else {
1742            panic!("expected tool invocation");
1743        };
1744        assert_eq!(details.status, ToolCallStatus::Failed);
1745        assert_eq!(details.outcome, Some(ToolOutcome::HookDenied));
1746    }
1747
1748    #[test]
1749    fn complete_tool_call_infers_outcome_from_status() {
1750        let mut emitter = SharedLifecycleEmitter::default();
1751        let call_id = "call_1".to_string();
1752        emitter.start_tool_call(&call_id, Some("exec_command".to_string()), None);
1753        emitter.sync_tool_call_arguments(&call_id, "{\"cmd\":\"pwd\"}", Some("exec_command".to_string()), None);
1754        emitter.complete_tool_call(&call_id, ToolCallStatus::Completed, None);
1755        let events = emitter.drain_events();
1756        // events[0] = tool_started, events[1] = tool_invocation_updated, events[2] = tool_invocation_completed
1757        let ThreadEvent::ItemCompleted(ItemCompletedEvent { item }) = &events[2] else {
1758            panic!("expected completed item at index 2, got {:?}", events[0]);
1759        };
1760        let ThreadItemDetails::ToolInvocation(details) = &item.details else {
1761            panic!("expected tool invocation");
1762        };
1763        assert_eq!(details.outcome, Some(ToolOutcome::Success));
1764    }
1765
1766    #[test]
1767    fn append_tool_call_delta_throttles_intermediate_updates() {
1768        let mut emitter = SharedLifecycleEmitter::default();
1769        let call_id = "call_t".to_string();
1770        emitter.start_tool_call(&call_id, Some("exec_command".to_string()), None);
1771        // Clear the ItemStarted event so we only count delta-driven ItemUpdated events.
1772        let _ = emitter.drain_events();
1773
1774        // Send 600 one-byte deltas. The first delta always emits (update_events == 0).
1775        // Subsequent deltas only emit after MIN_TOOL_ARG_UPDATE_BYTES (512) new bytes.
1776        // Expected ItemUpdated events: at 1 byte (first) and at 513 bytes (threshold met).
1777        for _ in 0..600 {
1778            emitter.append_tool_call_delta(&call_id, "x", None, None);
1779        }
1780        let events = emitter.drain_events();
1781        let item_updated_count = events.iter().filter(|e| matches!(e, ThreadEvent::ItemUpdated(_))).count();
1782        assert_eq!(
1783            item_updated_count, 2,
1784            "expected 2 throttled ItemUpdated events for 600 1-byte deltas, got {item_updated_count}"
1785        );
1786
1787        // The complete event must still carry the full accumulated arguments.
1788        emitter.complete_tool_call(&call_id, ToolCallStatus::Completed, None);
1789        let events = emitter.drain_events();
1790        let completed = events
1791            .iter()
1792            .find_map(|e| {
1793                if let ThreadEvent::ItemCompleted(ItemCompletedEvent { item }) = e {
1794                    Some(item)
1795                } else {
1796                    None
1797                }
1798            })
1799            .expect("should have a completed event");
1800        let ThreadItemDetails::ToolInvocation(details) = &completed.details else {
1801            panic!("expected tool invocation in completed event");
1802        };
1803        assert!(
1804            details.arguments.as_ref().is_some_and(|a| a.to_string().contains("xxx")),
1805            "completed event should carry the full accumulated arguments"
1806        );
1807    }
1808
1809    #[test]
1810    fn append_tool_call_delta_caps_intermediate_update_events() {
1811        let mut emitter = SharedLifecycleEmitter::default();
1812        let call_id = "call_c".to_string();
1813        emitter.start_tool_call(&call_id, Some("exec_command".to_string()), None);
1814        let _ = emitter.drain_events();
1815
1816        // Send 5000 one-byte deltas. With MIN_TOOL_ARG_UPDATE_BYTES=512 and
1817        // MAX_TOOL_ARG_UPDATE_EVENTS=8, emissions stop after 8 updates even
1818        // though the threshold keeps being met.
1819        for _ in 0..5000 {
1820            emitter.append_tool_call_delta(&call_id, "x", None, None);
1821        }
1822        let events = emitter.drain_events();
1823        let item_updated_count = events.iter().filter(|e| matches!(e, ThreadEvent::ItemUpdated(_))).count();
1824        assert_eq!(
1825            item_updated_count, MAX_TOOL_ARG_UPDATE_EVENTS,
1826            "intermediate updates should be capped at MAX_TOOL_ARG_UPDATE_EVENTS, got {item_updated_count}"
1827        );
1828    }
1829
1830    #[test]
1831    fn flush_open_tool_call_arguments_emits_full_args_for_throttled_small_calls() {
1832        let mut emitter = SharedLifecycleEmitter::default();
1833        let call_id = "call_flush".to_string();
1834        emitter.start_tool_call(&call_id, Some("shell".to_string()), None);
1835        let _ = emitter.drain_events();
1836
1837        // Stream a small JSON tool call in two deltas. The first delta emits
1838        // eagerly (incomplete JSON); the second is below the byte threshold
1839        // and is throttled out.
1840        emitter.append_tool_call_delta(&call_id, "{\"cmd\":\"ec", None, None);
1841        emitter.append_tool_call_delta(&call_id, "ho hi\"}", None, None);
1842        let intermediate = emitter.drain_events();
1843        let intermediate_updated = intermediate.iter().filter(|e| matches!(e, ThreadEvent::ItemUpdated(_))).count();
1844        assert_eq!(intermediate_updated, 1, "first delta emits one eager update");
1845
1846        // Flush should emit a final update with the full, valid-JSON arguments.
1847        emitter.flush_open_tool_call_arguments();
1848        let flushed = emitter.drain_events();
1849        let updated = flushed
1850            .iter()
1851            .filter_map(|e| {
1852                if let ThreadEvent::ItemUpdated(ItemUpdatedEvent { item }) = e {
1853                    Some(&item.details)
1854                } else {
1855                    None
1856                }
1857            })
1858            .next_back();
1859        let ThreadItemDetails::ToolInvocation(details) = updated.expect("flush should emit an update") else {
1860            panic!("expected tool invocation update");
1861        };
1862        assert_eq!(
1863            details.arguments.as_ref().and_then(|a| a.get("cmd")).and_then(|c| c.as_str()),
1864            Some("echo hi"),
1865            "flush should carry the full accumulated arguments"
1866        );
1867        // Tool call should still be open (no completed event).
1868        assert!(flushed.iter().all(|e| !matches!(e, ThreadEvent::ItemCompleted(_))));
1869    }
1870
1871    #[test]
1872    fn flush_open_tool_call_arguments_skips_redundant_flush() {
1873        let mut emitter = SharedLifecycleEmitter::default();
1874        let call_id = "call_skip".to_string();
1875        emitter.start_tool_call(&call_id, Some("shell".to_string()), None);
1876        let _ = emitter.drain_events();
1877
1878        // A single large delta (>= MIN_TOOL_ARG_UPDATE_BYTES) emits with the
1879        // full arguments, so the last_emitted_args_len already equals the
1880        // accumulated length. A subsequent flush should be a no-op.
1881        let big = "x".repeat(MIN_TOOL_ARG_UPDATE_BYTES);
1882        emitter.append_tool_call_delta(&call_id, &big, None, None);
1883        let _ = emitter.drain_events();
1884
1885        emitter.flush_open_tool_call_arguments();
1886        let flushed = emitter.drain_events();
1887        assert!(flushed.is_empty(), "flush should skip when the last update already carried the full arguments");
1888    }
1889}