rho-coding-agent 3.5.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
//! `/jobs`: every job the daemon runs, across projects, in one list, with
//! the keys to act on the selected one (#1668).
//!
//! The list is `rho/job/list`, which the daemon rail already polls; the
//! view takes each answer while it is open. A row's keys send their
//! requests on the followed session's connection and go on without
//! waiting; a request the daemon refuses shows as the view's notice. A
//! request another session waits on is answered by that session's id, with
//! no attachment to it, so the view answers prompts in any project.
//! Attaching switches the session this TUI follows, and moves the TUI to
//! that session's workspace (`daemon_switch`).

use std::{
    collections::HashMap,
    path::PathBuf,
    sync::{Arc, Mutex, PoisonError},
    time::Instant,
};

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
    style::Modifier,
    text::{Line, Span},
};
use rho_protocol::{
    methods::{SessionAnswer, SessionCancel, SessionNew, SessionPrompt, SessionSteer},
    Ask, ClientEnvironment, ContentBlock, ErrorCode, InputAnswer, InputRequest, JobId, JobKind,
    JobState, JobSummary, PromptAuthor, SessionAnswerParams, SessionCancelParams, SessionId,
    SessionNewParams, SessionPart, SessionPromptParams, SessionSteerParams,
};

use super::{
    approval::ApprovalPrompt,
    daemon_launch::{DaemonLaunch, DaemonTarget},
    overlay_panel::{reveal_panel_cursor, terminal_area, PanelBody, PanelKeyOutcome, PanelState},
    panel_text::indented_wrapped_lines,
    render::truncate_one_line,
    App, ComposerMode, DefaultTerminal, PanelOverlay, Theme,
};
use crate::{
    app::daemon_client::{Daemon, DaemonError},
    session::{Session, SessionTarget},
};

mod rows;

use rows::{groups, needs_input, Group, Row, Status};

const BROWSE_FOOTER: &str =
    "↑↓ · Enter attach · m message · c cancel · n new · / filter · Tab next ask · Esc close";
const ASK_FOOTER: &str =
    "y allow once · a allow for session · d deny · ↑↓ · Enter attach · Esc close";
const INPUT_FOOTER: &str = "Enter confirm · Esc cancel";
const NEW_FOOTER: &str = "Enter confirm · Tab worktree · Esc cancel";

/// What the view's keys go to.
#[derive(Debug)]
enum Mode {
    /// The list: keys select a row and act on it.
    Browse,
    /// Typing the filter, which applies as it is typed.
    Filter,
    /// Typing a message for session `session`, which steers its turn when
    /// one is under way as the message is sent, and starts its next when
    /// none is.
    Message { session: SessionId, text: String },
    /// Typing the directory a new session works in, and whether it works
    /// in a git worktree of its own there (#1673), which Tab toggles.
    NewWorkspace { path: String, worktree: bool },
    /// Typing the new session's first prompt.
    NewPrompt {
        workspace: PathBuf,
        worktree: bool,
        text: String,
    },
}

/// What closing the view asks of the TUI: to follow this session.
#[derive(Debug)]
pub(super) struct Attach(SessionId);

/// The `/jobs` overlay.
pub(super) struct JobsView {
    daemon: Arc<Daemon>,
    /// The session this TUI follows, whose job the view opens on; none
    /// before its first prompt opened it.
    followed: Option<SessionId>,
    /// What this TUI opens its sessions with. A session started here opens
    /// with its setup, though always saved, and in the followed session's
    /// workspace as the launch's agent too, so attaching finds the agent
    /// the launch named; following a session there already checked that
    /// agent. Another workspace may not define it, so a session there runs
    /// as its default.
    launch: DaemonLaunch,
    /// The daemon's jobs as last listed; `None` before the first answer.
    jobs: Option<Vec<JobSummary>>,
    selected: Option<JobId>,
    filter: String,
    mode: Mode,
    /// Why the last request failed, until the next key.
    notice: Arc<Mutex<Option<String>>>,
    /// The messages left unsent, with Esc or because the daemon refused
    /// them, by the session each was for, which `m` on that session takes
    /// up again.
    drafts: Arc<Mutex<HashMap<SessionId, String>>>,
    /// The session whose turn the last key, `c`, asked to cancel, which a
    /// second `c` confirms.
    cancel_armed: Option<SessionId>,
    attach: Option<Attach>,
    panel: PanelState,
}

