rho-coding-agent 1.17.0

A lightweight agent harness inspired by Pi
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! Live provider stream and transcript event handling for the interactive TUI.
//!
//! This module owns App methods that switch and drain assistant/reasoning
//! streams, schedule stream previews, record usage and cost from view-model
//! events, drive tool-call lifecycle display state, and merge finished text
//! into the transcript. Expand/collapse of truncated tool output lives in
//! `tool_output_ui`. Stream finalization that must happen before recording a
//! lifecycle event is classified exhaustively via
//! [`should_finish_streams_before_recording`].

use std::time::Instant;

use ratatui::{backend::Backend, DefaultTerminal, Terminal};

use super::{
    activity::ActivityPhase,
    event_adapter::ViewModelEvent,
    markdown::{update_code_block_state, CodeFenceState},
    render::padded_content_width,
    stream::StreamFragment,
    tool_output_ui::is_tool_entry,
    usage_cost::{
        add_optional, merge_usage, usage_difference, usage_with_estimated_cost, CostSource,
    },
    App, Entry, FinalAnswerDelta, LiveStreamPreview, ReasoningEntry, StreamKind, ToolEntry,
    ToolEntryState, STREAM_PREVIEW_DELAY, STREAM_PREVIEW_MIN_CHARS,
};

pub(super) fn final_answer_delta<'a>(emitted_text: &str, answer: &'a str) -> FinalAnswerDelta<'a> {
    match answer.strip_prefix(emitted_text) {
        Some("") => FinalAnswerDelta::None,
        Some(suffix) => FinalAnswerDelta::Append(suffix),
        None => FinalAnswerDelta::Mismatch,
    }
}

fn should_finish_streams_before_recording(event: &ViewModelEvent) -> bool {
    match event {
        ViewModelEvent::StepStarted(_)
        | ViewModelEvent::ToolCallUpdated { .. }
        | ViewModelEvent::ToolCallProposed { .. }
        | ViewModelEvent::ToolStarted { .. }
        | ViewModelEvent::ToolFinished { .. } => true,
        ViewModelEvent::RunStarted
        | ViewModelEvent::SteeringApplied(_)
        | ViewModelEvent::ProviderStreamReset
        | ViewModelEvent::ProviderRetry
        | ViewModelEvent::OutputDelta(_)
        | ViewModelEvent::ReasoningDelta(_)
        | ViewModelEvent::ContextUsage(_)
        | ViewModelEvent::Usage(_)
        | ViewModelEvent::ToolUpdated { .. } => false,
    }
}

impl App {
    pub(super) fn reset_streams(&mut self) {
        self.streams.reset();
        // Discard an unfinished reasoning phase. Callers that should keep a
        // summary must finalize before reset (for example `finish_streams`).
        self.turn.reasoning_phase_mut().reset();
    }

    pub(super) fn handle_agent_event<B: Backend>(
        &mut self,
        event: ViewModelEvent,
        terminal: &mut Terminal<B>,
    ) -> Result<bool, B::Error> {
        if let Some(phase) = event.activity_phase() {
            self.turn.set_activity_phase(phase);
        }
        match event {
            ViewModelEvent::ProviderStreamReset => {
                self.reset_provider_attempt_stream();
                Ok(true)
            }
            ViewModelEvent::OutputDelta(text) => {
                let switched = self.switch_stream_kind(StreamKind::Assistant);
                self.streams.assistant_stream.push_delta(&text);
                let drained = self.drain_stream(terminal, StreamKind::Assistant)?;
                self.update_stream_preview_deadline(StreamKind::Assistant);
                Ok(switched || drained)
            }
            ViewModelEvent::ReasoningDelta(text) => {
                let show_reasoning = self.info.runtime.show_reasoning_output;
                self.turn
                    .reasoning_phase_mut()
                    .on_reasoning_delta(show_reasoning);
                if !show_reasoning {
                    return Ok(true);
                }
                let switched = self.switch_stream_kind(StreamKind::Reasoning);
                self.streams.reasoning_stream.push_delta(&text);
                let drained = self.drain_stream(terminal, StreamKind::Reasoning)?;
                self.update_stream_preview_deadline(StreamKind::Reasoning);
                Ok(switched || drained)
            }
            other => {
                if should_finish_streams_before_recording(&other) {
                    self.finish_streams();
                }
                if let Some(entry) = self.record_agent_event(other) {
                    self.insert_entry(&entry);
                }
                self.drain_streams(terminal)?;
                Ok(true)
            }
        }
    }

