Files
codex/codex-rs/tui/src/chatwidget/streaming.rs
T
Felipe Coury 58cb1ccf8d Smooth transitions between TUI reasoning headings (#64202)
## Why

Streaming reasoning summaries can replace the status heading before the
current line finishes, making fast updates hard to read.

## What changed

With shimmer active, sample the latest usable reasoning heading every
3.5 seconds while letting the visible line finish as its text arrives.
Fade out the previous heading and reveal the next one across the visible
terminal columns. Retry messages still appear immediately, and reduced
motion and unsupported terminals keep the static display.

Use the same prepared frame for layout and rendering so the status row
can reflow when the heading changes.

## Testing

Cover chunks that finish one heading and start another before a draw,
delayed frames, and split Markdown bold markers. Snapshot the transition
in light and dark themes and verify that hook status text reflows at the
fade boundary.

GitOrigin-RevId: 63c579602f030f461ac81c4841106b29755710b1
2026-11-26 19:16:52 +00:00

985 lines
40 KiB
Rust

//! Streaming transcript updates for `ChatWidget`.
//!
//! This module owns assistant, plan, and reasoning deltas, including stream-tail
//! cells, commit ticks, and interrupt deferral.
use super::*;
use crate::app_event::CapturedSideDisplay;
use crate::app_event::CapturedSideStream;
use crate::app_event::CapturedSideWork;
use crate::markdown_render::ListSpacing;
fn streamed_message_matches_completed(streamed: &str, completed: &str) -> bool {
streamed == completed || streamed.strip_suffix('\n') == Some(completed)
}
impl ChatWidget {
/// Finish the visible line and remember the latest one for the next sample.
fn refresh_reasoning_heading(&mut self) -> bool {
let item_id = self.status_state.reasoning_item_id.as_deref();
let part = self.reasoning_summary_parts.len();
if let Some(row) = self.bottom_pane.status_widget_mut() {
row.extend_reasoning(item_id, part, &self.reasoning_buffer);
}
if let Some(heading) = StatusHeader::from_summary(item_id, part, &self.reasoning_buffer)
&& self.reasoning_header.as_ref() != Some(&heading)
{
self.reasoning_header = Some(heading);
return true;
}
false
}
pub(super) fn on_reasoning_item_started(&mut self, id: String) {
if self.status_state.reasoning_resume_turn_id.take().is_some()
&& self.status_state.reasoning_item_id.as_ref() != Some(&id)
{
self.on_agent_reasoning_final();
}
if self.status_state.reasoning_item_id.as_ref() == Some(&id) {
return;
}
self.status_state.reasoning_item_id = Some(id);
self.reasoning_buffer.clear();
self.reasoning_summary_parts.clear();
self.restore_reasoning_status_header();
}
pub(super) fn restore_reasoning_status_header(&mut self) {
if self.safety_buffering_is_waiting()
|| self.unified_exec_wait_streak.is_some()
|| self.status_state.compaction.is_some()
|| !self.status_state.pending_guardian_review_status.is_empty()
{
return;
}
self.refresh_reasoning_heading();
if let Some(header) = self.reasoning_header.clone() {
self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Thinking;
self.set_status_header(header);
} else if self.bottom_pane.is_task_running()
|| self.status_state.current_status.is_guardian_review()
{
self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Working;
self.set_status_header(String::from("Working"));
}
}
/// Preserve received answer and plan source before ordinary turn termination.
pub(super) fn flush_answer_and_plan_streams(&mut self) {
self.flush_answer_stream_with_separator();
if let Some(mut controller) = self.plan_stream_controller.take() {
self.clear_active_stream_tail();
let (cell, source) = controller.finalize();
if let Some(cell) = cell {
self.add_boxed_history(cell);
}
if let Some(source) = source {
self.note_stream_consolidation_queued();
self.app_event_tx
.send(AppEvent::ConsolidateProposedPlan(source));
}
self.request_pending_usage_output_insertion_after_stream_shutdown();
}
}
pub(super) fn flush_answer_stream_with_separator(&mut self) {
self.flush_answer_stream(/*completed_message*/ None, /*phase*/ None);
}
fn flush_answer_stream(
&mut self,
completed_message: Option<&str>,
phase: Option<MessagePhase>,
) {
let had_stream_controller = self.stream_controller.is_some();
if let Some(mut controller) = self.stream_controller.take() {
let needs_scrollback_reflow = controller.needs_scrollback_reflow();
self.clear_active_stream_tail();
let interrupted_item = self
.transcript
.active_streamed_agent_message
.take()
.filter(|_| completed_message.is_none());
if let Some((turn, item)) = &interrupted_item {
self.transcript.last_flushed_agent_message = interrupted_item.clone();
if let Some(seen) = &mut self.transcript.replayed_cloud_text {
self.transcript.response_order += 1;
seen.entry(turn.clone())
.or_default()
.entry(item.clone())
.or_insert((false, self.transcript.response_order));
}
}
let (cell, streamed_source) = controller.finalize();
let completed_display = completed_message.map(|source| {
parse_assistant_markdown(source, self.config.cwd.as_path()).visible_markdown
});
let completed_message_differs = completed_display.as_deref().is_some_and(|completed| {
let Some(streamed) = streamed_source.as_deref() else {
return true;
};
// Stream finalization supplies one trailing newline when the last delta omitted it.
!streamed_message_matches_completed(streamed, completed)
});
let scrollback_reflow = if needs_scrollback_reflow || completed_message_differs {
crate::app_event::ConsolidationScrollbackReflow::Required
} else {
crate::app_event::ConsolidationScrollbackReflow::IfResizeReflowRan
};
// Match newline-committed streaming behavior: once assistant output is ready to be
// committed into history, hide the inline status row so transcript content replaces it.
if cell.is_some() {
self.bottom_pane.hide_status_indicator();
}
let deferred_history_cell =
if scrollback_reflow == crate::app_event::ConsolidationScrollbackReflow::Required {
cell
} else {
if let Some(cell) = cell {
self.add_boxed_history(cell);
}
None
};
// Consolidate the run of streaming AgentMessageCells into a single AgentMarkdownCell
// that can re-render from source on resize.
let copy_source = completed_message.map(str::to_owned).or(streamed_source);
let source = copy_source.as_deref().map(|source| {
parse_assistant_markdown(source, self.config.cwd.as_path()).visible_markdown
});
if let Some(source) = source {
let inline_visualization_context = self.thread_id.and_then(|thread_id| {
crate::inline_visualization::InlineVisualizationContext::from_config(
&self.config,
thread_id,
)
});
self.note_stream_consolidation_queued();
self.app_event_tx.send(AppEvent::ConsolidateAgentMessage {
emitted_cells: controller.emitted_cells(),
phase,
interrupted_item,
source,
copy_source,
cwd: self.config.cwd.to_path_buf(),
inline_visualization_context,
scrollback_reflow,
deferred_history_cell,
});
}
}
self.adaptive_chunking.reset();
if had_stream_controller && self.stream_controllers_idle() {
self.app_event_tx.send(AppEvent::StopCommitAnimation);
}
if had_stream_controller {
self.request_pending_usage_output_insertion_after_stream_shutdown();
}
if completed_message.is_some() {
self.transcript.active_streamed_agent_message = None;
self.transcript.last_flushed_agent_message = None;
}
}
pub(super) fn stream_controllers_idle(&self) -> bool {
self.stream_controller
.as_ref()
.map(|controller| controller.queued_lines() == 0)
.unwrap_or(true)
&& self
.plan_stream_controller
.as_ref()
.map(|controller| controller.queued_lines() == 0)
.unwrap_or(true)
}
/// Restore the status indicator only after message completion is pending,
/// the turn is still running, and all stream queues have drained.
///
/// This gate prevents flicker while normal output is still actively
/// streaming, but still restores a visible "working" affordance when a
/// message ends before the turn itself has completed.
pub(super) fn maybe_restore_status_indicator_after_stream_idle(&mut self) {
if !self.status_state.pending_status_indicator_restore
|| !self.bottom_pane.is_task_running()
|| !self.stream_controllers_idle()
{
return;
}
self.bottom_pane.ensure_status_indicator();
self.set_status(
self.status_state.current_status.header.clone(),
self.status_state.current_status.details.clone(),
StatusDetailsCapitalization::Preserve,
self.status_state.current_status.details_max_lines,
);
self.status_state.pending_status_indicator_restore = false;
}
/// Capture at handoff, while links and visualization directives still have the outgoing cwd.
pub(crate) fn take_side_display(
&mut self,
width: u16,
) -> (Option<CapturedSideStream>, CapturedSideDisplay) {
self.flush_completed_tool_activity();
let visualizations = self.thread_id.and_then(|id| {
crate::inline_visualization::InlineVisualizationContext::from_config(&self.config, id)
});
let stream = if let Some(controller) = &self.stream_controller {
let source = controller.source_snapshot();
let markdown = parse_assistant_markdown(&source, self.config.cwd.as_path());
let cell = history_cell::AgentMarkdownCell::from_parsed_message(
markdown.visible_markdown,
source,
&self.config.cwd,
visualizations.clone(),
&[],
);
Some(CapturedSideStream::Answer {
cell: Arc::new(cell),
item: self.transcript.active_streamed_agent_message.clone(),
})
} else if self.plan_stream_controller.is_some() {
Some(CapturedSideStream::Plan(Arc::new(
history_cell::new_proposed_plan(
self.transcript.plan_delta_buffer.clone(),
&self.config.cwd,
),
)))
} else {
None
};
let active = self
.transcript
.take_active_cell()
.filter(|cell| match &stream {
Some(CapturedSideStream::Answer { .. }) => {
!cell.as_any().is::<history_cell::StreamingAgentTailCell>()
}
Some(CapturedSideStream::Plan(_)) => {
!cell.as_any().is::<history_cell::StreamingPlanTailCell>()
}
None => true,
});
let display = CapturedSideDisplay {
rendered_completion_turn_ids: self.turn_lifecycle.rendered_completion_turn_ids.clone(),
generated_images: std::mem::take(&mut self.turn_lifecycle.generated_images),
active,
last_completed_agent_message: self.transcript.last_completed_agent_message.clone(),
auxiliary: self
.active_cell_transcript_hyperlink_lines(width)
.unwrap_or_default(),
draft: {
let snapshot = self.bottom_pane.composer_recovery_snapshot();
let mut draft = Box::new(crate::bottom_pane::TextArea::new());
draft.set_text_with_elements(&snapshot.text, &snapshot.text_elements);
draft
},
status_line: self.status_line_content().cloned(),
work: self
.last_turn_id()
.filter(|_| self.is_agent_turn_running())
.map(|turn_id| {
CapturedSideWork::new(
turn_id.to_owned(),
self.new_status_indicator(),
self.bottom_pane.status_elapsed().unwrap_or_default(),
)
}),
cwd: self.session_cwd().to_path_buf(),
visualizations,
};
(stream, display)
}
pub(super) fn finalize_completed_assistant_message(
&mut self,
message: &str,
phase: Option<MessagePhase>,
) {
if !message.trim().is_empty()
&& self
.stream_controller
.as_ref()
.is_none_or(|stream| !stream.has_text())
{
self.stream_controller = None;
let displayed =
parse_assistant_markdown(message, self.config.cwd.as_path()).visible_markdown;
self.handle_streaming_delta(displayed);
}
// Item completion is authoritative. Use it for consolidation so any
// deltas dropped by a saturated transport cannot truncate the transcript.
self.flush_answer_stream(Some(message), phase);
self.handle_stream_finished();
self.request_redraw();
}
pub(super) fn on_agent_message_delta(&mut self, delta: String) {
self.handle_streaming_delta(delta);
}
pub(super) fn on_plan_delta(&mut self, delta: String) {
if self.active_mode_kind() != ModeKind::Plan {
return;
}
if !self.transcript.plan_item_active {
self.transcript.plan_item_active = true;
self.transcript.plan_delta_buffer.clear();
}
self.transcript.plan_delta_buffer.push_str(&delta);
if self.plan_stream_controller.is_none() {
// Before starting a plan stream, flush any active exec cell group.
self.flush_unified_exec_wait_streak();
self.flush_active_cell();
self.plan_stream_controller = Some(
PlanStreamController::new(
self.current_stream_width(/*reserved_cols*/ 4),
&self.config.cwd,
self.history_render_mode(),
)
.with_list_spacing(
if self.local_settings.transcript_mode.is_owned() {
ListSpacing::Compact
} else {
ListSpacing::AfterMultiline
},
),
);
}
let changed = self
.plan_stream_controller
.as_mut()
.is_some_and(|controller| controller.push(&delta));
if (changed || delta.contains('\n')) && self.sync_active_stream_tail() {
self.request_redraw();
}
if changed {
self.app_event_tx.send(AppEvent::StartCommitAnimation);
self.run_catch_up_commit_tick();
}
}
pub(super) fn on_plan_item_completed(&mut self, text: String) {
let (plan_text, source) = if text.trim().is_empty() {
(
self.transcript.plan_delta_buffer.trim().to_string(),
self.transcript.plan_delta_buffer.clone(),
)
} else {
(text.clone(), text)
};
if !plan_text.trim().is_empty() {
self.transcript.response_order += 1;
self.transcript
.record_agent_markdown(plan_text.clone(), source);
self.transcript.latest_proposed_plan_markdown = Some(plan_text.clone());
}
// Plan commit ticks can hide the status row; remember whether we streamed plan output so
// completion can restore it once stream queues are idle.
let should_restore_after_stream = self.plan_stream_controller.is_some();
self.transcript.plan_delta_buffer.clear();
self.transcript.plan_item_active = false;
self.transcript.saw_plan_item_this_turn = true;
let (finalized_streamed_cell, consolidated_plan_source) =
if let Some(mut controller) = self.plan_stream_controller.take() {
let source_only = controller.has_live_tail() && controller.tail_starts_stream();
self.clear_active_stream_tail();
let (cell, source) = controller.finalize();
if source_only {
(None, source)
} else {
(cell, source)
}
} else {
(None, None)
};
if let Some(cell) = finalized_streamed_cell {
self.add_boxed_history(cell);
// TODO: Replace streamed output with the final plan item text if plan streaming is
// removed or if we need to reconcile mismatches between streamed and final content.
if let Some(source) = consolidated_plan_source {
self.note_stream_consolidation_queued();
self.app_event_tx
.send(AppEvent::ConsolidateProposedPlan(source));
}
} else if !plan_text.is_empty() {
self.add_to_history(history_cell::new_proposed_plan(plan_text, &self.config.cwd));
} else if let Some(source) = consolidated_plan_source {
self.note_stream_consolidation_queued();
self.app_event_tx
.send(AppEvent::ConsolidateProposedPlan(source));
}
if should_restore_after_stream {
self.status_state.pending_status_indicator_restore = true;
self.maybe_restore_status_indicator_after_stream_idle();
self.request_pending_usage_output_insertion_after_stream_shutdown();
}
}
pub(super) fn replace_reasoning_parts(
&mut self,
mut summary: Vec<String>,
content: Vec<String>,
) {
if self.config.show_raw_agent_reasoning {
summary.extend(content);
}
// Empty completions follow some streamed items. Preserve their deltas.
if summary.iter().all(String::is_empty) {
return;
}
self.reasoning_buffer.clear();
self.reasoning_summary_parts.clear();
for part in summary {
self.on_reasoning_section_break();
self.on_agent_reasoning_delta(part);
}
}
pub(super) fn on_agent_reasoning_delta(&mut self, delta: String) {
// Accumulate the current reasoning block for history and activity text.
self.reasoning_buffer.push_str(&delta);
if self.safety_buffering_is_waiting() {
return;
}
if self.unified_exec_wait_streak.is_some() {
// Unified exec waiting should take precedence over reasoning-derived status headers.
return;
}
if !self.status_state.pending_guardian_review_status.is_empty() {
return;
}
let changed = self.refresh_reasoning_heading();
let Some(header) = &self.reasoning_header else {
// No usable summary has arrived yet.
return;
};
let status = &self.status_state.current_status;
if !changed
&& self.status_state.terminal_title_status_kind == TerminalTitleStatusKind::Thinking
&& status.header == header.text
&& status.details.is_none()
&& status.details_max_lines == STATUS_DETAILS_DEFAULT_MAX_LINES
&& self
.bottom_pane
.status_widget()
.is_none_or(|status| status.header() == header.text)
{
return;
}
// Update the shimmer header to the extracted reasoning chunk header.
let header = header.clone();
self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Thinking;
if !self.set_status_header(header) {
self.request_redraw();
}
}
pub(super) fn on_agent_reasoning_final(&mut self) {
// At the end of a reasoning block, record transcript-only content.
if !self.reasoning_buffer.is_empty() {
self.reasoning_summary_parts
.push(std::mem::take(&mut self.reasoning_buffer));
}
let item_id = self.status_state.reasoning_item_id.as_deref();
self.reasoning_header = self
.reasoning_summary_parts
.iter()
.enumerate()
.rev()
.find_map(|(index, part)| StatusHeader::from_summary(item_id, index, part))
.or(self.reasoning_header.take());
if !self.reasoning_summary_parts.is_empty() {
let reasoning_parts = std::mem::take(&mut self.reasoning_summary_parts);
let mut cell =
history_cell::new_reasoning_summary_block(reasoning_parts, &self.config.cwd);
if let Some(id) = &self.status_state.reasoning_item_id {
cell.set_source_item_id(id.clone());
}
let cell: Box<dyn HistoryCell> = cell;
let result = match self.transcript.active_cell.as_mut() {
Some(active) => active.append_reasoning(cell),
None => Err(cell),
};
match result {
Ok(()) => self.bump_active_cell_revision(),
Err(cell) => self.add_boxed_history(cell),
}
}
self.reasoning_buffer.clear();
// Keep the last useful summary through tools and later empty items.
self.status_state.reasoning_item_id = None;
self.status_state.reasoning_resume_turn_id = None;
self.reasoning_summary_parts.clear();
self.request_redraw();
}
pub(super) fn on_reasoning_section_break(&mut self) {
// Start a new reasoning block for header extraction and accumulate transcript.
if !self.reasoning_buffer.is_empty() {
self.reasoning_summary_parts
.push(std::mem::take(&mut self.reasoning_buffer));
}
}
pub(super) fn on_stream_error(&mut self, message: String, additional_details: Option<String>) {
self.status_state.remember_retry_status_header();
self.bottom_pane.ensure_status_indicator();
self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Thinking;
self.set_status(
message,
additional_details,
StatusDetailsCapitalization::CapitalizeFirst,
STATUS_DETAILS_DEFAULT_MAX_LINES,
);
}
pub(crate) fn reconcile_corrected_cloud_copy(
&mut self,
item: &(String, String),
previous: Option<&dyn history_cell::HistoryCell>,
) {
if self.transcript.last_agent_copy_item.as_ref() != Some(item) {
return;
}
let agent = previous.and_then(|cell| {
cell.as_any()
.downcast_ref::<history_cell::AgentMarkdownCell>()
});
let source = previous.and_then(history_cell::HistoryCell::copy_source);
self.transcript.last_agent_copy_item = agent.and_then(|cell| cell.interrupted_item.clone());
self.transcript.last_agent_markdown = source.map(|source| {
let markdown = if agent.is_some() {
parse_assistant_markdown(source, self.config.cwd.as_path()).visible_markdown
} else {
source.to_owned()
};
crate::markdown_render::followup_labels(&markdown).into_owned()
});
self.transcript.last_agent_source = source.map(str::to_owned);
}
/// Handle completion of an `AgentMessage` turn item.
///
/// An unphased message can finish while the turn still has work to do.
pub(super) fn on_agent_message_item_completed(
&mut self,
item: AgentMessageItem,
turn_id: &str,
from_replay: bool,
) {
if !from_replay && let Some(questions) = &item.questions {
self.add_async_questions(&item.id, questions);
}
if self.transcript.has_replayed_cloud_text(turn_id, &item.id) {
return;
}
let key = (turn_id.to_owned(), item.id.clone());
let mut message = String::new();
for content in &item.content {
match content {
AgentMessageContent::Text { text } => message.push_str(text),
}
}
let parsed = parse_assistant_markdown(&message, self.config.cwd.as_path());
let questions = item.questions.as_deref().unwrap_or_default();
let cloud = self.transcript.replayed_cloud_text.is_some();
let completing = !cloud || !from_replay || self.transcript.recording_finished_cloud_text;
self.transcript.response_order += 1;
let mut order = self.transcript.response_order;
let mut correcting = self.transcript.last_flushed_agent_message.as_ref() == Some(&key);
let mut first_observation = false;
if (from_replay || completing || !parsed.visible_markdown.is_empty())
&& let Some(seen) = &mut self.transcript.replayed_cloud_text
{
let items = seen.entry(turn_id.to_owned()).or_default();
let (finished, position) = items.entry(item.id.clone()).or_insert_with(|| {
first_observation = true;
(completing, order)
});
correcting |= completing && !*finished;
*finished |= completing;
order = *position;
}
if cloud && from_replay && !completing && parsed.visible_markdown.is_empty() {
if first_observation {
self.prepare_assistant_message();
self.add_to_history(history_cell::PendingAgentMessageCell(key));
}
return;
}
let owns_stream = self.transcript.active_streamed_agent_message.as_ref() == Some(&key);
let unrelated_stream = cloud
&& self.stream_controller.is_some()
&& self.transcript.active_streamed_agent_message.is_some()
&& !owns_stream;
let unrelated_activity = unrelated_stream
|| (cloud && order < 0 && !owns_stream)
|| (cloud
&& correcting
&& self.is_agent_turn_running()
&& self.last_turn_id().is_some_and(|active| active != turn_id));
let latest_copy_order = self
.transcript
.last_agent_copy_item
.as_ref()
.and_then(|(turn, id)| {
self.transcript
.replayed_cloud_text
.as_ref()?
.get(turn)?
.get(id)
.map(|(_, position)| *position)
})
.or_else(|| {
self.transcript
.committed_turn_response
.as_ref()
.map(|(position, _)| *position)
})
.or(self.transcript.historical_copy_order);
let current_copy = (!correcting
|| (cloud
&& order < 0
&& (self.transcript.last_agent_copy_item.is_some()
|| self.transcript.last_agent_source.is_none()))
|| self.transcript.last_agent_copy_item.as_ref() == Some(&key)
|| (!unrelated_activity
&& self.transcript.last_flushed_agent_message.as_ref() == Some(&key)))
&& latest_copy_order.is_none_or(|latest| order >= latest);
if !unrelated_activity && current_copy && (completing || !cloud) {
self.transcript.last_completed_agent_message = Some(key.clone());
}
if correcting && owns_stream && !unrelated_activity {
// Commit any resumed stream fragment before replacing all fragments with
// the authoritative message. Markdown references can span interruptions.
self.flush_answer_stream_with_separator();
}
if (from_replay || !questions.is_empty() || correcting || unrelated_activity)
&& (correcting || !owns_stream || self.stream_controller.is_none())
&& (!parsed.visible_markdown.is_empty() || correcting)
{
if !unrelated_activity {
self.prepare_assistant_message();
self.mark_safety_buffering_agent_message_started();
self.bottom_pane.hide_status_indicator();
}
let context = self.thread_id.and_then(|thread_id| {
crate::inline_visualization::InlineVisualizationContext::from_config(
&self.config,
thread_id,
)
});
let mut cell = history_cell::AgentMarkdownCell::from_parsed_message(
parsed.visible_markdown.clone(),
message.clone(),
self.config.cwd.as_path(),
context,
questions,
)
.with_phase(item.phase.clone());
if parsed.visible_markdown.is_empty() {
cell = cell.with_copy_source(/*source*/ None);
}
if cloud && (from_replay && !completing || order < 0) {
cell.interrupted_item = Some(key.clone());
}
if correcting {
self.app_event_tx
.send(AppEvent::CorrectFlushedAgentMessage {
item: key.clone(),
cell,
});
} else {
self.add_to_history(cell);
}
if !unrelated_activity {
self.handle_stream_finished();
}
self.request_redraw();
} else if !unrelated_activity {
self.finalize_completed_assistant_message(&message, item.phase.clone());
}
if self.transcript.last_flushed_agent_message.as_ref() == Some(&key) {
self.transcript.last_flushed_agent_message = None;
}
let committed_response = self.transcript.committed_turn_response.take();
if !parsed.visible_markdown.is_empty() && current_copy {
self.transcript
.record_agent_markdown(parsed.visible_markdown.clone(), message);
self.transcript.last_agent_copy_item = Some(key);
}
let newer = committed_response
.as_ref()
.is_none_or(|(previous, _)| order >= *previous);
self.transcript.committed_turn_response = if completing
&& !parsed.visible_markdown.is_empty()
&& newer
&& self
.last_turn_id()
.is_none_or(|active_turn| active_turn == turn_id)
{
Some((
order,
crate::markdown_render::followup_labels(&parsed.visible_markdown).into_owned(),
))
} else {
committed_response
};
if !from_replay
&& let Some(cwd) = parsed.last_created_branch_cwd()
&& let Some(thread_id) = self.thread_id
&& let Some(runner) = self.workspace_command_runner.clone()
{
let branch_cwd = PathBuf::from(cwd);
let cwd = self.config.cwd.to_path_buf();
let tx = self.app_event_tx.clone();
tokio::spawn(async move {
if let Some(branch) =
crate::branch_summary::current_branch_name(runner.as_ref(), &branch_cwd).await
{
tx.send(AppEvent::SyncThreadGitBranch {
thread_id,
branch,
cwd,
});
}
});
}
if unrelated_activity {
return;
}
self.status_state.pending_status_indicator_restore = item.questions.is_some()
|| match item.phase {
None if self.turn_lifecycle.agent_turn_running && !self.statusline_disconnected => {
true
}
Some(MessagePhase::FinalAnswer) | None => {
!self.input_queue.pending_steers.is_empty()
}
Some(MessagePhase::Commentary | MessagePhase::PartialAnswer) => true,
};
self.maybe_restore_status_indicator_after_stream_idle();
}
/// Periodic tick for stream commits. In smooth mode this preserves one-line pacing, while
/// catch-up mode drains larger batches to reduce queue lag.
pub(crate) fn on_commit_tick(&mut self) {
self.run_commit_tick();
}
/// Runs a regular periodic commit tick.
pub(super) fn run_commit_tick(&mut self) {
self.run_commit_tick_with_scope(CommitTickScope::AnyMode);
}
/// Runs an opportunistic commit tick only if catch-up mode is active.
pub(super) fn run_catch_up_commit_tick(&mut self) {
self.run_commit_tick_with_scope(CommitTickScope::CatchUpOnly);
}
/// Runs a commit tick for the current stream queue snapshot.
///
/// `scope` selects paced, catch-up, or replay draining. While lines are actively streaming
/// we hide the status row to avoid duplicate "in progress" affordances. We only re-show
/// the row after message completion once stream queues are idle.
pub(crate) fn run_commit_tick_with_scope(&mut self, scope: CommitTickScope) {
let now = Instant::now();
let outcome = run_commit_tick(
&mut self.adaptive_chunking,
self.stream_controller.as_mut(),
self.plan_stream_controller.as_mut(),
scope,
now,
);
for cell in outcome.cells {
self.bottom_pane.hide_status_indicator();
self.add_boxed_history(cell);
}
if scope == CommitTickScope::AnyMode || outcome.has_controller {
self.sync_active_stream_tail();
}
if outcome.has_controller && outcome.all_idle {
self.maybe_restore_status_indicator_after_stream_idle();
self.app_event_tx.send(AppEvent::StopCommitAnimation);
}
if self.turn_lifecycle.agent_turn_running {
self.refresh_runtime_metrics();
}
}
pub(super) fn flush_interrupt_queue(&mut self) {
let mut mgr = std::mem::take(&mut self.interrupts);
mgr.flush_all(self);
self.interrupts = mgr;
}
pub(super) fn flush_interrupt_activity(&mut self) {
let mut mgr = std::mem::take(&mut self.interrupts);
mgr.flush_activity(self);
self.interrupts = mgr;
}
/// Move a lifecycle payload into the interrupt queue or its immediate handler.
#[inline]
pub(super) fn defer_or_handle<T>(
&mut self,
payload: T,
push: impl FnOnce(&mut InterruptManager, T),
handle: impl FnOnce(&mut Self, T),
) {
// Preserve deterministic FIFO across queued interrupts: once anything
// is queued due to an active write cycle, continue queueing until the
// queue is flushed to avoid reordering (e.g., ExecEnd before ExecBegin).
if self.stream_controller.is_some() || !self.interrupts.is_empty() {
push(&mut self.interrupts, payload);
} else {
handle(self, payload);
}
}
pub(super) fn handle_stream_finished(&mut self) {
if self.task_complete_pending {
self.bottom_pane.hide_status_indicator();
self.task_complete_pending = false;
}
// A completed stream indicates non-exec content was just inserted.
self.flush_interrupt_queue();
}
#[inline]
pub(super) fn handle_streaming_delta(&mut self, delta: String) {
if !delta.is_empty() {
self.mark_safety_buffering_agent_message_started();
}
if self.stream_controller.is_none() {
self.prepare_assistant_message();
let inline_visualization_context = self.thread_id.and_then(|thread_id| {
crate::inline_visualization::InlineVisualizationContext::from_config(
&self.config,
thread_id,
)
});
self.stream_controller = Some(
StreamController::new_with_inline_visualizations(
self.current_stream_width(/*reserved_cols*/ 2),
&self.config.cwd,
self.history_render_mode(),
inline_visualization_context,
)
.with_list_spacing(
if self.local_settings.transcript_mode.is_owned() {
ListSpacing::Compact
} else {
ListSpacing::AfterMultiline
},
),
);
}
let changed = self
.stream_controller
.as_mut()
.is_some_and(|controller| controller.push(&delta));
if (changed || delta.contains('\n')) && self.sync_active_stream_tail() {
self.request_redraw();
}
if changed {
self.app_event_tx.send(AppEvent::StartCommitAnimation);
self.run_catch_up_commit_tick();
}
}
pub(super) fn active_cell_is_stream_tail(&self) -> bool {
self.transcript.active_cell.as_ref().is_some_and(|cell| {
cell.as_any().is::<history_cell::StreamingAgentTailCell>()
|| cell.as_any().is::<history_cell::StreamingPlanTailCell>()
})
}
pub(super) fn has_active_stream_tail(&self) -> bool {
(self.stream_controller.is_some() || self.plan_stream_controller.is_some())
&& self.active_cell_is_stream_tail()
}
pub(super) fn sync_active_stream_tail(&mut self) -> bool {
if let Some(controller) = self.stream_controller.as_ref() {
let tail_lines = controller.current_tail_lines();
if tail_lines.is_empty() {
return self.clear_active_stream_tail();
}
self.bottom_pane.hide_status_indicator();
let cell = history_cell::StreamingAgentTailCell::new(
tail_lines,
controller.tail_starts_stream(),
);
if self
.transcript
.active_cell
.as_ref()
.and_then(|active| {
active
.as_any()
.downcast_ref::<history_cell::StreamingAgentTailCell>()
})
.is_some_and(|active| active == &cell)
{
return false;
}
self.transcript.active_cell = Some(Box::new(cell));
self.bump_active_cell_revision();
return true;
}
if let Some(controller) = self.plan_stream_controller.as_ref() {
let tail_lines = controller.current_tail_display_lines();
if tail_lines.is_empty() {
return self.clear_active_stream_tail();
}
self.bottom_pane.hide_status_indicator();
let cell = history_cell::StreamingPlanTailCell::new(
tail_lines,
!controller.tail_starts_stream(),
);
if self
.transcript
.active_cell
.as_ref()
.and_then(|active| {
active
.as_any()
.downcast_ref::<history_cell::StreamingPlanTailCell>()
})
.is_some_and(|active| active == &cell)
{
return false;
}
self.transcript.active_cell = Some(Box::new(cell));
self.bump_active_cell_revision();
return true;
}
self.clear_active_stream_tail()
}
pub(super) fn clear_active_stream_tail(&mut self) -> bool {
if self.active_cell_is_stream_tail() {
self.transcript.active_cell = None;
self.bump_active_cell_revision();
return true;
}
false
}
}