impl std::fmt::Debug for JobsView {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("JobsView")
            .field("selected", &self.selected)
            .field("mode", &self.mode)
            .finish_non_exhaustive()
    }
}

impl JobsView {
    fn new(daemon: Arc<Daemon>, followed: Option<SessionId>, launch: DaemonLaunch) -> Self {
        Self {
            daemon,
            followed,
            launch,
            jobs: None,
            selected: None,
            filter: String::new(),
            mode: Mode::Browse,
            notice: Arc::default(),
            drafts: Arc::default(),
            cancel_armed: None,
            attach: None,
            panel: PanelState::default(),
        }
    }

    fn groups(&self) -> Vec<Group> {
        groups(self.jobs.as_deref().unwrap_or_default(), &self.filter)
    }

    fn job(&self, id: &JobId) -> Option<&JobSummary> {
        self.jobs.as_ref()?.iter().find(|job| &job.id == id)
    }

    fn selected_job(&self) -> Option<&JobSummary> {
        self.job(self.selected.as_ref()?)
    }

    /// Takes the daemon's latest list, keeping the selection on its job
    /// while that is listed. The first list selects the followed session's
    /// job. Returns whether the selection's rows may have moved or grown,
    /// so the view scrolls to them again.
    fn show(&mut self, jobs: Vec<JobSummary>) -> bool {
        let before = self.cursor_place();
        if self.jobs.is_none() {
            self.selected = jobs
                .iter()
                .find(|job| job.session.is_some() && job.session == self.followed)
                .map(|job| job.id.clone());
        }
        self.jobs = Some(jobs);
        self.select_listed();
        before != self.cursor_place()
    }

    /// Where the selection is in the list, and whether its job asks
    /// something, which shows under its row.
    fn cursor_place(&self) -> (Option<usize>, bool) {
        let at = self
            .selected
            .as_ref()
            .and_then(|selected| self.listed().iter().position(|job| job == selected));
        (at, self.open_request().is_some())
    }

    /// Moves the selection to a listed row when it names none.
    fn select_listed(&mut self) {
        let listed: Vec<JobId> = self.listed();
        if !self
            .selected
            .as_ref()
            .is_some_and(|selected| listed.contains(selected))
        {
            self.selected = listed.into_iter().next();
        }
    }

    /// The listed jobs, in row order.
    fn listed(&self) -> Vec<JobId> {
        self.groups()
            .into_iter()
            .flat_map(|group| group.rows)
            .map(|row| row.job)
            .collect()
    }

    /// Moves the selection `by` rows, stopping at either end.
    fn step(&mut self, by: isize) {
        let listed = self.listed();
        let at = self
            .selected
            .as_ref()
            .and_then(|selected| listed.iter().position(|job| job == selected));
        let next = match at {
            Some(at) => at
                .saturating_add_signed(by)
                .min(listed.len().saturating_sub(1)),
            None => 0,
        };
        self.selected = listed.into_iter().nth(next);
    }

    /// Selects the next job after the selection that needs input, wrapping.
    fn jump_to_needs_input(&mut self) {
        let listed = self.listed();
        let start = self
            .selected
            .as_ref()
            .and_then(|selected| listed.iter().position(|job| job == selected))
            .map_or(0, |at| at + 1);
        let next = (0..listed.len())
            .map(|offset| &listed[(start + offset) % listed.len()])
            .find(|id| self.job(id).is_some_and(needs_input));
        match next {
            Some(next) => self.selected = Some(next.clone()),
            None => self.say("no job needs input"),
        }
    }