    pub(super) fn switch_stream_kind(&mut self, kind: StreamKind) -> bool {
        let inserted = if self
            .streams
            .current_stream_kind
            .is_some_and(|current| current != kind)
        {
            self.finish_current_stream()
        } else {
            false
        };
        // Closing into assistant ends the reasoning phase so the thought
        // footer lands after any finished reasoning text.
        let thought = if kind == StreamKind::Assistant
            && self.streams.current_stream_kind != Some(StreamKind::Assistant)
        {
            self.close_reasoning_phase()
        } else {
            false
        };
        self.streams.current_stream_kind = Some(kind);
        self.update_stream_preview_deadline(kind);
        inserted || thought
    }

    pub(super) fn drain_streams<B: Backend>(
        &mut self,
        terminal: &mut Terminal<B>,
    ) -> Result<bool, B::Error> {
        let reasoning_drained = self.drain_stream(terminal, StreamKind::Reasoning)?;
        let assistant_drained = self.drain_stream(terminal, StreamKind::Assistant)?;
        Ok(reasoning_drained || assistant_drained)
    }

    pub(super) fn drain_stream<B: Backend>(
        &mut self,
        terminal: &mut Terminal<B>,
        kind: StreamKind,
    ) -> Result<bool, B::Error> {
        let width = terminal.size()?.width as usize;
        let inner_width = padded_content_width(width);
        let fragment = match kind {
            StreamKind::Assistant => self.streams.assistant_stream.drain_renderable_markdown(
                inner_width,
                self.streams.assistant_stream_code_fence.is_open(),
            ),
            StreamKind::Reasoning => self.streams.reasoning_stream.drain_renderable_markdown(
                inner_width,
                self.streams.reasoning_stream_code_fence.is_open(),
            ),
        };
        if let Some(fragment) = fragment {
            self.streams.live_stream_preview = None;
            self.insert_stream_fragment(fragment, kind);
            Ok(true)
        } else {
            Ok(false)
        }
    }

    pub(super) fn finish_current_stream(&mut self) -> bool {
        self.streams
            .current_stream_kind
            .is_some_and(|kind| self.finish_stream(kind))
    }

    pub(super) fn drain_stream_preview(
        &mut self,
        terminal: &mut DefaultTerminal,
    ) -> std::io::Result<bool> {
        if self
            .streams
            .stream_preview_deadline
            .is_none_or(|deadline| Instant::now() < deadline)
        {
            return Ok(false);
        }
        let Some(kind) = self.streams.current_stream_kind else {
            self.streams.stream_preview_deadline = None;
            return Ok(false);
        };
        let width = terminal.size()?.width as usize;
        let inner_width = padded_content_width(width);
        let preview = match kind {
            StreamKind::Assistant => self.streams.assistant_stream.drain_preview_markdown(
                inner_width,
                self.streams.assistant_stream_code_fence.is_open(),
            ),
            StreamKind::Reasoning => self.streams.reasoning_stream.drain_preview_markdown(
                inner_width,
                self.streams.reasoning_stream_code_fence.is_open(),
            ),
        };
        self.streams.stream_preview_deadline = None;
        self.update_stream_preview_deadline(kind);
        if let Some(preview) = preview {
            self.streams.live_stream_preview = Some(LiveStreamPreview {
                kind,
                text: preview.render_text().to_string(),
                include_leading_blank: preview.include_leading_blank(),
            });
            Ok(true)
        } else {
            Ok(false)
        }
    }

