par-term 0.48.0

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
//! egui frame rendering for the GPU submit pipeline.
//!
//! `render_egui_frame` runs all egui dialogs and overlay panels for the current
//! frame (phase 3 of the render cycle). It is split from `gpu_submit.rs` to keep
//! that module within the 500-line target while grouping the egui-specific logic
//! in one place.

use super::egui_overlays;
use super::plugin_overlay_render;
use super::types::PostRenderActions;
use crate::app::window_state::WindowState;
use crate::badge::{BadgeInsets, render_badge};
use crate::progress_bar::{ProgressBarSnapshot, render_progress_bars};

/// Parameters for [`WindowState::render_egui_frame`], bundled to stay within
/// the clippy `too_many_arguments` limit.
pub(super) struct RenderEguiParams<'a> {
    pub(super) actions: &'a mut PostRenderActions,
    pub(super) hovered_mark: &'a Option<crate::config::ScrollbackMark>,
    pub(super) window_size_for_badge: Option<&'a winit::dpi::PhysicalSize<u32>>,
    pub(super) progress_snapshot: &'a Option<ProgressBarSnapshot>,
    pub(super) visible_lines: usize,
    pub(super) scrollback_len: usize,
    pub(super) any_modal_visible: bool,
    pub(super) show_scrollbar: bool,
}

