Skip to main content

adk_surface/tui/
mod.rs

1//! The terminal (spec 3.3 §5.2): the same home as the web, from the keyboard.
2//!
3//! The terminal is a client of the [`SurfaceEngine`] like every other surface: it shows what
4//! the engine projects, in the engine's words (§8), and changes nothing except through
5//! [`Command`](crate::Command)s. It holds no state a reconnect cannot rebuild.
6//!
7//! | Mode | What it is | Entry point |
8//! |---|---|---|
9//! | Full screen (default) | A status line; the roster, what is coming up and "While you were away" on the left; the thread on the right; the decision as a box answered by key; footer key hints | [`TerminalSurface::run`] with [`UiMode::FullScreen`] |
10//! | Inline | The same thread and boxes printed into the terminal's scrollback | [`TerminalSurface::run`] with [`UiMode::Inline`] |
11//! | JSON | One engine event per line and an exit code, for CI | [`TerminalSurface::run_json`] |
12//!
13//! A decision is answered by key — `y` allow once, `a` always allow, `e` edit, `n` deny, `?`
14//! details — and only by those keys, only while the message box is empty, and only once the
15//! box has been on screen for a moment, so a keystroke meant for a message never answers a
16//! decision that just appeared (§7.4 rules 1 and 2, §11 S-I4). Esc never decides: it moves
17//! between answering by key and typing. A message typed while a decision is open is queued and
18//! shown as queued. Every string from a model, a tool or a file goes through
19//! [`terminal_safe`] first (§11 S-I9).
20//!
21//! # Exit codes
22//!
23//! | Code | Constant | Meaning |
24//! |---|---|---|
25//! | 0 | [`EXIT_DONE`] | The turn finished, or the person left the full-screen or inline UI |
26//! | 1 | [`EXIT_ERROR`] | The turn failed, ended without a reply, or every agent is stopped |
27//! | 3 | [`EXIT_WAITING`] | A decision waits for a person; it stays in the inbox for any surface |
28//! | 4 | [`EXIT_BUDGET`] | Today's spend reached the daily spending limit |
29//! | 129, 130, 143 | — | `SIGHUP`, `SIGINT`, `SIGTERM` in the full-screen or inline UI: the terminal was restored first |
30//!
31//! # Example
32//!
33//! ```rust,no_run
34//! use std::sync::Arc;
35//! use adk_surface::tui::{TerminalSurface, ThemeChoice, UiMode};
36//! use adk_surface::{Caller, LocalSource, Origin, SurfaceEngine, SurfaceKind};
37//!
38//! # async fn example(sessions: Arc<dyn adk_session::SessionService>, approvals: Arc<dyn adk_core::ApprovalService>) -> std::io::Result<()> {
39//! let source = LocalSource::builder("adk-rust").sessions(sessions).approvals(approvals).build()
40//!     .map_err(std::io::Error::other)?;
41//! let engine = SurfaceEngine::builder(Arc::new(source)).build();
42//! let me = Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard).with_paired_local();
43//! let code = TerminalSurface::new(engine, me).theme(ThemeChoice::Auto).run(UiMode::FullScreen).await?;
44//! std::process::exit(code);
45//! # }
46//! ```
47
48mod agents;
49mod app;
50mod commands;
51mod drawn;
52mod full;
53mod inline;
54mod json;
55mod markdown;
56mod pump;
57mod safe;
58mod term;
59#[cfg(test)]
60mod tests;
61mod theme;
62mod view;
63#[cfg(feature = "voice")]
64mod voice;
65
66use std::io::{IsTerminal, Write};
67use std::str::FromStr;
68use std::sync::{Arc, Mutex};
69use std::time::Duration;
70
71use futures::future::BoxFuture;
72use tokio::sync::mpsc::UnboundedReceiver;
73
74pub use commands::{CommandContext, TerminalCommand};
75pub use safe::terminal_safe;
76pub use theme::{Appearance, Theme, ThemeChoice};
77#[cfg(feature = "voice")]
78pub use voice::TerminalVoice;
79
80use crate::engine::SurfaceEngine;
81use crate::origin::Caller;
82
83/// The turn finished, or the person left the terminal (spec 3.3 §5.2).
84pub const EXIT_DONE: i32 = 0;
85/// The turn failed, ended without a reply, or every agent is stopped (spec 3.3 §5.2).
86pub const EXIT_ERROR: i32 = 1;
87/// A decision waits for a person (spec 3.3 §7.3): it never expires, and any surface may
88/// answer it. The same code `adk-rust code` uses for a held call.
89pub const EXIT_WAITING: i32 = 3;
90/// Today's spend reached the daily spending limit (spec 3.3 §8.1).
91pub const EXIT_BUDGET: i32 = 4;
92
93/// How long the terminal waits between reads of the engine when the source signals nothing.
94const POLL: Duration = Duration::from_millis(400);
95
96/// A writer whose bytes outlive the terminal drawing into it.
97#[derive(Clone, Default)]
98struct Shared(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
99
100impl Write for Shared {
101    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
102        self.0.lock().unwrap_or_else(|e| e.into_inner()).extend_from_slice(buf);
103        Ok(buf.len())
104    }
105
106    fn flush(&mut self) -> std::io::Result<()> {
107        Ok(())
108    }
109}
110
111/// Full screen or inline (spec 3.3 §5.2).
112///
113/// # Example
114///
115/// ```rust
116/// use adk_surface::tui::UiMode;
117///
118/// assert_eq!("inline".parse::<UiMode>().unwrap(), UiMode::Inline);
119/// assert_eq!("full".parse::<UiMode>().unwrap(), UiMode::FullScreen);
120/// ```
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
122pub enum UiMode {
123    /// The whole terminal, in the alternate screen.
124    #[default]
125    FullScreen,
126    /// Lines in the terminal's scrollback.
127    Inline,
128}
129
130impl FromStr for UiMode {
131    type Err = String;
132
133    fn from_str(value: &str) -> Result<Self, Self::Err> {
134        match value.trim().to_ascii_lowercase().as_str() {
135            "full" | "full-screen" | "fullscreen" => Ok(Self::FullScreen),
136            "inline" => Ok(Self::Inline),
137            other => Err(format!("unknown UI '{other}': use full or inline")),
138        }
139    }
140}
141
142/// What the terminal writes: text for a person, or one JSON event per line (spec 3.3 §5.2).
143///
144/// # Example
145///
146/// ```rust
147/// use adk_surface::tui::OutputFormat;
148///
149/// assert_eq!("json".parse::<OutputFormat>().unwrap(), OutputFormat::Json);
150/// ```
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
152pub enum OutputFormat {
153    /// For a person.
154    #[default]
155    Text,
156    /// One engine event per line, then an `end` line; the exit code says how it ended.
157    Json,
158}
159
160impl FromStr for OutputFormat {
161    type Err = String;
162
163    fn from_str(value: &str) -> Result<Self, Self::Err> {
164        match value.trim().to_ascii_lowercase().as_str() {
165            "text" => Ok(Self::Text),
166            "json" => Ok(Self::Json),
167            other => Err(format!("unknown output '{other}': use text or json")),
168        }
169    }
170}
171
172/// Opens the session `/session` names, or a new one for `None`: the id to show, or why not, in
173/// words the terminal shows as they are.
174type Opener =
175    Arc<dyn Fn(Option<String>) -> BoxFuture<'static, Result<String, String>> + Send + Sync>;
176
177/// How `/session` opens a session: the application's rule, or any id as given.
178#[derive(Clone, Default)]
179struct SessionGate(Option<Opener>);
180
181impl std::fmt::Debug for SessionGate {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        f.write_str(if self.0.is_some() { "SessionGate(set)" } else { "SessionGate(none)" })
184    }
185}
186
187/// Notices that arrive while the terminal runs; the first UI to run takes them.
188#[derive(Clone, Default)]
189struct LateNotices(Arc<Mutex<Option<UnboundedReceiver<String>>>>);
190
191impl LateNotices {
192    fn take(&self) -> Option<UnboundedReceiver<String>> {
193        self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take()
194    }
195}
196
197impl std::fmt::Debug for LateNotices {
198    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199        f.write_str("LateNotices")
200    }
201}
202
203/// The terminal surface over an engine, for one caller (spec 3.3 §5.2).
204///
205/// The caller is the person at the keyboard: [`SurfaceKind::Terminal`](crate::SurfaceKind)
206/// with [`Origin::Keyboard`](crate::Origin), and
207/// [`with_paired_local`](Caller::with_paired_local) only when the terminal reaches the kernel
208/// on its own machine, which lets it approve high-risk calls and resume after a stop (§7.2,
209/// S-I10).
210#[derive(Debug, Clone)]
211pub struct TerminalSurface {
212    engine: SurfaceEngine,
213    caller: Caller,
214    session: Option<String>,
215    theme: ThemeChoice,
216    model: Option<String>,
217    place: Option<String>,
218    home: Option<String>,
219    poll: Duration,
220    notices: Vec<String>,
221    late: LateNotices,
222    signals: bool,
223    gate: SessionGate,
224    commands: commands::Commands,
225    #[cfg(feature = "voice")]
226    voice: voice::VoiceSlot,
227}
228
229impl TerminalSurface {
230    /// The terminal over `engine`, as `caller`.
231    pub fn new(engine: SurfaceEngine, caller: Caller) -> Self {
232        Self {
233            engine,
234            caller,
235            session: None,
236            theme: ThemeChoice::Auto,
237            model: None,
238            place: None,
239            home: None,
240            poll: POLL,
241            notices: Vec::new(),
242            late: LateNotices::default(),
243            signals: true,
244            gate: SessionGate::default(),
245            commands: commands::Commands::default(),
246            #[cfg(feature = "voice")]
247            voice: voice::VoiceSlot::default(),
248        }
249    }
250
251    /// Talks with the agents by voice (spec 3.3 §5.6; feature `voice`): the conversation's own
252    /// session is the thread shown, its state is a line above the message box — in the inline
253    /// UI, what it heard and each countdown are printed into the scrollback — and `c` cancels a
254    /// spoken "allow once" while it counts down. In process only: the conversation runs on the
255    /// hub's harness. JSON output and piped input have no voice conversation.
256    #[cfg(feature = "voice")]
257    #[must_use]
258    pub fn voice(self, voice: TerminalVoice) -> Self {
259        *self.voice.lock().unwrap_or_else(|e| e.into_inner()) = Some(voice);
260        self
261    }
262
263    /// Opens `session`. Without one, the terminal opens the session of the oldest decision
264    /// waiting for the caller, else a new session.
265    #[must_use]
266    pub fn session(mut self, session: impl Into<String>) -> Self {
267        self.session = Some(session.into());
268        self
269    }
270
271    /// Light, dark, or detected from the terminal's background (the default).
272    #[must_use]
273    pub fn theme(mut self, theme: ThemeChoice) -> Self {
274        self.theme = theme;
275        self
276    }
277
278    /// The model, for the status line, such as `claude-sonnet-5-5`.
279    #[must_use]
280    pub fn model(mut self, model: impl Into<String>) -> Self {
281        self.model = Some(model.into());
282        self
283    }
284
285    /// Where the agents run, for the status line, such as `kernel` or `in process`.
286    #[must_use]
287    pub fn place(mut self, place: impl Into<String>) -> Self {
288        self.place = Some(place.into());
289        self
290    }
291
292    /// The web home's address, such as `http://127.0.0.1:8080`: a decision with images links
293    /// to itself there, and `o` opens it (spec 3.7 §8.2, board choice A16).
294    #[must_use]
295    pub fn home(mut self, url: impl Into<String>) -> Self {
296        self.home = Some(url.into().trim_end_matches('/').to_string());
297        self
298    }
299
300    /// How often the terminal reads the engine when the source signals nothing sooner.
301    #[must_use]
302    pub fn poll_interval(mut self, poll: Duration) -> Self {
303        self.poll = poll;
304        self
305    }
306
307    /// A line the full-screen and inline UIs show under the thread when they start, such as
308    /// a workspace that is not trusted (spec 3.3 §5.2). JSON mode writes none.
309    ///
310    /// # Example
311    ///
312    /// ```rust,no_run
313    /// # use std::sync::Arc;
314    /// # use adk_surface::tui::TerminalSurface;
315    /// # use adk_surface::{Caller, Origin, SurfaceEngine, SurfaceKind};
316    /// # fn example(engine: SurfaceEngine) {
317    /// let me = Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard);
318    /// let terminal = TerminalSurface::new(engine, me)
319    ///     .notice("Instruction files in this workspace are not loaded: it is not trusted.");
320    /// # }
321    /// ```
322    #[must_use]
323    pub fn notice(mut self, text: impl Into<String>) -> Self {
324        self.notices.push(text.into());
325        self
326    }
327
328    /// Lines the full-screen and inline UIs show under the thread as they arrive on
329    /// `notices`, as [`notice`](Self::notice) shows one at the start: what work the
330    /// application runs beside the terminal found, such as long-term memory catching up on
331    /// earlier sessions. JSON mode writes none. Once the terminal has ended, a send fails and
332    /// hands the line back, so the application can print it.
333    ///
334    /// # Example
335    ///
336    /// ```rust,no_run
337    /// # use adk_surface::tui::TerminalSurface;
338    /// # use adk_surface::{Caller, Origin, SurfaceEngine, SurfaceKind};
339    /// # fn example(engine: SurfaceEngine) {
340    /// let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
341    /// let me = Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard);
342    /// let terminal = TerminalSurface::new(engine, me).notices_from(rx);
343    /// tokio::spawn(async move {
344    ///     let _ = tx.send("2 facts from an earlier session were added".to_string());
345    /// });
346    /// # }
347    /// ```
348    #[must_use]
349    pub fn notices_from(mut self, notices: UnboundedReceiver<String>) -> Self {
350        self.late = LateNotices(Arc::new(Mutex::new(Some(notices))));
351        self
352    }
353
354    /// How `/session` opens a session in the full-screen and inline UIs: `open` gets the id
355    /// typed, or `None` for `/session new`, and returns the session to show, or why it may not
356    /// be opened, which the terminal shows. Without it, any id opens as given. An application
357    /// whose sessions are bound to something, such as the workspace a harness works in, checks
358    /// and records that binding here (spec 3.3 §5.2).
359    ///
360    /// # Example
361    ///
362    /// ```rust,no_run
363    /// # use adk_surface::tui::TerminalSurface;
364    /// # use adk_surface::{Caller, Origin, SurfaceEngine, SurfaceKind};
365    /// # fn example(engine: SurfaceEngine) {
366    /// let me = Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard);
367    /// let terminal = TerminalSurface::new(engine, me).open_sessions_with(|requested| {
368    ///     Box::pin(async move {
369    ///         match requested {
370    ///             Some(id) if id.starts_with("ops-") => Ok(id),
371    ///             Some(id) => Err(format!("session {id} is not one of this workspace's")),
372    ///             None => Ok(format!("ops-{}", uuid::Uuid::new_v4())),
373    ///         }
374    ///     })
375    /// });
376    /// # }
377    /// ```
378    #[must_use]
379    pub fn open_sessions_with<F>(mut self, open: F) -> Self
380    where
381        F: Fn(Option<String>) -> BoxFuture<'static, Result<String, String>> + Send + Sync + 'static,
382    {
383        self.gate = SessionGate(Some(Arc::new(open)));
384        self
385    }
386
387    /// Adds a slash command: `/name args` in the message box runs it and shows what it
388    /// returns, and Tab completes its name (spec 3.3 §5.2). The terminal's own commands win
389    /// over one of the same name, and so does the first one added.
390    ///
391    /// # Example
392    ///
393    /// ```rust
394    /// # use std::sync::Arc;
395    /// # use adk_surface::tui::{TerminalCommand, TerminalSurface};
396    /// # use adk_surface::{Caller, Origin, SurfaceEngine, SurfaceKind};
397    /// # fn example(engine: SurfaceEngine, todos: Arc<dyn TerminalCommand>) {
398    /// let me = Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard);
399    /// let terminal = TerminalSurface::new(engine, me).command(todos);
400    /// # }
401    /// ```
402    #[must_use]
403    pub fn command(mut self, command: Arc<dyn TerminalCommand>) -> Self {
404        self.commands.add(command);
405        self
406    }
407
408    /// Whether the full-screen and inline UIs give the terminal back on `SIGINT`, `SIGTERM`
409    /// and `SIGHUP` (Ctrl-C elsewhere) and end with 130, 143 or 129: on by default.
410    ///
411    /// The handlers are tokio's, which last as long as the process: once [`run`](Self::run)
412    /// has returned, these signals no longer end the process unless something else handles
413    /// them. An application that goes on after the terminal and relies on their default
414    /// action turns this off and handles them itself.
415    ///
416    /// # Example
417    ///
418    /// ```rust,no_run
419    /// # use adk_surface::tui::{TerminalSurface, UiMode};
420    /// # use adk_surface::{Caller, Origin, SurfaceEngine, SurfaceKind};
421    /// # async fn example(engine: SurfaceEngine) -> std::io::Result<()> {
422    /// let me = Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard);
423    /// // This application serves on after the terminal and handles its own signals.
424    /// TerminalSurface::new(engine, me).restore_on_signals(false).run(UiMode::FullScreen).await?;
425    /// # Ok(())
426    /// # }
427    /// ```
428    #[must_use]
429    pub fn restore_on_signals(mut self, enabled: bool) -> Self {
430        self.signals = enabled;
431        self
432    }
433
434    /// Whether standard input and output are a terminal the full-screen UI (spec 3.3 §5.2) can
435    /// draw on: both are terminals, `TERM` is not `dumb`, and the window is at least 60 by 16.
436    pub fn capable_terminal() -> bool {
437        std::io::stdin().is_terminal()
438            && std::io::stdout().is_terminal()
439            && std::env::var("TERM").map_or(cfg!(windows), |term| term != "dumb")
440            && crossterm::terminal::size().is_ok_and(|(cols, rows)| cols >= 60 && rows >= 16)
441    }
442
443    /// Runs the terminal until the person leaves, or a signal ends it; returns the exit code
444    /// (spec 3.3 §5.2).
445    ///
446    /// Full screen takes the alternate screen, raw mode and bracketed paste; inline takes raw
447    /// mode and bracketed paste and prints into the scrollback. Both give the terminal back on
448    /// exit, on a panic in the terminal's own code (a panic another task catches, such as a
449    /// tool's, leaves it), and on `SIGINT`, `SIGTERM` and `SIGHUP` unless
450    /// [`restore_on_signals`](Self::restore_on_signals) turns that off. With standard input
451    /// not a terminal, or `TERM=dumb`, inline writes plain lines, each line read is a message,
452    /// and the run ends as [`run_json`](Self::run_json) does once input ends and the turn
453    /// settles.
454    ///
455    /// # Errors
456    ///
457    /// Returns the terminal's I/O error, or the engine's error from the first read.
458    pub async fn run(self, ui: UiMode) -> std::io::Result<i32> {
459        match ui {
460            UiMode::FullScreen => full::run(self).await,
461            UiMode::Inline => inline::run(self).await,
462        }
463    }
464
465    /// Sends `message` (when given) and writes the session's engine events to `out`, one
466    /// JSON object per line, until the turn settles; then an `end` line, and returns the exit
467    /// code (spec 3.3 §5.2).
468    ///
469    /// | Line `type` | What |
470    /// |---|---|
471    /// | `command` | The outcome of sending the message: `sent` or `queued` |
472    /// | `entry`, `decisions`, `reset` | A [`FeedFrame`](crate::FeedFrame) of the session, as the engine projects it |
473    /// | `agent` | An agent a person added changed while the run lasted (spec 3.3 §5.7): `change` is `added`, `changed`, `paused`, `resumed` or `removed`, `agent` its roster row |
474    /// | `end` | `outcome` (`done`, `error`, `waitingForYou`, `budgetReached`), `exitCode`, `sessionId`, `text` |
475    ///
476    /// # Errors
477    ///
478    /// Returns the writer's I/O error.
479    pub async fn run_json<W: Write + Send>(
480        self,
481        message: Option<String>,
482        out: W,
483    ) -> std::io::Result<i32> {
484        json::run(self, message, out).await
485    }
486
487    /// One frame of the full-screen UI (spec 3.3 §5.2) as a terminal of `cols` by `rows`
488    /// receives it — the escape sequences and text, drawn from what the engine shows now,
489    /// with the decision keys live — for tests, screenshots and documentation. `Auto` draws
490    /// the dark set, in 24-bit colour.
491    ///
492    /// # Errors
493    ///
494    /// Returns the engine's error from reading the shown session's thread.
495    pub async fn screen(&self, cols: u16, rows: u16) -> std::io::Result<Vec<u8>> {
496        use ratatui::backend::CrosstermBackend;
497        use ratatui::layout::Rect;
498        use ratatui::{Terminal, TerminalOptions, Viewport};
499
500        let session = self.initial_session().await;
501        let engine = &self.engine;
502        let caller = &self.caller;
503        let mut app = app::App::new(engine.source().app_name(), session.clone());
504        app.agents_pane.granted = engine.granted().to_vec();
505        app.model = self.model.clone();
506        app.place = self.place.clone();
507        app.commands = self.commands.clone();
508        let now = std::time::Instant::now();
509        let armed = now.checked_sub(app::ARM_DELAY * 2).unwrap_or(now);
510        let status = match engine.status(caller, Some(&session)).await {
511            Ok(status) => Some(status),
512            Err(_) => engine.status(caller, None).await.ok(),
513        };
514        if let Some(status) = status {
515            app.update(app::Update::Status(status), now);
516        }
517        if let Ok(agents) = engine.agents(caller).await {
518            app.update(app::Update::Agents(agents), now);
519        }
520        if let Ok(removed) = engine.removed_agents(caller).await {
521            app.update(app::Update::Removed(removed), now);
522        }
523        if let Ok(briefing) = engine.briefing(caller, pump::start_of_today()).await {
524            app.update(app::Update::Briefing(briefing), now);
525        }
526        let thread = match engine.thread(caller, &session).await {
527            Ok(thread) => thread,
528            Err(crate::SurfaceError::NotFound { .. }) => Vec::new(),
529            Err(error) => return Err(std::io::Error::other(error)),
530        };
531        for entry in thread {
532            let frame = crate::FeedFrame::Entry { entry };
533            app.update(app::Update::Frame { session: session.clone(), generation: 0, frame }, now);
534        }
535        let cards = engine
536            .decisions(caller)
537            .await
538            .map_err(std::io::Error::other)?
539            .into_iter()
540            .filter(|card| card.session_id == session)
541            .collect();
542        let frame = crate::FeedFrame::Decisions { cards };
543        app.update(app::Update::Frame { session: session.clone(), generation: 0, frame }, armed);
544        app.queued = engine.queued(caller, &session);
545
546        let appearance = match self.theme {
547            ThemeChoice::Light => Appearance::Light,
548            ThemeChoice::Dark | ThemeChoice::Auto => Appearance::Dark,
549        };
550        let mut renderer = view::Renderer::new(Theme::new(appearance, true));
551        let options = TerminalOptions { viewport: Viewport::Fixed(Rect::new(0, 0, cols, rows)) };
552        let bytes = Shared::default();
553        let mut terminal = Terminal::with_options(CrosstermBackend::new(bytes.clone()), options)?;
554        terminal.draw(|frame| {
555            renderer.draw(frame, &app, now);
556        })?;
557        drop(terminal);
558        Ok(std::mem::take(&mut *bytes.0.lock().unwrap_or_else(|e| e.into_inner())))
559    }
560
561    /// The session `/session` asked for, through the application's gate.
562    async fn open_session(&self, requested: Option<String>) -> Result<String, String> {
563        match &self.gate.0 {
564            Some(open) => open(requested).await,
565            None => Ok(requested.unwrap_or_else(|| uuid::Uuid::new_v4().to_string())),
566        }
567    }
568
569    /// What the full-screen and inline loops do with an effect of a key; returns whether the
570    /// person is leaving.
571    async fn apply(
572        &self,
573        effect: app::Effect,
574        app: &mut app::App,
575        pump: &pump::Pump,
576        commands: &mut pump::Commands,
577        tx: &tokio::sync::mpsc::UnboundedSender<app::Update>,
578        shown: &mut Vec<String>,
579    ) -> bool {
580        match effect {
581            app::Effect::Execute(command) => {
582                commands.execute(&self.engine, &self.caller, command, tx);
583            }
584            app::Effect::Session(session) => {
585                if !shown.contains(&session) {
586                    shown.push(session.clone());
587                }
588                pump.switch(session);
589            }
590            app::Effect::OpenSession(requested) => match self.open_session(requested).await {
591                Ok(session) => {
592                    for effect in app.switch_session(session) {
593                        if let app::Effect::Session(session) = effect {
594                            if !shown.contains(&session) {
595                                shown.push(session.clone());
596                            }
597                            pump.switch(session);
598                        }
599                    }
600                }
601                Err(why) => app.notice(why, app::Tone::Problem),
602            },
603            app::Effect::Unqueue(session) => {
604                app.took_back(self.engine.unqueue_last(&self.caller, &session));
605            }
606            app::Effect::Briefing => pump.refresh_briefing(),
607            app::Effect::Open(url) => match open_in_browser(&url) {
608                Ok(()) => app.notice(format!("Opened {url}"), app::Tone::Info),
609                Err(why) => {
610                    app.notice(format!("Open {url} in your browser: {why}"), app::Tone::Problem)
611                }
612            },
613            app::Effect::RunCommand { serial, name, args } => {
614                let found = self.commands.find(&name).or_else(|| self.commands.shadowed(&name));
615                match found {
616                    Some(command) => {
617                        let context = CommandContext::new(app.session.clone());
618                        commands.run_added(command, args, context, serial, tx);
619                    }
620                    None => app.update(
621                        app::Update::CommandDone {
622                            serial,
623                            result: Err(format!("No command /{name}. /help lists them.")),
624                        },
625                        std::time::Instant::now(),
626                    ),
627                }
628            }
629            app::Effect::Quit => return true,
630        }
631        false
632    }
633
634    /// What leaving does not deliver, said once the terminal is given back: input queued in
635    /// this process, and commands that had not finished (spec 3.3 §7.4 rule 2, S-I10).
636    async fn leave(&self, commands: pump::Commands, shown: &[String], out: &mut impl Write) {
637        if commands.running() {
638            let _ = writeln!(out, "Finishing what you sent…");
639        }
640        let left = commands.finish(pump::FINISH_WAIT).await;
641        if !left.is_empty() {
642            let _ = writeln!(out, "Left before this finished: {}.", left.join(", "));
643        }
644        let queued: Vec<String> = shown
645            .iter()
646            .flat_map(|session| self.engine.queued(&self.caller, session))
647            .map(|text| format!("\"{}\"", safe::safe_line(&text)))
648            .collect();
649        if !queued.is_empty() {
650            let _ = writeln!(
651                out,
652                "Not sent — queued in this terminal, which has closed: {}",
653                queued.join(", ")
654            );
655        }
656        let _ = out.flush();
657    }
658
659    /// The session to open: the one set, the session of the oldest decision waiting, or new.
660    async fn initial_session(&self) -> String {
661        if let Some(session) = &self.session {
662            return session.clone();
663        }
664        if let Ok(cards) = self.engine.decisions(&self.caller).await
665            && let Some(card) = cards.first()
666        {
667            return card.session_id.clone();
668        }
669        uuid::Uuid::new_v4().to_string()
670    }
671}
672
673/// Opens `url`, an `http` or `https` address, in the person's browser.
674fn open_in_browser(url: &str) -> std::result::Result<(), String> {
675    if !(url.starts_with("http://") || url.starts_with("https://")) {
676        return Err("only a web address opens".into());
677    }
678    let mut command = if cfg!(target_os = "macos") {
679        std::process::Command::new("open")
680    } else if cfg!(windows) {
681        let mut start = std::process::Command::new("cmd");
682        start.args(["/C", "start", ""]);
683        start
684    } else {
685        std::process::Command::new("xdg-open")
686    };
687    command
688        .arg(url)
689        .stdin(std::process::Stdio::null())
690        .stdout(std::process::Stdio::null())
691        .stderr(std::process::Stdio::null())
692        .spawn()
693        .map(|_| ())
694        .map_err(|error| error.to_string())
695}