    pub(super) fn record_agent_event(&mut self, event: ViewModelEvent) -> Option<Entry> {
        match event {
            ViewModelEvent::RunStarted => {
                self.usage.usage_cost_tracker.run_started();
                self.usage.usage_before_current_run = self.usage.cumulative_usage.clone();
                self.usage.run_usage.clear();
                None
            }
            ViewModelEvent::StepStarted(step) => {
                self.usage.usage_cost_tracker.step_started();
                self.usage.run_usage.step_started();
                self.reset_streams();
                self.turn.provider_attempt_mut().begin(self.history.len());
                self.turn
                    .reasoning_phase_mut()
                    .begin_step(self.info.runtime.show_reasoning_output);
                self.begin_provider_turn_ui();
                self.turn.clear_tool_calls();
                self.turn.start_loading_if_needed();
                self.status = format!("running step {step}");
                None
            }
            ViewModelEvent::SteeringApplied(ids) => {
                self.mark_steering_applied(&ids);
                None
            }
            ViewModelEvent::ToolStarted {
                call_id,
                display_lines,
            } => {
                self.turn.tool_started(call_id, display_lines);
                None
            }
            ViewModelEvent::ToolUpdated {
                call_id,
                display_lines,
            } => {
                self.turn.tool_updated(call_id, display_lines);
                None
            }
            ViewModelEvent::ToolCallUpdated {
                index,
                call_id,
                display_lines,
            } => {
                self.turn.tool_call_preview(index, call_id, display_lines);
                None
            }
            ViewModelEvent::ToolCallProposed {
                call_id,
                display_lines,
            } => {
                self.turn.tool_call_proposed(call_id, display_lines);
                None
            }
            ViewModelEvent::ProviderStreamReset | ViewModelEvent::ProviderRetry => {
                self.usage.usage_cost_tracker.attempt_restarted();
                self.usage.run_usage.attempt_reset();
                None
            }
            ViewModelEvent::OutputDelta(_) | ViewModelEvent::ReasoningDelta(_) => None,
            ViewModelEvent::ContextUsage(usage) => {
                self.info.services.diagnostics.record_context(usage.clone());
                self.usage.current_context = Some(usage);
                None
            }
            ViewModelEvent::Usage(usage) => {
                let current_cost_source = self.usage.usage_cost_tracker.record_usage(&usage);
                let model_metadata = self.model_metadata.as_ref();
                let mut current_run_usage =
                    self.usage.run_usage.apply_snapshot(usage, |snapshot| {
                        usage_with_estimated_cost(snapshot, model_metadata)
                    });
                let step_baseline = self
                    .usage
                    .run_usage
                    .before_step()
                    .cloned()
                    .map(|usage| usage_with_estimated_cost(usage, model_metadata));
                let mut latest_usage = usage_difference(&current_run_usage, step_baseline.as_ref());
                latest_usage = usage_with_estimated_cost(latest_usage, model_metadata);
                if current_cost_source == CostSource::Estimated {
                    current_run_usage.cost_usd_micros = add_optional(
                        step_baseline
                            .as_ref()
                            .and_then(|usage| usage.cost_usd_micros),
                        latest_usage.cost_usd_micros,
                    );
                    if let Some(current) = self.usage.run_usage.current_mut() {
                        current.cost_usd_micros = current_run_usage.cost_usd_micros;
                    }
                }
                self.usage.latest_usage = Some(latest_usage);
                self.usage
                    .cumulative_usage
                    .clone_from(&self.usage.usage_before_current_run);
                merge_usage(&mut self.usage.cumulative_usage, current_run_usage);
                None
            }
            ViewModelEvent::ToolFinished {
                call_id,
                ok,
                display_style,
                mut display_lines,
                image_asset,
            } => {
                self.statusline.refresh_git_branch();
                let expanded = self.turn.tool_finished(&call_id);
                self.turn
                    .set_activity_phase(if self.turn.tool_calls().is_running() {
                        ActivityPhase::RunningTool
                    } else {
                        ActivityPhase::Starting
                    });
                let image =
                    image_asset
                        .as_ref()
                        .and_then(|asset| match self.load_feed_image(asset) {
                            Ok(image) => image,
                            Err(error) => {
                                display_lines.push(format!("image preview unavailable: {error}"));
                                None
                            }
                        });
                Some(Entry::Tool(ToolEntry {
                    state: ToolEntryState::Finished { ok, display_style },
                    display_lines,
                    expanded,
                    image,
                }))
            }
        }
    }

