Skip to main content

tea_cli/tui/
reducer.rs

1use std::future::Future;
2use std::pin::Pin;
3
4use futures_util::stream::{FuturesOrdered, StreamExt as _};
5use tea_protocol::{
6    AgentEvent, AgentEventType, EventDelta, EventEnvelope, ReasoningEffort, SessionId,
7};
8use tea_session::SessionSnapshot;
9use tokio::sync::mpsc;
10
11use super::ComposerAttachment;
12use super::Overlay;
13use super::state::{
14    ApprovalChoice, HostedToolView, MAX_VISIBLE_QUEUE_ITEMS, StreamingBlock, ToolProgressView,
15    ToolView, TuiState,
16};
17
18/// Default bound for terminal actions awaiting reduction.
19pub const DEFAULT_ACTION_CAPACITY: usize = 128;
20/// Default bound for effects awaiting an executor.
21pub const DEFAULT_EFFECT_CAPACITY: usize = 32;
22const MAX_EPHEMERAL_TEXT_BYTES: usize = 1024 * 1024;
23
24/// Typed inputs reduced into [`TuiState`].
25#[derive(Debug)]
26pub enum Action {
27    /// One ordered canonical runtime event.
28    Event(Box<EventEnvelope>),
29    /// A fresh canonical snapshot returned by an effect.
30    SnapshotLoaded(Box<SessionSnapshot>),
31    /// A snapshot query failed with a safe diagnostic.
32    SnapshotLoadFailed(String),
33    /// The subscriber reconnected and requires authoritative rebuild.
34    Reconnected,
35    /// Terminal dimensions changed.
36    Resize {
37        /// New display-cell width.
38        width: u16,
39        /// New row height.
40        height: u16,
41    },
42    /// Replace local editor contents.
43    SetEditor(String),
44    /// Add one validated image to the active session composer.
45    AddAttachment(ComposerAttachment),
46    /// Remove one image by its one-based composer index.
47    RemoveAttachment {
48        /// One-based attachment index shown to the user.
49        index: usize,
50    },
51    /// Remove every image from the active session composer.
52    ClearAttachments,
53    /// Show an accepted prompt until its canonical user message is durable.
54    ShowPendingUserPrompt(String),
55    /// Begin the local activity projection once a prompt is accepted by the service.
56    StartRunActivity,
57    /// Advance the active-run elapsed counter by one or more whole seconds.
58    AdvanceRunElapsed(u64),
59    /// Stop local activity without discarding its measured elapsed time.
60    FinishRunActivity,
61    /// Replace the queued next-turn reasoning selection.
62    SetPendingReasoningEffort(Option<ReasoningEffort>),
63    /// Browse older transcript content without changing canonical state.
64    ScrollTranscriptUp {
65        /// Number of wrapped terminal rows to move toward older content.
66        rows: usize,
67    },
68    /// Browse newer transcript content without changing canonical state.
69    ScrollTranscriptDown {
70        /// Number of wrapped terminal rows to move toward the live tail.
71        rows: usize,
72    },
73    /// Return the transcript to the live tail and clear unread state.
74    FollowTranscriptTail,
75    /// Select one supported resolution for the pending approval.
76    SelectApproval(ApprovalChoice),
77    /// Mark whether an approval command has been accepted by the service.
78    SetApprovalSubmitting(bool),
79    /// Toggle all reasoning blocks.
80    ToggleThinking,
81    /// Toggle one tool's detail view.
82    ToggleTool(tea_protocol::ToolCallId),
83    /// Toggle every currently visible tool detail.
84    ToggleAllTools,
85    /// Project one queued steering message.
86    QueueSteering(String),
87    /// Project one queued follow-up message.
88    QueueFollowUp(String),
89    /// Replace the active local interaction overlay.
90    SetOverlay(Option<Overlay>),
91    /// Add one bounded local notification.
92    Notify(String),
93    /// Replace safe MCP lifecycle rows from a host projection.
94    SetMcpHealth(Vec<String>),
95}
96
97/// Side effects requested by the pure reducer.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub enum Effect {
100    /// Reload one immutable canonical session snapshot.
101    ReloadSnapshot {
102        /// Session requiring an authoritative rebuild.
103        session_id: SessionId,
104    },
105    /// Request a new terminal frame.
106    Render,
107}
108
109/// Failure to enqueue work into a bounded application loop.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
111pub enum DispatchError {
112    /// The bounded action queue is full.
113    #[error("terminal action queue is full")]
114    Full,
115    /// The terminal application loop has stopped.
116    #[error("terminal action loop is closed")]
117    Closed,
118}
119
120/// Cloneable bounded sender for terminal actions.
121#[derive(Debug, Clone)]
122pub struct ActionSender {
123    sender: mpsc::Sender<Action>,
124}
125
126impl ActionSender {
127    /// Enqueues one action without waiting.
128    ///
129    /// # Errors
130    ///
131    /// Returns [`DispatchError::Full`] under backpressure or
132    /// [`DispatchError::Closed`] after shutdown.
133    pub fn try_send(&self, action: Action) -> Result<(), DispatchError> {
134        self.sender.try_send(action).map_err(|error| match error {
135            mpsc::error::TrySendError::Full(_) => DispatchError::Full,
136            mpsc::error::TrySendError::Closed(_) => DispatchError::Closed,
137        })
138    }
139
140    /// Waits for bounded action capacity.
141    ///
142    /// # Errors
143    ///
144    /// Returns [`DispatchError::Closed`] after shutdown.
145    pub async fn send(&self, action: Action) -> Result<(), DispatchError> {
146        self.sender
147            .send(action)
148            .await
149            .map_err(|_| DispatchError::Closed)
150    }
151}
152
153/// Async boundary used by the bounded application loop.
154pub trait EffectExecutor: Send + Sync {
155    /// Starts one typed effect and optionally returns a typed completion action.
156    ///
157    /// The executor must copy any needed projection data from `state` before
158    /// returning. The returned owned future lets the application loop poll
159    /// several effects concurrently without spawning detached tasks.
160    fn execute(
161        &self,
162        effect: Effect,
163        state: &TuiState,
164    ) -> Pin<Box<dyn Future<Output = Option<Action>> + Send + 'static>>;
165}
166
167/// Owned bounded Action → Effect application loop.
168///
169/// The reducer runs synchronously. Effects are polled concurrently through a
170/// bounded owned set, so no task is detached and shutdown is deterministic.
171#[derive(Debug)]
172pub struct ActionLoop {
173    actions: mpsc::Receiver<Action>,
174    effect_capacity: usize,
175}
176
177impl ActionLoop {
178    /// Creates an application loop with explicit non-zero queue bounds.
179    ///
180    /// # Panics
181    ///
182    /// Panics when either capacity is zero.
183    #[must_use]
184    pub fn new(action_capacity: usize, effect_capacity: usize) -> (ActionSender, Self) {
185        assert!(action_capacity > 0, "action capacity must be non-zero");
186        assert!(effect_capacity > 0, "effect capacity must be non-zero");
187        let (action_sender, actions) = mpsc::channel(action_capacity);
188        (
189            ActionSender {
190                sender: action_sender,
191            },
192            Self {
193                actions,
194                effect_capacity,
195            },
196        )
197    }
198
199    /// Runs until every action sender is dropped and all accepted effects finish.
200    ///
201    /// Effects are polled concurrently up to the configured bound and their
202    /// completion actions are reduced in dispatch order. Action reception is
203    /// backpressured while that bound is full, so terminal input remains
204    /// bounded without dropping authoritative snapshot reloads.
205    pub async fn run(mut self, state: &mut TuiState, executor: &dyn EffectExecutor) {
206        type EffectFuture = Pin<Box<dyn Future<Output = Option<Action>> + Send + 'static>>;
207        let mut running = FuturesOrdered::<EffectFuture>::new();
208        let mut actions_open = true;
209        loop {
210            if !actions_open && running.is_empty() {
211                break;
212            }
213            tokio::select! {
214                action = self.actions.recv(), if actions_open && running.len() < self.effect_capacity => {
215                    match action {
216                        Some(action) => {
217                            let effects = reduce(state, action);
218                            enqueue_effects(
219                                &mut running,
220                                effects,
221                                self.effect_capacity,
222                                executor,
223                                state,
224                            );
225                        }
226                        None => actions_open = false,
227                    }
228                }
229                result = running.next(), if !running.is_empty() => {
230                    if let Some(Some(action)) = result {
231                        let effects = reduce(state, action);
232                        enqueue_effects(
233                            &mut running,
234                            effects,
235                            self.effect_capacity,
236                            executor,
237                            state,
238                        );
239                    }
240                }
241            }
242        }
243    }
244}
245
246fn enqueue_effects(
247    running: &mut FuturesOrdered<Pin<Box<dyn Future<Output = Option<Action>> + Send + 'static>>>,
248    effects: Vec<Effect>,
249    capacity: usize,
250    executor: &dyn EffectExecutor,
251    state: &TuiState,
252) {
253    for effect in effects {
254        if running.len() == capacity {
255            // A reducer emits authoritative reload before its coalescible frame,
256            // so only an observational render can reach this branch.
257            debug_assert!(matches!(effect, Effect::Render));
258            continue;
259        }
260        running.push_back(executor.execute(effect, state));
261    }
262}
263
264/// Pure deterministic state transition.
265#[must_use]
266#[allow(clippy::too_many_lines)] // Keep the complete state-action grammar auditable together.
267pub fn reduce(state: &mut TuiState, action: Action) -> Vec<Effect> {
268    match action {
269        Action::Event(event) => reduce_event(state, &event),
270        Action::SnapshotLoaded(snapshot) => {
271            if snapshot.state().session_id() == state.session_id {
272                state.rebuild(&snapshot);
273            } else {
274                state.notify("ignored snapshot for a different session");
275            }
276            vec![Effect::Render]
277        }
278        Action::SnapshotLoadFailed(message) => {
279            state.resyncing = false;
280            state.notify(format!("session resync failed: {message}"));
281            state.bump_generation();
282            vec![Effect::Render]
283        }
284        Action::Reconnected => request_resync(state, "event stream reconnected"),
285        Action::Resize { width, height } => {
286            state.viewport_width = width.max(1);
287            state.viewport_height = height.max(1);
288            state.bump_generation();
289            vec![Effect::Render]
290        }
291        Action::SetEditor(editor) => {
292            state.editor = bounded_text(editor, MAX_EPHEMERAL_TEXT_BYTES);
293            state.bump_generation();
294            vec![Effect::Render]
295        }
296        Action::AddAttachment(attachment) => {
297            if let Err(error) = state.add_attachment(attachment) {
298                state.notify(error.to_string());
299            }
300            state.bump_generation();
301            vec![Effect::Render]
302        }
303        Action::RemoveAttachment { index } => {
304            if !state.remove_attachment(index) {
305                state.notify("attachment index is out of range");
306            }
307            state.bump_generation();
308            vec![Effect::Render]
309        }
310        Action::ClearAttachments => {
311            state.clear_attachments();
312            state.bump_generation();
313            vec![Effect::Render]
314        }
315        Action::ShowPendingUserPrompt(text) => {
316            state.show_pending_user_prompt(bounded_text(text, MAX_EPHEMERAL_TEXT_BYTES));
317            state.bump_generation();
318            vec![Effect::Render]
319        }
320        Action::StartRunActivity => {
321            state.running = true;
322            state.run_elapsed_seconds = 0;
323            state.model_retry = None;
324            state.run_status = None;
325            state.usage = None;
326            state.cost = None;
327            state.notifications.clear();
328            state.bump_generation();
329            vec![Effect::Render]
330        }
331        Action::AdvanceRunElapsed(seconds) => {
332            if state.running && seconds > 0 {
333                state.run_elapsed_seconds = state.run_elapsed_seconds.saturating_add(seconds);
334                if let Some(retry) = state.model_retry.as_mut() {
335                    retry.advance(seconds);
336                }
337                state.bump_generation();
338                vec![Effect::Render]
339            } else {
340                Vec::new()
341            }
342        }
343        Action::FinishRunActivity => {
344            if state.running {
345                state.running = false;
346                state.model_retry = None;
347                state.bump_generation();
348                vec![Effect::Render]
349            } else {
350                Vec::new()
351            }
352        }
353        Action::SetPendingReasoningEffort(effort) => {
354            if state.pending_reasoning_effort == effort {
355                Vec::new()
356            } else {
357                state.pending_reasoning_effort = effort;
358                state.bump_generation();
359                vec![Effect::Render]
360            }
361        }
362        Action::ScrollTranscriptUp { rows } => {
363            state.transcript_viewport.scroll_up(rows);
364            state.bump_generation();
365            vec![Effect::Render]
366        }
367        Action::ScrollTranscriptDown { rows } => {
368            state.transcript_viewport.scroll_down(rows);
369            state.bump_generation();
370            vec![Effect::Render]
371        }
372        Action::FollowTranscriptTail => {
373            state.transcript_viewport.follow_tail();
374            state.bump_generation();
375            vec![Effect::Render]
376        }
377        Action::SelectApproval(choice) => {
378            if state.approval.is_some() && !state.approval_submitting {
379                state.approval_choice = choice;
380                state.bump_generation();
381                vec![Effect::Render]
382            } else {
383                Vec::new()
384            }
385        }
386        Action::SetApprovalSubmitting(submitting) => {
387            if state.approval.is_some() && state.approval_submitting != submitting {
388                state.approval_submitting = submitting;
389                state.bump_generation();
390                vec![Effect::Render]
391            } else {
392                Vec::new()
393            }
394        }
395        Action::ToggleThinking => {
396            state.preferences.thinking_collapsed = !state.preferences.thinking_collapsed;
397            state.bump_generation();
398            vec![Effect::Render]
399        }
400        Action::ToggleTool(tool_call_id) => {
401            if !state.preferences.expanded_tools.remove(&tool_call_id) {
402                state.preferences.expanded_tools.insert(tool_call_id);
403            }
404            state.bump_generation();
405            vec![Effect::Render]
406        }
407        Action::ToggleAllTools => {
408            if state
409                .tools
410                .keys()
411                .all(|id| state.preferences.expanded_tools.contains(id))
412            {
413                state.preferences.expanded_tools.clear();
414            } else {
415                state
416                    .preferences
417                    .expanded_tools
418                    .extend(state.tools.keys().copied());
419            }
420            state.bump_generation();
421            vec![Effect::Render]
422        }
423        Action::QueueSteering(text) => {
424            push_queue(&mut state.steering_queue, text);
425            state.bump_generation();
426            vec![Effect::Render]
427        }
428        Action::QueueFollowUp(text) => {
429            push_queue(&mut state.follow_up_queue, text);
430            state.bump_generation();
431            vec![Effect::Render]
432        }
433        Action::SetOverlay(overlay) => {
434            state.overlay = overlay;
435            state.bump_generation();
436            vec![Effect::Render]
437        }
438        Action::Notify(message) => {
439            state.notify(message);
440            state.bump_generation();
441            vec![Effect::Render]
442        }
443        Action::SetMcpHealth(rows) => {
444            state.set_mcp_health(rows);
445            state.bump_generation();
446            vec![Effect::Render]
447        }
448    }
449}
450
451#[allow(clippy::too_many_lines)] // Keep the complete protocol-event grammar auditable together.
452fn reduce_event(state: &mut TuiState, envelope: &EventEnvelope) -> Vec<Effect> {
453    if envelope.session_id() != state.session_id {
454        state.notify("ignored event for a different session");
455        return vec![Effect::Render];
456    }
457    if state
458        .observed_event_ids
459        .iter()
460        .any(|event_id| *event_id == envelope.event_id())
461    {
462        return Vec::new();
463    }
464    if envelope.sequence() <= state.event_cursor {
465        if envelope.event_type().compatibility()
466            == tea_protocol::EventCompatibility::SkippableObservation
467        {
468            state.remember_event(envelope.event_id());
469            return Vec::new();
470        }
471        return request_resync(state, "late state-bearing event detected");
472    }
473    // Durable records and observations do not advance one-for-one, so the
474    // protocol guarantees monotonic event order rather than contiguity.
475    if state.resyncing {
476        state.event_cursor = envelope.sequence();
477        state.remember_event(envelope.event_id());
478        return Vec::new();
479    }
480
481    state.event_cursor = envelope.sequence();
482    state.remember_event(envelope.event_id());
483    let mut effects = vec![Effect::Render];
484    match envelope.event() {
485        AgentEvent::RunStarted {} => {
486            state.running = true;
487            state.run_elapsed_seconds = 0;
488            state.model_retry = None;
489            state.observation_run_id = envelope.run_id();
490            state.run_status = None;
491            state.usage = None;
492            state.cost = None;
493            state.notifications.clear();
494            state.hosted_tools.clear();
495            state.hosted_tool_order.clear();
496        }
497        AgentEvent::MessageDelta {
498            message_id,
499            content_index,
500            delta,
501        } => {
502            let (thinking, text) = match delta {
503                EventDelta::TextDelta { text } => (false, text.as_str()),
504                EventDelta::ThinkingDelta { text } => (true, text.as_str()),
505            };
506            if !state.streaming.contains_key(message_id) {
507                state.record_stream(*message_id);
508            }
509            let message = state.streaming.entry(*message_id).or_default();
510            let block = message
511                .blocks
512                .entry(*content_index)
513                .or_insert_with(|| StreamingBlock {
514                    thinking,
515                    text: String::new(),
516                    generation: 0,
517                });
518            if block.thinking != thinking {
519                return request_resync(state, "stream block type changed");
520            }
521            if block.text.len().saturating_add(text.len()) > MAX_EPHEMERAL_TEXT_BYTES {
522                return request_resync(state, "streamed message exceeded UI bound");
523            }
524            block.text.push_str(text);
525            block.generation = block.generation.wrapping_add(1);
526            state.note_transcript_item();
527        }
528        AgentEvent::ToolCallRequested {
529            tool_call_id,
530            tool_name,
531            arguments,
532        } => {
533            state.record_tool_activity(*tool_call_id);
534            state
535                .tools
536                .entry(*tool_call_id)
537                .or_insert_with(|| ToolView {
538                    tool_call_id: *tool_call_id,
539                    tool_name: tool_name.clone(),
540                    arguments: arguments.clone(),
541                    status: "requested".to_owned(),
542                    approval_decision: None,
543                    progress: None,
544                    presentation: None,
545                    preview: None,
546                });
547            state.note_transcript_item();
548        }
549        AgentEvent::ToolExecutionProgress {
550            tool_call_id,
551            message,
552            completed_units,
553            total_units,
554        } => {
555            if let Some(tool) = state.tools.get_mut(tool_call_id) {
556                "running".clone_into(&mut tool.status);
557                tool.progress = Some(ToolProgressView {
558                    message: message.clone(),
559                    completed_units: *completed_units,
560                    total_units: *total_units,
561                });
562                state.note_transcript_item();
563            } else {
564                return request_resync(state, "tool progress referenced an unknown call");
565            }
566        }
567        AgentEvent::ToolExecutionPreview {
568            tool_call_id,
569            presentation,
570        } => {
571            if let Some(tool) = state.tools.get_mut(tool_call_id) {
572                tool.preview = Some(presentation.clone());
573            } else {
574                return request_resync(state, "tool preview referenced an unknown call");
575            }
576        }
577        AgentEvent::HostedToolStarted {
578            tool_call_id,
579            tool_name,
580        } => {
581            if state.hosted_tools.contains_key(tool_call_id) {
582                return request_resync(state, "hosted tool reused an active identity");
583            }
584            state.record_hosted_tool_activity(*tool_call_id);
585            state.hosted_tools.insert(
586                *tool_call_id,
587                HostedToolView {
588                    tool_call_id: *tool_call_id,
589                    tool_name: tool_name.clone(),
590                    arguments: None,
591                    outcome: None,
592                    source_count: None,
593                },
594            );
595            state.note_transcript_item();
596        }
597        AgentEvent::HostedToolCompleted {
598            tool_call_id,
599            tool_name,
600            arguments,
601            outcome,
602            source_count,
603        } => {
604            let Some(tool) = state.hosted_tools.get_mut(tool_call_id) else {
605                return request_resync(state, "hosted completion referenced an unknown call");
606            };
607            if tool.tool_name != *tool_name || tool.outcome.is_some() {
608                return request_resync(state, "hosted completion changed an active identity");
609            }
610            tool.arguments = Some(arguments.clone());
611            tool.outcome = Some(outcome.clone());
612            tool.source_count = Some(*source_count);
613            state.note_transcript_item();
614        }
615        AgentEvent::ModelRetryScheduled {
616            message_id,
617            attempt,
618            max_retries,
619            delay_ms,
620        } => {
621            state.streaming.remove(message_id);
622            state.streaming_order.retain(|id| id != message_id);
623            state.hosted_tools.clear();
624            state.hosted_tool_order.clear();
625            state.model_retry = Some(super::state::ModelRetryView::new(
626                *message_id,
627                *attempt,
628                *max_retries,
629                *delay_ms,
630            ));
631        }
632        AgentEvent::ModelRetryStarted { .. } => {
633            state.model_retry = None;
634        }
635        AgentEvent::ApprovalRequested { .. }
636        | AgentEvent::TurnCheckpointed {}
637        | AgentEvent::SessionCompacted { .. }
638        | AgentEvent::SessionForked { .. } => {
639            state.resyncing = true;
640            effects.insert(
641                0,
642                Effect::ReloadSnapshot {
643                    session_id: state.session_id,
644                },
645            );
646        }
647        AgentEvent::RunFinished {
648            status,
649            usage,
650            cost,
651        } => {
652            state.running = false;
653            state.model_retry = None;
654            state.run_status = Some(*status);
655            state.usage.clone_from(usage);
656            state.cost.clone_from(cost);
657            state.resyncing = true;
658            effects.insert(
659                0,
660                Effect::ReloadSnapshot {
661                    session_id: state.session_id,
662                },
663            );
664        }
665    }
666    state.bump_generation();
667    effects
668}
669
670fn request_resync(state: &mut TuiState, reason: &str) -> Vec<Effect> {
671    if state.resyncing {
672        Vec::new()
673    } else {
674        state.resyncing = true;
675        state.notify(reason);
676        state.bump_generation();
677        vec![
678            Effect::ReloadSnapshot {
679                session_id: state.session_id,
680            },
681            Effect::Render,
682        ]
683    }
684}
685
686fn push_queue(queue: &mut std::collections::VecDeque<String>, text: String) {
687    if queue.len() == MAX_VISIBLE_QUEUE_ITEMS {
688        queue.pop_front();
689    }
690    queue.push_back(bounded_text(text, 64 * 1024));
691}
692
693fn bounded_text(mut text: String, max_bytes: usize) -> String {
694    if text.len() <= max_bytes {
695        return text;
696    }
697    let mut boundary = max_bytes;
698    while !text.is_char_boundary(boundary) {
699        boundary -= 1;
700    }
701    text.truncate(boundary);
702    text
703}
704
705/// Returns whether an event is observational and safe to drop after a newer cursor.
706#[must_use]
707pub const fn is_observational(event: AgentEventType) -> bool {
708    matches!(
709        event,
710        AgentEventType::MessageDelta
711            | AgentEventType::ToolExecutionProgress
712            | AgentEventType::ToolExecutionPreview
713            | AgentEventType::HostedToolStarted
714            | AgentEventType::HostedToolCompleted
715            | AgentEventType::ModelRetryScheduled
716            | AgentEventType::ModelRetryStarted
717    )
718}