    fn say(&self, notice: impl Into<String>) {
        *self.notice.lock().unwrap_or_else(PoisonError::into_inner) = Some(notice.into());
    }

    fn notice(&self) -> Option<String> {
        self.notice
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }

    /// Sends `request` without waiting; a refusal becomes the notice
    /// `could not <what>: <why>`.
    fn send<F, E>(&self, what: &'static str, request: impl FnOnce(Arc<Daemon>) -> F)
    where
        F: std::future::Future<Output = Result<(), E>> + Send + 'static,
        E: std::fmt::Display,
    {
        let notice = Arc::clone(&self.notice);
        let request = request(Arc::clone(&self.daemon));
        tokio::spawn(async move {
            if let Err(error) = request.await {
                *notice.lock().unwrap_or_else(PoisonError::into_inner) =
                    Some(format!("could not {what}: {error}"));
            }
        });
    }

    /// The selected job's oldest open request, with the session it is
    /// answered on.
    fn open_request(&self) -> Option<(&SessionId, &InputRequest)> {
        let job = self.selected_job()?;
        let request = job.live.as_ref()?.inputs.first()?;
        Some((job.session.as_ref()?, request))
    }

    /// Answers the selected job's open approval with `answer`.
    fn answer(&self, answer: InputAnswer) {
        let Some((session, request)) = self.open_request() else {
            return;
        };
        let params = SessionAnswerParams {
            session: session.clone(),
            request: request.id,
            answer,
        };
        self.send("answer the request", |daemon| async move {
            daemon.request::<SessionAnswer>(&params).await.map(|_| ())
        });
    }

    /// The session a message, a cancel, or an attach for the selected job
    /// goes to: the job's own, or for a run, the session that started it.
    fn session_of_selected(&self) -> Option<&SessionId> {
        let jobs = self.jobs.as_ref()?;
        let mut job = self.selected_job()?;
        // Each step goes up one job, so a chain is never longer than the
        // list.
        for _ in 0..jobs.len() {
            if job.kind == JobKind::Session {
                return job.session.as_ref();
            }
            let parent = job.parent.as_ref()?;
            job = jobs.iter().find(|job| &job.id == parent)?;
        }
        None
    }

    /// The project the selected job lists under, as `rows::groups` groups
    /// it: a run nested under a session in a worktree lists under that
    /// session's project, not the worktree it runs in.
    fn selected_project(&self) -> Option<PathBuf> {
        let selected = self.selected.as_ref()?;
        self.groups()
            .into_iter()
            .find(|group| group.rows.iter().any(|row| &row.job == selected))
            .map(|group| group.workspace)
    }

    /// Cancels the turn of the selected job's session, at the second `c`
    /// in a row on it: `c` copies in every other panel, and a cancelled
    /// turn does not come back.
    fn cancel(&mut self) {
        let Some(session) = self.session_of_selected() else {
            return self.say("could not cancel job: no session of the daemon's started it");
        };
        let session = session.clone();
        if self.cancel_armed.take().as_ref() != Some(&session) {
            self.say("c again cancels this session's turn");
            self.cancel_armed = Some(session);
            return;
        }
        let params = SessionCancelParams { session };
        self.send("cancel the turn", |daemon| async move {
            daemon.request::<SessionCancel>(&params).await.map(|_| ())
        });
    }

    fn begin_message(&mut self) {
        let Some(session) = self.session_of_selected() else {
            return self.say("could not message job: no session of the daemon's started it");
        };
        let session = session.clone();
        if self.waits_on_request(&session) {
            return self.say("could not message job: it waits on a request; answer it first");
        }
        let text = self
            .drafts
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(&session)
            .unwrap_or_default();
        self.mode = Mode::Message { session, text };
    }

    /// Whether `session`'s turn waits on a request of its own, as last
    /// listed.
    fn waits_on_request(&self, session: &SessionId) -> bool {
        self.jobs.iter().flatten().any(|job| {
            job.kind == JobKind::Session
                && job.session.as_ref() == Some(session)
                && job.state == JobState::WaitingForInput
        })
    }

    /// Whether `session`'s job has a turn under way, as last listed.
    fn turn_under_way(&self, session: &SessionId) -> bool {
        self.jobs.iter().flatten().any(|job| {
            job.kind == JobKind::Session
                && job.session.as_ref() == Some(session)
                && job.state.in_progress()
        })
    }

    fn begin_new_session(&mut self) {
        let workspace = self
            .selected_project()
            .unwrap_or_else(|| self.launch.cwd.clone());
        self.mode = Mode::NewWorkspace {
            path: workspace.to_string_lossy().into_owned(),
            worktree: false,
        };
    }

    /// Runs the input a mode held once Enter confirmed it.
    fn confirm(&mut self) {
        match std::mem::replace(&mut self.mode, Mode::Browse) {
            Mode::Browse | Mode::Filter => {}
            Mode::Message { text, .. } if text.trim().is_empty() => {}
            // A turn waiting on a request takes neither a steer nor a
            // prompt: the draft stays, and Esc keeps it for the next `m`
            // once the request is answered from the list.
            Mode::Message { session, text } if self.waits_on_request(&session) => {
                self.mode = Mode::Message { session, text };
                self.say(
                    "could not send the message: the session waits on a request; \
                     Esc keeps this draft while you answer it",
                );
            }
            Mode::Message { session, text } => {
                // A message the daemon refuses comes back as the draft.
                let under_way = self.turn_under_way(&session);
                let drafts = Arc::clone(&self.drafts);
                self.send("send the message", move |daemon| async move {
                    let sent = message(daemon, session.clone(), text.clone(), under_way).await;
                    if sent.is_err() {
                        drafts
                            .lock()
                            .unwrap_or_else(PoisonError::into_inner)
                            .insert(session, text);
                    }
                    sent
                });
            }
            Mode::NewWorkspace { path, worktree } => {
                let workspace = PathBuf::from(path.trim());
                if workspace.is_absolute() {
                    self.mode = Mode::NewPrompt {
                        workspace,
                        worktree,
                        text: String::new(),
                    };
                } else {
                    // Kept, so the path is fixed rather than typed again.
                    self.mode = Mode::NewWorkspace { path, worktree };
                    self.say("could not start session: the workspace must be an absolute path");
                }
            }
            Mode::NewPrompt { text, .. } if text.trim().is_empty() => {}
            Mode::NewPrompt {
                workspace,
                worktree,
                text,
            } => {
                let mut setup = self.launch.setup.clone();
                // Saved even under `--no-save`: no client follows it, so
                // one kept in memory alone is discarded once idle, and
                // attaching finds a session by its file.
                setup.without.remove(&SessionPart::Saving);
                // The same directory however each path spells it: the
                // daemon lists a workspace canonicalized, and a typed path
                // or the followed workspace's need not be. A path that does not resolve
                // is compared as written.
                let resolved = |path: &PathBuf| {
                    crate::paths::canonicalize(path).unwrap_or_else(|_| path.clone())
                };
                let agent = (resolved(&workspace) == resolved(&self.launch.cwd))
                    .then(|| self.launch.agent.clone())
                    .flatten();
                self.send("start session", |daemon| async move {
                    let params = SessionNewParams {
                        cwd: workspace,
                        environment: ClientEnvironment::of_this_process(),
                        agent,
                        setup,
                        parent: None,
                        grant: None,
                        worktree,
                    };
                    let opened = daemon.request::<SessionNew>(&params).await?;
                    // Nothing runs in a checkout the person kept it out of.
                    crate::worktree::require(worktree, opened.worktree.as_ref())?;
                    Ok::<_, anyhow::Error>(prompt(daemon, opened.session, text).await?)
                });
            }
        }
    }

    /// The text a typing mode edits.
    fn input_mut(&mut self) -> Option<&mut String> {
        match &mut self.mode {
            Mode::Browse => None,
            Mode::Filter => Some(&mut self.filter),
            Mode::Message { text, .. } | Mode::NewPrompt { text, .. } => Some(text),
            Mode::NewWorkspace { path, .. } => Some(path),
        }
    }

    fn typing_key(&mut self, key: KeyEvent) -> PanelKeyOutcome {
        match (key.modifiers, key.code) {
            (KeyModifiers::CONTROL, KeyCode::Char('c')) => return PanelKeyOutcome::Unhandled,
            (_, KeyCode::Esc) => match std::mem::replace(&mut self.mode, Mode::Browse) {
                Mode::Filter => self.filter.clear(),
                // Kept, so a request that held it back can be answered
                // from the list first.
                Mode::Message { session, text } if !text.trim().is_empty() => {
                    self.drafts
                        .lock()
                        .unwrap_or_else(PoisonError::into_inner)
                        .insert(session, text);
                }
                Mode::Browse
                | Mode::Message { .. }
                | Mode::NewWorkspace { .. }
                | Mode::NewPrompt { .. } => {}
            },
            (_, KeyCode::Enter) => self.confirm(),
            (_, KeyCode::Tab) => {
                if let Mode::NewWorkspace { worktree, .. } | Mode::NewPrompt { worktree, .. } =
                    &mut self.mode
                {
                    *worktree = !*worktree;
                }
            }
            (_, KeyCode::Backspace) => {
                if let Some(input) = self.input_mut() {
                    input.pop();
                }
            }
            (KeyModifiers::NONE | KeyModifiers::SHIFT, KeyCode::Char(typed)) => {
                if let Some(input) = self.input_mut() {
                    input.push(typed);
                }
            }
            _ => {}
        }
        self.select_listed();
        PanelKeyOutcome::Handled
    }

    fn browse_key(&mut self, key: KeyEvent) -> PanelKeyOutcome {
        let approval = matches!(
            self.open_request(),
            Some((
                _,
                InputRequest {
                    ask: Ask::Approval(_),
                    ..
                }
            ))
        );
        match (key.modifiers, key.code) {
            (KeyModifiers::NONE, KeyCode::Up | KeyCode::Char('k')) => self.step(-1),
            (KeyModifiers::NONE, KeyCode::Down | KeyCode::Char('j')) => self.step(1),
            (KeyModifiers::NONE, KeyCode::Tab) => self.jump_to_needs_input(),
            (KeyModifiers::NONE, KeyCode::Char('/')) => self.mode = Mode::Filter,
            (KeyModifiers::NONE, KeyCode::Char('m')) => self.begin_message(),
            (KeyModifiers::NONE, KeyCode::Char('n')) => self.begin_new_session(),
            (KeyModifiers::NONE, KeyCode::Char('c')) => self.cancel(),
            (KeyModifiers::NONE, KeyCode::Char('y')) if approval => {
                self.answer(InputAnswer::AllowOnce);
            }
            (KeyModifiers::NONE, KeyCode::Char('a')) if approval => {
                self.answer(InputAnswer::AllowForSession);
            }
            (KeyModifiers::NONE, KeyCode::Char('d')) if approval => {
                self.answer(InputAnswer::Deny { reason: None });
            }
            (KeyModifiers::NONE, KeyCode::Enter) => {
                match self.session_of_selected() {
                    // Already followed: closing the view shows it.
                    Some(session) if self.followed.as_ref() == Some(session) => {}
                    Some(session) => self.attach = Some(Attach(session.clone())),
                    None if self.selected.is_some() => {
                        self.say("could not attach job: no session of the daemon's started it");
                        return PanelKeyOutcome::Handled;
                    }
                    None => {}
                }
                // The shared keys close the view, which then attaches.
                return PanelKeyOutcome::Unhandled;
            }
            // A filter clears before the view closes.
            (KeyModifiers::NONE, KeyCode::Esc) if !self.filter.is_empty() => {
                self.filter.clear();
                self.select_listed();
            }
            // Close, page, and copy keys.
            _ => return PanelKeyOutcome::Unhandled,
        }
        PanelKeyOutcome::Handled
    }

    /// The body's rows at `width`, and the rows the selection takes: its
    /// own and those of what its job asks.
    fn rows(&self, width: usize) -> (Vec<Line<'static>>, Option<std::ops::Range<usize>>) {
        let mut lines = Vec::new();
        let mut selected_rows = None;
        let groups = self.groups();
        if groups.is_empty() {
            let empty = match (&self.jobs, self.filter.is_empty()) {
                (None, _) => "Loading jobs",
                (Some(_), true) => "No jobs are running",
                (Some(_), false) => "No jobs match the filter",
            };
            lines.extend(indented_wrapped_lines(empty, 1, width, Theme::dim()));
        }
        for group in groups {
            lines.push(Line::styled(
                format!(" {}", crate::paths::display(&group.workspace)),
                Theme::dim().add_modifier(Modifier::BOLD),
            ));
            for row in &group.rows {
                let selected = self.selected.as_ref() == Some(&row.job);
                let first = lines.len();
                lines.push(row_line(row, selected, width));
                if selected {
                    lines.extend(self.request_lines(width));
                    selected_rows = Some(first..lines.len());
                }
            }
            lines.push(Line::default());
        }
        (lines, selected_rows)
    }

    /// The rows that stay in view under the list: the filter, the field a
    /// typing mode fills, and why the last request failed.
    fn pinned(&self, width: usize) -> Vec<Line<'static>> {
        let mut lines = Vec::new();
        let filtering = matches!(self.mode, Mode::Filter);
        if filtering || !self.filter.is_empty() {
            lines.push(input_line("Filter", &self.filter, filtering));
        }
        match &self.mode {
            Mode::Browse | Mode::Filter => {}
            Mode::Message { session, text } => {
                let label = if self.turn_under_way(session) {
                    "Steer"
                } else {
                    "Message"
                };
                lines.push(input_line(label, text, /*typing*/ true));
            }
            Mode::NewWorkspace { path, worktree } => {
                lines.push(input_line("Workspace", path, /*typing*/ true));
                lines.push(worktree_line(*worktree));
            }
            Mode::NewPrompt { text, worktree, .. } => {
                lines.push(input_line("Prompt", text, /*typing*/ true));
                lines.push(worktree_line(*worktree));
            }
        }
        if let Some(notice) = self.notice() {
            lines.extend(indented_wrapped_lines(&notice, 1, width, Theme::warning()));
        }
        lines
    }

