Skip to main content

tui/app/
eval.rs

1//! Eval bridge and routing logic for `App`.
2//!
3//! Methods that touch `console_eval`, submit nomiscript forms, route replies,
4//! and keep the tab-fetch state machines in sync all live here so `app.rs`
5//! stays focused on pure state shape and navigation.
6
7use crate::tabs::nms::ConsoleState;
8use cli_core::eval::config_text;
9use cli_core::render::{WireValue, parse_wire};
10
11use crate::app::App;
12use crate::app::deliver::refresh_after;
13use crate::app::pending::rejection;
14use crate::form::Form;
15use crate::route::{Route, RouteCtx};
16use crate::tabs::config::ConfigTab;
17use crate::tabs::fetch::Fetch;
18use crate::tabs::list::ListTab;
19use crate::tabs::nms::format_result;
20use crate::tabs::nms_eval::{DrainItem, MAIN_STREAM, UNAVAILABLE};
21use crate::view::ViewId;
22use crate::window::WindowId;
23
24impl App {
25    pub fn submit_console_form(&mut self, console: WindowId, form: String) {
26        if let Some(state) = self.win_mut::<ConsoleState>(console) {
27            state.push_scrollback(format!("> {form}"));
28            state.reset_scroll();
29        }
30        if self.console_eval.is_none() {
31            self.notify(vec!["console not connected".to_string()]);
32            return;
33        }
34        let id = self
35            .console_stream(console)
36            .and_then(|stream| self.submit_routed(stream, Some(console), RouteCtx::None, form));
37        if id.is_none() {
38            self.notify(vec![UNAVAILABLE.to_string()]);
39        }
40    }
41
42    /// The stream of console `console`; its first call opens it.
43    fn console_stream(&mut self, console: WindowId) -> Option<u32> {
44        if let Some(stream) = self.win::<ConsoleState>(console)?.stream {
45            return Some(stream);
46        }
47        let stream = self.console_eval.as_mut()?.open_stream()?;
48        self.win_mut::<ConsoleState>(console)?.stream = Some(stream);
49        Some(stream)
50    }
51
52    /// Closes the stream of console `console` when it had opened one.
53    pub(super) fn close_console_stream(&mut self, console: WindowId) {
54        let stream = self.win::<ConsoleState>(console).and_then(|c| c.stream);
55        if let (Some(stream), Some(eval)) = (stream, &mut self.console_eval) {
56            eval.close(stream);
57        }
58    }
59
60    /// Submits `form` to the front-most console window, or to a new one; returns it.
61    pub fn submit_to_console(&mut self, form: String) -> WindowId {
62        let console = self.window_or_open(ViewId::Console).window;
63        self.submit_console_form(console, form);
64        console
65    }
66
67    /// Shows the first line of an app notice in the status bar; the whole text goes to the log.
68    pub(super) fn notify(&mut self, lines: Vec<String>) {
69        let Some(first) = lines.first() else {
70            return;
71        };
72        tracing::warn!("{}", lines.join("\n"));
73        let mut shown = first.clone();
74        if lines.len() > 1 {
75            shown.push_str(" … (see log)");
76        }
77        self.set_status(shown);
78    }
79
80    /// Aborts what the front console is evaluating.
81    pub fn interrupt_console(&mut self) {
82        let stream = self.front::<ConsoleState>().and_then(|c| c.stream);
83        if let (Some(stream), Some(eval)) = (stream, &mut self.console_eval) {
84            eval.interrupt(stream);
85        }
86    }
87
88    /// Applies every ready reply; `true` when there was one, so the screen is stale.
89    pub fn drain_eval(&mut self) -> bool {
90        let items = {
91            let Some(eval) = &mut self.console_eval else {
92                return false;
93            };
94            eval.drain()
95        };
96        let any = !items.is_empty();
97        for item in items {
98            self.apply_drained(item);
99        }
100        any
101    }
102
103    pub(super) fn apply_drained(&mut self, item: DrainItem) {
104        match item {
105            DrainItem::Routed { id, wire } => self.route_reply(id, &wire),
106            DrainItem::Unroutable(wire) => self.notify(format_result(&wire)),
107        }
108    }
109
110    pub fn fetch_config(&mut self, window: WindowId) {
111        let Some(seq) = self
112            .win_mut::<ConfigTab>(window)
113            .map(|tab| tab.seq.advance())
114        else {
115            return;
116        };
117        let ctx = RouteCtx::Config { seq };
118        if let Some(id) = self.dispatch_eval(window, ctx, "(list-config)".to_string())
119            && let Some(config) = self.win_mut::<ConfigTab>(window)
120        {
121            config.set_loading(id);
122        }
123    }
124
125    pub(super) fn ensure_list_loaded(&mut self, window: WindowId) {
126        let Some(list) = self.win::<ListTab>(window) else {
127            return;
128        };
129        if !matches!(list.state, Fetch::Idle) {
130            return;
131        }
132        let form = list.request_form();
133        if let Some(id) = self.dispatch_eval(window, RouteCtx::None, form)
134            && let Some(list) = self.win_mut::<ListTab>(window)
135        {
136            list.set_loading_id(id);
137        }
138    }
139
140    /// Submit `form` to the eval worker, insert a `Route` to `window`, and return the id.
141    ///
142    /// Returns `None` when no console is attached or its ids ran out.
143    pub(super) fn dispatch_eval(
144        &mut self,
145        window: WindowId,
146        ctx: RouteCtx,
147        form: String,
148    ) -> Option<i64> {
149        self.submit_routed(MAIN_STREAM, Some(window), ctx, form)
150    }
151
152    /// Like `dispatch_eval`, for a reply that belongs to the app or a dialog.
153    pub(super) fn dispatch_app_eval(&mut self, ctx: RouteCtx, form: String) -> Option<i64> {
154        self.submit_routed(MAIN_STREAM, None, ctx, form)
155    }
156
157    fn submit_routed(
158        &mut self,
159        stream: u32,
160        target: Option<WindowId>,
161        ctx: RouteCtx,
162        form: String,
163    ) -> Option<i64> {
164        let eval = self.console_eval.as_mut()?;
165        let id = eval.submit(stream, form)?;
166        self.pending_routes.insert(id, Route { target, ctx });
167        Some(id)
168    }
169
170    /// Drop the filter of Transactions window `window` and fetch the whole list again.
171    pub fn clear_transaction_filter(&mut self, window: WindowId) {
172        self.next_filter_seq(window);
173        if self
174            .win_mut::<ListTab>(window)
175            .is_some_and(ListTab::clear_filter)
176        {
177            self.load_window(window);
178        }
179    }
180
181    /// Route one drained reply to its destination window, or, if the id has
182    /// no pending route, show the reply as an orphan-warn status. A reply to the
183    /// pending form's own request settles the form first.
184    pub(crate) fn route_reply(&mut self, id: i64, wire: &str) {
185        if let Some(route) = self.take_orphan_route(id) {
186            self.settle_orphan(route, wire);
187            return;
188        }
189        let form = self.take_pending_form(id);
190        let route = self.pending_routes.remove(&id);
191        let mutates = route.as_ref().is_some_and(|route| route.ctx.mutates());
192        let target = route.as_ref().and_then(|route| route.target);
193        let failed = parse_wire(wire).is_err();
194        if !failed && target.is_some() && self.status_owner == target {
195            self.clear_status();
196        }
197        let before = self.status.clone();
198        match (route, form) {
199            (route, Some(form)) => self.settle_pending_form(form, route, wire),
200            (Some(route), None) if self.is_stale_page(&route, id) => {}
201            (Some(route), None) => self.deliver_reply(route, wire),
202            (None, None) => {
203                let mut lines = format_result(wire);
204                let head = format!("[warn] orphan reply id={id}");
205                match lines.first_mut() {
206                    Some(first) => *first = format!("{head}: {first}"),
207                    None => lines.push(head),
208                }
209                self.notify(lines);
210            }
211        }
212        if failed && self.status != before {
213            self.status_owner = target.filter(|_| !mutates);
214        }
215    }
216
217    /// The route of request `id` when the window it targeted has closed.
218    fn take_orphan_route(&mut self, id: i64) -> Option<Route> {
219        let target = self.pending_routes.get(&id)?.target?;
220        match self.window_view(target) {
221            Some(_) => None,
222            None => self.pending_routes.remove(&id),
223        }
224    }
225
226    /// A reply for a closed window is dropped, except that a succeeded mutation still
227    /// refreshes every window of its kind.
228    fn settle_orphan(&mut self, route: Route, wire: &str) {
229        if matches!(route.ctx, RouteCtx::BulkDelete { .. }) {
230            return self.settle_orphan_bulk(wire);
231        }
232        let Some(kind) = refresh_after(&route.ctx, wire) else {
233            return;
234        };
235        self.refresh_windows(kind);
236        if matches!(route.ctx, RouteCtx::ConfigSet { .. }) {
237            self.read_ui_config();
238        }
239    }
240
241    /// A page fetch of the Transactions tab nobody waits for any more: a newer
242    /// request (a filter, a refresh) superseded it.
243    fn is_stale_page(&self, route: &Route, id: i64) -> bool {
244        let Some(window) = route.target else {
245            return false;
246        };
247        self.window_view(window) == Some(ViewId::Transactions)
248            && matches!(route.ctx, RouteCtx::None)
249            && self
250                .win::<ListTab>(window)
251                .is_some_and(|list| !list.awaits(id))
252    }
253
254    fn settle_pending_form(&mut self, form: Form, route: Option<Route>, wire: &str) {
255        match parse_wire(wire) {
256            Ok(WireValue::Value(value)) => match route {
257                Some(Route {
258                    ctx: RouteCtx::MergePreview,
259                    ..
260                }) => self.confirm_merge_preview(form, &value),
261                Some(route) => self.deliver_reply(route, wire),
262                None => {}
263            },
264            Err(e) => {
265                self.rollback_options(&form);
266                self.unlock_pending_form(form, rejection(&e));
267            }
268        }
269    }
270}
271
272/// The text a `get-config` reply holds; a failed or empty read is no value.
273pub(super) fn config_value_in(wire: &str) -> Option<String> {
274    let Ok(WireValue::Value(value)) = parse_wire(wire) else {
275        return None;
276    };
277    config_text(&value).ok().flatten()
278}