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                let is_help = request.is_help_modal;
335                let overlay = crate::tui::core_tui::types::OverlayRequest::Modal(request.into());
336                // Help is informational with no caller waiting on a typed
337                // response. Keep it queued behind the active overlay so it
338                // cannot replace a blocking prompt and strand that caller.
339                if is_help {
340                    self.core.show_overlay(overlay);
341                } else {
342                    self.core.show_blocking_overlay(overlay);
343                }
344                self.show_transient_surface(TransientSurface::FloatingOverlay);
345            }
346            TransientRequest::List(request) => {
347                self.core
348                    .show_blocking_overlay(crate::tui::core_tui::types::OverlayRequest::List(request.into()));
349                self.show_transient_surface(TransientSurface::FloatingOverlay);
350            }
351            TransientRequest::Wizard(request) => {
352                self.core
353                    .show_blocking_overlay(crate::tui::core_tui::types::OverlayRequest::Wizard(request.into()));
354                self.show_transient_surface(TransientSurface::FloatingOverlay);
355            }
356            TransientRequest::Diff(request) => {
357                self.show_diff_overlay(request);
358            }
359            TransientRequest::FilePalette(request) => {
360                self.load_file_palette(request.dir_lister, request.workspace);
361                match request.visible {
362                    Some(true) => {
363                        self.ensure_inline_lists_visible_for_trigger();
364                        self.file_palette_active = true;
365                        self.show_transient_surface(TransientSurface::FilePalette);
366                    }
367                    Some(false) => {
368                        self.close_file_palette();
369                    }
370                    None => {}
371                }
372            }
373            TransientRequest::AgentPalette(request) => {
374                self.load_agent_palette(request.agents);
375                match request.visible {
376                    Some(true) => {
377                        self.ensure_inline_lists_visible_for_trigger();
378                        self.agent_palette_active = true;
379                        self.show_transient_surface(TransientSurface::AgentPalette);
380                    }
381                    Some(false) => {
382                        self.close_agent_palette();
383                    }
384                    None => {}
385                }
386            }
387            TransientRequest::HistoryPicker => {
388                events::open_history_picker(self);
389            }
390            TransientRequest::SlashPalette => {
391                self.ensure_inline_lists_visible_for_trigger();
392                self.show_transient_surface(TransientSurface::SlashPalette);
393            }
394            TransientRequest::TaskPanel(TaskPanelTransientRequest { lines, statuses, current, visible, metadata }) => {
395                // Visibility-only requests (show/hide) must not mutate panel body,
396                // metadata, or terminal-title progress. Content updates own those
397                // fields; typed metadata is the authoritative progress source.
398                if visible.is_none() {
399                    // Parallel statuses must align 1:1 with lines; mismatched
400                    // legacy payloads fall back to the uniform base style.
401                    let aligned = statuses.len() == lines.len();
402                    self.task_panel_statuses = if aligned { statuses } else { Vec::new() };
403                    self.task_panel_current =
404                        (aligned.then_some(current).flatten()).filter(|index| *index < lines.len());
405                    self.task_panel_lines = lines;
406                    self.core.mark_task_panel_content_dirty();
407                    match metadata {
408                        Some(metadata) => {
409                            self.core.set_task_panel_progress_label(Some(format!(
410                                "{}/{}",
411                                metadata.completed, metadata.total
412                            )));
413                            let percent = if metadata.total == 0 {
414                                None
415                            } else {
416                                let completed = metadata.completed.min(metadata.total) as u64;
417                                let total = metadata.total as u64;
418                                let percent = completed.saturating_mul(100) / total.max(1);
419                                Some(u8::try_from(percent.min(100)).unwrap_or(100))
420                            };
421                            self.core
422                                .program_status
423                                .apply(vtcode_commons::program_status::ProgramStatusUpdate::Progress { percent });
424                            self.task_panel_metadata = Some(metadata);
425                        }
426                        None => {
427                            // Content updates without typed metadata (session
428                            // clear) must not leave stale title/progress on the
429                            // panel header or terminal title.
430                            self.task_panel_metadata = None;
431                            self.core.set_task_panel_progress_label(None);
432                            self.core
433                                .program_status
434                                .apply(vtcode_commons::program_status::ProgramStatusUpdate::Progress { percent: None });
435                        }
436                    }
437                }
438                if let Some(visible) = visible {
439                    let suppressed = visible && !self.core.appearance.should_show_task_panel();
440                    if !suppressed {
441                        self.set_task_panel_visible(visible);
442                    }
443                    // When suppressed, the lines are retained so the manual
444                    // `toggle_task_panel` keybinding can reveal them later.
445                } else {
446                    self.core.mark_dirty();
447                }
448            }
449            TransientRequest::LocalAgents(LocalAgentsTransientRequest { visible }) => {
450                if let Some(visible) = visible {
451                    if visible {
452                        self.ensure_inline_lists_visible_for_trigger();
453                        self.open_local_agents_drawer(false);
454                    } else {
455                        self.close_local_agents_drawer(true);
456                    }
457                } else {
458                    self.core.mark_dirty();
459                }
460            }
461        }
462        self.core.mark_dirty();
463    }
464
465    /// Show a help modal using the ratatui-cheese Help widget.
466    ///
467    /// The help flag travels on the request so a queued help modal still
468    /// renders as help when it activates instead of clobbering the overlay
469    /// that is currently visible.
470    fn show_help_modal(&mut self) {
471        self.show_transient(TransientRequest::Modal(crate::tui::core_tui::app::types::ModalOverlayRequest {
472            title: "Keyboard Shortcuts".to_string(),
473            lines: Vec::new(),
474            secure_prompt: None,
475            is_help_modal: true,
476        }));
477    }
478
479    fn should_auto_open_local_agents(&self) -> bool {
480        if self.has_active_overlay() {
481            return false;
482        }
483
484        matches!(
485            self.visible_transient_surface(),
486            None | Some(TransientSurface::TaskPanel | TransientSurface::LocalAgents)
487        )
488    }
489
490    pub(crate) fn close_transient(&mut self) {
491        match self.visible_transient_surface() {
492            Some(TransientSurface::FloatingOverlay) => self.close_overlay(),
493            Some(TransientSurface::DiffPreview) => self.close_diff_overlay(),
494            Some(TransientSurface::ToolOutputViewer) => self.close_tool_output_viewer(),
495            Some(TransientSurface::HistoryPicker) => self.close_history_picker(),
496            Some(TransientSurface::AgentPalette) => self.close_agent_palette(),
497            Some(TransientSurface::FilePalette) => self.close_file_palette(),
498            Some(TransientSurface::SlashPalette) => slash::clear_slash_suggestions(self),
499            Some(TransientSurface::TaskPanel) => self.set_task_panel_visible(false),
500            Some(TransientSurface::LocalAgents) => {
501                self.close_local_agents_drawer(true);
502            }
503            None => {}
504        }
505    }
506
507    fn open_local_agents_drawer(&mut self, auto_opened: bool) {
508        self.local_agents_auto_opened = auto_opened;
509        self.show_transient_surface(TransientSurface::LocalAgents);
510    }
511
512    fn close_local_agents_drawer(&mut self, clear_auto_opened: bool) {
513        if clear_auto_opened {
514            self.local_agents_auto_opened = false;
515        }
516        self.close_transient_surface(TransientSurface::LocalAgents);
517    }
518
519    fn sync_transient_focus(&mut self) {
520        if self.core.activity_state.is_busy() {
521            self.core.set_input_enabled(false);
522            self.core.set_cursor_visible(false);
523            return;
524        }
525        let Some(surface) = self.visible_transient_surface() else {
526            self.core.set_input_enabled(true);
527            self.core.set_cursor_visible(true);
528            return;
529        };
530
531        match surface.focus_policy() {
532            TransientFocusPolicy::Modal | TransientFocusPolicy::CapturedInput => {
533                self.core.set_input_enabled(false);
534                self.core.set_cursor_visible(false);
535            }
536            TransientFocusPolicy::SharedInput | TransientFocusPolicy::Passive => {
537                self.core.set_input_enabled(true);
538                self.core.set_cursor_visible(true);
539            }
540        }
541    }
542
543    pub(super) fn sync_transient_activity_signal(&self) {
544        let Some(signal) = self.transient_active_signal.as_ref() else {
545            return;
546        };
547        let active = self
548            .visible_transient_surface()
549            .is_some_and(|surface| !matches!(surface, TransientSurface::TaskPanel));
550        signal.set_active(active);
551    }
552
553    pub(super) fn apply_transient_visibility_change(&mut self, change: TransientVisibilityChange) {
554        if matches!(change.previous_visible, Some(TransientSurface::FilePalette | TransientSurface::AgentPalette))
555            || matches!(change.current_visible, Some(TransientSurface::FilePalette | TransientSurface::AgentPalette))
556        {
557            self.core.request_full_clear();
558        }
559        self.core
560            .set_local_agents_drawer_visible(change.current_visible == Some(TransientSurface::LocalAgents));
561        self.sync_transient_focus();
562        self.sync_transient_activity_signal();
563    }
564
565    pub fn handle_command(&mut self, command: InlineCommand) {
566        match command {
567            InlineCommand::SetLocalAgents { entries } => {
568                let has_delegated_entries = entries
569                    .iter()
570                    .any(|entry| entry.kind == crate::tui::core_tui::types::LocalAgentKind::Delegated);
571                // Auto-open is for live delegated work attention. Finished rows
572                // stay listed for history, so close the auto-opened window when
573                // nothing delegated is still loading (not when the list empties).
574                let has_live_delegated = entries.iter().any(|entry| {
575                    entry.kind == crate::tui::core_tui::types::LocalAgentKind::Delegated && entry.is_loading()
576                });
577                let update = self.local_agents_state.set_entries(entries.clone());
578                let background_count = self.local_agents_state.loading_count();
579                let finished_count = self.local_agents_state.finished_count();
580                self.core.set_local_agents(entries);
581                self.core.set_background_activity_count(background_count);
582                self.core.set_background_finished_count(finished_count);
583                if update.has_new_delegated_entries && self.should_auto_open_local_agents() {
584                    self.ensure_inline_lists_visible_for_trigger();
585                    self.open_local_agents_drawer(true);
586                } else if self.local_agents_auto_opened && !has_live_delegated {
587                    self.close_local_agents_drawer(true);
588                } else if !self.local_agents_visible() && !has_delegated_entries {
589                    self.local_agents_auto_opened = false;
590                }
591            }
592            InlineCommand::SetActivePlan { entry } => {
593                self.core.set_active_plan(entry);
594            }
595            InlineCommand::SetArchivedHistory { entries } => {
596                let mut input_entries = Vec::new();
597                let archived = entries
598                    .into_iter()
599                    .map(|e| {
600                        input_entries.push(
601                            crate::tui::core_tui::session::input_manager::InputHistoryEntry::from_content_and_timestamp(
602                                e.content.clone(),
603                                e.created_at,
604                            ),
605                        );
606                        history_picker::ArchivedPrompt {
607                            content: e.content,
608                            created_at: e.created_at,
609                            session_label: e.session_label,
610                            in_workspace: e.in_workspace,
611                        }
612                    })
613                    .collect();
614                self.history_picker_state.set_archived_prompts(archived);
615                self.core.input_manager.prepend_archived_history(input_entries);
616                self.core.mark_dirty();
617            }
618            InlineCommand::SetInput(value) => {
619                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::SetInput(value));
620                self.update_input_triggers();
621            }
622            InlineCommand::RestoreInputDraft(input) => {
623                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::RestoreInputDraft(input));
624                self.update_input_triggers();
625            }
626            InlineCommand::ApplySuggestedPrompt(value) => {
627                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ApplySuggestedPrompt(value));
628                self.update_input_triggers();
629            }
630            InlineCommand::SetInlinePromptSuggestion { suggestion, llm_generated } => {
631                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::SetInlinePromptSuggestion {
632                    suggestion,
633                    llm_generated,
634                });
635                self.update_input_triggers();
636            }
637            InlineCommand::ClearInlinePromptSuggestion => {
638                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ClearInlinePromptSuggestion);
639                self.update_input_triggers();
640            }
641            InlineCommand::ClearInput => {
642                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ClearInput);
643                self.update_input_triggers();
644            }
645            InlineCommand::RecordToolOutput { id, lines } => {
646                self.record_tool_output_block(id, lines);
647            }
648            InlineCommand::AppendToolOutputLine { id, kind, segments } => {
649                self.append_tool_output_line(id, kind, segments);
650            }
651            InlineCommand::AppendCompactActivity(metadata) => {
652                self.append_compact_activity(metadata);
653            }
654            InlineCommand::ReplaceCompactActivity(metadata) => {
655                self.replace_compact_activity(metadata);
656            }
657            InlineCommand::CollapsePtyBlock(metadata) => {
658                self.collapse_pty_block(metadata);
659            }
660            InlineCommand::SetKeyBindings { bindings } => {
661                self.core.set_bindings(BindingStore::new(bindings));
662                self.refresh_compact_activity_presentations();
663            }
664            InlineCommand::SetAppearance { appearance } => {
665                let enabling_screen_reader = appearance.screen_reader_mode && !self.core.appearance.screen_reader_mode;
666                if enabling_screen_reader && let Some(viewer) = self.tool_output_viewer_state.as_mut() {
667                    viewer.set_render_mode(tool_output_viewer::TranscriptRenderMode::Raw);
668                }
669                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::SetAppearance { appearance });
670                self.refresh_compact_activity_presentations();
671            }
672            InlineCommand::SetFullscreenInteraction { interaction } => {
673                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::SetFullscreenInteraction {
674                    interaction,
675                });
676            }
677            InlineCommand::ReplaceLast { count, kind, lines, link_ranges } => {
678                let remove_count = count.min(self.core.lines.len());
679                let first_removed = self.core.lines.len().saturating_sub(remove_count);
680                self.compact_activity_entries.retain(|entry| entry.line_index < first_removed);
681                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ReplaceLast {
682                    count,
683                    kind,
684                    lines,
685                    link_ranges,
686                });
687            }
688            InlineCommand::ClearScreen => {
689                self.tool_output_blocks.clear();
690                self.compact_activity_entries.clear();
691                self.compact_activity_hit_regions.clear();
692                self.diff_review_anchors.clear();
693                self.tool_output_revision = self.tool_output_revision.wrapping_add(1);
694                self.handle_core_command(crate::tui::core_tui::types::InlineCommand::ClearScreen);
695            }
696            InlineCommand::CloseTransient => self.close_transient(),
697            InlineCommand::ShowTransient { request } => self.show_transient(*request),
698            InlineCommand::RecordDiffReview(anchor) => self.record_diff_review(anchor),
699            InlineCommand::FocusTranscriptReview { id } => self.open_tool_output_viewer(
700                self.core.transcript_width.max(1),
701                self.core.transcript_rows.max(1),
702                Some(id),
703            ),
704            InlineCommand::UpdateFilePaletteSearch { files } => {
705                if let Some(palette) = &mut self.file_palette {
706                    palette.set_search_index(files);
707                }
708            }
709            InlineCommand::SetSlashCommands { commands } => {
710                self.slash_palette.set_commands(commands);
711            }
712            _ => {
713                if let Some(core_cmd) = to_core_command(&command) {
714                    self.handle_core_command(core_cmd);
715                }
716            }
717        }
718    }
719}
720
721fn normalize_tool_output_header(header: &str) -> String {
722    crate::tui::core_tui::session::text_utils::strip_ansi_codes(header)
723        .trim_end()
724        .to_owned()
725}
726
727fn rendered_core_line_text(core: &CoreSessionState, line_index: usize) -> String {
728    let Some(line) = core.lines.get(line_index) else {
729        return String::new();
730    };
731    core.render_message_spans_for_line(line)
732        .into_iter()
733        .map(|span| crate::tui::core_tui::session::text_utils::strip_ansi_codes(span.content.as_ref()).into_owned())
734        .collect()
735}
736
737fn folded_pty_header(core: &CoreSessionState, line_index: usize) -> String {
738    let first = rendered_core_line_text(core, line_index);
739    if !first.trim_start().starts_with('•') {
740        return first;
741    }
742
743    let mut folded = first.trim_end().to_owned();
744    let mut continuation_index = line_index + 1;
745    while let Some(line) = core.lines.get(continuation_index) {
746        if line.kind != InlineMessageKind::Pty {
747            break;
748        }
749        let continuation = rendered_core_line_text(core, continuation_index);
750        let Some(fragment) = continuation.trim_start().strip_prefix('│') else {
751            break;
752        };
753        folded.push(' ');
754        folded.push_str(fragment.trim());
755        continuation_index += 1;
756    }
757    folded
758}
759
760impl std::ops::Deref for AppSession {
761    type Target = CoreSessionState;
762
763    fn deref(&self) -> &Self::Target {
764        &self.core
765    }
766}
767
768impl std::ops::DerefMut for AppSession {
769    fn deref_mut(&mut self) -> &mut Self::Target {
770        &mut self.core
771    }
772}
773
774impl TuiSessionDriver for AppSession {
775    type Command = InlineCommand;
776    type Event = InlineEvent;
777
778    fn handle_command(&mut self, command: Self::Command) {
779        AppSession::handle_command(self, command);
780    }
781
782    fn handle_event(
783        &mut self,
784        event: CrosstermEvent,
785        events: &UnboundedSender<Self::Event>,
786        callback: Option<&(dyn Fn(&Self::Event) + Send + Sync + 'static)>,
787    ) {
788        AppSession::handle_event(self, event, events, callback);
789    }
790
791    fn handle_tick(&mut self) {
792        // Background work (managed subagents, background subprocesses, retained
793        // exec sessions) animates the same shimmer phase: `core.handle_tick`
794        // already ORs `background_status_shimmer_active` into its single update
795        // per tick, so no separate drawer-visible pass is needed here.
796        self.core.handle_tick();
797    }
798
799    fn needs_animation_tick(&self) -> bool {
800        // Hidden terminal view: no frame can be observed, so never extend
801        // active-rate ticking (mirrors the core gate; AppSession's own
802        // drawer/viewer terms must not bypass it).
803        if !self.core.is_terminal_visible() {
804            return false;
805        }
806        // Core covers drag, spinner, shimmer, core background, and expiries;
807        // AppSession adds its own drawer-local background loading count, which
808        // feeds `has_status_spinner` but lives outside `core`, plus the
809        // review-viewer landing tint, whose refresh clears it on the tick.
810        self.core.needs_animation_tick()
811            || (self.core.appearance.should_animate_progress_status() && self.background_activity_active())
812            || self.tool_output_viewer_state.as_ref().is_some_and(|viewer| viewer.flash_live())
813    }
814
815    fn render(&mut self, frame: &mut Frame<'_>) {
816        AppSession::render(self, frame);
817    }
818
819    fn take_redraw(&mut self) -> bool {
820        self.core.take_redraw()
821    }
822
823    fn is_terminal_visible(&self) -> bool {
824        self.core.is_terminal_visible()
825    }
826
827    fn use_steady_cursor(&self) -> bool {
828        self.core.use_steady_cursor()
829    }
830
831    fn is_hovering_link(&self) -> bool {
832        self.core.is_hovering_link()
833    }
834
835    fn is_selecting_text(&self) -> bool {
836        self.core.is_selecting_text()
837    }
838
839    fn should_exit(&self) -> bool {
840        self.core.should_exit()
841    }
842
843    fn request_exit(&mut self) {
844        self.core.request_exit();
845    }
846
847    fn mark_dirty(&mut self) {
848        self.core.mark_dirty();
849    }
850
851    fn update_terminal_title(&mut self) {
852        self.core.update_terminal_title();
853    }
854
855    fn attach_program_status_terminal(&mut self) {
856        self.core.program_status.attach_terminal();
857    }
858
859    fn flush_program_status(&mut self) {
860        self.core.program_status.flush();
861    }
862
863    fn shutdown_program_status(&mut self) {
864        self.core.program_status.shutdown();
865    }
866
867    fn clear_terminal_title(&mut self) {
868        self.core.clear_terminal_title();
869    }
870
871    fn is_running_activity(&self) -> bool {
872        // Turn-scoped only. Background tasks and drawer previews are
873        // asynchronous, so they must not lock mode switches, block slash
874        // commands, or convert plain submissions into queued input.
875        self.core.is_running_activity()
876    }
877
878    fn has_status_spinner(&self) -> bool {
879        // Drives the animation tick rate and the drawer row shimmer, so it
880        // includes background activity even when the drawer is closed.
881        self.core.has_status_spinner() || self.background_activity_active()
882    }
883
884    fn thinking_spinner_active(&self) -> bool {
885        self.core.thinking_spinner.is_active
886    }
887
888    fn has_active_navigation_ui(&self) -> bool {
889        self.transient_host.has_active_navigation_surface()
890    }
891
892    fn apply_coalesced_scroll(&mut self, line_delta: i32, page_delta: i32) {
893        self.core.apply_coalesced_scroll(line_delta, page_delta);
894    }
895
896    fn set_show_logs(&mut self, show: bool) {
897        self.core.show_logs = show;
898    }
899
900    fn set_active_pty_sessions(&mut self, sessions: Option<Arc<AtomicUsize>>) {
901        self.core.active_pty_sessions = sessions;
902    }
903
904    fn set_workspace_root(&mut self, root: Option<std::path::PathBuf>) {
905        self.core.set_workspace_root(root);
906    }
907
908    fn set_log_receiver(&mut self, receiver: tokio::sync::mpsc::Receiver<crate::tui::core_tui::log::LogEntry>) {
909        self.core.set_log_receiver(receiver);
910    }
911
912    fn set_fullscreen_active(&mut self, active: bool) {
913        self.core.set_fullscreen_active(active);
914    }
915
916    fn set_fullscreen_interaction(&mut self, config: FullscreenInteractionSettings) {
917        self.core.set_fullscreen_interaction(config);
918    }
919
920    fn set_preview_callback(&mut self, callback: Option<crate::tui::core_tui::types::PreviewCallback>) {
921        self.preview_callback = callback;
922    }
923}