    /// What the selected job's open request asks, under its row.
    fn request_lines(&self, width: usize) -> Vec<Line<'static>> {
        let Some((_, request)) = self.open_request() else {
            return Vec::new();
        };
        let asks = match &request.ask {
            Ask::Approval(ask) => ApprovalPrompt::of_daemon_ask(ask).summary(),
            Ask::PlanApproval(_) => {
                vec!["A plan waits for approval. Enter attach to read it".into()]
            }
            Ask::Question(question) => {
                vec![format!("{} Enter attach to answer", question.title)]
            }
            // `Ask` is non-exhaustive.
            _ => vec!["A request this rho cannot show. Enter attach".into()],
        };
        asks.iter()
            .flat_map(|line| indented_wrapped_lines(line, 5, width, Theme::text()))
            .collect()
    }
}

/// Hands `text` to `session`: steers its turn when one is `under_way`,
/// else starts its next. The list that said which is up to a poll old, so
/// a turn that ended or began since takes the message the other way.
async fn message(
    daemon: Arc<Daemon>,
    session: SessionId,
    text: String,
    under_way: bool,
) -> Result<(), DaemonError> {
    let steer = |daemon: Arc<Daemon>, session: SessionId, text: String| async move {
        let params = SessionSteerParams { session, text };
        daemon.request::<SessionSteer>(&params).await.map(|_| ())
    };
    let refused_as = |error: &DaemonError, code: ErrorCode| matches!(error, DaemonError::Request(error) if error.error_code() == Some(code));
    if under_way {
        match steer(Arc::clone(&daemon), session.clone(), text.clone()).await {
            Err(error) if refused_as(&error, ErrorCode::NotSteerable) => {
                prompt(daemon, session, text).await
            }
            steered => steered,
        }
    } else {
        match prompt(Arc::clone(&daemon), session.clone(), text.clone()).await {
            Err(error) if refused_as(&error, ErrorCode::SessionBusy) => {
                steer(daemon, session, text).await
            }
            prompted => prompted,
        }
    }
}