    pub(super) fn push_transcript_entry(&mut self, entry: Entry) {
        match entry {
            Entry::Assistant(text) => {
                let index = if matches!(self.history.last(), Some(Entry::Assistant(_))) {
                    self.history.len().saturating_sub(1)
                } else {
                    self.history.len()
                };
                match self.history.last_mut() {
                    Some(Entry::Assistant(previous)) => {
                        previous.push_str(&text);
                        self.history.lines_mut().assistant_appended(index);
                    }
                    _ => {
                        self.history.lines_mut().invalidate_from(index);
                        self.history.push(Entry::Assistant(text));
                    }
                }
                self.mark_markdown_images_dirty_from(index);
            }
            Entry::Reasoning(reasoning) => match self.history.last_mut() {
                Some(Entry::Reasoning(previous)) if previous.thought_for.is_none() => {
                    previous.text.push_str(&reasoning.text);
                    if reasoning.thought_for.is_some() {
                        previous.thought_for = reasoning.thought_for;
                    }
                    let index = self.history.len().saturating_sub(1);
                    self.history.lines_mut().invalidate_from(index);
                }
                _ => {
                    let index = self.history.len();
                    self.history.lines_mut().invalidate_from(index);
                    self.history.push(Entry::Reasoning(reasoning));
                }
            },
            other => {
                self.history.set_last_status_notice(match &other {
                    Entry::Notice(text) => Some(text.clone()),
                    _ => None,
                });
                let index = self.history.len();
                self.history.lines_mut().invalidate_from(index);
                self.history.push(other);
            }
        }
    }
    pub(super) fn finish_streams(&mut self) -> bool {
        let reasoning_finished = self.finish_stream(StreamKind::Reasoning);
        let assistant_finished = self.finish_stream(StreamKind::Assistant);
        self.streams.current_stream_kind = None;
        self.streams.stream_preview_deadline = None;
        self.streams.live_stream_preview = None;
        let thought = self.close_reasoning_phase();
        reasoning_finished || assistant_finished || thought
    }

    /// Ends the current reasoning stretch, attaching or inserting a thought duration.
    pub(super) fn close_reasoning_phase(&mut self) -> bool {
        let Some(elapsed) = self.turn.reasoning_phase_mut().finalize() else {
            return false;
        };
        match self.history.last_mut() {
            Some(Entry::Reasoning(reasoning)) if reasoning.thought_for.is_none() => {
                reasoning.thought_for = Some(elapsed);
                let index = self.history.len().saturating_sub(1);
                self.history.lines_mut().invalidate_from(index);
                true
            }
            _ => {
                self.insert_entry(&Entry::Reasoning(ReasoningEntry::summary_only(elapsed)));
                true
            }
        }
    }

    pub(super) fn finish_stream(&mut self, kind: StreamKind) -> bool {
        let fragment = match kind {
            StreamKind::Assistant => self.streams.assistant_stream.finish(),
            StreamKind::Reasoning => self.streams.reasoning_stream.finish(),
        };
        self.update_stream_preview_deadline(kind);
        if let Some(fragment) = fragment {
            self.streams.live_stream_preview = None;
            self.insert_stream_fragment(fragment, kind);
            true
        } else {
            false
        }
    }

    pub(super) fn update_stream_preview_deadline(&mut self, kind: StreamKind) {
        let pending_chars = match kind {
            StreamKind::Assistant => self.streams.assistant_stream.pending_text().chars().count(),
            StreamKind::Reasoning => self.streams.reasoning_stream.pending_text().chars().count(),
        };
        if pending_chars < STREAM_PREVIEW_MIN_CHARS {
            self.streams.stream_preview_deadline = None;
        } else if self.streams.stream_preview_deadline.is_none() {
            self.streams.stream_preview_deadline = Some(Instant::now() + STREAM_PREVIEW_DELAY);
        }
    }

    pub(super) fn insert_final_answer_suffix(&mut self, answer: &str) {
        match final_answer_delta(self.streams.assistant_stream.emitted_text(), answer) {
            FinalAnswerDelta::None => {}
            FinalAnswerDelta::Append(suffix) => {
                self.streams.assistant_stream.push_delta(suffix);
                if let Some(fragment) = self.streams.assistant_stream.finish() {
                    self.insert_stream_fragment(fragment, StreamKind::Assistant);
                }
            }
            FinalAnswerDelta::Mismatch => {
                self.replace_current_turn_assistant_transcript(answer);
            }
        }
    }

    pub(super) fn insert_stream_fragment(&mut self, fragment: StreamFragment, kind: StreamKind) {
        let render_text = fragment.render_text();
        if !render_text.is_empty() {
            let code_fence = match kind {
                StreamKind::Assistant => &mut self.streams.assistant_stream_code_fence,
                StreamKind::Reasoning => &mut self.streams.reasoning_stream_code_fence,
            };
            update_code_block_state(render_text, code_fence);
            self.history.set_last_inserted_was_tool(false);
        }
        let text = fragment.into_text();
        self.push_transcript_entry(kind.entry(text));
    }

