rho-coding-agent 2.20.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
use std::time::{Duration, Instant};

use crate::tui::DefaultTerminal;
use crossterm::event::{Event, KeyEventKind};

use crate::herdr::{HerdrDelivery, HerdrSession};

use super::herdr_resume::HerdrSyncStep;
use super::program_status::{BlockedKind, ProgramStatus, ProgramStatusReporter};
use super::{
    media_attach, mouse_capture, ActivityPhase, ActivityStatus, App, BackgroundCounts,
    ComposerMode, ExitReceipt, HerdrState, InteractiveRuntime, PanelOverlay, UserWait,
    ViewModelEvent,
};

/// What blocks the session on the user, while resting or during a turn.
enum UserBlock<'a> {
    /// An approval or questionnaire prompt is open.
    Prompt(UserWait),
    /// No provider is usable until the user signs in.
    Auth(&'a str),
    /// The goal stopped with this reason.
    Goal(&'a str),
}

impl<'a> UserBlock<'a> {
    fn message(&self) -> &'a str {
        match self {
            Self::Prompt(wait) => wait.message(),
            Self::Auth(message) | Self::Goal(message) => message,
        }
    }

    fn program_status(&self) -> ProgramStatus {
        match self {
            Self::Prompt(wait) => ProgramStatus::Blocked {
                kind: Some(match wait {
                    UserWait::Approval => BlockedKind::Permission,
                    UserWait::Questionnaire => BlockedKind::Question,
                }),
                message: wait.message().to_string(),
            },
            Self::Auth(message) => ProgramStatus::Blocked {
                kind: Some(BlockedKind::Auth),
                message: (*message).to_string(),
            },
            Self::Goal(reason) => ProgramStatus::Blocked {
                kind: None,
                message: (*reason).to_string(),
            },
        }
    }
}

impl App {
    /// Drop task work for overlays that closed without their close path (for
    /// example an approval replaced the composer), and drain side chat.
    /// Runs in both idle and running loops.
    pub(super) async fn reconcile_overlays(&mut self) -> anyhow::Result<bool> {
        self.cancel_orphaned_doctor_probes().await;
        self.cancel_orphaned_info_refresh().await;
        self.drop_closed_diff_viewer();
        Ok(self.poll_side_chat())
    }

    fn insert_recovered_history(&mut self) -> std::io::Result<bool> {
        let messages = std::mem::take(&mut self.info.session.recovered_messages);
        let had_recovered_messages = !messages.is_empty();
        let entries = self.transcript_entries(&messages);
        if entries.is_empty() {
            return Ok(had_recovered_messages);
        }

        self.set_history_entries(entries);
        Ok(had_recovered_messages)
    }

