Skip to main content

vtcode_ui/tui/core_tui/app/session/
mod.rs

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;
22/// Diff preview overlay for file changes.
23pub(crate) mod diff_preview;
24mod events;
25/// File palette for workspace file selection.
26pub mod file_palette;
27/// Command history picker state and rendering.
28pub mod history_picker;
29mod impl_events;
30mod impl_render;
31mod layout;
32mod local_agents;
33mod palette;
34/// Session rendering logic and layout composition.
35pub(crate) mod render;
36/// Slash command detection and suggestion UI.
37pub(crate) mod slash;
38/// Slash command palette widget.
39pub mod slash_palette;
40mod task_panel;
41#[path = "transcript_review/mod.rs"]
42mod tool_output_viewer;
43mod transient;
44/// Workspace trust state management.
45pub 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    /// Session-local identifier used to keep a completed capture tied to its
65    /// corresponding transcript entry while the overlay is refreshed.
66    pub(crate) id: u64,
67    /// Index of the summary line when the capture was recorded. The review
68    /// layer uses this identity anchor without reverse-matching command text,
69    /// which is ambiguous when the same command runs more than once.
70    pub(crate) anchor_line: Option<usize>,
71    /// Number of core transcript lines present when this capture was queued.
72    /// PTY previews may use this boundary to find their already-rendered
73    /// header without searching through earlier calls.
74    pub(crate) anchor_search_start: usize,
75    /// Original transcript position for a capture that has no identity anchor.
76    /// `None` is retained for blocks constructed by older callers/tests, which
77    /// are appended as genuine orphan content.
78    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
94/// App-level session that layers VT Code features on top of the core session.
95pub 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    /// Create a new session with explicit log visibility, theme, and slash commands.
134    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    /// Create a new session with explicit log visibility, theme, slash commands, and key bindings.
176    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        // Bound session-local anchors so a long edit-heavy session cannot grow
241        // without limit; the newest notices stay available for explicit expand.
242        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        // Anchors are activation-only; recording them does not change visible
248        // transcript content, so skip mark_dirty to avoid cache invalidation
249        // on every clipped preview.
250    }
251
252    /// Open full-viewport ReadonlyReview for a completed-edit expand notice.
253    ///
254    /// Matching order:
255    /// 1. stored `notice` contained in the clicked transcript text
256    /// 2. longest specific workspace `file_path` contained in that text
257    /// 3. the sole stored anchor, when only one exists
258    ///
259    /// Refuse rather than open an arbitrary last anchor when multiple payloads
260    /// are present and the notice carries no distinctive path. Takes the
261    /// matching anchor out of the session list so unified content is moved,
262    /// not cloned.
263    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                // Visibility-only requests (show/hide) must not mutate panel body,
388                // metadata, or terminal-title progress. Content updates own those
389                // fields; typed metadata is the authoritative progress source.
390                if visible.is_none() {
391                    // Parallel statuses must align 1:1 with lines; mismatched
392                    // legacy payloads fall back to the uniform base style.
393                    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                            // Content updates without typed metadata (session
420                            // clear) must not leave stale title/progress on the
421                            // panel header or terminal title.
422                            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                    // When suppressed, the lines are retained so the manual
436                    // `toggle_task_panel` keybinding can reveal them later.
437                } 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    /// Show a help modal using the ratatui-cheese Help widget.
458    ///
459    /// The help flag travels on the request so a queued help modal still
460    /// renders as help when it activates instead of clobbering the overlay
461    /// that is currently visible.
462    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                // Auto-open is for live delegated work attention. Finished rows
564                // stay listed for history, so close the auto-opened window when
565                // nothing delegated is still loading (not when the list empties).
566                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::SetArchivedHistory { entries } => {
585                let mut input_entries = Vec::new();
586                let archived = entries
587                    .into_iter()
588                    .map(|e| {
589                        input_entries.push(
590                            crate::tui::core_tui::session::input_manager::InputHistoryEntry::from_content_and_timestamp(
591                                e.content.clone(),
592                                e.created_at,
593                            ),
594                        );
595                        history_picker::ArchivedPrompt {
596                            content: e.content,
597                            created_at: e.created_at,
598                            session_label: e.session_label,
599                        }
600                    })
601                    .collect();
602                self.history_picker_state.set_archived_prompts(archived);
603                self.core.input_manager.prepend_archived_history(input_entries);
604                self.core.mark_dirty();
605            }
606            InlineCommand::SetInput(value) => {
607                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::SetInput(value));
608                self.update_input_triggers();
609            }
610            InlineCommand::RestoreInputDraft(input) => {
611                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::RestoreInputDraft(input));
612                self.update_input_triggers();
613            }
614            InlineCommand::ApplySuggestedPrompt(value) => {
615                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ApplySuggestedPrompt(value));
616                self.update_input_triggers();
617            }
618            InlineCommand::SetInlinePromptSuggestion { suggestion, llm_generated } => {
619                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::SetInlinePromptSuggestion {
620                    suggestion,
621                    llm_generated,
622                });
623                self.update_input_triggers();
624            }
625            InlineCommand::ClearInlinePromptSuggestion => {
626                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ClearInlinePromptSuggestion);
627                self.update_input_triggers();
628            }
629            InlineCommand::ClearInput => {
630                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ClearInput);
631                self.update_input_triggers();
632            }
633            InlineCommand::RecordToolOutput { id, lines } => {
634                self.record_tool_output_block(id, lines);
635            }
636            InlineCommand::AppendToolOutputLine { id, kind, segments } => {
637                self.append_tool_output_line(id, kind, segments);
638            }
639            InlineCommand::AppendCompactActivity(metadata) => {
640                self.append_compact_activity(metadata);
641            }
642            InlineCommand::ReplaceCompactActivity(metadata) => {
643                self.replace_compact_activity(metadata);
644            }
645            InlineCommand::CollapsePtyBlock(metadata) => {
646                self.collapse_pty_block(metadata);
647            }
648            InlineCommand::SetKeyBindings { bindings } => {
649                self.core.set_bindings(BindingStore::new(bindings));
650                self.refresh_compact_activity_presentations();
651            }
652            InlineCommand::SetAppearance { appearance } => {
653                let enabling_screen_reader = appearance.screen_reader_mode && !self.core.appearance.screen_reader_mode;
654                if enabling_screen_reader && let Some(viewer) = self.tool_output_viewer_state.as_mut() {
655                    viewer.set_render_mode(tool_output_viewer::TranscriptRenderMode::Raw);
656                }
657                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::SetAppearance { appearance });
658                self.refresh_compact_activity_presentations();
659            }
660            InlineCommand::SetFullscreenInteraction { interaction } => {
661                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::SetFullscreenInteraction {
662                    interaction,
663                });
664            }
665            InlineCommand::ReplaceLast { count, kind, lines, link_ranges } => {
666                let remove_count = count.min(self.core.lines.len());
667                let first_removed = self.core.lines.len().saturating_sub(remove_count);
668                self.compact_activity_entries.retain(|entry| entry.line_index < first_removed);
669                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ReplaceLast {
670                    count,
671                    kind,
672                    lines,
673                    link_ranges,
674                });
675            }
676            InlineCommand::ClearScreen => {
677                self.tool_output_blocks.clear();
678                self.compact_activity_entries.clear();
679                self.compact_activity_hit_regions.clear();
680                self.diff_review_anchors.clear();
681                self.tool_output_revision = self.tool_output_revision.wrapping_add(1);
682                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ClearScreen);
683            }
684            InlineCommand::CloseTransient => self.close_transient(),
685            InlineCommand::ShowTransient { request } => self.show_transient(*request),
686            InlineCommand::RecordDiffReview(anchor) => self.record_diff_review(anchor),
687            InlineCommand::FocusTranscriptReview { id } => self.open_tool_output_viewer(
688                self.core.transcript_width.max(1),
689                self.core.transcript_rows.max(1),
690                Some(id),
691            ),
692            InlineCommand::UpdateFilePaletteSearch { files } => {
693                if let Some(palette) = &mut self.file_palette {
694                    palette.set_search_index(files);
695                }
696            }
697            InlineCommand::SetSlashCommands { commands } => {
698                self.slash_palette.set_commands(commands);
699            }
700            _ => {
701                if let Some(core_cmd) = to_core_command(&command) {
702                    self.handle_core_command(core_cmd);
703                }
704            }
705        }
706    }
707}
708
709fn normalize_tool_output_header(header: &str) -> String {
710    crate::tui::core_tui::session::text_utils::strip_ansi_codes(header)
711        .trim_end()
712        .to_owned()
713}
714
715fn rendered_core_line_text(core: &CoreSessionState, line_index: usize) -> String {
716    let Some(line) = core.lines.get(line_index) else {
717        return String::new();
718    };
719    core.render_message_spans_for_line(line)
720        .into_iter()
721        .map(|span| crate::tui::core_tui::session::text_utils::strip_ansi_codes(span.content.as_ref()).into_owned())
722        .collect()
723}
724
725fn folded_pty_header(core: &CoreSessionState, line_index: usize) -> String {
726    let first = rendered_core_line_text(core, line_index);
727    if !first.trim_start().starts_with('•') {
728        return first;
729    }
730
731    let mut folded = first.trim_end().to_owned();
732    let mut continuation_index = line_index + 1;
733    while let Some(line) = core.lines.get(continuation_index) {
734        if line.kind != InlineMessageKind::Pty {
735            break;
736        }
737        let continuation = rendered_core_line_text(core, continuation_index);
738        let Some(fragment) = continuation.trim_start().strip_prefix('│') else {
739            break;
740        };
741        folded.push(' ');
742        folded.push_str(fragment.trim());
743        continuation_index += 1;
744    }
745    folded
746}
747
748impl std::ops::Deref for AppSession {
749    type Target = CoreSessionState;
750
751    fn deref(&self) -> &Self::Target {
752        &self.core
753    }
754}
755
756impl std::ops::DerefMut for AppSession {
757    fn deref_mut(&mut self) -> &mut Self::Target {
758        &mut self.core
759    }
760}
761
762impl TuiSessionDriver for AppSession {
763    type Command = InlineCommand;
764    type Event = InlineEvent;
765
766    fn handle_command(&mut self, command: Self::Command) {
767        AppSession::handle_command(self, command);
768    }
769
770    fn handle_event(
771        &mut self,
772        event: CrosstermEvent,
773        events: &UnboundedSender<Self::Event>,
774        callback: Option<&(dyn Fn(&Self::Event) + Send + Sync + 'static)>,
775    ) {
776        AppSession::handle_event(self, event, events, callback);
777    }
778
779    fn handle_tick(&mut self) {
780        // Background work (managed subagents, background subprocesses, retained
781        // exec sessions) animates the same shimmer phase: `core.handle_tick`
782        // already ORs `background_status_shimmer_active` into its single update
783        // per tick, so no separate drawer-visible pass is needed here.
784        self.core.handle_tick();
785    }
786
787    fn needs_animation_tick(&self) -> bool {
788        // Core covers drag, spinner, shimmer, core background, and expiries;
789        // AppSession adds its own drawer-local background loading count, which
790        // feeds `has_status_spinner` but lives outside `core`.
791        self.core.needs_animation_tick()
792            || (self.core.appearance.should_animate_progress_status() && self.background_activity_active())
793    }
794
795    fn render(&mut self, frame: &mut Frame<'_>) {
796        AppSession::render(self, frame);
797    }
798
799    fn take_redraw(&mut self) -> bool {
800        self.core.take_redraw()
801    }
802
803    fn use_steady_cursor(&self) -> bool {
804        self.core.use_steady_cursor()
805    }
806
807    fn is_hovering_link(&self) -> bool {
808        self.core.is_hovering_link()
809    }
810
811    fn is_selecting_text(&self) -> bool {
812        self.core.is_selecting_text()
813    }
814
815    fn should_exit(&self) -> bool {
816        self.core.should_exit()
817    }
818
819    fn request_exit(&mut self) {
820        self.core.request_exit();
821    }
822
823    fn mark_dirty(&mut self) {
824        self.core.mark_dirty();
825    }
826
827    fn update_terminal_title(&mut self) {
828        self.core.update_terminal_title();
829    }
830
831    fn attach_program_status_terminal(&mut self) {
832        self.core.program_status.attach_terminal();
833    }
834
835    fn flush_program_status(&mut self) {
836        self.core.program_status.flush();
837    }
838
839    fn shutdown_program_status(&mut self) {
840        self.core.program_status.shutdown();
841    }
842
843    fn clear_terminal_title(&mut self) {
844        self.core.clear_terminal_title();
845    }
846
847    fn is_running_activity(&self) -> bool {
848        // Turn-scoped only. Background tasks and drawer previews are
849        // asynchronous, so they must not lock mode switches, block slash
850        // commands, or convert plain submissions into queued input.
851        self.core.is_running_activity()
852    }
853
854    fn has_status_spinner(&self) -> bool {
855        // Drives the animation tick rate and the drawer row shimmer, so it
856        // includes background activity even when the drawer is closed.
857        self.core.has_status_spinner() || self.background_activity_active()
858    }
859
860    fn thinking_spinner_active(&self) -> bool {
861        self.core.thinking_spinner.is_active
862    }
863
864    fn has_active_navigation_ui(&self) -> bool {
865        self.transient_host.has_active_navigation_surface()
866    }
867
868    fn apply_coalesced_scroll(&mut self, line_delta: i32, page_delta: i32) {
869        self.core.apply_coalesced_scroll(line_delta, page_delta);
870    }
871
872    fn set_show_logs(&mut self, show: bool) {
873        self.core.show_logs = show;
874    }
875
876    fn set_active_pty_sessions(&mut self, sessions: Option<Arc<AtomicUsize>>) {
877        self.core.active_pty_sessions = sessions;
878    }
879
880    fn set_workspace_root(&mut self, root: Option<std::path::PathBuf>) {
881        self.core.set_workspace_root(root);
882    }
883
884    fn set_log_receiver(&mut self, receiver: UnboundedReceiver<crate::tui::core_tui::log::LogEntry>) {
885        self.core.set_log_receiver(receiver);
886    }
887
888    fn set_fullscreen_active(&mut self, active: bool) {
889        self.core.set_fullscreen_active(active);
890    }
891
892    fn set_fullscreen_interaction(&mut self, config: FullscreenInteractionSettings) {
893        self.core.set_fullscreen_interaction(config);
894    }
895
896    fn set_preview_callback(&mut self, callback: Option<crate::tui::core_tui::types::PreviewCallback>) {
897        self.preview_callback = callback;
898    }
899}