    pub(super) fn replace_current_turn_assistant_transcript(&mut self, answer: &str) {
        let start = self.turn.current_turn_start().unwrap_or(0);
        let assistant_indices = self
            .history
            .entries()
            .iter()
            .enumerate()
            .skip(start)
            .filter_map(|(index, entry)| matches!(entry, Entry::Assistant(_)).then_some(index))
            .collect::<Vec<_>>();

        let Some((first, stale)) = assistant_indices.split_first() else {
            self.push_transcript_entry(Entry::Assistant(answer.to_string()));
            return;
        };

        if let Entry::Assistant(text) = &mut self.history.entries_mut()[*first] {
            *text = answer.to_string();
        }
        self.history.images_mut().clear();
        self.history.invalidate_from(*first);
        for index in stale.iter().rev() {
            self.history.entries_mut().remove(*index);
        }
    }

    pub(super) fn insert_entry(&mut self, entry: &Entry) {
        self.record_inserted_entry(entry.clone());
    }

    pub(super) fn notify_status(&mut self, status: impl Into<String>) {
        let status = status.into();
        self.status = status.clone();
        if self.history.last_status_notice() == Some(status.as_str()) {
            return;
        }
        self.insert_entry(&Entry::Notice(status));
    }

    pub(super) fn record_inserted_entry(&mut self, entry: Entry) {
        self.history.set_last_status_notice(match &entry {
            Entry::Notice(text) => Some(text.clone()),
            Entry::User(_)
            | Entry::Assistant(_)
            | Entry::Reasoning(_)
            | Entry::RuntimeInfo(_)
            | Entry::UsageLimits(_)
            | Entry::Tool(_)
            | Entry::Error(_) => None,
        });
        self.history
            .set_last_inserted_was_tool(is_tool_entry(&entry));
        self.push_transcript_entry(entry);
    }

    /// Apply the live `show_reasoning_output` setting to in-flight turn UI.
    pub(super) fn apply_reasoning_output_visibility(&mut self) {
        if self.info.runtime.show_reasoning_output {
            self.turn
                .reasoning_phase_mut()
                .set_hidden_placeholder(false);
            return;
        }

        self.discard_live_reasoning_output();

        // Keep the Thinking... placeholder while this step is still waiting for
        // or streaming reasoning. Later phases (response, tools) stay clear.
        let hide_placeholder = self.is_ui_busy()
            && (self.turn.reasoning_phase().has_started()
                || matches!(
                    self.turn.activity_phase(),
                    ActivityPhase::Starting
                        | ActivityPhase::WaitingForProvider
                        | ActivityPhase::Thinking
                        | ActivityPhase::RetryingProvider
                ));
        self.turn
            .reasoning_phase_mut()
            .set_hidden_placeholder(hide_placeholder);
    }

    pub(super) fn discard_live_reasoning_output(&mut self) {
        let clearing_reasoning = matches!(
            self.streams.current_stream_kind,
            Some(StreamKind::Reasoning)
        ) || self
            .streams
            .live_stream_preview
            .as_ref()
            .is_some_and(|preview| preview.kind == StreamKind::Reasoning);
        if !clearing_reasoning {
            return;
        }
        if matches!(
            self.streams.current_stream_kind,
            Some(StreamKind::Reasoning)
        ) {
            self.streams.reasoning_stream.reset();
            self.streams.reasoning_stream_code_fence = CodeFenceState::default();
            self.streams.current_stream_kind = None;
        }
        self.streams.stream_preview_deadline = None;
        self.streams.live_stream_preview = None;
    }

    pub(super) fn reset_provider_attempt_stream(&mut self) {
        self.reset_streams();
        self.turn.clear_tool_calls();
        if let Some(start) = self
            .turn
            .provider_attempt_mut()
            .reset_output(self.history.entries_mut())
        {
            self.history.images_mut().clear();
            self.history.invalidate_from(start);
        }
        self.status = "retrying provider response".into();
    }
}

#[cfg(test)]
#[path = "transcript_events_tests.rs"]
mod tests;