/// Starts a turn of `session` on `text`, as the person at this TUI.
async fn prompt(daemon: Arc<Daemon>, session: SessionId, text: String) -> Result<(), DaemonError> {
    let params = SessionPromptParams {
        session,
        content: vec![ContentBlock::Text { text }],
        timeout_ms: None,
        environment: ClientEnvironment::of_this_process(),
        idempotency_key: None,
        grant: None,
        author: PromptAuthor::Person,
    };
    daemon.request::<SessionPrompt>(&params).await.map(|_| ())
}

fn input_line(label: &str, text: &str, typing: bool) -> Line<'static> {
    let cursor = if typing { "â–ˆ" } else { "" };
    Line::from(vec![
        Span::styled(format!(" {label}: "), Theme::dim()),
        Span::styled(format!("{text}{cursor}"), Theme::text()),
    ])
}

/// Whether the session being started works in a worktree of its own.
fn worktree_line(worktree: bool) -> Line<'static> {
    let choice = if worktree {
        "new git worktree and branch"
    } else {
        "off"
    };
    Line::from(vec![
        Span::styled(" Worktree: ", Theme::dim()),
        Span::styled(choice, Theme::text()),
    ])
}

fn row_line(row: &Row, selected: bool, width: usize) -> Line<'static> {
    let marker = if selected { "â–¸" } else { " " };
    let nesting = match row.depth {
        0 => String::new(),
        depth => format!("{}â”” ", "  ".repeat(depth - 1)),
    };
    let status_style = match row.status {
        Status::NeedsInput => Theme::warning().add_modifier(Modifier::BOLD),
        Status::Running => Theme::accent(),
        Status::Queued | Status::Idle | Status::Ended => Theme::dim(),
    };
    let title_style = if selected {
        Theme::text_strong().add_modifier(Modifier::BOLD)
    } else {
        Theme::text()
    };
    let lead = format!(" {marker} {:<11} ", row.status.label());
    let facts: String = row.facts.iter().map(|fact| format!(" · {fact}")).collect();
    let used = super::display_width(&lead) + super::display_width(&facts);
    let title = truncate_one_line(
        &format!("{nesting}{}", row.title),
        width.saturating_sub(used).max(1),
    );
    Line::from(vec![
        Span::styled(lead, status_style),
        Span::styled(title, title_style),
        Span::styled(facts, Theme::dim()),
    ])
}