    pub(super) fn run<'a>(
        mut self,
        terminal: &'a mut DefaultTerminal,
        agent: &'a mut InteractiveRuntime,
    ) -> impl std::future::Future<
        Output = (anyhow::Result<Option<ExitReceipt>>, ProgramStatusReporter),
    > + 'a {
        // Keep the event-loop future and its construction temporary off the
        // enclosing startup poll frames, which must fit Windows' main stack.
        Box::pin(async move {
            let result = self.run_inner(terminal, agent).await;
            // Return the reporter on both success and error for startup's
            // canonical teardown, without retaining App on its stack frame.
            (result, self.program_status)
        })
    }

    async fn run_inner(
        &mut self,
        terminal: &mut DefaultTerminal,
        agent: &mut InteractiveRuntime,
    ) -> anyhow::Result<Option<ExitReceipt>> {
        self.start_model_metadata_fetch(agent);
        self.start_github_pr_fetch();
        let had_recovered_messages = self.insert_recovered_history()?;
        self.maybe_offer_loaded_session_context_handoff(agent, had_recovered_messages)?;
        let open_resume_after_draw = self.info.session.open_resume_picker;
        self.info.session.open_resume_picker = false;
        // A first launch opens the full-screen setup instead of a session.
        // Afterwards the header and statusline carry setup state, so a
        // signed-out session needs no history entry that would scroll away.
        self.start_setup_screen(terminal);
        self.reconcile_auto_classifier_gate(agent).await?;
        if agent.mcp_connect_pending() {
            self.set_status_quiet("connecting MCP servers");
        }
        let mut needs_redraw = true;
        let mut first_frame = true;
        while !self.should_quit {
            if let Some(run_id) = self
                .workflow_panel
                .take_watch_request()
                .filter(|_| self.can_open_workflow_watch_from_rail())
            {
                let result = async {
                    let Some(run) = self.load_run_for_watch(run_id.parse()?)? else {
                        return Ok(());
                    };
                    self.open_workflow_watch(run, terminal).await
                }
                .await;
                if let Err(error) = result {
                    self.insert_entry(&super::Entry::Error(format!(
                        "could not watch workflow: {error:#}"
                    )));
                }
                needs_redraw = true;
            }
            let background_ready = self.tasks.has_finished()
                || self.prompt_history.load_finished()
                || agent.startup_hydrate_ready();
            needs_redraw |= self.poll_background(terminal, agent, first_frame).await?;
            self.sync_herdr_session().await;
            needs_redraw |= background_ready;
            needs_redraw |= self.update_activity_panels(agent)?;
            needs_redraw |= self
                .poll_subagent_questionnaires(agent.session_id())
                .await?;
            // Subscribe before draining so an exit between drain and wait is not lost.
            let process_exit = agent
                .processes()
                .map(crate::tools::process::ProcessManager::notified_owned);
            needs_redraw |= self.poll_subagent_completions(terminal, agent).await?;
            if needs_redraw {
                terminal.draw(|frame| self.draw(frame))?;
                needs_redraw = false;
                if first_frame {
                    first_frame = false;
                    if open_resume_after_draw {
                        self.open_resume_picker()?;
                    }
                    // Only skip the first event wait when startup work still
                    // needs a loop-top poll. A blanket continue changed paste
                    // timing on ordinary launches.
                    if open_resume_after_draw || self.info.session.startup_prompt.is_some() {
                        needs_redraw = true;
                        continue;
                    }
                }
            }
            let subagents_active = agent.subagents().is_some_and(|manager| {
                manager.has_active_or_pending_notification(agent.session_id().as_str())
            }) || agent
                .workflow_tracker()
                .has_active_or_pending_notification(agent.session_id().as_str())
                || agent
                    .processes()
                    .is_some_and(crate::tools::process::ProcessManager::has_pending_notification)
                || self.pending_subagent_questionnaire.is_some()
                || self.subagent_inbox.has_queued_questionnaires()
                || self.subagent_inbox.has_parent_action_requests();
            let idle_timeout = if self.tasks.has_pending()
                || self.computer_lifecycle_pending()
                || self.prompt_history.load_pending()
                || self.pending_session_title.is_some()
                || self.mcp_argument_completions.is_pending()
                || self.exclusive.wants_fast_ticks()
                || !self.pending_inline_shells.is_empty()
                || self.history.images().has_pending()
                || agent.startup_hydrate_pending()
                || self.loading_active()
                || self.side_chat_busy()
            {
                Duration::from_millis(100)
            } else if subagents_active
                || self.process_panel.is_active()
                || self.questionnaire_timeout_running()
            {
                Duration::from_millis(500)
            } else if self.info.services.herdr.is_enabled() {
                super::herdr_resume::HERDR_SYNC_INTERVAL
            } else {
                Duration::from_secs(3600)
            };
            // About to wait for the user: a turn that finished since the
            // last wait notifies now, once per batch of turns, and the
            // terminal hears the resting status at the same moment.
            let notification = self.notifier.take_ready();
            self.send_notification(notification);
            let resting = self.resting_program_status();
            self.report_program_status(resting);
            let redraw_on_timeout = self.animation_active(Instant::now());
            let timeout = self.event_poll_timeout(idle_timeout);
            let media_attach_pending = !self.media_attach_tasks.is_empty();
            tokio::select! {
                biased;
                event = self.terminal_session.as_mut().expect("terminal session initialized").next_event() => {
                    self.handle_terminal_event(event?, terminal, agent).await?;
                    needs_redraw = true;
                    needs_redraw |= self.flush_due_paste_burst();
                }
                () = self.subagent_inbox.recv() => {
                    needs_redraw = true;
                }
                () = async {
                    match process_exit {
                        Some(notified) => notified.await,
                        None => std::future::pending().await,
                    }
                } => {
                    needs_redraw = true;
                }
                outcome = media_attach::next_media_attach_completion(&mut self.media_attach_tasks), if media_attach_pending => {
                    self.finish_media_attach(outcome);
                    needs_redraw = true;
                }
                output = super::sessions_hub_tasks::next_sessions_task(&mut self.pending_sessions_task) => {
                    self.finish_sessions_task(output)?;
                    needs_redraw = true;
                }
                _ = tokio::time::sleep(timeout) => {
                    needs_redraw |= self.questionnaire_timeout_running();
                    needs_redraw |= self.tick_questionnaire_timeout();
                    needs_redraw |= self.flush_due_paste_burst();
                    needs_redraw |= redraw_on_timeout;
                }
            }
        }
        self.prompt_history.flush();
        self.abort_compact(agent).await;
        self.tasks.cancel_all().await;
        agent.cancel_startup_hydrates();
        self.mcp_argument_completions.cancel();
        if let Some(mut pending) = self.pending_session_title.take() {
            pending.cancel();
            let _ = (&mut pending).await;
        }
        Ok(self.exit_receipt())
    }

    fn poll_background<'a>(
        &'a mut self,
        terminal: &'a mut DefaultTerminal,
        agent: &'a mut InteractiveRuntime,
        first_frame: bool,
    ) -> impl std::future::Future<Output = anyhow::Result<bool>> + 'a {
        // Background work and input dispatch are separate phases. Do not keep
        // background future temporaries on the stack while handling input.
        Box::pin(async move {
            let mut needs_redraw = self.apply_finished_tasks(terminal, agent).await?;
            needs_redraw |= self.apply_pending_compaction_config(agent)?;
            self.apply_pending_classifier_config(agent);
            needs_redraw |= self.poll_startup_hydrates(agent).await?;
            needs_redraw |= self.poll_computer_connection(agent).await;
            needs_redraw |= self.poll_compact(agent).await?;
            needs_redraw |= self.apply_pending_permission_mode(agent).await?;
            needs_redraw |= self.release_pending_held_turn(terminal, agent).await?;
            needs_redraw |= self.start_next_follow_up(terminal, agent).await?;
            if !first_frame {
                needs_redraw |= self.start_startup_prompt(terminal, agent).await?;
            }
            needs_redraw |= self.poll_prompt_history();
            needs_redraw |= self.poll_pending_session_title()?;
            needs_redraw |= self.reconcile_overlays().await?;
            // The composer decides what to ask about and changes on key events.
            needs_redraw |= self.poll_mcp_argument_completion().await;
            needs_redraw |= self.poll_markdown_images();
            let shell_changed = self.finish_completed_inline_shells().await?;
            if !self.is_ui_busy() {
                self.insert_deferred_inline_shell_context(agent)?;
                needs_redraw |= self.start_deferred_info_tree();
            }
            needs_redraw |= shell_changed;
            Ok(needs_redraw)
        })
    }

    pub(super) async fn handle_terminal_event(
        &mut self,
        event: Event,
        terminal: &mut DefaultTerminal,
        agent: &mut InteractiveRuntime,
    ) -> anyhow::Result<()> {
        self.observe_questionnaire_input(&event);
        self.notifier.observe_focus(&event);
        match self.take_exclusive_event(event) {
            Ok(resize) => {
                if resize {
                    self.apply_terminal_resize(terminal)?;
                }
                return Ok(());
            }
            Err(event) => match event {
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    self.clear_selections();
                    self.subagent_panel.clear_pointer_state();
                    self.process_panel.clear_pointer_state();
                    self.workflow_panel.clear_pointer_state();
                    self.handle_key(key, terminal, agent).await?;
                }
                Event::Paste(text) => {
                    self.input_ui.cancel_pointer_click_sequence();
                    self.apply_external_paste(&text);
                }
                Event::Resize(_, _) => {
                    self.apply_terminal_resize(terminal)?;
                }
                Event::Mouse(mouse) => {
                    self.flush_pending_paste_burst();
                    // Drop an action a running-turn event left behind, so only
                    // this event's pointer can fire one.
                    self.input_ui.take_pointer_action();
                    self.handle_mouse_event(mouse.kind, mouse.column, mouse.row, terminal)?;
                    if let Some(action) = self.input_ui.take_pointer_action() {
                        // Boxed like idle modal keys, so resolver futures stay
                        // out of this event's poll frame.
                        Box::pin(self.run_idle_pointer_action(action, terminal, agent)).await?;
                    }
                }
                Event::FocusGained => self.on_focus_gained(),
                Event::FocusLost => {
                    self.input_ui.cancel_pointer_click_sequence();
                    self.input_ui.finalize_selection();
                    self.settle_side_composer_pointer();
                    self.subagent_panel.clear_pointer_state();
                    self.process_panel.clear_pointer_state();
                    self.workflow_panel.clear_pointer_state();
                }
                Event::Key(_) => {}
            },
        }
        Ok(())
    }

    pub(super) fn on_focus_gained(&mut self) {
        self.input_ui.cancel_pointer_click_sequence();
        // Some Windows hosts drop application mouse tracking on focus
        // changes; re-assert so wheel scrolling keeps working.
        mouse_capture::reassert();
        self.refresh_workspace_on_focus();
    }

    pub(super) fn event_poll_timeout(&self, idle_timeout: Duration) -> Duration {
        // Each frame measures one slice of older rows; input still wins the race.
        if self.transcript_search_indexing() {
            return Duration::ZERO;
        }
        let now = Instant::now();
        let timeout = self.input_ui.paste_burst().poll_timeout(now, idle_timeout);
        let timeout = self
            .history
            .copy_notice()
            .and_then(|notice| notice.visible_until().checked_duration_since(now))
            .map_or(timeout, |remaining| remaining.min(timeout));
        let timeout = self
            .status_overlay
            .as_ref()
            .and_then(|overlay| overlay.visible_until().checked_duration_since(now))
            .map_or(timeout, |remaining| remaining.min(timeout));
        if self.history.scrollbar_hovered() || self.history.scrollbar_drag().is_some() {
            return timeout;
        }
        self.history
            .scrollbar_visible_until()
            .and_then(|visible_until| visible_until.checked_duration_since(now))
            .map_or(timeout, |remaining| remaining.min(timeout))
    }

    pub(super) fn animation_active(&self, now: Instant) -> bool {
        self.loading_active()
            || self.transcript_search_indexing()
            || self.exclusive_should_redraw(now)
            || self.subagent_panel.is_active()
            || self.process_panel.is_active()
            || self.workflow_panel.is_active()
            || self
                .history
                .copy_notice()
                .is_some_and(|notice| now < notice.visible_until())
            || self
                .status_overlay
                .as_ref()
                .is_some_and(|overlay| overlay.is_visible(now))
            || matches!(
                self.input_ui.composer(),
                ComposerMode::Panel(PanelOverlay::Limits(overlay)) if overlay.is_checking()
            )
            || matches!(
                self.input_ui.composer(),
                ComposerMode::Panel(PanelOverlay::Doctor(overlay)) if overlay.is_checking()
            )
            || matches!(
                self.input_ui.composer(),
                ComposerMode::Panel(PanelOverlay::Spend(overlay)) if overlay.shows_spinner()
            )
            || self.side_chat_busy()
            || self.history.scrollbar_hovered()
            || self.history.scrollbar_drag().is_some()
            || self
                .history
                .scrollbar_visible_until()
                .is_some_and(|until| now < until)
    }

    pub(super) async fn report_herdr_state(&mut self, state: HerdrState, message: Option<&str>) {
        if !self.info.services.herdr.is_enabled() {
            return;
        }
        let (key, session) = self.current_herdr_session();
        self.herdr_sync.note_sent(session.as_ref());
        let delivery = self
            .info
            .services
            .herdr
            .report_state(state, message, session.as_ref())
            .await;
        self.confirm_herdr_claim(key, session.as_ref(), delivery);
    }

    /// Writes a notification unless config turned them off or Herdr, which
    /// already shows pane state, owns them.
    fn send_notification(&self, bytes: Option<Vec<u8>>) {
        let enabled = self.info.runtime.notifications && !self.info.services.herdr.is_enabled();
        if let Some(bytes) = bytes.filter(|_| enabled) {
            super::notifications::write_to_terminal(&bytes);
        }
    }

    /// Claims the pane before the first frame without delaying it. The report
    /// is built here so its `seq` precedes any report the first frame sends.
    /// Delivery is not awaited: until a claim is confirmed,
    /// [`Self::sync_herdr_session`] keeps claiming.
    pub(super) fn spawn_initial_herdr_report(&mut self) {
        let herdr = self.info.services.herdr.clone();
        if !herdr.is_enabled() {
            return;
        }
        let session = self.herdr_session();
        let message = self.info.services.auth_unavailable.as_deref();
        let state = if message.is_some() {
            HerdrState::Blocked
        } else {
            HerdrState::Idle
        };
        if let Some(report) = herdr.state_report(state, message, session.as_ref()) {
            self.herdr_sync.note_sent(session.as_ref());
            tokio::spawn(async move {
                let _ = herdr.send(report).await;
            });
        }
    }

    /// Brings Herdr in line with the session and the resume command pins:
    /// a new, switched, or dropped session, `/model`, `/permissions`,
    /// reasoning, or a config change from another pane. Runs every loop pass;
    /// a failed report stays pending and is retried on the next pass.
    pub(super) async fn sync_herdr_session(&mut self) {
        if !self.info.services.herdr.is_enabled() {
            return;
        }
        let (key, step) = self.herdr_sync_step();
        let herdr = self.info.services.herdr.clone();
        match step {
            HerdrSyncStep::InSync => {}
            HerdrSyncStep::Claim(session) => self.claim_herdr_pane(key, session).await,
            HerdrSyncStep::Report(session) => {
                self.herdr_sync.note_sent(Some(&session));
                if let HerdrDelivery::Accepted = herdr.report_session(&session).await {
                    self.accept_herdr_key(key);
                }
            }
            HerdrSyncStep::Reclaim(session) => match herdr.release().await {
                HerdrDelivery::Accepted => {
                    self.herdr_sync.note_released();
                    self.claim_herdr_pane(key, session).await;
                }
                HerdrDelivery::Failed => {}
            },
        }
    }

    /// Claims the pane in the current resting state. Herdr takes a resume
    /// command on a claim like this, not on a session update before one.
    async fn claim_herdr_pane(
        &mut self,
        key: super::herdr_resume::HerdrResumeKey,
        session: Option<HerdrSession>,
    ) {
        let (state, message) = self.resting_herdr_state();
        let message = message.map(str::to_string);
        self.herdr_sync.note_sent(session.as_ref());
        let delivery = self
            .info
            .services
            .herdr
            .report_state(state, message.as_deref(), session.as_ref())
            .await;
        self.confirm_herdr_claim(key, session.as_ref(), delivery);
    }

    /// A turn or tool run is in progress.
    pub(super) async fn report_working(&mut self) {
        self.report_program_status(ProgramStatus::Working);
        self.report_herdr_state(HerdrState::Working, None).await;
    }

    /// A prompt now blocks the agent on the user: notify an unfocused
    /// terminal and show the wait in Herdr and the terminal's program status.
    pub(super) async fn wait_for_user(&mut self, wait: UserWait) {
        let notification = self.notifier.user_wait(wait);
        self.send_notification(notification);
        let block = UserBlock::Prompt(wait);
        self.report_program_status(block.program_status());
        self.report_herdr_state(HerdrState::Blocked, Some(block.message()))
            .await;
    }

    /// Reports the resting state to Herdr. The terminal's program status
    /// follows once the event loop waits for input, so a goal run or queued
    /// follow-ups do not flash `done` between turns.
    pub(super) async fn report_resting_herdr_state(&mut self) {
        let (state, message) = self.resting_herdr_state();
        let message = message.map(str::to_string);
        self.report_herdr_state(state, message.as_deref()).await;
    }

    /// The state Herdr should show while no turn runs.
    fn resting_herdr_state(&self) -> (HerdrState, Option<&str>) {
        match self.resting_wait() {
            Some(wait) => (HerdrState::Blocked, Some(wait.message())),
            None => (HerdrState::Idle, None),
        }
    }

    /// The program status while no turn runs.
    fn resting_program_status(&self) -> ProgramStatus {
        match self.resting_wait() {
            Some(wait) => wait.program_status(),
            None => self.settled_program_status.clone(),
        }
    }

    fn resting_wait(&self) -> Option<UserBlock<'_>> {
        let prompt = match self.input_ui.composer() {
            ComposerMode::Approval(_) => Some(UserWait::Approval),
            ComposerMode::Questionnaire(_) => Some(UserWait::Questionnaire),
            ComposerMode::Input
            | ComposerMode::Picker(_)
            | ComposerMode::Panel(_)
            | ComposerMode::Side
            | ComposerMode::SecretInput(_)
            | ComposerMode::ConfigNumberInput(_)
            | ComposerMode::TextInput(_)
            | ComposerMode::TranscriptSearch(_)
            | ComposerMode::InteractivePending(_)
            | ComposerMode::InlineChoice(_) => None,
        };
        if let Some(prompt) = prompt {
            return Some(UserBlock::Prompt(prompt));
        }
        if let Some(message) = self.info.services.auth_unavailable.as_deref() {
            return Some(UserBlock::Auth(message));
        }
        self.goal
            .as_ref()
            .filter(|goal| goal.is_blocked())
            .and_then(|goal| goal.last_reason.as_deref())
            .map(UserBlock::Goal)
    }

    /// Writes a program status report the terminal has not heard yet.
    fn report_program_status(&mut self, status: ProgramStatus) {
        if let Some(bytes) = self.program_status.report(status) {
            super::notifications::write_to_terminal(&bytes);
        }
    }

    pub(super) fn activity_status(&self) -> Option<ActivityStatus> {
        // Keep the activity rail in zen mode. Zen only strips transcript chrome
        // (tools, reasoning, Thinking...); live status still belongs on screen so
        // subagent rows are not an orphaned full-width strip.
        let phase = match self.input_ui.composer() {
            ComposerMode::Approval(_) => ActivityPhase::WaitingForApproval,
            ComposerMode::Questionnaire(_) => ActivityPhase::WaitingForInput,
            _ => self.turn.activity_phase(),
        };
        let retry = match self.input_ui.composer() {
            ComposerMode::Approval(_) | ComposerMode::Questionnaire(_) => None,
            _ => self.turn.provider_retry(),
        };
        ActivityStatus::from_parent_and_background(
            self.loading_active().then_some((phase, retry)),
            BackgroundCounts {
                subagent_count: self.subagent_panel.count(),
                job_count: self.process_panel.live_count(),
                workflow_count: self.workflow_panel.live_count(),
            },
            self.subagent_panel.is_active()
                || self.process_panel.is_active()
                || self.workflow_panel.is_active(),
        )
    }

    pub(super) fn apply_terminal_resize(
        &mut self,
        terminal: &mut DefaultTerminal,
    ) -> std::io::Result<()> {
        self.flush_pending_paste_burst();
        self.clamp_overlay_detail_scroll(terminal);
        self.clamp_panel_overlay_scroll(terminal);
        self.clear_selections();
        self.clear_hovered_copy_buttons();
        self.subagent_panel.clear_pointer_state();
        self.process_panel.clear_pointer_state();
        self.workflow_panel.clear_pointer_state();
        self.hide_history_scrollbar();
        self.clamp_history_scroll_for_terminal(terminal)
    }

    pub(super) fn update_activity_panels(
        &mut self,
        agent: &InteractiveRuntime,
    ) -> anyhow::Result<bool> {
        // Tick the occupant first so a journal read error cannot leave panel
        // costs half-applied.
        let mut changed = self.refresh_exclusive_screen()?;
        let panel_changed = self
            .subagent_panel
            .update(agent.subagents(), agent.session_id().as_str());
        if panel_changed {
            self.refresh_attach_picker();
        }
        changed |= panel_changed;
        changed |= self.process_panel.update(agent.processes());
        changed |= self
            .workflow_panel
            .update(agent.workflow_tracker(), agent.session_id().as_str());
        changed |= self.refresh_todo_list(agent);
        // Fold terminal subagent/advisor costs on every panel refresh path (idle
        // poll, in-turn wait, goal wait). Claiming is idempotent per run/call.
        changed |= self.claim_non_main_costs(agent);
        changed |= self.apply_finished_ui_tasks();
        self.restore_mcp_hold_activity_if_needed(agent.mcp_connect_pending());
        if self.activity_status().is_some() {
            self.turn.start_loading_if_needed();
        }
        Ok(changed)
    }

    /// Pull finished non-main costs into the parent session total.
    fn claim_non_main_costs(&mut self, agent: &InteractiveRuntime) -> bool {
        let mut changed = false;
        if let Some(manager) = agent.subagents() {
            let claimed = manager.claim_terminal_costs_usd_micros(agent.session_id().as_str());
            if claimed > 0 {
                self.usage.subagent_total_cost_usd_micros = self
                    .usage
                    .subagent_total_cost_usd_micros
                    .saturating_add(claimed);
                changed = true;
            }
        }
        if let Some(advisor) = agent.advisor() {
            let claimed = advisor.claim_cost_usd_micros();
            if claimed > 0 {
                self.usage.advisor_total_cost_usd_micros = self
                    .usage
                    .advisor_total_cost_usd_micros
                    .saturating_add(claimed);
                changed = true;
            }
        }
        changed
    }

    pub(super) fn loading_active(&self) -> bool {
        self.is_ui_busy()
            || self.streams.loading_streams_active()
            || matches!(self.turn.activity_phase(), ActivityPhase::ConnectingMcp)
    }

    pub(super) fn handle_queued_agent_event(
        &mut self,
        event: ViewModelEvent,
        terminal: &mut DefaultTerminal,
    ) -> Result<bool, rho_providers::model::ModelError> {
        Ok(self.handle_agent_event(event, terminal)?)
    }

    pub(super) fn reset_usage(&mut self) {
        self.usage.cumulative_usage = None;
        self.usage.usage_cost_tracker.reset();
        self.usage.usage_before_current_run = None;
        self.usage.run_usage.clear();
        self.usage.subagent_total_cost_usd_micros = 0;
        self.usage.advisor_total_cost_usd_micros = 0;
        self.usage.latest_usage = None;
        self.usage.model_performance.clear();
        self.usage.cache_stats.reset();
    }

    fn exit_receipt(&self) -> Option<ExitReceipt> {
        self.info.session.session_id.as_ref().map(|session_id| {
            ExitReceipt::capture(
                session_id.clone(),
                self.session_title(),
                self.usage.cumulative_usage.as_ref(),
                self.model_metadata.as_ref(),
                self.usage.extra_cost_usd_micros(),
            )
        })
    }
}