impl WindowState {
    /// Run all egui dialogs and overlay panels for the current frame (phase 3).
    ///
    /// Takes pre-captured state values and updates `actions` with deferred UI responses.
    /// Returns the egui output (`FullOutput` + `Context`) needed by the wgpu render call,
    /// or `None` if the egui context/window is not yet initialised for this window.
    pub(super) fn render_egui_frame(
        &mut self,
        params: RenderEguiParams<'_>,
    ) -> Option<(egui::FullOutput, egui::Context)> {
        let RenderEguiParams {
            actions,
            hovered_mark,
            window_size_for_badge,
            progress_snapshot,
            visible_lines,
            scrollback_len,
            any_modal_visible,
            show_scrollbar,
        } = params;
        let egui_start = std::time::Instant::now();

        // Capture values for FPS overlay before closure
        let show_fps = self.debug.show_fps_overlay;
        let fps_value = self.debug.fps_value;
        let frame_time_ms = if !self.debug.frame_times.is_empty() {
            let avg = self.debug.frame_times.iter().sum::<std::time::Duration>()
                / self.debug.frame_times.len() as u32;
            avg.as_secs_f64() * 1000.0
        } else {
            0.0
        };

        // Profile variables follow the active tab even with badges off (the
        // Profile widget reads them); the badge itself is per-tab (B60).
        self.sync_tab_profile_variable();
        let badge_state = self.badge_state.enabled.then(|| self.frame_badge());

        // Agent-usage upkeep runs every frame regardless of the status bar's
        // visibility — the popup panel opens by its own action and reads the
        // same store.
        self.status_bar_ui.update_agent_usage(&self.config.load());

        // Plugin upkeep runs every frame regardless of the status bar's
        // visibility — plugin output must keep flowing while the bar is
        // hidden (same rule as agent usage above).
        self.status_bar_ui.update_plugins(&self.config.load());

        // A plugin whose supervisor gave up (crash-loop past the restart
        // cap) is a triage offer, same consent surface as a crashed pane.
        for cap in self.status_bar_ui.drain_plugin_crash_caps() {
            let label = self
                .crash_triage
                .record_plugin_crash_cap(&cap)
                .map(|offer| offer.label.clone());
            if let Some(label) = label {
                self.show_toast(format!(
                    "Crash captured ({label}) — Triage in the command palette"
                ));
            }
        }

        // Capture session variables for status bar rendering (skip if bar is hidden)
        let status_bar_session_vars = if self.config.load().status_bar.status_bar_enabled
            && !self
                .status_bar_ui
                .should_hide(&self.config.load(), self.is_fullscreen)
        {
            Some(self.badge_state.variables.read().clone())
        } else {
            None
        };

        // Refresh the agent-roster widget lines from the mux roster cache
        // (A2b task 2) before the egui closure uniquely borrows `*self`.
        // Without the mux feature there is no cache and no widget content —
        // the widget self-hides.
        #[cfg(feature = "mux")]
        {
            let tmux_state = &self.tmux_state;
            let roster = &tmux_state.agent_roster;
            // Scope the widget to the attached session: a mapped pane is by
            // construction one of this session's panes, so other sessions'
            // agents and closed-but-unreconciled panes never render.
            let visible =
                |pane: par_term_tmux::TmuxPaneId| tmux_state.tmux_pane_owners.contains_key(&pane);
            self.status_bar_ui.agent_roster_summary = roster.summary_line(&visible);
            self.status_bar_ui.agent_roster_tooltip = roster.tooltip_text(&visible);
        }
        #[cfg(not(feature = "mux"))]
        {
            self.status_bar_ui.agent_roster_summary = None;
            self.status_bar_ui.agent_roster_tooltip = None;
        }
        // Tab/pane agent badges and the session chip (UX.md V1-V3), from
        // the same roster cache.
        #[cfg(feature = "mux")]
        self.refresh_tab_mux_views();
        #[cfg(feature = "mux")]
        let session_chip = self.session_chip();
        #[cfg(not(feature = "mux"))]
        let session_chip = crate::session_chip::SessionChip::default();

        // Broadcast status-bar item (V5): the active tab's receivers while
        // broadcast is on.
        self.status_bar_ui.broadcast_receivers = self.broadcast_status_item();

        // Capture values for badge insets (before egui borrow to avoid method-call borrows)
        let badge_is_tmux = self.is_tmux_connected();
        let badge_tmux_sb_height =
            crate::tmux_status_bar_ui::TmuxStatusBarUI::height(&self.config.load(), badge_is_tmux);
        let badge_custom_sb_height = self
            .status_bar_ui
            .height(&self.config.load(), self.is_fullscreen);

        // Resolve the confirmation dialog's target tab now, for the same borrow
        // reason as the move-tab values below: the dialog takes `&mut
        // self.trigger_state` and the lookup reads `self.tab_manager`. Resolving
        // per frame rather than at queue time keeps the named tab current.
        let pending_action_target_note = self.pending_action_target_note();

        // Capture move-tab context values BEFORE the egui closure so the
        // `self.is_gateway_active()` method call (which borrows `&self`) does
        // not conflict with the closure's unique borrow of `*self`.
        let move_gateway_active = self.is_gateway_active();
        let move_tab_count = self.tab_manager.tab_count();
        let move_candidates = self.overlay_ui.move_tab_candidates.clone();
        let context_tab_has_multiple_panes = self
            .tab_bar_ui
            .context_menu_tab_id()
            .and_then(|tid| self.tab_manager.get_tab(tid))
            .is_some_and(|tab: &crate::tab::Tab| tab.has_multiple_panes());
        #[cfg(feature = "mux")]
        let context_demote_refusal = self
            .tab_bar_ui
            .context_menu_tab_id()
            .and_then(|tid| self.mux_demote_refusal(tid, None));
        #[cfg(not(feature = "mux"))]
        let context_demote_refusal = None;

        // Collect pane bounds for identify overlay (before egui borrow)
        let pane_identify_bounds: Vec<(usize, crate::pane::PaneBounds)> =
            if self.overlay_state.pane_identify_hide_time.is_some() {
                self.tab_manager
                    .active_tab()
                    .and_then(|tab| tab.pane_manager())
                    .map(|pm| {
                        // Tree-order index, drawn only on the visible panes:
                        // a zoomed pane keeps the number it has unzoomed.
                        let zoomed = pm.zoomed_pane_id();
                        pm.all_panes()
                            .iter()
                            .enumerate()
                            .filter(|(_, pane)| zoomed.is_none_or(|z| z == pane.id))
                            .map(|(i, pane)| (i, pane.bounds))
                            .collect()
                    })
                    .unwrap_or_default()
            } else {
                Vec::new()
            };

        // Broadcast receiver outlines (V5), resolved before the egui borrow.
        let broadcast_outlines: Vec<crate::pane::PaneBounds> = self
            .tab_manager
            .active_tab()
            .map(|tab| tab.broadcast_outline_bounds())
            .unwrap_or_default();

        // Live plugin overlays (overlay kind), cloned before the egui
        // borrow — plugin id + last upserted scene each — plus the focused
        // overlay's plugin id for the interactive renderer.
        let plugin_overlays: Vec<(String, par_term_scripting::protocol::PluginOverlay)> = self
            .status_bar_ui
            .plugin_host()
            .overlays()
            .iter()
            .map(|(id, overlay)| (id.clone(), overlay.clone()))
            .collect();
        let focused_overlay_plugin = self
            .status_bar_ui
            .plugin_host()
            .focused_overlay()
            .map(str::to_string);
        // Widget interactions collected inside the closure; applied after it
        // through PostRenderActions (the closure cannot run host code).
        let mut overlay_interactions: Vec<super::plugin_overlay_ui::OverlayInteraction> =
            Vec::new();

        // Pane-hint selection badges (before egui borrow). Letter → pane-id
        // assignments are captured at arm time; bounds resolve live each frame
        // so the badges track resize/split changes while the mode is armed.
        let pane_hint_badges: Vec<egui_overlays::PaneHintBadge> =
            if let crate::app::pane_hint_select::PaneHintSelectState::Selecting {
                assignments,
                typed,
                ..
            } = &self.pane_hint_select
            {
                let badges = self
                    .tab_manager
                    .active_tab()
                    .and_then(|tab| tab.pane_manager())
                    .map(|pm| {
                        let all = pm.all_panes();
                        // After the first of two letters, only the labels
                        // it starts stay on screen.
                        assignments
                            .iter()
                            .filter(|(label, _)| label.starts_with(typed.as_str()))
                            .filter_map(|(label, pane_id)| {
                                let pane = all.iter().find(|p| p.id == *pane_id)?;
                                Some(egui_overlays::PaneHintBadge {
                                    label: label.clone(),
                                    bounds: pane.bounds,
                                })
                            })
                            .collect()
                    })
                    .unwrap_or_default();
                // Badges resolve from live pane state each frame: a layout
                // change that removed assigned panes simply drops their badges.
                badges
            } else {
                Vec::new()
            };

        // Capture demote state snapshot for overlay rendering inside the egui closure.
        // This must happen before the closure borrows `*self`.
        let demote_snapshot: super::types::DemoteSnapshot = match &self.pane_transfer_state {
            super::super::tab_ops::pane_transfer::PaneTransferState::Idle => {
                super::types::DemoteSnapshot::Idle
            }
            super::super::tab_ops::pane_transfer::PaneTransferState::DemotePickTab { .. } => {
                super::types::DemoteSnapshot::PickTab
            }
            super::super::tab_ops::pane_transfer::PaneTransferState::DemotePickPane { .. } => {
                super::types::DemoteSnapshot::PickPane
            }
            super::super::tab_ops::pane_transfer::PaneTransferState::DemoteChooseDirection {
                source_tab_id,
                target_tab_id,
                target_pane_id,
            } => super::types::DemoteSnapshot::ChooseDirection {
                source_tab_id: *source_tab_id,
                target_tab_id: *target_tab_id,
                target_pane_id: *target_pane_id,
            },
        };

        // Capture pane bounds for the demote direction overlay (if applicable)
        let demote_pane_bounds: Option<crate::pane::PaneBounds> = match demote_snapshot {
            super::types::DemoteSnapshot::ChooseDirection {
                target_tab_id,
                target_pane_id,
                ..
            } => self
                .tab_manager
                .get_tab(target_tab_id)
                .and_then(|t| t.pane_manager())
                .and_then(|pm| pm.get_pane(target_pane_id))
                .map(|p| p.bounds),
            _ => None,
        };

        // Pane-rename submit collected inside the egui closure below; the
        // egui state borrow spans the closure, so the rename itself runs
        // after the block ends.
        let mut pane_rename_submit: Option<(crate::pane::PaneId, String)> = None;
        // Set when the palette opens inside the closure; the directory
        // refresh needs `&mut self`, so it runs after the closure.
        let mut refresh_mux_directory = false;
        let pane_hint_banner = self.pane_hint_banner();
        // Toasts stack below the tab bar when it sits at the top (MD4).
        let toast_top_inset = match self.config.load().tabs.tab_bar_position {
            par_term_config::TabBarPosition::Top => self
                .tab_bar_ui
                .get_height(self.tab_manager.visible_tab_count(), &self.config.load()),
            _ => 0.0,
        };

        // IME preedit overlay inputs, captured before the egui closure: the
        // composing text and the focused cursor's rect in logical points.
        let ime_preedit = self.overlay_state.ime_preedit.clone();
        let ime_cursor_logical = self.focused_cursor_pixel_rect().map(|(x, y, w, h)| {
            let scale = self
                .window
                .as_ref()
                .map(|w| w.scale_factor() as f32)
                .unwrap_or(1.0);
            (
                x as f32 / scale,
                y as f32 / scale,
                w as f32 / scale,
                h as f32 / scale,
            )
        });

        // par-mux held panes (`%pane-exited`) in the active tab: the
        // exited banner's geometry, captured before the egui borrow; a
        // Restart click is applied after the closure.
        #[cfg(feature = "mux")]
        let exited_pane_banners = super::exited_pane_overlay::gather_exited_pane_banners(
            &self.tmux_state,
            self.tab_manager.active_tab(),
            self.window
                .as_ref()
                .map(|w| w.scale_factor() as f32)
                .unwrap_or(1.0),
        );
        #[cfg(feature = "mux")]
        let mut exited_pane_restart: Option<par_term_tmux::TmuxPaneId> = None;

        let result = if let Some(window) = self.window.as_ref() {
            if let (Some(egui_ctx), Some(egui_state)) = (&self.egui.ctx, &mut self.egui.state) {
                let mut raw_input = egui_state.take_egui_input(window);

                // Inject pending events from menu accelerators (Cmd+V/C/A intercepted by muda)
                raw_input.events.append(&mut self.egui.pending_events);

                // When no modal UI overlay is visible, filter out Tab key events to prevent
                // egui's default focus navigation from stealing Tab/Shift+Tab from the terminal.
                if !any_modal_visible {
                    raw_input.events.retain(|e| {
                        !matches!(
                            e,
                            egui::Event::Key {
                                key: egui::Key::Tab,
                                ..
                            }
                        )
                    });
                }

                let egui_output = egui_ctx.run_ui(raw_input, |ctx| {
                    // FPS overlay (top-right corner)
                    egui_overlays::render_fps_overlay(ctx, show_fps, fps_value, frame_time_ms);

                    // Resize overlay (centered)
                    egui_overlays::render_resize_overlay(
                        ctx,
                        self.overlay_state.resize_overlay_visible,
                        self.overlay_state.resize_dimensions,
                    );

                    // Copy mode status bar overlay (bottom-left)
                    {
                        let mode_text = if self.copy_mode.is_searching {
                            "SEARCH"
                        } else {
                            match self.copy_mode.visual_mode {
                                crate::copy_mode::VisualMode::None => "COPY",
                                crate::copy_mode::VisualMode::Char => "VISUAL",
                                crate::copy_mode::VisualMode::Line => "V-LINE",
                                crate::copy_mode::VisualMode::Block => "V-BLOCK",
                            }
                        };
                        let status = self.copy_mode.status_text();
                        egui_overlays::render_copy_mode_status_bar(
                            ctx,
                            self.copy_mode.active,
                            self.config.load().copy_mode.copy_mode_show_status,
                            self.copy_mode.is_searching,
                            self.copy_mode.visual_mode,
                            mode_text,
                            &status,
                        );
                    }

                    // IME preedit (composing) text at the terminal cursor
                    egui_overlays::render_ime_preedit_overlay(
                        ctx,
                        ime_preedit.as_deref(),
                        ime_cursor_logical,
                    );

                    // Toasts, mode banner, leader which-key, demote (OV7/OV8)
                    super::egui_dialogs::render_notifications(
                        ctx,
                        &self.overlay_state,
                        pane_hint_banner,
                        toast_top_inset,
                        (demote_snapshot, demote_pane_bounds),
                        actions,
                    );

                    // Scrollbar mark tooltip (near mouse pointer)
                    egui_overlays::render_scrollbar_mark_tooltip(ctx, hovered_mark.as_ref());

                    // Render tab bar if visible (action handled after closure)
                    let tab_bar_right_reserved =
                        if self.overlay_ui.ai_inspector.open {
                            self.overlay_ui.ai_inspector.consumed_width()
                        } else {
                            0.0
                        } + self.overlay_ui.profile_drawer_ui.consumed_width();
                    // Populate move-tab context so the right-click context
                    // menu has fresh state. Values captured before the closure
                    // to avoid borrowing `self` for `is_gateway_active()`
                    // while the closure already uniquely borrows `*self`.
                    self.tab_bar_ui.set_move_tab_context(
                        move_gateway_active,
                        move_tab_count,
                        move_candidates.clone(),
                        context_tab_has_multiple_panes,
                        context_demote_refusal,
                    );
                    actions.tab_action = self.tab_bar_ui.render(
                        ctx,
                        &self.tab_manager,
                        &self.config.load(),
                        &self.overlay_ui.profile_manager,
                        tab_bar_right_reserved,
                        &session_chip,
                    );

                    // Render tmux status bar if connected
                    self.overlay_ui.tmux_status_bar_ui.render(
                        ctx,
                        &self.config.load(),
                        self.tmux_state.tmux_session.as_ref(),
                        self.tmux_state.tmux_session_name.as_deref(),
                    );

                    // Render custom status bar
                    if let Some(ref session_vars) = status_bar_session_vars {
                        let (_bar_height, status_bar_action) = self.status_bar_ui.render(
                            ctx,
                            &self.config.load(),
                            session_vars,
                            self.is_fullscreen,
                        );
                        if status_bar_action
                            == Some(crate::status_bar::StatusBarAction::ShowUpdateDialog)
                        {
                            self.update_state.show_dialog = true;
                        }
                        if status_bar_action
                            == Some(crate::status_bar::StatusBarAction::OpenAgentUsagePanel)
                        {
                            self.overlay_ui.agent_usage_panel.open();
                        }
                        if status_bar_action
                            == Some(crate::status_bar::StatusBarAction::OpenAgentPalette)
                        {
                            // The palette is the roster's list surface (A2b
                            // task 3) — runtime rows joined at open time.
                            super::egui_dialogs::open_command_palette_with_runtime_rows(
                                &self.status_bar_ui,
                                &self.agent_commands,
                                &mut self.crash_triage,
                                &self.config,
                                &mut self.overlay_ui.command_palette,
                                &self.overlay_ui.profile_manager,
                                &self.keybinding_registry,
                                #[cfg(feature = "mux")]
                                &self.tmux_state,
                            );
                            refresh_mux_directory = true;
                        }
                    }

                    // Show help UI
                    self.overlay_ui.help_ui.show(
                        ctx,
                        &self.keybinding_registry,
                        &self.config.load().keybindings,
                    );

                    // Show clipboard history UI and collect action
                    actions.clipboard = self.overlay_ui.clipboard_history_ui.show(ctx);

                    // Show command history UI and collect action
                    self.overlay_ui
                        .sync_picker_chords(&self.keybinding_registry);
                    actions.command_history = self.overlay_ui.command_history_ui.show(ctx);

                    // Show paste special UI and collect action
                    actions.paste_special = self.overlay_ui.paste_special_ui.show(ctx);

                    // Pane-title rename popup (right-click a pane title bar,
                    // or the `rename_pane` action on the focused pane). The
                    // closure cannot take a whole-&mut-self method (the
                    // egui state borrow above), so the submit is applied
                    // after the egui block ends.
                    if let crate::pane_rename_ui::PaneRenameOutcome::Submit { pane_id, name } =
                        self.overlay_ui.pane_rename_ui.render(ctx)
                    {
                        pane_rename_submit = Some((pane_id, name));
                    }

                    // Show search UI and collect action
                    actions.search =
                        self.overlay_ui
                            .search_ui
                            .show(ctx, visible_lines, scrollback_len);

                    // Show command palette and collect the chosen action
                    actions.command_palette = self.overlay_ui.command_palette.show(ctx);

                    // Show agent-usage panel; `r` inside it requests a rescan
                    if let Some(crate::agent_usage::panel::PanelAction::RefreshRequested) = self
                        .overlay_ui
                        .agent_usage_panel
                        .show(ctx, self.status_bar_ui.usage_snapshot())
                    {
                        self.status_bar_ui.refresh_usage_now();
                    }

                    // Show AI Inspector panel and collect action
                    actions.inspector = self
                        .overlay_ui
                        .ai_inspector
                        .show(ctx, &self.agent_state.available_agents);

                    // Pane context menu (UX.md V10): rows show live chords.
                    {
                        let registry = &self.keybinding_registry;
                        let chord_for = |id: &str| {
                            registry
                                .chord_for_action(id)
                                .map(|combo| crate::command_palette::catalog::chord_display(&combo))
                        };
                        if let Some(choice) =
                            self.overlay_ui.pane_context_menu.render(ctx, &chord_for)
                        {
                            actions.pane_menu = Some(choice);
                        }
                    }

                    // Tree picker (UX.md A15): the chosen jump is applied
                    // by the window manager, which may focus another window.
                    if let Some(target) = self.overlay_ui.tree_picker_ui.show(ctx) {
                        self.overlay_ui.pending_tree_jump = Some(target);
                    }

                    // Session picker (par-mux + tmux, UX.md A16)
                    actions.session_picker = super::session_picker_render::show_session_picker(
                        ctx,
                        &mut self.overlay_ui.tmux_session_picker_ui,
                        &self.config,
                        &self.tmux_state,
                    );

                    // Show shader install dialog if visible
                    actions.shader_install = self.overlay_ui.shader_install_ui.show(ctx);

                    // Show integrations welcome dialog if visible
                    actions.integrations = self.overlay_ui.integrations_ui.show(ctx);

                    // Show close confirmation dialog if visible
                    actions.close_confirm = self.overlay_ui.close_confirmation_ui.show(ctx);

                    // Show par-mux last-tab close dialog if visible
                    actions.mux_last_tab = self.overlay_ui.mux_last_tab_ui.show(ctx);

                    // Show quit confirmation dialog if visible
                    actions.quit_confirm = self.overlay_ui.quit_confirmation_ui.show(ctx);

                    // Show remote shell install dialog if visible
                    actions.remote_install = self.overlay_ui.remote_shell_install_ui.show(ctx);

                    // Show SSH Quick Connect dialog if visible
                    actions.ssh_connect = self.overlay_ui.ssh_connect_ui.show(ctx);

                    // Render update dialog overlay
                    super::egui_dialogs::render_update_dialog(
                        ctx,
                        &mut self.update_state,
                        &mut self.status_bar_ui,
                        &self.config,
                        actions,
                    );

                    // Open Profiles… popup and the Profiles drawer (UX.md
                    // PR1/PR2): one launcher, floating or pinned.
                    actions.profile_launcher = super::egui_dialogs::render_profile_launcher(
                        ctx,
                        &mut self.overlay_ui,
                        &self.config.load(),
                        badge_custom_sb_height,
                    );

                    // Render progress bar overlay
                    if let (Some(snap), Some(size)) = (progress_snapshot, window_size_for_badge) {
                        let tab_count = self.tab_manager.visible_tab_count();
                        let tb_height = self.tab_bar_ui.get_height(tab_count, &self.config.load());
                        let (top_inset, bottom_inset) =
                            match self.config.load().tabs.tab_bar_position {
                                par_term_config::TabBarPosition::Top => (tb_height, 0.0),
                                par_term_config::TabBarPosition::Bottom => (0.0, tb_height),
                                par_term_config::TabBarPosition::Left => (0.0, 0.0),
                            };
                        render_progress_bars(
                            ctx,
                            snap,
                            &self.config.load(),
                            size.width as f32,
                            size.height as f32,
                            top_inset,
                            bottom_inset,
                        );
                    }

                    // Pane identify overlay (large index numbers centered on each pane)
                    egui_overlays::render_pane_identify_overlay(ctx, &pane_identify_bounds);

                    // par-mux held-pane banners over the frozen screens.
                    #[cfg(feature = "mux")]
                    {
                        exited_pane_restart =
                            super::exited_pane_overlay::render_exited_pane_banners(
                                ctx,
                                &exited_pane_banners,
                            );
                    }

                    // Plugin overlays (overlay kind) sit above terminal
                    // content but below modal-mode chrome (mode-stack
                    // contract, docs/plans/2026-09-24-overlay-plugin-design.md).
                    plugin_overlay_render::render_plugin_overlays(
                        ctx,
                        &plugin_overlays,
                        &mut overlay_interactions,
                        focused_overlay_plugin.as_deref(),
                    );

                    egui_overlays::render_broadcast_outlines(ctx, &broadcast_outlines);

                    // Pane-hint selection badges — modal-mode chrome, drawn
                    // above every plugin overlay (mode-stack contract).
                    egui_overlays::render_pane_hint_overlay(ctx, &pane_hint_badges);

                    // Trigger action confirmation dialog (center modal, shown when pending_trigger_actions is non-empty)
                    egui_overlays::render_trigger_prompt_dialog(
                        ctx,
                        &mut self.trigger_state,
                        pending_action_target_note.as_deref(),
                    );

                    // Agent-command first-run confirmation (D4b). Approvals
                    // land in the store's execution queue, drained from
                    // `about_to_wait` — the egui closure cannot run
                    // `&mut self` executors.
                    egui_overlays::render_agent_command_confirm_dialog(
                        ctx,
                        &mut self.agent_commands,
                    );

                    // Render file transfer progress overlay (bottom-right corner)
                    crate::app::file_transfers::render_file_transfer_overlay(
                        &self.file_transfer_state,
                        ctx,
                    );

                    // Render badge overlay (top-right corner, offset by UI insets)
                    if let (Some(badge), Some(size)) = (&badge_state, window_size_for_badge) {
                        let tab_count = self.tab_manager.visible_tab_count();
                        let tb_height = self.tab_bar_ui.get_height(tab_count, &self.config.load());

                        let top_inset = match self.config.load().tabs.tab_bar_position {
                            par_term_config::TabBarPosition::Top => tb_height,
                            _ => 0.0,
                        };
                        let bottom_inset = match self.config.load().tabs.tab_bar_position {
                            par_term_config::TabBarPosition::Bottom => tb_height,
                            _ => 0.0,
                        } + badge_tmux_sb_height
                            + badge_custom_sb_height;
                        let scrollbar_inset = if show_scrollbar {
                            self.config.load().scrollbar.scrollbar_width + 2.0
                        } else {
                            0.0
                        };
                        let right_inset = scrollbar_inset
                            + if self.overlay_ui.ai_inspector.open {
                                self.overlay_ui.ai_inspector.consumed_width()
                            } else {
                                0.0
                            };

                        let insets = BadgeInsets {
                            top: top_inset,
                            bottom: bottom_inset,
                            right: right_inset,
                        };
                        render_badge(ctx, badge, size.width as f32, size.height as f32, &insets);
                    }
                });

                // Handle egui platform output (clipboard, cursor changes, etc.)
                egui_state.handle_platform_output(window, egui_output.platform_output.clone());

                Some((egui_output, egui_ctx.clone()))
            } else {
                // egui context/state not yet initialised for this window.
                None
            }
        } else {
            // Window not yet created; skip egui rendering this frame.
            crate::debug_error!("RENDER", "egui render skipped: window is None");
            None
        };

        // Mark egui as initialized after first ctx.run_ui() - makes is_using_pointer() reliable
        if !self.egui.initialized && result.is_some() {
            self.egui.initialized = true;
        }

        // Apply the pane rename collected above (the egui state borrow has
        // ended here).
        if let Some((pane_id, name)) = pane_rename_submit {
            self.rename_pane(pane_id, &name);
        }
        #[cfg(feature = "mux")]
        if refresh_mux_directory {
            self.refresh_mux_directory();
        }
        #[cfg(not(feature = "mux"))]
        let _ = refresh_mux_directory;

        #[cfg(feature = "mux")]
        if let Some(pane) = exited_pane_restart {
            self.restart_mux_pane(pane);
        }

        // Apply the interactions the interactive overlays collected: focus
        // requests first (so a click both focuses and reports), then the
        // semantic events. Done outside the egui closure — these run host
        // code (focus bookkeeping, plugin stdin writes).
        for interaction in overlay_interactions {
            if interaction.focus_request {
                self.status_bar_ui
                    .plugin_host_mut()
                    .focus_overlay(&interaction.plugin_id);
            }
            if !interaction.widget_id.is_empty() {
                self.status_bar_ui.plugin_host_mut().send_overlay_event(
                    &interaction.plugin_id,
                    &interaction.widget_id,
                    interaction.event,
                );
            }
        }

        let debug_egui_time = egui_start.elapsed();
        self.debug.last_egui_time = debug_egui_time;

        result
    }
}

/// Helper to get the current scroll offset from the active tab.
pub(super) fn scroll_offset_from_tab(tab_manager: &crate::tab::TabManager) -> usize {
    tab_manager
        .active_tab()
        .map(|t| t.active_scroll_state().offset)
        .unwrap_or(0)
}