magi-code 0.96.1

Repository-aware CLI coding agent for terminal work
Documentation
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
mod fast_mode;
mod transcript_cache;
pub(crate) use fast_mode::FastDisplayState;
pub(crate) use fast_mode::StoredFastObservation;
mod activity_motion;
pub(crate) use super::prompt_editor::{
    PROMPT_MOVEMENT_FAILED_STATUS, PROMPT_TOO_LARGE_STATUS, PromptEditResult, PromptEditor,
    PromptMovementOutcome, PromptTextNormalizer, normalize_prompt_text_bounded,
};
use super::{
    activity::{self, ActivityNode},
    autocomplete,
    selection::{ActiveSelection, TextPosition},
    toast::{COPIED_TO_CLIPBOARD, ToastSeverity, ToastState},
    transcript,
};
use crate::output::{
    ActivityId, ActivityKind, ActivityMetadata, ActivityStatus, ContextUsageSource, OutputEvent,
    StreamingRedactor, redact_sensitive_text,
};
use crate::rendering::DisplayLine;
use crate::tui::{
    PADDED_INLINE_SEPARATOR, layout::TuiPane, normalize_inline_separators,
    theme::MissionControlTheme,
};
use chrono::{DateTime, Local};
use ratatui::layout::Position;
use std::cell::{Cell, Ref, RefCell};
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::Instant;

pub(crate) use super::activity::activity_status_mark;
pub(crate) use super::transcript::{TranscriptEntries, TranscriptRenderCache};
pub(crate) use super::transcript_cards::TranscriptActivityLink;
pub(crate) const MOUSE_WHEEL_SCROLL_ROWS: u16 = 3;
pub(crate) use super::autocomplete::{AutocompleteCandidate, AutocompleteKind, AutocompleteState};

mod activity_state;
mod layout;
mod modal;
mod output_events;
mod primary_agent_state;
mod prompt_actions;
pub(in crate::tui) mod prompt_state;
mod provider_context;
mod subagent_viewer;
mod transcript_state;

use activity_state::ActiveSubagentTranscript;
pub(crate) use activity_state::ActiveToolTranscript;
use modal::ModalState;
pub(crate) use modal::{
    ConnectProviderField, ConnectProviderStage, ConnectProviderState, LoginProviderEntry,
    McpServerToggleRow, ModalKind, OAuthControl, PreviewMessage, SessionPickerFocus,
    SessionPickerRow, SessionPreview, SessionPreviewPartial, SessionPreviewState, SkillToggleRow,
    SubagentProfileToggleRow, SystemPromptCard, SystemPromptModalState, ThemeSaveState,
    ToolToggleRow,
};
pub(crate) use primary_agent_state::PrimaryAgentEntry;
pub(crate) use prompt_state::RunningPromptState;
pub(crate) use transcript_state::ContextUsageState;
use transcript_state::{
    is_transient_status_error, merge_context_usage, transcript_tool_metadata, transcript_tool_row,
};

pub(crate) const MAX_AUTOCOMPLETE_VISIBLE_ROWS: usize = 6;

pub(crate) mod session_files;
mod summary;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub(crate) enum RightColumnTab {
    #[default]
    Activity,
    Diff,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum TuiFocusPane {
    Transcript,
    #[default]
    Prompt,
}

#[derive(Debug, Default)]
pub(crate) struct ActivityRenderCache {
    visible_nodes: Option<Vec<(usize, ActivityId)>>,
    selected_detail: Option<ActivityDetailCache>,
}

#[derive(Debug, Clone)]
struct ActivityBodyWrapCache {
    total_rows: usize,
    visual_starts: Vec<(usize, usize)>,
}

#[derive(Debug, Clone)]
struct ActivityDetailCache {
    id: Option<ActivityId>,
    summary_lines: Vec<DisplayLine>,
    body_lines: Vec<DisplayLine>,
    metadata_header: Option<usize>,
    body_wrap_cache: HashMap<u16, ActivityBodyWrapCache>,
    body_wrap_widths: VecDeque<u16>,
}

impl ActivityRenderCache {
    fn clear(&mut self) {
        self.visible_nodes = None;
        self.selected_detail = None;
    }