impl PanelBody for JobsView {
    fn state(&self) -> &PanelState {
        &self.panel
    }

    fn state_mut(&mut self) -> &mut PanelState {
        &mut self.panel
    }

    fn title(&self) -> &str {
        "Jobs"
    }

    fn footer(&self) -> &str {
        match &self.mode {
            Mode::Browse => match self.open_request() {
                Some((
                    _,
                    InputRequest {
                        ask: Ask::Approval(_),
                        ..
                    },
                )) => ASK_FOOTER,
                Some(_) | None => BROWSE_FOOTER,
            },
            Mode::Filter | Mode::Message { .. } => INPUT_FOOTER,
            Mode::NewWorkspace { .. } | Mode::NewPrompt { .. } => NEW_FOOTER,
        }
    }

    fn body_lines(&self, width: usize, _now: Instant) -> Vec<Line<'static>> {
        self.rows(width).0
    }

    fn pinned_lines(&self, width: usize) -> Vec<Line<'static>> {
        self.pinned(width)
    }

    fn cursor_rows(&self, width: usize) -> Option<std::ops::Range<usize>> {
        self.rows(width).1
    }

    fn handle_key(&mut self, key: KeyEvent) -> PanelKeyOutcome {
        // A notice is of the request before this key, and only `c` right
        // after `c` confirms a cancel.
        *self.notice.lock().unwrap_or_else(PoisonError::into_inner) = None;
        if key.code != KeyCode::Char('c') {
            self.cancel_armed = None;
        }
        match self.mode {
            Mode::Browse => self.browse_key(key),
            Mode::Filter
            | Mode::Message { .. }
            | Mode::NewWorkspace { .. }
            | Mode::NewPrompt { .. } => self.typing_key(key),
        }
    }

    fn close(self: Box<Self>, app: &mut App) {
        app.jobs_view_attach = self.attach;
    }
}

