1use std::collections::VecDeque;
2
3pub(super) use ratatui::crossterm::event::{
4 Event as CrosstermEvent, KeyCode, KeyEvent, KeyEventKind, MouseEvent, MouseEventKind,
5};
6pub(super) use ratatui::prelude::*;
7pub(super) use ratatui::widgets::Clear;
8pub(super) use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
9
10use crate::tui::config::constants::ui;
11use crate::tui::core_tui::app::types::{
12 CompactActivityMetadata, DiffOverlayRequest, DiffPreviewMode, DiffPreviewState, InlineCommand, InlineEvent,
13 InlineMessageKind, InlineSegment, LocalAgentsTransientRequest, SlashCommandItem, TaskPanelMetadata,
14 TaskPanelTransientRequest, ToolOutputId, TransientActivitySignal, TransientRequest,
15};
16use crate::tui::core_tui::runner::TuiSessionDriver;
17use crate::tui::core_tui::session::Session as CoreSessionState;
18use crate::tui::core_tui::session::action::BindingStore;
19use vtcode_commons::ui_protocol::TaskItemStatus;
20
21mod agent_palette;
22pub(crate) mod diff_preview;
24mod events;
25pub mod file_palette;
27pub mod history_picker;
29mod impl_events;
30mod impl_render;
31mod layout;
32mod local_agents;
33mod palette;
34pub(crate) mod render;
36pub(crate) mod slash;
38pub mod slash_palette;
40mod task_panel;
41#[path = "transcript_review/mod.rs"]
42mod tool_output_viewer;
43mod transient;
44pub mod trust;
46
47use self::file_palette::FilePalette;
48use self::history_picker::HistoryPickerState;
49use self::local_agents::LocalAgentsState;
50use self::slash_palette::SlashPalette;
51use self::tool_output_viewer::ToolOutputViewerState;
52use self::transient::{TransientFocusPolicy, TransientHost, TransientSurface, TransientVisibilityChange};
53use crate::tui::core_tui::style::theme_from_styles;
54use crate::tui::options::FullscreenInteractionSettings;
55use crate::tui::ui::theme;
56use agent_palette::AgentPalette;
57use std::sync::{
58 Arc,
59 atomic::{AtomicUsize, Ordering},
60};
61
62#[derive(Clone, Debug, Default)]
63pub(crate) struct ToolOutputBlock {
64 pub(crate) id: u64,
67 pub(crate) anchor_line: Option<usize>,
71 pub(crate) anchor_search_start: usize,
75 pub(crate) recorded_at_line: Option<usize>,
79 pub(crate) lines: Vec<String>,
80}
81
82#[derive(Clone, Debug)]
83pub(crate) struct CompactActivityEntry {
84 pub(crate) line_index: usize,
85 pub(crate) metadata: CompactActivityMetadata,
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub(crate) struct CompactActivityHitRegion {
90 pub(crate) area: Rect,
91 pub(crate) review_anchor: ToolOutputId,
92}
93
94pub struct AppSession {
96 pub(crate) core: CoreSessionState,
97 agent_palette: Option<AgentPalette>,
98 agent_palette_active: bool,
99 file_palette: Option<FilePalette>,
100 pub(crate) file_palette_active: bool,
101 inline_lists_visible: bool,
102 pub(crate) slash_palette: SlashPalette,
103 pub(crate) history_picker_state: HistoryPickerState,
104 local_agents_state: LocalAgentsState,
105 local_agents_auto_opened: bool,
106 pub(crate) show_task_panel: bool,
107 pub(crate) task_panel_lines: Vec<String>,
108 pub(crate) task_panel_statuses: Vec<TaskItemStatus>,
109 pub(crate) task_panel_current: Option<usize>,
110 pub(crate) task_panel_metadata: Option<TaskPanelMetadata>,
111 diff_preview_state: Option<DiffPreviewState>,
112 tool_output_viewer_state: Option<ToolOutputViewerState>,
113 pub(crate) tool_output_blocks: Vec<ToolOutputBlock>,
114 pub(crate) tool_output_revision: u64,
115 pub(crate) compact_activity_entries: Vec<CompactActivityEntry>,
116 pub(crate) compact_activity_hit_regions: Vec<CompactActivityHitRegion>,
117 pub(crate) diff_review_anchors: Vec<vtcode_commons::ui_protocol::DiffReviewAnchor>,
118 diff_overlay_queue: VecDeque<DiffOverlayRequest>,
119 transient_host: TransientHost,
120 transient_active_signal: Option<Arc<TransientActivitySignal>>,
121 preview_callback: Option<crate::tui::core_tui::types::PreviewCallback>,
122}
123
124pub(super) type Session = AppSession;
125
126mod commands;
127mod overlays;
128mod tool_output;
129
130use commands::to_core_command;
131
132impl AppSession {
133 pub(crate) fn new_with_logs(
135 theme: crate::tui::core_tui::types::InlineTheme,
136 placeholder: Option<String>,
137 view_rows: u16,
138 show_logs: bool,
139 appearance: Option<crate::tui::core_tui::session::config::AppearanceConfig>,
140 slash_commands: Vec<SlashCommandItem>,
141 app_name: String,
142 ) -> Self {
143 let core = CoreSessionState::new_with_logs(theme, placeholder, view_rows, show_logs, appearance, app_name);
144
145 Self {
146 core,
147 agent_palette: None,
148 agent_palette_active: false,
149 file_palette: None,
150 file_palette_active: false,
151 inline_lists_visible: true,
152 slash_palette: SlashPalette::with_commands(slash_commands),
153 history_picker_state: HistoryPickerState::new(),
154 local_agents_state: LocalAgentsState::default(),
155 local_agents_auto_opened: false,
156 show_task_panel: false,
157 task_panel_lines: Vec::new(),
158 task_panel_statuses: Vec::new(),
159 task_panel_current: None,
160 task_panel_metadata: None,
161 diff_preview_state: None,
162 tool_output_viewer_state: None,
163 tool_output_blocks: Vec::new(),
164 tool_output_revision: 0,
165 compact_activity_entries: Vec::new(),
166 compact_activity_hit_regions: Vec::new(),
167 diff_review_anchors: Vec::new(),
168 diff_overlay_queue: VecDeque::new(),
169 transient_host: TransientHost::default(),
170 transient_active_signal: None,
171 preview_callback: None,
172 }
173 }
174
175 pub(crate) fn new_with_logs_and_bindings(
177 theme: crate::tui::core_tui::types::InlineTheme,
178 placeholder: Option<String>,
179 view_rows: u16,
180 show_logs: bool,
181 appearance: Option<crate::tui::core_tui::session::config::AppearanceConfig>,
182 slash_commands: Vec<SlashCommandItem>,
183 app_name: String,
184 bindings: BindingStore,
185 ) -> Self {
186 let core = CoreSessionState::new_with_bindings(
187 theme,
188 placeholder,
189 view_rows,
190 show_logs,
191 appearance,
192 app_name,
193 bindings,
194 );
195
196 Self {
197 core,
198 agent_palette: None,
199 agent_palette_active: false,
200 file_palette: None,
201 file_palette_active: false,
202 inline_lists_visible: true,
203 slash_palette: SlashPalette::with_commands(slash_commands),
204 history_picker_state: HistoryPickerState::new(),
205 local_agents_state: LocalAgentsState::default(),
206 local_agents_auto_opened: false,
207 show_task_panel: false,
208 task_panel_lines: Vec::new(),
209 task_panel_statuses: Vec::new(),
210 task_panel_current: None,
211 task_panel_metadata: None,
212 diff_preview_state: None,
213 tool_output_viewer_state: None,
214 tool_output_blocks: Vec::new(),
215 tool_output_revision: 0,
216 compact_activity_entries: Vec::new(),
217 compact_activity_hit_regions: Vec::new(),
218 diff_review_anchors: Vec::new(),
219 diff_overlay_queue: VecDeque::new(),
220 transient_host: TransientHost::default(),
221 transient_active_signal: None,
222 preview_callback: None,
223 }
224 }
225
226 pub fn new(theme: crate::tui::core_tui::types::InlineTheme, placeholder: Option<String>, view_rows: u16) -> Self {
227 Self::new_with_logs(theme, placeholder, view_rows, true, None, Vec::new(), "Agent TUI".to_string())
228 }
229
230 pub fn core(&self) -> &CoreSessionState {
231 &self.core
232 }
233
234 pub fn core_mut(&mut self) -> &mut CoreSessionState {
235 &mut self.core
236 }
237
238 pub(crate) fn record_diff_review(&mut self, anchor: vtcode_commons::ui_protocol::DiffReviewAnchor) {
239 self.diff_review_anchors.push(anchor);
240 const MAX_DIFF_REVIEW_ANCHORS: usize = 32;
243 if self.diff_review_anchors.len() > MAX_DIFF_REVIEW_ANCHORS {
244 let excess = self.diff_review_anchors.len() - MAX_DIFF_REVIEW_ANCHORS;
245 self.diff_review_anchors.drain(..excess);
246 }
247 }
251
252 pub(crate) fn open_diff_review_for_notice(&mut self, notice_text: &str) -> bool {
264 if !notice_text.contains("review full diff") {
265 return false;
266 }
267
268 fn is_generic_label(path: &str) -> bool {
269 vtcode_commons::ui_protocol::is_generic_diff_review_path(path)
270 }
271
272 let by_notice = self
273 .diff_review_anchors
274 .iter()
275 .enumerate()
276 .rev()
277 .find(|(_, anchor)| !anchor.notice.is_empty() && notice_text.contains(anchor.notice.as_str()))
278 .map(|(index, _)| index);
279
280 let mut by_path: Option<usize> = None;
281 for (index, anchor) in self.diff_review_anchors.iter().enumerate() {
282 if is_generic_label(anchor.file_path.as_str()) {
283 continue;
284 }
285 if !notice_text.contains(anchor.file_path.as_str()) {
286 continue;
287 }
288 let better = match by_path {
289 None => true,
290 Some(prev_index) => anchor.file_path.len() > self.diff_review_anchors[prev_index].file_path.len(),
291 };
292 if better {
293 by_path = Some(index);
294 }
295 }
296
297 let index = by_notice
298 .or(by_path)
299 .or_else(|| (self.diff_review_anchors.len() == 1).then_some(0));
300 let Some(index) = index else {
301 return false;
302 };
303 let anchor = self.diff_review_anchors.swap_remove(index);
304 self.open_diff_review_anchor(anchor)
305 }
306
307 fn open_diff_review_anchor(&mut self, anchor: vtcode_commons::ui_protocol::DiffReviewAnchor) -> bool {
308 self.show_diff_overlay(DiffOverlayRequest {
309 file_path: anchor.file_path,
310 before: String::new(),
311 after: String::new(),
312 hunks: Vec::new(),
313 current_hunk: 0,
314 mode: DiffPreviewMode::ReadonlyReview,
315 unified: Some(anchor.unified),
316 });
317 true
318 }
319
320 fn close_history_picker(&mut self) {
321 if !self.history_picker_state.active {
322 return;
323 }
324 self.history_picker_state.cancel(&mut self.core.input_manager);
325 self.close_transient_surface(TransientSurface::HistoryPicker);
326 self.update_input_triggers();
327 self.mark_dirty();
328 }
329
330 pub(crate) fn show_transient(&mut self, request: TransientRequest) {
331 self.core.clear_inline_prompt_suggestion();
332 match request {
333 TransientRequest::Modal(request) => {
334 self.core
335 .show_overlay(crate::tui::core_tui::types::OverlayRequest::Modal(request.into()));
336 self.show_transient_surface(TransientSurface::FloatingOverlay);
337 }
338 TransientRequest::List(request) => {
339 self.core
340 .show_overlay(crate::tui::core_tui::types::OverlayRequest::List(request.into()));
341 self.show_transient_surface(TransientSurface::FloatingOverlay);
342 }
343 TransientRequest::Wizard(request) => {
344 self.core
345 .show_overlay(crate::tui::core_tui::types::OverlayRequest::Wizard(request.into()));
346 self.show_transient_surface(TransientSurface::FloatingOverlay);
347 }
348 TransientRequest::Diff(request) => {
349 self.show_diff_overlay(request);
350 }
351 TransientRequest::FilePalette(request) => {
352 self.load_file_palette(request.dir_lister, request.workspace);
353 match request.visible {
354 Some(true) => {
355 self.ensure_inline_lists_visible_for_trigger();
356 self.file_palette_active = true;
357 self.show_transient_surface(TransientSurface::FilePalette);
358 }
359 Some(false) => {
360 self.close_file_palette();
361 }
362 None => {}
363 }
364 }
365 TransientRequest::AgentPalette(request) => {
366 self.load_agent_palette(request.agents);
367 match request.visible {
368 Some(true) => {
369 self.ensure_inline_lists_visible_for_trigger();
370 self.agent_palette_active = true;
371 self.show_transient_surface(TransientSurface::AgentPalette);
372 }
373 Some(false) => {
374 self.close_agent_palette();
375 }
376 None => {}
377 }
378 }
379 TransientRequest::HistoryPicker => {
380 events::open_history_picker(self);
381 }
382 TransientRequest::SlashPalette => {
383 self.ensure_inline_lists_visible_for_trigger();
384 self.show_transient_surface(TransientSurface::SlashPalette);
385 }
386 TransientRequest::TaskPanel(TaskPanelTransientRequest { lines, statuses, current, visible, metadata }) => {
387 if visible.is_none() {
391 let aligned = statuses.len() == lines.len();
394 self.task_panel_statuses = if aligned { statuses } else { Vec::new() };
395 self.task_panel_current =
396 (aligned.then_some(current).flatten()).filter(|index| *index < lines.len());
397 self.task_panel_lines = lines;
398 self.core.mark_task_panel_content_dirty();
399 match metadata {
400 Some(metadata) => {
401 self.core.set_task_panel_progress_label(Some(format!(
402 "{}/{}",
403 metadata.completed, metadata.total
404 )));
405 let percent = if metadata.total == 0 {
406 None
407 } else {
408 let completed = metadata.completed.min(metadata.total) as u64;
409 let total = metadata.total as u64;
410 let percent = completed.saturating_mul(100) / total.max(1);
411 Some(u8::try_from(percent.min(100)).unwrap_or(100))
412 };
413 self.core
414 .program_status
415 .apply(vtcode_commons::program_status::ProgramStatusUpdate::Progress { percent });
416 self.task_panel_metadata = Some(metadata);
417 }
418 None => {
419 self.task_panel_metadata = None;
423 self.core.set_task_panel_progress_label(None);
424 self.core
425 .program_status
426 .apply(vtcode_commons::program_status::ProgramStatusUpdate::Progress { percent: None });
427 }
428 }
429 }
430 if let Some(visible) = visible {
431 let suppressed = visible && !self.core.appearance.should_show_task_panel();
432 if !suppressed {
433 self.set_task_panel_visible(visible);
434 }
435 } else {
438 self.core.mark_dirty();
439 }
440 }
441 TransientRequest::LocalAgents(LocalAgentsTransientRequest { visible }) => {
442 if let Some(visible) = visible {
443 if visible {
444 self.ensure_inline_lists_visible_for_trigger();
445 self.open_local_agents_drawer(false);
446 } else {
447 self.close_local_agents_drawer(true);
448 }
449 } else {
450 self.core.mark_dirty();
451 }
452 }
453 }
454 self.core.mark_dirty();
455 }
456
457 fn show_help_modal(&mut self) {
463 self.show_transient(TransientRequest::Modal(crate::tui::core_tui::app::types::ModalOverlayRequest {
464 title: "Keyboard Shortcuts".to_string(),
465 lines: Vec::new(),
466 secure_prompt: None,
467 is_help_modal: true,
468 }));
469 }
470
471 fn should_auto_open_local_agents(&self) -> bool {
472 if self.has_active_overlay() {
473 return false;
474 }
475
476 matches!(
477 self.visible_transient_surface(),
478 None | Some(TransientSurface::TaskPanel | TransientSurface::LocalAgents)
479 )
480 }
481
482 pub(crate) fn close_transient(&mut self) {
483 match self.visible_transient_surface() {
484 Some(TransientSurface::FloatingOverlay) => self.close_overlay(),
485 Some(TransientSurface::DiffPreview) => self.close_diff_overlay(),
486 Some(TransientSurface::ToolOutputViewer) => self.close_tool_output_viewer(),
487 Some(TransientSurface::HistoryPicker) => self.close_history_picker(),
488 Some(TransientSurface::AgentPalette) => self.close_agent_palette(),
489 Some(TransientSurface::FilePalette) => self.close_file_palette(),
490 Some(TransientSurface::SlashPalette) => slash::clear_slash_suggestions(self),
491 Some(TransientSurface::TaskPanel) => self.set_task_panel_visible(false),
492 Some(TransientSurface::LocalAgents) => {
493 self.close_local_agents_drawer(true);
494 }
495 None => {}
496 }
497 }
498
499 fn open_local_agents_drawer(&mut self, auto_opened: bool) {
500 self.local_agents_auto_opened = auto_opened;
501 self.show_transient_surface(TransientSurface::LocalAgents);
502 }
503
504 fn close_local_agents_drawer(&mut self, clear_auto_opened: bool) {
505 if clear_auto_opened {
506 self.local_agents_auto_opened = false;
507 }
508 self.close_transient_surface(TransientSurface::LocalAgents);
509 }
510
511 fn sync_transient_focus(&mut self) {
512 if self.core.activity_state.is_busy() {
513 self.core.set_input_enabled(false);
514 self.core.set_cursor_visible(false);
515 return;
516 }
517 let Some(surface) = self.visible_transient_surface() else {
518 self.core.set_input_enabled(true);
519 self.core.set_cursor_visible(true);
520 return;
521 };
522
523 match surface.focus_policy() {
524 TransientFocusPolicy::Modal | TransientFocusPolicy::CapturedInput => {
525 self.core.set_input_enabled(false);
526 self.core.set_cursor_visible(false);
527 }
528 TransientFocusPolicy::SharedInput | TransientFocusPolicy::Passive => {
529 self.core.set_input_enabled(true);
530 self.core.set_cursor_visible(true);
531 }
532 }
533 }
534
535 pub(super) fn sync_transient_activity_signal(&self) {
536 let Some(signal) = self.transient_active_signal.as_ref() else {
537 return;
538 };
539 let active = self
540 .visible_transient_surface()
541 .is_some_and(|surface| !matches!(surface, TransientSurface::TaskPanel));
542 signal.set_active(active);
543 }
544
545 pub(super) fn apply_transient_visibility_change(&mut self, change: TransientVisibilityChange) {
546 if matches!(change.previous_visible, Some(TransientSurface::FilePalette | TransientSurface::AgentPalette))
547 || matches!(change.current_visible, Some(TransientSurface::FilePalette | TransientSurface::AgentPalette))
548 {
549 self.core.request_full_clear();
550 }
551 self.core
552 .set_local_agents_drawer_visible(change.current_visible == Some(TransientSurface::LocalAgents));
553 self.sync_transient_focus();
554 self.sync_transient_activity_signal();
555 }
556
557 pub fn handle_command(&mut self, command: InlineCommand) {
558 match command {
559 InlineCommand::SetLocalAgents { entries } => {
560 let has_delegated_entries = entries
561 .iter()
562 .any(|entry| entry.kind == crate::tui::core_tui::types::LocalAgentKind::Delegated);
563 let has_live_delegated = entries.iter().any(|entry| {
567 entry.kind == crate::tui::core_tui::types::LocalAgentKind::Delegated && entry.is_loading()
568 });
569 let update = self.local_agents_state.set_entries(entries.clone());
570 let background_count = self.local_agents_state.loading_count();
571 let finished_count = self.local_agents_state.finished_count();
572 self.core.set_local_agents(entries);
573 self.core.set_background_activity_count(background_count);
574 self.core.set_background_finished_count(finished_count);
575 if update.has_new_delegated_entries && self.should_auto_open_local_agents() {
576 self.ensure_inline_lists_visible_for_trigger();
577 self.open_local_agents_drawer(true);
578 } else if self.local_agents_auto_opened && !has_live_delegated {
579 self.close_local_agents_drawer(true);
580 } else if !self.local_agents_visible() && !has_delegated_entries {
581 self.local_agents_auto_opened = false;
582 }
583 }
584 InlineCommand::SetActivePlan { entry } => {
585 self.core.set_active_plan(entry);
586 }
587 InlineCommand::SetArchivedHistory { entries } => {
588 let mut input_entries = Vec::new();
589 let archived = entries
590 .into_iter()
591 .map(|e| {
592 input_entries.push(
593 crate::tui::core_tui::session::input_manager::InputHistoryEntry::from_content_and_timestamp(
594 e.content.clone(),
595 e.created_at,
596 ),
597 );
598 history_picker::ArchivedPrompt {
599 content: e.content,
600 created_at: e.created_at,
601 session_label: e.session_label,
602 in_workspace: e.in_workspace,
603 }
604 })
605 .collect();
606 self.history_picker_state.set_archived_prompts(archived);
607 self.core.input_manager.prepend_archived_history(input_entries);
608 self.core.mark_dirty();
609 }
610 InlineCommand::SetInput(value) => {
611 self.handle_core_command(crate::tui::core_tui::types::InlineCommand::SetInput(value));
612 self.update_input_triggers();
613 }
614 InlineCommand::RestoreInputDraft(input) => {
615 self.handle_core_command(crate::tui::core_tui::types::InlineCommand::RestoreInputDraft(input));
616 self.update_input_triggers();
617 }
618 InlineCommand::ApplySuggestedPrompt(value) => {
619 self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ApplySuggestedPrompt(value));
620 self.update_input_triggers();
621 }
622 InlineCommand::SetInlinePromptSuggestion { suggestion, llm_generated } => {
623 self.handle_core_command(crate::tui::core_tui::types::InlineCommand::SetInlinePromptSuggestion {
624 suggestion,
625 llm_generated,
626 });
627 self.update_input_triggers();
628 }
629 InlineCommand::ClearInlinePromptSuggestion => {
630 self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ClearInlinePromptSuggestion);
631 self.update_input_triggers();
632 }
633 InlineCommand::ClearInput => {
634 self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ClearInput);
635 self.update_input_triggers();
636 }
637 InlineCommand::RecordToolOutput { id, lines } => {
638 self.record_tool_output_block(id, lines);
639 }
640 InlineCommand::AppendToolOutputLine { id, kind, segments } => {
641 self.append_tool_output_line(id, kind, segments);
642 }
643 InlineCommand::AppendCompactActivity(metadata) => {
644 self.append_compact_activity(metadata);
645 }
646 InlineCommand::ReplaceCompactActivity(metadata) => {
647 self.replace_compact_activity(metadata);
648 }
649 InlineCommand::CollapsePtyBlock(metadata) => {
650 self.collapse_pty_block(metadata);
651 }
652 InlineCommand::SetKeyBindings { bindings } => {
653 self.core.set_bindings(BindingStore::new(bindings));
654 self.refresh_compact_activity_presentations();
655 }
656 InlineCommand::SetAppearance { appearance } => {
657 let enabling_screen_reader = appearance.screen_reader_mode && !self.core.appearance.screen_reader_mode;
658 if enabling_screen_reader && let Some(viewer) = self.tool_output_viewer_state.as_mut() {
659 viewer.set_render_mode(tool_output_viewer::TranscriptRenderMode::Raw);
660 }
661 self.handle_core_command(crate::tui::core_tui::types::InlineCommand::SetAppearance { appearance });
662 self.refresh_compact_activity_presentations();
663 }
664 InlineCommand::SetFullscreenInteraction { interaction } => {
665 self.handle_core_command(crate::tui::core_tui::types::InlineCommand::SetFullscreenInteraction {
666 interaction,
667 });
668 }
669 InlineCommand::ReplaceLast { count, kind, lines, link_ranges } => {
670 let remove_count = count.min(self.core.lines.len());
671 let first_removed = self.core.lines.len().saturating_sub(remove_count);
672 self.compact_activity_entries.retain(|entry| entry.line_index < first_removed);
673 self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ReplaceLast {
674 count,
675 kind,
676 lines,
677 link_ranges,
678 });
679 }
680 InlineCommand::ClearScreen => {
681 self.tool_output_blocks.clear();
682 self.compact_activity_entries.clear();
683 self.compact_activity_hit_regions.clear();
684 self.diff_review_anchors.clear();
685 self.tool_output_revision = self.tool_output_revision.wrapping_add(1);
686 self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ClearScreen);
687 }
688 InlineCommand::CloseTransient => self.close_transient(),
689 InlineCommand::ShowTransient { request } => self.show_transient(*request),
690 InlineCommand::RecordDiffReview(anchor) => self.record_diff_review(anchor),
691 InlineCommand::FocusTranscriptReview { id } => self.open_tool_output_viewer(
692 self.core.transcript_width.max(1),
693 self.core.transcript_rows.max(1),
694 Some(id),
695 ),
696 InlineCommand::UpdateFilePaletteSearch { files } => {
697 if let Some(palette) = &mut self.file_palette {
698 palette.set_search_index(files);
699 }
700 }
701 InlineCommand::SetSlashCommands { commands } => {
702 self.slash_palette.set_commands(commands);
703 }
704 _ => {
705 if let Some(core_cmd) = to_core_command(&command) {
706 self.handle_core_command(core_cmd);
707 }
708 }
709 }
710 }
711}
712
713fn normalize_tool_output_header(header: &str) -> String {
714 crate::tui::core_tui::session::text_utils::strip_ansi_codes(header)
715 .trim_end()
716 .to_owned()
717}
718
719fn rendered_core_line_text(core: &CoreSessionState, line_index: usize) -> String {
720 let Some(line) = core.lines.get(line_index) else {
721 return String::new();
722 };
723 core.render_message_spans_for_line(line)
724 .into_iter()
725 .map(|span| crate::tui::core_tui::session::text_utils::strip_ansi_codes(span.content.as_ref()).into_owned())
726 .collect()
727}
728
729fn folded_pty_header(core: &CoreSessionState, line_index: usize) -> String {
730 let first = rendered_core_line_text(core, line_index);
731 if !first.trim_start().starts_with('•') {
732 return first;
733 }
734
735 let mut folded = first.trim_end().to_owned();
736 let mut continuation_index = line_index + 1;
737 while let Some(line) = core.lines.get(continuation_index) {
738 if line.kind != InlineMessageKind::Pty {
739 break;
740 }
741 let continuation = rendered_core_line_text(core, continuation_index);
742 let Some(fragment) = continuation.trim_start().strip_prefix('│') else {
743 break;
744 };
745 folded.push(' ');
746 folded.push_str(fragment.trim());
747 continuation_index += 1;
748 }
749 folded
750}
751
752impl std::ops::Deref for AppSession {
753 type Target = CoreSessionState;
754
755 fn deref(&self) -> &Self::Target {
756 &self.core
757 }
758}
759
760impl std::ops::DerefMut for AppSession {
761 fn deref_mut(&mut self) -> &mut Self::Target {
762 &mut self.core
763 }
764}
765
766impl TuiSessionDriver for AppSession {
767 type Command = InlineCommand;
768 type Event = InlineEvent;
769
770 fn handle_command(&mut self, command: Self::Command) {
771 AppSession::handle_command(self, command);
772 }
773
774 fn handle_event(
775 &mut self,
776 event: CrosstermEvent,
777 events: &UnboundedSender<Self::Event>,
778 callback: Option<&(dyn Fn(&Self::Event) + Send + Sync + 'static)>,
779 ) {
780 AppSession::handle_event(self, event, events, callback);
781 }
782
783 fn handle_tick(&mut self) {
784 self.core.handle_tick();
789 }
790
791 fn needs_animation_tick(&self) -> bool {
792 if !self.core.is_terminal_visible() {
796 return false;
797 }
798 self.core.needs_animation_tick()
803 || (self.core.appearance.should_animate_progress_status() && self.background_activity_active())
804 || self.tool_output_viewer_state.as_ref().is_some_and(|viewer| viewer.flash_live())
805 }
806
807 fn render(&mut self, frame: &mut Frame<'_>) {
808 AppSession::render(self, frame);
809 }
810
811 fn take_redraw(&mut self) -> bool {
812 self.core.take_redraw()
813 }
814
815 fn is_terminal_visible(&self) -> bool {
816 self.core.is_terminal_visible()
817 }
818
819 fn use_steady_cursor(&self) -> bool {
820 self.core.use_steady_cursor()
821 }
822
823 fn is_hovering_link(&self) -> bool {
824 self.core.is_hovering_link()
825 }
826
827 fn is_selecting_text(&self) -> bool {
828 self.core.is_selecting_text()
829 }
830
831 fn should_exit(&self) -> bool {
832 self.core.should_exit()
833 }
834
835 fn request_exit(&mut self) {
836 self.core.request_exit();
837 }
838
839 fn mark_dirty(&mut self) {
840 self.core.mark_dirty();
841 }
842
843 fn update_terminal_title(&mut self) {
844 self.core.update_terminal_title();
845 }
846
847 fn attach_program_status_terminal(&mut self) {
848 self.core.program_status.attach_terminal();
849 }
850
851 fn flush_program_status(&mut self) {
852 self.core.program_status.flush();
853 }
854
855 fn shutdown_program_status(&mut self) {
856 self.core.program_status.shutdown();
857 }
858
859 fn clear_terminal_title(&mut self) {
860 self.core.clear_terminal_title();
861 }
862
863 fn is_running_activity(&self) -> bool {
864 self.core.is_running_activity()
868 }
869
870 fn has_status_spinner(&self) -> bool {
871 self.core.has_status_spinner() || self.background_activity_active()
874 }
875
876 fn thinking_spinner_active(&self) -> bool {
877 self.core.thinking_spinner.is_active
878 }
879
880 fn has_active_navigation_ui(&self) -> bool {
881 self.transient_host.has_active_navigation_surface()
882 }
883
884 fn apply_coalesced_scroll(&mut self, line_delta: i32, page_delta: i32) {
885 self.core.apply_coalesced_scroll(line_delta, page_delta);
886 }
887
888 fn set_show_logs(&mut self, show: bool) {
889 self.core.show_logs = show;
890 }
891
892 fn set_active_pty_sessions(&mut self, sessions: Option<Arc<AtomicUsize>>) {
893 self.core.active_pty_sessions = sessions;
894 }
895
896 fn set_workspace_root(&mut self, root: Option<std::path::PathBuf>) {
897 self.core.set_workspace_root(root);
898 }
899
900 fn set_log_receiver(&mut self, receiver: UnboundedReceiver<crate::tui::core_tui::log::LogEntry>) {
901 self.core.set_log_receiver(receiver);
902 }
903
904 fn set_fullscreen_active(&mut self, active: bool) {
905 self.core.set_fullscreen_active(active);
906 }
907
908 fn set_fullscreen_interaction(&mut self, config: FullscreenInteractionSettings) {
909 self.core.set_fullscreen_interaction(config);
910 }
911
912 fn set_preview_callback(&mut self, callback: Option<crate::tui::core_tui::types::PreviewCallback>) {
913 self.preview_callback = callback;
914 }
915}