    fn invalidate_visible_nodes(&mut self) {
        self.visible_nodes = None;
    }

    fn invalidate_selected_detail(&mut self) {
        self.selected_detail = None;
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct ThinkingTranscriptIdentity {
    pub(crate) item_id: String,
    pub(crate) turn_id: Option<String>,
}

#[derive(Debug, Default)]
pub(crate) struct ScrollViewStates {
    pub(crate) transcript: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) activity_tree: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) detail: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) help: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) system_prompt: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) session_list: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) session_preview: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) connect_provider: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) logout_picker: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) model_picker: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) skills_modal: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) mcp_modal: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) tools_modal: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) subagents_modal: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) rewind_modal: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) usage_modal: RefCell<tui_scrollview::ScrollViewState>,
    pub(crate) theme_modal: RefCell<tui_scrollview::ScrollViewState>,
}

/// One welcome layout and its current logo; never part of session history.
#[derive(Debug)]
pub(crate) struct WelcomeRenderCache {
    pub(crate) key: (MissionControlTheme, u16, u16),
    pub(crate) update_version: Option<String>,
    pub(crate) update_notice: Option<ratatui::widgets::Paragraph<'static>>,
    pub(crate) update_height: u16,
    pub(crate) compact: bool,
    pub(crate) logo_phase: Option<usize>,
    pub(crate) logo: ratatui::widgets::Paragraph<'static>,
    pub(crate) body: ratatui::widgets::Paragraph<'static>,
    pub(crate) height: u16,
    pub(crate) logo_height: u16,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct SubagentCardSelection {
    pub(crate) task_id: Option<ActivityId>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LastSessionHeader {
    pub(crate) session_id: Option<String>,
    pub(crate) model: String,
}

#[derive(Debug, Default)]
pub(crate) struct MissionControlState {
    pub(crate) conversation_modal: Option<Box<super::render::TranscriptModal>>,
    pub(crate) subagent_controls: crate::subagents::control::SubagentControls,
    pub(crate) subagent_control_namespace: String,
    pub(crate) subagent_prompt_drafts: HashMap<ActivityId, subagent_viewer::SubagentPromptDraft>,
    // layout/activity tree
    pub(crate) transcript_only_layout: bool,
    pub(crate) right_column_tab: RightColumnTab,
    pub(crate) summary: summary::SummaryDisplay,
    pub(crate) session_files: session_files::SessionFiles,
    pub(crate) diff: super::diff::DiffPage,
    pub(crate) nodes: HashMap<ActivityId, ActivityNode>,
    pub(crate) roots: Vec<ActivityId>,
    pub(crate) children: HashMap<ActivityId, Vec<ActivityId>>,
    pub(crate) expanded: HashSet<ActivityId>,
    pub(crate) transcript: TranscriptEntries,
    pub(crate) images: RefCell<super::images::TranscriptImages>,
    pub(crate) transcript_timestamp_context: Option<DateTime<Local>>,
    pub(crate) subagent_card_selection: HashMap<ActivityId, SubagentCardSelection>,
    pub(crate) activity_update_sequence: u64,
    pub(crate) subagent_card_rows: usize,
    pub(super) transcript_cache: RefCell<TranscriptRenderCache>,
    pub(super) subagent_viewer_timeline_cache:
        RefCell<subagent_viewer::SubagentViewerTimelineCache>,
    pub(super) final_assistant_plain_first_entries: RefCell<HashSet<usize>>,
    pub(super) final_assistant_rich_refresh_entries: RefCell<HashSet<usize>>,
    pub(super) final_assistant_plain_first_enabled: Cell<bool>,
    pub(super) transcript_visual_generation: Cell<u64>,
    pub(crate) theme: MissionControlTheme,
    pub(crate) reduced_motion: bool,
    #[cfg(any(test, debug_assertions))]
    pub(crate) perf: super::perf::TuiPerfCounters,
    pub(super) activity_render_cache: RefCell<ActivityRenderCache>,

    pub(crate) scroll_views: ScrollViewStates,
    pub(crate) detail_scroll_offset: Cell<usize>,
    pub(crate) detail_metadata_expanded: bool,
    pub(crate) transcript_tail_distance: Cell<usize>,
    pub(crate) transcript_scroll_anchor: Cell<Option<transcript::TranscriptScrollAnchor>>,
    pub(crate) active_tool_transcripts: HashMap<ActivityId, ActiveToolTranscript>,
    pub(crate) assistant_streaming: bool,
    pub(crate) active_assistant_text: String,
    // StreamingRedactor holds back a short tail so split credentials are not exposed mid-stream.
    pub(crate) active_assistant_redactor: StreamingRedactor,
    pub(crate) active_assistant_transcript_index: Option<usize>,
    pub(crate) pending_assistant_completion_index: Option<usize>,
    // Explicit display-only identity for the currently running compaction card.
    pub(crate) pending_compaction_transcript_index: Option<usize>,
    pub(crate) active_thinking_text: String,
    pub(crate) thinking_transcript_identities: HashMap<ThinkingTranscriptIdentity, usize>,
    #[cfg(test)]
    pub(crate) thinking_append_work_bytes: usize,
    pub(crate) active_thinking_redactor: StreamingRedactor,
    pub(crate) active_thinking_control_sanitizer: transcript::StreamingControlSanitizer,
    pub(crate) active_thinking_transcript_index: Option<usize>,
    pub(crate) context_usage: Option<ContextUsageState>,
    pub(crate) session_usage: super::session_usage::SessionUsageLedger,
    pub(crate) session_active_time: crate::sessions::active_time::SessionActiveTime,
    pub(crate) displayed_session_active_seconds: u64,
    // Display-only fallback while session usage is incomplete or cache data is unknown.
    pub(crate) last_known_session_cache_percent: Option<u64>,
    // Display-only configured policy; usage totals are tracked independently.
    pub(crate) compaction_settings: crate::config::CompactionSettings,
    pub(crate) selected: usize,
    pub(crate) prompt_editor: PromptEditor,
    pub(crate) prompt_history: crate::tui::prompt_history::PromptHistory,
    pub(crate) prompt_history_loaded: bool,
    pub(crate) dismissed_prompt_history_revision: Option<u64>,
    pub(crate) visible_prompt_history_revision: Cell<Option<u64>>,
    // focus and layout state
    pub(crate) focus_pane: TuiFocusPane,
    pub(crate) last_standalone_ctrl: Option<Instant>,
    // Display-only session state; Fast observations are never serialized.
    pub(crate) fast_observations: HashMap<(String, String), StoredFastObservation>,
    pub(crate) fast_warning_keys: HashSet<crate::fast::FastWarningKey>,
    pub(crate) fast_observation_accept_sequence: u64,
    pub(crate) fast_mode_enabled: bool,
    pub(crate) fast_mode_request_state: crate::fast::FastRequestState,
    pub(crate) fast_mode_capable: bool,
    pub(crate) fast_mode_effective: bool,
    pub(crate) color_enabled: bool,
    pub(crate) fast_mode_rainbow_phase: usize,
    // Display-only clock for the empty-transcript welcome screen.
    pub(crate) welcome_animation_phase: usize,
    pub(crate) welcome_render_cache: RefCell<Option<WelcomeRenderCache>>,
    pub(crate) release_notes: Option<&'static str>,
    pub(crate) update_restart_welcome: bool,
    pub(crate) release_notes_drawn: std::cell::Cell<bool>,
    pub(crate) release_notes_displayed: std::cell::Cell<bool>,
    pub(crate) release_notes_viewport: std::cell::Cell<(u16, u16)>,
    pub(crate) release_notes_area: std::cell::Cell<ratatui::layout::Rect>,
    pub(crate) release_notes_offset: std::cell::Cell<usize>,
    pub(crate) release_notes_page_end: std::cell::Cell<usize>,
    pub(crate) release_notes_viewed: std::cell::Cell<usize>,
    pub(crate) release_notes_total: std::cell::Cell<usize>,
    // Display-only update notice; never part of session history.
    pub(crate) available_update_version: Option<String>,
    pub(crate) activity_motion: activity_motion::ActivityMotion,
    pub(crate) ignore_next_standalone_ctrl_release: bool,
    pub(crate) activity_follow_tail: bool,

    // footer/status and provider display state
    pub(crate) status: String,
    pub(crate) footer_session: String,
    pub(crate) footer_session_id: Option<String>,
    pub(crate) footer_cwd: String,
    pub(crate) footer_git_branch: Option<String>,
    pub(crate) provider: String,
    pub(crate) model: String,
    pub(crate) last_session_header: Option<LastSessionHeader>,
    pub(crate) provider_ready: bool,
    pub(crate) thinking_level: crate::thinking::ThinkingLevel,
    pub(crate) effective_thinking_level: crate::thinking::ThinkingLevel,
    pub(crate) thinking_levels: Vec<crate::thinking::ThinkingLevel>,
    pub(crate) running_prompt: Option<RunningPromptState>,
    pub(crate) active_worker_id: Option<u64>,
    pub(crate) last_run_finished_worker_id: Option<u64>,
    pub(crate) pending_steering_count: usize,

    // prompt affordances and transient UI overlays
    pub(crate) show_help: bool,
    pub(crate) autocomplete: Option<AutocompleteState>,
    pub(crate) autocomplete_dismissed_token: Option<String>,
    pub(crate) selection: Option<ActiveSelection>,
    pub(crate) toast: Option<ToastState>,
    pub(crate) pending_model_catalog_request_id: Option<u64>,
    pub(crate) pending_usage_request_id: Option<u64>,
    pub(crate) codex_quota_label: Option<String>,
    pub(crate) claude_quota_label: Option<String>,
    pub(crate) last_agent_activity: Option<std::time::Instant>,
    pub(crate) pending_startup_critical_request_id: Option<u64>,
    pub(crate) pending_startup_decorative_request_id: Option<u64>,
    pub(crate) startup_prompt_queued: bool,
    // modal and primary-agent display state
    pub(crate) modals: ModalState,
    pub(crate) primary_agents: Vec<PrimaryAgentEntry>,
    pub(crate) selected_primary_agent: Option<usize>,
}

impl MissionControlState {
    pub(crate) fn subagent_card_rows(&self) -> usize {
        if self.subagent_card_rows == 0 {
            crate::config::DEFAULT_TUI_SUBAGENT_CARD_ROWS
        } else {
            self.subagent_card_rows
        }
    }
}
impl MissionControlState {
    pub(crate) fn pin_subagent_card_task(&mut self, batch_id: ActivityId, task_id: ActivityId) {
        self.subagent_card_selection.insert(
            batch_id,
            SubagentCardSelection {
                task_id: Some(task_id),
            },
        );
        self.invalidate_transcript_cache();
    }

    pub(crate) fn scroll_offset(
        &self,
        view: &std::cell::RefCell<tui_scrollview::ScrollViewState>,
    ) -> usize {
        usize::from(view.borrow().offset().y)
    }

    pub(crate) fn set_scroll_offset(
        &self,
        view: &std::cell::RefCell<tui_scrollview::ScrollViewState>,
        offset: usize,
    ) {
        if std::ptr::eq(view, &self.scroll_views.detail) {
            self.detail_scroll_offset.set(offset);
            return;
        }
        if std::ptr::eq(view, &self.scroll_views.transcript) {
            self.transcript_tail_distance.set(offset);
            if offset == 0 {
                self.transcript_scroll_anchor.set(None);
            }
        }
        let offset = offset.min(usize::from(u16::MAX));
        view.borrow_mut()
            .set_offset(Position::new(0, offset as u16));
    }

    pub(crate) fn transcript_scroll_offset(&self) -> usize {
        self.transcript_tail_distance.get()
    }

    pub(crate) fn activity_scroll_offset(&self) -> usize {
        self.scroll_offset(&self.scroll_views.activity_tree)
    }

    pub(crate) fn detail_offset(&self) -> usize {
        self.detail_scroll_offset.get()
    }

    pub(crate) fn help_offset(&self) -> usize {
        self.scroll_offset(&self.scroll_views.help)
    }

    pub(crate) fn reset_core_scroll_views(&mut self) {
        self.set_scroll_offset(&self.scroll_views.transcript, 0);
        self.set_scroll_offset(&self.scroll_views.activity_tree, 0);
        self.detail_scroll_offset.set(0);
        self.set_scroll_offset(&self.scroll_views.help, 0);
    }

    pub(crate) fn refresh_thinking_levels(
        &mut self,
        selected: crate::thinking::ThinkingLevel,
        available: Vec<crate::thinking::ThinkingLevel>,
    ) {
        self.thinking_level = selected;
        self.thinking_levels = crate::thinking::normalize_thinking_levels(&available);
        self.effective_thinking_level =
            crate::thinking::resolve_thinking_level(&self.thinking_levels, selected);
    }

    pub(crate) fn set_theme(&mut self, theme: MissionControlTheme, reduced_motion: bool) -> bool {
        let presentation_changed = !self.theme.presentation_eq(theme);
        let newer_revision = theme.revision() > self.theme.revision();
        let motion_changed = self.reduced_motion != reduced_motion;
        if !presentation_changed && !newer_revision && !motion_changed {
            return false;
        }
        self.theme = theme;
        self.reduced_motion = reduced_motion;
        self.fast_mode_rainbow_phase = 0;
        self.invalidate_transcript_cache();
        true
    }

    pub(crate) fn theme_revision(&self) -> u64 {
        self.theme.revision()
    }

    pub(crate) fn welcome_animation_active(&self) -> bool {
        !self.transcript_only_layout
            && self.transcript.is_empty()
            && self.color_enabled
            && !self.reduced_motion
    }

    pub(crate) fn next_thinking_level(&self) -> Option<crate::thinking::ThinkingLevel> {
        crate::thinking::next_thinking_level(&self.thinking_levels, self.thinking_level)
    }

    pub(crate) fn thinking_label(&self) -> &'static str {
        self.effective_thinking_level.label()
    }

    pub(crate) fn refresh_compaction_settings(&mut self, settings: &crate::config::Settings) {
        self.compaction_settings = settings.compaction.clone();
        if self.provider == crate::providers::CLAUDE_SUBSCRIPTION_PROVIDER {
            // Claude capacity is local policy; no catalog or settings I/O on the UI thread.
            let mut budget = settings.context.clone().unwrap_or_default();
            budget.apply_model_limits(&self.provider, &self.model);
            settings
                .compaction
                .apply_conversation_limit(&mut budget, &self.provider);
            self.update_context_window(budget.max_tokens);
        }
    }

    pub(crate) fn update_context_window(&mut self, max_tokens: usize) {
        let current_tokens = self
            .context_usage
            .map(|usage| usage.current_tokens)
            .unwrap_or(0);
        let reasoning_tokens = self.context_usage.and_then(|usage| usage.reasoning_tokens);
        let source = self
            .context_usage
            .map(|usage| usage.source)
            .unwrap_or(ContextUsageSource::FallbackEstimate);
        let request_sequence = self
            .context_usage
            .map(|usage| usage.request_sequence)
            .unwrap_or(0);
        self.context_usage = Some(ContextUsageState {
            current_tokens,
            max_tokens,
            reasoning_tokens,
            source,
            request_sequence,
        });
    }

    pub(crate) fn reset_context_for_model_switch(&mut self) {
        self.context_usage = None;
    }

    pub(crate) fn invalidate_activity_render_cache(&self) {
        self.activity_render_cache.borrow_mut().clear();
    }

    pub(crate) fn invalidate_activity_visible_nodes_cache(&self) {
        self.activity_render_cache
            .borrow_mut()
            .invalidate_visible_nodes();
    }

    pub(crate) fn invalidate_selected_activity_detail_cache(&self) {
        self.activity_render_cache
            .borrow_mut()
            .invalidate_selected_detail();
    }

    pub(crate) fn selected_activity_summary_lines(&self) -> Vec<DisplayLine> {
        self.ensure_selected_activity_detail_cache();
        self.activity_render_cache
            .borrow()
            .selected_detail
            .as_ref()
            .map(|detail| detail.summary_lines.clone())
            .unwrap_or_else(|| vec![DisplayLine::plain(no_activity_selected_text())])
    }

    fn ensure_selected_activity_detail_cache(&self) {
        let selected_id = self
            .modals
            .activity_detail
            .clone()
            .or_else(|| self.selected_activity_id());
        if self
            .activity_render_cache
            .borrow()
            .selected_detail
            .as_ref()
            .is_some_and(|detail| detail.id == selected_id)
        {
            return;
        }

        let lines = selected_id
            .as_ref()
            .and_then(|id| self.nodes.get(id))
            .map(|node| {
                let mut detail =
                    activity::activity_detail_lines(node, self.detail_metadata_expanded);
                if node.kind == ActivityKind::SubagentTask {
                    let descendants = self.safe_subagent_descendant_lines(&node.id);
                    if !descendants.is_empty() {
                        if !detail.body.is_empty() {
                            detail.body.push(DisplayLine::plain(""));
                        }
                        detail.body.push(DisplayLine::plain("Recent activity"));
                        detail.body.extend(descendants);
                    }
                }
                detail
            })
            .unwrap_or_else(|| activity::ActivityDetailLines {
                summary: vec![DisplayLine::plain(no_activity_selected_text())],
                body: Vec::new(),
                metadata_header: None,
            });
        self.activity_render_cache.borrow_mut().selected_detail = Some(ActivityDetailCache {
            id: selected_id,
            summary_lines: lines.summary,
            body_lines: lines.body,
            metadata_header: lines.metadata_header,
            body_wrap_cache: HashMap::new(),
            body_wrap_widths: VecDeque::new(),
        });
    }
    fn safe_subagent_descendant_lines(&self, task_id: &ActivityId) -> Vec<DisplayLine> {
        let mut nodes = self
            .nodes
            .values()
            .filter(|node| self.activity_is_descendant_of(&node.id, task_id))
            .collect::<Vec<_>>();
        nodes.sort_by(|left, right| {
            right
                .own_update_sequence
                .cmp(&left.own_update_sequence)
                .then_with(|| right.id.as_str().cmp(left.id.as_str()))
        });
        let mut lines = Vec::new();
        for node in nodes {
            let source = if node.preview.trim().is_empty() {
                node.metadata.label.as_str()
            } else {
                node.preview.as_str()
            };
            let Some(line) = source.lines().rev().find(|line| !line.trim().is_empty()) else {
                continue;
            };
            let line = normalize_inline_separators(&transcript::sanitize_preview(
                &redact_sensitive_text(line),
            ));
            if !line.is_empty()
                && lines
                    .last()
                    .is_none_or(|last: &DisplayLine| last.plain_text() != line)
            {
                lines.push(DisplayLine::plain(line));
            }
            if lines.len() == 6 {
                break;
            }
        }
        lines
    }

    pub(crate) fn toggle_detail_metadata(&mut self, visible_rows: u16, wrap_width: u16) -> bool {
        self.ensure_selected_activity_detail_cache();
        if self
            .activity_render_cache
            .borrow()
            .selected_detail
            .as_ref()
            .is_none_or(|detail| detail.metadata_header.is_none())
        {
            return false;
        }
        let offset = self.detail_offset();
        self.detail_metadata_expanded = !self.detail_metadata_expanded;
        self.invalidate_selected_activity_detail_cache();
        let body_rows = self.detail_body_viewport_rows(visible_rows, wrap_width);
        let clamped = offset.min(self.detail_overflow(body_rows, wrap_width));
        self.set_scroll_offset(&self.scroll_views.detail, clamped);
        true
    }

    pub(crate) fn detail_metadata_header_visual_rows(
        &self,
        wrap_width: u16,
    ) -> Option<std::ops::Range<usize>> {
        self.ensure_selected_activity_body_wrap_cache(wrap_width);
        let cache = self.activity_render_cache.borrow();
        let detail = cache.selected_detail.as_ref()?;
        let header = detail.metadata_header?;
        let starts = &detail
            .body_wrap_cache
            .get(&wrap_width.max(1))?
            .visual_starts;
        let start = starts.iter().position(|(line, _)| *line == header)?;
        let end = starts[start..]
            .iter()
            .position(|(line, _)| *line != header)
            .map_or(starts.len(), |offset| start + offset);
        Some(start..end)
    }

    pub(crate) fn start_prompt_selection_at(&mut self, byte: usize) {
        self.selection = None;
        if self.prompt_editor.start_selection_at(byte) == PromptMovementOutcome::Failed {
            self.status = PROMPT_MOVEMENT_FAILED_STATUS.to_string();
        }
    }

    pub(crate) fn update_prompt_selection_at(&mut self, byte: usize) -> bool {
        let outcome = self.prompt_editor.update_selection_at(byte);
        if outcome == PromptMovementOutcome::Failed {
            self.status = PROMPT_MOVEMENT_FAILED_STATUS.to_string();
        }
        !matches!(outcome, PromptMovementOutcome::Unchanged)
    }

    pub(crate) fn start_selection(&mut self, pane: TuiPane, position: TextPosition) {
        match pane {
            TuiPane::Prompt => self.start_prompt_selection_at(position.byte),
            TuiPane::Transcript => {
                self.prompt_editor.cancel_selection();
                self.selection = Some(ActiveSelection::new(pane, position));
            }
            _ => {
                self.clear_selection();
            }
        }
    }

    pub(crate) fn update_selection(&mut self, pane: TuiPane, position: TextPosition) -> bool {
        match pane {
            TuiPane::Prompt => self.update_prompt_selection_at(position.byte),
            TuiPane::Transcript => {
                let Some(selection) = &mut self.selection else {
                    return false;
                };
                if selection.pane != pane {
                    self.selection = None;
                    return true;
                }
                let before = selection.current;
                selection.set_current(position);
                before != position
            }
            _ => false,
        }
    }

    pub(crate) fn finish_selection(
        &mut self,
        pane: TuiPane,
        transcript_wrap_width: u16,
    ) -> Option<String> {
        match pane {
            TuiPane::Prompt => self.prompt_editor.finish_selection(),
            TuiPane::Transcript => {
                let selection = self.selection.take()?;
                if selection.pane != pane {
                    return None;
                }
                let (start, end) = selection.byte_range()?;
                super::transcript_cards::visual_text_for_width(self, transcript_wrap_width.max(1))
                    .get(start..end)
                    .map(ToOwned::to_owned)
                    .filter(|text| !text.is_empty())
            }
            _ => None,
        }
    }

    pub(crate) fn clear_selection(&mut self) -> bool {
        self.prompt_editor.cancel_selection() || self.selection.take().is_some()
    }

    pub(crate) fn transcript_text_position_for_cell(
        &self,
        row: u16,
        column: u16,
        visible_rows: u16,
        wrap_width: u16,
    ) -> Option<TextPosition> {
        let render_scroll = self.transcript_render_scroll(visible_rows, wrap_width);
        super::transcript_cards::text_position_for_visual_cell(
            self,
            render_scroll.saturating_add(usize::from(row)),
            usize::from(column),
            wrap_width,
        )
        .map(|position| TextPosition::new(position.byte, usize::from(row), position.col))
    }

    pub(crate) fn show_copy_success_toast(&mut self, now: Instant) {
        self.toast = Some(ToastState::new(
            COPIED_TO_CLIPBOARD,
            ToastSeverity::Success,
            now,
        ));
    }

    pub(crate) fn show_copy_failure_toast(&mut self, now: Instant) {
        self.toast = Some(ToastState::new(
            "Clipboard copy failed",
            ToastSeverity::Error,
            now,
        ));
    }

    pub(crate) fn set_pending_steering_count(&mut self, count: usize) -> bool {
        let changed = self.pending_steering_count != count;
        self.pending_steering_count = count;
        changed
    }

    pub(crate) fn show_steering_injected_feedback(&mut self, now: Instant) {
        self.status = "Steering injected".to_string();
        self.toast = Some(ToastState::new(
            "Steering injected",
            ToastSeverity::Success,
            now,
        ));
    }

    pub(crate) fn expire_toast(&mut self, now: Instant) -> bool {
        if self.toast.as_ref().is_some_and(|toast| toast.expired(now)) {
            self.toast = None;
            true
        } else {
            false
        }
    }
}

fn no_activity_selected_text() -> &'static str {
    "No activity selected."
}

fn short_session_id(session_id: &str) -> String {
    let char_count = session_id.chars().count();
    if char_count <= 8 {
        return session_id.to_string();
    }
    let prefix: String = session_id.chars().take(4).collect();
    let suffix: String = session_id
        .chars()
        .rev()
        .take(4)
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();
    format!("{prefix}...{suffix}")
}

#[cfg(test)]
mod profiling_support;