impl App {
    /// Opens `/jobs`.
    pub(super) fn execute_jobs_command(&mut self) -> anyhow::Result<()> {
        let session = &self.info.session.daemon;
        let view = JobsView::new(
            session.daemon(),
            session.id().map(SessionId::new),
            session.launch().clone(),
        );
        self.input_ui
            .set_composer(ComposerMode::Panel(PanelOverlay::Jobs(Box::new(view))));
        // The first list is owed now, not at the rail's next poll.
        self.owe_daemon_jobs();
        self.set_status_quiet("jobs");
        Ok(())
    }

    pub(super) fn jobs_view_open(&self) -> bool {
        matches!(
            self.input_ui.composer(),
            ComposerMode::Panel(PanelOverlay::Jobs(_))
        )
    }

    /// Shows the daemon's `jobs` in an open `/jobs`, scrolled to the
    /// selection when the list moved it or its job began to ask.
    pub(super) fn show_jobs_view(&mut self, jobs: &[JobSummary], terminal: &DefaultTerminal) {
        if let ComposerMode::Panel(PanelOverlay::Jobs(view)) = self.input_ui.composer_mut() {
            if let (true, Some(area)) = (view.show(jobs.to_vec()), terminal_area(terminal)) {
                reveal_panel_cursor(view.as_mut(), area);
            }
        }
    }

    /// Follows the session a closed `/jobs` asked to attach to. Only
    /// between turns: a session switch leaves the turn under way behind.
    pub(super) async fn attach_from_jobs_view(&mut self, terminal: &mut DefaultTerminal) {
        let Some(Attach(session)) = self.jobs_view_attach.take() else {
            return;
        };
        // A saved session attaches as `/resume` does, with its checks, but
        // from any workspace. One the daemon has open and has not saved
        // yet, as a session just started, has no file to find: it is
        // followed by its id.
        let attached = match Session::workspace_of(session.as_str()) {
            Ok(Some(workspace)) => {
                let target = SessionTarget::new(session.as_str(), workspace);
                self.resume_daemon_target(target, terminal).await
            }
            Ok(None) => self.follow_unsaved_session(session, terminal).await,
            // The store could not say, so no check below would hold.
            Err(error) => Err(error),
        };
        if let Err(error) = attached {
            self.set_status(format!("could not attach session: {error:#}"));
        }
    }

    /// Follows `session`, which the daemon has loaded and has not saved. A
    /// launch that named an agent follows only that agent's sessions, and
    /// an unsaved session's agent is recorded nowhere this TUI reads, so
    /// such a launch refuses it until it saves.
    async fn follow_unsaved_session(
        &mut self,
        session: SessionId,
        terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<()> {
        anyhow::ensure!(
            self.info.session.resume_launch.definition.is_none(),
            "the session has saved nothing yet, so its agent cannot be checked against --agent; \
             attach once its first turn saves"
        );
        let short = super::session_picker::short_session_id(session.as_str());
        self.switch_daemon_session(DaemonTarget::Resume(session), terminal)
            .await?;
        self.set_status(format!("attached session {short}"));
        Ok(())
    }

    /// Drops what a `/jobs` closed during a turn asked for, saying why.
    pub(super) fn refuse_jobs_view_attach(&mut self) {
        if self.jobs_view_attach.take().is_some() {
            self.set_status("could not attach session: a model turn is running here");
        }
    }
}