Skip to main content

tea_cli/tui/
state.rs

1use std::collections::{BTreeMap, BTreeSet, VecDeque};
2
3use tea_protocol::{
4    ApprovalDecision, BranchId, CanonicalMessage, ContentBlock, ExactCost, HostedToolOutcome,
5    MessageId, ModelId, ModelRef, ProfileId, ReasoningEffort, RunStatus, SessionId,
6    SessionSequence, ToolCallId, ToolPresentation, Usage,
7};
8use tea_session::{ApprovalArtifactEntry, SessionSnapshot, ToolExecutionState};
9
10use super::Overlay;
11use super::attachment::{AttachmentError, ComposerAttachment, validate_addition};
12use super::selectors::Selector;
13
14/// Maximum local notifications retained by the terminal projection.
15pub const MAX_NOTIFICATIONS: usize = 32;
16/// Maximum configured MCP server rows retained in the terminal projection.
17pub const MAX_MCP_HEALTH_ROWS: usize = 64;
18/// Maximum steering or follow-up entries retained for rendering.
19pub const MAX_VISIBLE_QUEUE_ITEMS: usize = 64;
20/// Maximum event identities retained for duplicate observational-event detection.
21pub const MAX_OBSERVED_EVENT_IDS: usize = 1024;
22/// Maximum incomplete streamed messages retained in arrival order.
23pub const MAX_ACTIVE_STREAM_MESSAGES: usize = 64;
24/// Maximum incomplete or uncommitted tool activities retained in arrival order.
25pub const MAX_ACTIVE_TOOL_ITEMS: usize = 128;
26
27/// Immutable startup context counts shown above the transcript.
28#[derive(Debug, Clone, PartialEq, Eq, Default)]
29pub struct StartupContext {
30    workspace: String,
31    context_documents: usize,
32    skills: usize,
33    prompt_templates: usize,
34    diagnostics: usize,
35}
36
37impl StartupContext {
38    /// Creates a bounded, path-safe startup summary.
39    #[must_use]
40    pub fn new(
41        workspace: impl Into<String>,
42        context_documents: usize,
43        skills: usize,
44        prompt_templates: usize,
45        diagnostics: usize,
46    ) -> Self {
47        Self {
48            workspace: sanitize_summary(&workspace.into()),
49            context_documents,
50            skills,
51            prompt_templates,
52            diagnostics,
53        }
54    }
55
56    /// Returns the safe workspace label.
57    #[must_use]
58    pub fn workspace(&self) -> &str {
59        &self.workspace
60    }
61
62    /// Returns loaded context-document count.
63    #[must_use]
64    pub const fn context_documents(&self) -> usize {
65        self.context_documents
66    }
67
68    /// Returns discovered skill count.
69    #[must_use]
70    pub const fn skills(&self) -> usize {
71        self.skills
72    }
73
74    /// Returns discovered prompt-template count.
75    #[must_use]
76    pub const fn prompt_templates(&self) -> usize {
77        self.prompt_templates
78    }
79
80    /// Returns safe resource diagnostic count.
81    #[must_use]
82    pub const fn diagnostics(&self) -> usize {
83        self.diagnostics
84    }
85}
86
87/// Local-only view preferences; toggling them never changes durable state.
88#[derive(Debug, Clone, PartialEq, Eq, Default)]
89pub struct ViewPreferences {
90    /// Whether all reasoning blocks are collapsed.
91    pub thinking_collapsed: bool,
92    /// Tool calls whose arguments/output were explicitly expanded.
93    pub expanded_tools: BTreeSet<ToolCallId>,
94}
95
96/// Local transcript navigation state. It is never persisted in session records.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct TranscriptViewport {
99    offset_from_tail_rows: usize,
100    follow_tail: bool,
101    unread_items: usize,
102}
103
104impl Default for TranscriptViewport {
105    fn default() -> Self {
106        Self {
107            offset_from_tail_rows: 0,
108            follow_tail: true,
109            unread_items: 0,
110        }
111    }
112}
113
114impl TranscriptViewport {
115    /// Returns whether incoming transcript content is followed immediately.
116    #[must_use]
117    pub const fn follows_tail(&self) -> bool {
118        self.follow_tail
119    }
120
121    /// Returns the current line offset from the latest transcript content.
122    #[must_use]
123    pub const fn offset_from_tail_rows(&self) -> usize {
124        self.offset_from_tail_rows
125    }
126
127    /// Returns the number of incoming items received while browsing history.
128    #[must_use]
129    pub const fn unread_items(&self) -> usize {
130        self.unread_items
131    }
132
133    pub(crate) fn scroll_up(&mut self, rows: usize) {
134        self.follow_tail = false;
135        self.offset_from_tail_rows = self.offset_from_tail_rows.saturating_add(rows.max(1));
136    }
137
138    pub(crate) fn scroll_down(&mut self, rows: usize) {
139        self.offset_from_tail_rows = self.offset_from_tail_rows.saturating_sub(rows.max(1));
140        if self.offset_from_tail_rows == 0 {
141            self.follow_tail = true;
142            self.unread_items = 0;
143        }
144    }
145
146    pub(crate) fn follow_tail(&mut self) {
147        self.offset_from_tail_rows = 0;
148        self.follow_tail = true;
149        self.unread_items = 0;
150    }
151
152    pub(crate) fn note_new_item(&mut self) {
153        if !self.follow_tail {
154            self.unread_items = self.unread_items.saturating_add(1);
155            self.offset_from_tail_rows = self.offset_from_tail_rows.saturating_add(1);
156        }
157    }
158}
159
160/// One streamed content block not yet guaranteed durable.
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub struct StreamingBlock {
163    /// Whether this is hidden reasoning rather than visible assistant text.
164    pub thinking: bool,
165    /// Accumulated bounded deltas.
166    pub text: String,
167    /// Content generation used by render caches.
168    pub generation: u64,
169}
170
171/// Ephemeral streamed assistant message assembled by content index.
172#[derive(Debug, Clone, PartialEq, Eq, Default)]
173pub struct StreamingMessage {
174    /// Ordered partial blocks.
175    pub blocks: BTreeMap<u32, StreamingBlock>,
176}
177
178/// Latest transient progress for one tool call.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct ToolProgressView {
181    /// Bounded technical progress text.
182    pub message: String,
183    /// Completed work units.
184    pub completed_units: u64,
185    /// Total units when known.
186    pub total_units: Option<u64>,
187}
188
189/// Durable tool state plus optional transient progress.
190#[derive(Debug, Clone, PartialEq)]
191pub struct ToolView {
192    /// Stable tool-call identity.
193    pub tool_call_id: ToolCallId,
194    /// Registered tool name.
195    pub tool_name: String,
196    /// Validated provider-neutral arguments.
197    pub arguments: serde_json::Value,
198    /// Human-readable durable execution state.
199    pub status: String,
200    /// Durable approval decision when the canonical session retained one.
201    pub approval_decision: Option<ApprovalDecision>,
202    /// Latest non-durable progress.
203    pub progress: Option<ToolProgressView>,
204    /// Optional durable UI presentation kept out of model context.
205    pub presentation: Option<ToolPresentation>,
206    /// Optional non-durable preview shown while this call awaits approval.
207    pub preview: Option<ToolPresentation>,
208}
209
210/// Ephemeral projection of provider-hosted work before its assistant message is durable.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub struct HostedToolView {
213    /// Kernel-owned hosted activity identifier.
214    pub tool_call_id: ToolCallId,
215    /// Stable hosted tool name.
216    pub tool_name: String,
217    /// Arguments available after the provider completes the activity.
218    pub arguments: Option<serde_json::Value>,
219    /// Terminal outcome available after completion.
220    pub outcome: Option<HostedToolOutcome>,
221    /// Number of normalized durable sources reported at completion.
222    pub source_count: Option<u32>,
223}
224
225/// Ephemeral projection of one scheduled model retry.
226#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct ModelRetryView {
228    /// Ephemeral assistant message reused by the retry.
229    pub message_id: MessageId,
230    /// One-based retry number.
231    pub attempt: u32,
232    /// Maximum retry count, excluding the initial request.
233    pub max_retries: u32,
234    delay_ms: u64,
235    elapsed_seconds: u64,
236}
237
238impl ModelRetryView {
239    pub(crate) const fn new(
240        message_id: MessageId,
241        attempt: u32,
242        max_retries: u32,
243        delay_ms: u64,
244    ) -> Self {
245        Self {
246            message_id,
247            attempt,
248            max_retries,
249            delay_ms,
250            elapsed_seconds: 0,
251        }
252    }
253
254    /// Returns the rounded-up whole seconds remaining before the retry.
255    #[must_use]
256    pub const fn remaining_seconds(&self) -> u64 {
257        let elapsed_ms = self.elapsed_seconds.saturating_mul(1_000);
258        self.delay_ms.saturating_sub(elapsed_ms).saturating_add(999) / 1_000
259    }
260
261    pub(crate) fn advance(&mut self, seconds: u64) {
262        self.elapsed_seconds = self.elapsed_seconds.saturating_add(seconds);
263    }
264}
265
266/// Locally visible prompt accepted by the service but not yet durable.
267#[derive(Debug, Clone, PartialEq, Eq)]
268pub(crate) struct PendingUserPrompt {
269    text: String,
270    durable_message_count: usize,
271}
272
273impl PendingUserPrompt {
274    pub(crate) fn text(&self) -> &str {
275        &self.text
276    }
277}
278
279/// Persisted redacted approval projection suitable for terminal display.
280#[derive(Debug, Clone, PartialEq, Eq)]
281pub struct ApprovalView {
282    /// Stable approval identity.
283    pub approval_id: tea_protocol::ApprovalId,
284    /// Stable tool-call identity.
285    pub tool_call_id: ToolCallId,
286    /// Registered tool name.
287    pub tool_name: String,
288    /// Declared effect names.
289    pub effects: Vec<String>,
290    /// Persisted policy execution target.
291    pub target: String,
292    /// Redacted resource locators.
293    pub resources: Vec<String>,
294    /// Technical reason from the persisted presentation.
295    pub reason: String,
296    /// Persisted redacted argument JSON.
297    pub arguments: String,
298    /// Caller-clock expiry.
299    pub expires_at: tea_protocol::ProtocolTimestamp,
300}
301
302/// One canonical choice supported by the durable approval contract.
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
304pub enum ApprovalChoice {
305    /// Authorize only the pending tool call.
306    #[default]
307    AllowOnce,
308    /// Authorize matching resources for this session.
309    AllowSession,
310    /// Deny the pending tool call.
311    Deny,
312}
313
314impl ApprovalChoice {
315    /// Returns the protocol decision represented by this choice.
316    #[must_use]
317    pub const fn decision(self) -> tea_protocol::ApprovalDecision {
318        match self {
319            Self::AllowOnce => tea_protocol::ApprovalDecision::AllowOnce,
320            Self::AllowSession => tea_protocol::ApprovalDecision::AllowSession,
321            Self::Deny => tea_protocol::ApprovalDecision::Deny,
322        }
323    }
324
325    /// Returns the next choice in display order.
326    #[must_use]
327    pub const fn next(self) -> Self {
328        match self {
329            Self::AllowOnce => Self::AllowSession,
330            Self::AllowSession => Self::Deny,
331            Self::Deny => Self::AllowOnce,
332        }
333    }
334
335    /// Returns the previous choice in display order.
336    #[must_use]
337    pub const fn previous(self) -> Self {
338        match self {
339            Self::AllowOnce => Self::Deny,
340            Self::AllowSession => Self::AllowOnce,
341            Self::Deny => Self::AllowSession,
342        }
343    }
344
345    pub(crate) const fn label(self) -> &'static str {
346        match self {
347            Self::AllowOnce => "allow once",
348            Self::AllowSession => "allow for session",
349            Self::Deny => "deny",
350        }
351    }
352}
353
354/// Pure terminal projection of canonical durable state and bounded ephemeral observations.
355#[derive(Debug, Clone, PartialEq)]
356pub struct TuiState {
357    pub(crate) session_id: SessionId,
358    pub(crate) profile_id: ProfileId,
359    pub(crate) model_ref: Option<ModelRef>,
360    pub(crate) reasoning_effort: Option<ReasoningEffort>,
361    pub(crate) model_default_reasoning_effort: Option<ReasoningEffort>,
362    pub(crate) pending_reasoning_effort: Option<ReasoningEffort>,
363    pub(crate) active_branch_id: Option<BranchId>,
364    pub(crate) durable_tail: SessionSequence,
365    pub(crate) event_cursor: SessionSequence,
366    pub(crate) messages: Vec<CanonicalMessage>,
367    pub(crate) pending_user_prompt: Option<PendingUserPrompt>,
368    pub(crate) tools: BTreeMap<ToolCallId, ToolView>,
369    pub(crate) hosted_tools: BTreeMap<ToolCallId, HostedToolView>,
370    pub(crate) approval: Option<ApprovalView>,
371    pub(crate) approval_choice: ApprovalChoice,
372    pub(crate) approval_submitting: bool,
373    pub(crate) streaming: BTreeMap<MessageId, StreamingMessage>,
374    /// Arrival order for incomplete streamed messages. This is local UI state;
375    /// canonical snapshots remain the source of durable transcript ordering.
376    pub(crate) streaming_order: VecDeque<MessageId>,
377    /// Event/snapshot order for tool activities not yet represented by a
378    /// committed transcript cell.
379    pub(crate) tool_order: VecDeque<ToolCallId>,
380    pub(crate) hosted_tool_order: VecDeque<ToolCallId>,
381    pub(crate) model_retry: Option<ModelRetryView>,
382    pub(crate) observed_event_ids: VecDeque<tea_protocol::EventId>,
383    pub(crate) running: bool,
384    /// Locally measured whole seconds since the active request was accepted.
385    pub(crate) run_elapsed_seconds: u64,
386    pub(crate) observation_run_id: Option<tea_protocol::RunId>,
387    pub(crate) run_status: Option<RunStatus>,
388    pub(crate) usage: Option<Usage>,
389    pub(crate) cost: Option<ExactCost>,
390    pub(crate) steering_queue: VecDeque<String>,
391    pub(crate) follow_up_queue: VecDeque<String>,
392    pub(crate) attachments: Vec<ComposerAttachment>,
393    pub(crate) notifications: VecDeque<String>,
394    pub(crate) mcp_health: Vec<String>,
395    pub(crate) editor: String,
396    pub(crate) overlay: Option<Overlay>,
397    pub(crate) viewport_width: u16,
398    pub(crate) viewport_height: u16,
399    pub(crate) transcript_viewport: TranscriptViewport,
400    pub(crate) preferences: ViewPreferences,
401    pub(crate) startup: StartupContext,
402    pub(crate) generation: u64,
403    pub(crate) resyncing: bool,
404}
405
406#[derive(Debug, Clone, PartialEq, Default)]
407pub(crate) struct SessionEphemera {
408    steering_queue: VecDeque<String>,
409    follow_up_queue: VecDeque<String>,
410    attachments: Vec<ComposerAttachment>,
411    pending_reasoning_effort: Option<ReasoningEffort>,
412}
413
414impl TuiState {
415    /// Rebuilds a projection from one immutable canonical snapshot.
416    #[must_use]
417    pub fn from_snapshot(snapshot: &SessionSnapshot, startup: StartupContext) -> Self {
418        let state = snapshot.state();
419        let tools = durable_tools(snapshot);
420        let tool_order = tool_order(state.messages(), &tools);
421        let approval = pending_approval(snapshot);
422        Self {
423            session_id: state.session_id(),
424            profile_id: state.configuration().profile_id().clone(),
425            model_ref: state.configuration().model_ref().cloned(),
426            reasoning_effort: state.configuration().reasoning_effort(),
427            model_default_reasoning_effort: None,
428            pending_reasoning_effort: None,
429            active_branch_id: state.active_branch_id(),
430            durable_tail: state.tail_sequence(),
431            event_cursor: state.tail_sequence(),
432            messages: state.messages().to_vec(),
433            pending_user_prompt: None,
434            tools,
435            hosted_tools: BTreeMap::new(),
436            approval,
437            approval_choice: ApprovalChoice::default(),
438            approval_submitting: false,
439            streaming: BTreeMap::new(),
440            streaming_order: VecDeque::new(),
441            tool_order,
442            hosted_tool_order: VecDeque::new(),
443            model_retry: None,
444            observed_event_ids: VecDeque::new(),
445            running: false,
446            run_elapsed_seconds: 0,
447            observation_run_id: None,
448            run_status: None,
449            usage: None,
450            cost: None,
451            steering_queue: VecDeque::new(),
452            follow_up_queue: VecDeque::new(),
453            attachments: Vec::new(),
454            notifications: VecDeque::new(),
455            mcp_health: Vec::new(),
456            editor: String::new(),
457            overlay: None,
458            viewport_width: 80,
459            viewport_height: 24,
460            transcript_viewport: TranscriptViewport::default(),
461            preferences: ViewPreferences::default(),
462            startup,
463            generation: 0,
464            resyncing: false,
465        }
466    }
467
468    /// Returns session identity.
469    #[must_use]
470    pub const fn session_id(&self) -> SessionId {
471        self.session_id
472    }
473
474    /// Returns the active durable model selection.
475    #[must_use]
476    pub const fn model_id(&self) -> Option<&ModelId> {
477        match &self.model_ref {
478            Some(model) => Some(model.model_id()),
479            None => None,
480        }
481    }
482
483    /// Returns the active durable provider-qualified model selection.
484    #[must_use]
485    pub const fn model_ref(&self) -> Option<&ModelRef> {
486        self.model_ref.as_ref()
487    }
488
489    /// Returns the durable session reasoning selection, when explicit.
490    #[must_use]
491    pub const fn reasoning_effort(&self) -> Option<ReasoningEffort> {
492        self.reasoning_effort
493    }
494
495    /// Returns a queued next-turn reasoning selection, when present.
496    #[must_use]
497    pub const fn pending_reasoning_effort(&self) -> Option<ReasoningEffort> {
498        self.pending_reasoning_effort
499    }
500
501    /// Returns the effective durable or pending effort shown by the TUI.
502    #[must_use]
503    pub fn displayed_reasoning_effort(&self) -> &'static str {
504        self.pending_reasoning_effort
505            .or(self.reasoning_effort)
506            .or(self.model_default_reasoning_effort)
507            .map_or("default", ReasoningEffort::as_str)
508    }
509
510    /// Returns the current durable transcript.
511    #[must_use]
512    pub fn messages(&self) -> &[CanonicalMessage] {
513        &self.messages
514    }
515
516    /// Returns provider-neutral usage from the latest observed terminal run event.
517    #[must_use]
518    pub const fn usage(&self) -> Option<&Usage> {
519        self.usage.as_ref()
520    }
521
522    /// Returns the current event cursor.
523    #[must_use]
524    pub const fn event_cursor(&self) -> SessionSequence {
525        self.event_cursor
526    }
527
528    /// Returns whether a snapshot reload is pending after reconnect or a gap.
529    #[must_use]
530    pub const fn is_resyncing(&self) -> bool {
531        self.resyncing
532    }
533
534    /// Returns current render generation.
535    #[must_use]
536    pub const fn generation(&self) -> u64 {
537        self.generation
538    }
539
540    /// Returns local view preferences.
541    #[must_use]
542    pub const fn preferences(&self) -> &ViewPreferences {
543        &self.preferences
544    }
545
546    /// Returns local transcript navigation state.
547    #[must_use]
548    pub const fn transcript_viewport(&self) -> &TranscriptViewport {
549        &self.transcript_viewport
550    }
551
552    /// Returns the persisted approval projection, when pending.
553    #[must_use]
554    pub const fn approval(&self) -> Option<&ApprovalView> {
555        self.approval.as_ref()
556    }
557
558    /// Returns the selected approval choice.
559    #[must_use]
560    pub const fn approval_choice(&self) -> ApprovalChoice {
561        self.approval_choice
562    }
563
564    /// Returns whether the approval command is already owned by the service.
565    #[must_use]
566    pub const fn approval_submitting(&self) -> bool {
567        self.approval_submitting
568    }
569
570    /// Returns streamed incomplete messages.
571    #[must_use]
572    pub const fn streaming(&self) -> &BTreeMap<MessageId, StreamingMessage> {
573        &self.streaming
574    }
575
576    /// Returns durable/transient tool projections.
577    #[must_use]
578    pub const fn tools(&self) -> &BTreeMap<ToolCallId, ToolView> {
579        &self.tools
580    }
581
582    /// Returns ephemeral provider-hosted activity projections.
583    #[must_use]
584    pub const fn hosted_tools(&self) -> &BTreeMap<ToolCallId, HostedToolView> {
585        &self.hosted_tools
586    }
587
588    /// Returns the currently scheduled model retry, when waiting in backoff.
589    #[must_use]
590    pub const fn model_retry(&self) -> Option<&ModelRetryView> {
591        self.model_retry.as_ref()
592    }
593
594    /// Returns current editor contents.
595    #[must_use]
596    pub fn editor(&self) -> &str {
597        &self.editor
598    }
599
600    /// Returns whether a model/tool run is currently active.
601    #[must_use]
602    pub const fn is_running(&self) -> bool {
603        self.running
604    }
605
606    /// Returns elapsed whole seconds for the active request.
607    #[must_use]
608    pub const fn run_elapsed_seconds(&self) -> u64 {
609        self.run_elapsed_seconds
610    }
611
612    /// Returns the number of session-scoped ephemeral queued inputs shown.
613    #[must_use]
614    pub fn queued_message_count(&self) -> usize {
615        self.steering_queue.len() + self.follow_up_queue.len()
616    }
617
618    /// Returns validated images retained for the next idle prompt submission.
619    #[must_use]
620    pub fn attachments(&self) -> &[ComposerAttachment] {
621        &self.attachments
622    }
623
624    /// Clones the canonical image blocks in submission order.
625    #[must_use]
626    pub fn attachment_blocks(&self) -> Vec<ContentBlock> {
627        self.attachments
628            .iter()
629            .map(|attachment| attachment.content().clone())
630            .collect()
631    }
632
633    /// Returns aggregate encoded image bytes retained by the composer.
634    #[must_use]
635    pub fn attachment_encoded_bytes(&self) -> usize {
636        self.attachments
637            .iter()
638            .map(ComposerAttachment::encoded_bytes)
639            .sum()
640    }
641
642    /// Returns the active local selector, when open.
643    #[must_use]
644    pub fn selector(&self) -> Option<&Selector> {
645        self.overlay.as_ref().and_then(Overlay::selector)
646    }
647
648    pub(crate) fn take_queued_text(&mut self) -> String {
649        let mut queued = self
650            .steering_queue
651            .drain(..)
652            .chain(self.follow_up_queue.drain(..))
653            .collect::<Vec<_>>();
654        queued.retain(|text| !text.is_empty());
655        queued.join("\n")
656    }
657
658    pub(crate) fn take_session_ephemera(&mut self) -> SessionEphemera {
659        SessionEphemera {
660            steering_queue: std::mem::take(&mut self.steering_queue),
661            follow_up_queue: std::mem::take(&mut self.follow_up_queue),
662            attachments: std::mem::take(&mut self.attachments),
663            pending_reasoning_effort: self.pending_reasoning_effort.take(),
664        }
665    }
666
667    pub(crate) fn restore_session_ephemera(&mut self, ephemera: SessionEphemera) {
668        self.steering_queue = ephemera.steering_queue;
669        self.follow_up_queue = ephemera.follow_up_queue;
670        self.attachments = ephemera.attachments;
671        self.pending_reasoning_effort = ephemera.pending_reasoning_effort;
672    }
673
674    pub(crate) fn add_attachment(
675        &mut self,
676        attachment: ComposerAttachment,
677    ) -> Result<(), AttachmentError> {
678        validate_addition(
679            self.attachments.len(),
680            self.attachment_encoded_bytes(),
681            attachment.encoded_bytes(),
682        )?;
683        self.attachments.push(attachment);
684        Ok(())
685    }
686
687    pub(crate) fn remove_attachment(&mut self, index: usize) -> bool {
688        let Some(index) = index
689            .checked_sub(1)
690            .filter(|index| *index < self.attachments.len())
691        else {
692            return false;
693        };
694        self.attachments.remove(index);
695        true
696    }
697
698    pub(crate) fn clear_attachments(&mut self) {
699        self.attachments.clear();
700    }
701
702    pub(crate) fn rebuild(&mut self, snapshot: &SessionSnapshot) {
703        let state = snapshot.state();
704        let previous_message_count = self.messages.len();
705        self.session_id = state.session_id();
706        self.profile_id = state.configuration().profile_id().clone();
707        self.model_ref = state.configuration().model_ref().cloned();
708        self.reasoning_effort = state.configuration().reasoning_effort();
709        self.active_branch_id = state.active_branch_id();
710        self.durable_tail = state.tail_sequence();
711        // Event sequence is monotonic within the observation stream but may
712        // diverge from record sequence after a run starts. Preserve the live
713        // event cursor during an in-process rebuild; startup begins at the
714        // durable tail in `from_snapshot`.
715        self.messages = state.messages().to_vec();
716        if self.messages.len() > previous_message_count {
717            for _ in previous_message_count..self.messages.len() {
718                self.transcript_viewport.note_new_item();
719            }
720        }
721        if self
722            .pending_user_prompt
723            .as_ref()
724            .is_some_and(|pending| prompt_is_durable(&self.messages, pending))
725        {
726            self.pending_user_prompt = None;
727        }
728        let previews = self
729            .tools
730            .iter()
731            .filter_map(|(tool_call_id, tool)| {
732                tool.preview.clone().map(|preview| (*tool_call_id, preview))
733            })
734            .collect::<BTreeMap<_, _>>();
735        self.tools = durable_tools(snapshot);
736        self.tool_order = tool_order(&self.messages, &self.tools);
737        self.hosted_tools.clear();
738        self.hosted_tool_order.clear();
739        self.model_retry = None;
740        let approval = pending_approval(snapshot);
741        if let Some(pending) = &approval
742            && let Some(preview) = previews.get(&pending.tool_call_id)
743            && let Some(tool) = self.tools.get_mut(&pending.tool_call_id)
744        {
745            tool.preview = Some(preview.clone());
746        }
747        let approval_changed = self.approval.as_ref().map(|view| view.approval_id)
748            != approval.as_ref().map(|view| view.approval_id);
749        self.approval = approval;
750        if approval_changed || self.approval.is_none() {
751            self.approval_choice = ApprovalChoice::default();
752            self.approval_submitting = false;
753        }
754        // Deltas and progress cannot be reconstructed reliably after a gap.
755        self.streaming.clear();
756        self.streaming_order.clear();
757        self.resyncing = false;
758        self.bump_generation();
759    }
760
761    pub(crate) fn set_model_default_reasoning_effort(
762        &mut self,
763        effort: Option<ReasoningEffort>,
764    ) -> bool {
765        if self.model_default_reasoning_effort == effort {
766            false
767        } else {
768            self.model_default_reasoning_effort = effort;
769            self.bump_generation();
770            true
771        }
772    }
773
774    pub(crate) fn bump_generation(&mut self) {
775        self.generation = self.generation.wrapping_add(1);
776    }
777
778    pub(crate) fn show_pending_user_prompt(&mut self, text: String) {
779        self.pending_user_prompt = (!text.is_empty()).then_some(PendingUserPrompt {
780            text,
781            durable_message_count: self.messages.len(),
782        });
783        self.transcript_viewport.note_new_item();
784    }
785
786    pub(crate) fn record_stream(&mut self, message_id: MessageId) {
787        push_unique(
788            &mut self.streaming_order,
789            message_id,
790            MAX_ACTIVE_STREAM_MESSAGES,
791        );
792    }
793
794    pub(crate) fn record_tool_activity(&mut self, tool_call_id: ToolCallId) {
795        push_unique(&mut self.tool_order, tool_call_id, MAX_ACTIVE_TOOL_ITEMS);
796    }
797
798    pub(crate) fn record_hosted_tool_activity(&mut self, tool_call_id: ToolCallId) {
799        push_unique(
800            &mut self.hosted_tool_order,
801            tool_call_id,
802            MAX_ACTIVE_TOOL_ITEMS,
803        );
804    }
805
806    pub(crate) fn remember_event(&mut self, event_id: tea_protocol::EventId) {
807        if self.observed_event_ids.len() == MAX_OBSERVED_EVENT_IDS {
808            self.observed_event_ids.pop_front();
809        }
810        self.observed_event_ids.push_back(event_id);
811    }
812
813    pub(crate) fn notify(&mut self, message: impl Into<String>) {
814        if self.notifications.len() == MAX_NOTIFICATIONS {
815            self.notifications.pop_front();
816        }
817        self.notifications
818            .push_back(sanitize_summary(&message.into()));
819    }
820
821    pub(crate) fn set_mcp_health(&mut self, rows: Vec<String>) {
822        self.mcp_health = rows
823            .into_iter()
824            .take(MAX_MCP_HEALTH_ROWS)
825            .map(|row| sanitize_summary(&row))
826            .collect();
827    }
828
829    pub(crate) fn note_transcript_item(&mut self) {
830        self.transcript_viewport.note_new_item();
831    }
832}
833
834fn durable_tools(snapshot: &SessionSnapshot) -> BTreeMap<ToolCallId, ToolView> {
835    snapshot
836        .state()
837        .tool_calls()
838        .iter()
839        .map(|(id, tool)| {
840            let status = match tool.execution() {
841                ToolExecutionState::NotStarted => "proposed".to_owned(),
842                ToolExecutionState::Started { .. } => "running".to_owned(),
843                ToolExecutionState::Finished { is_error, .. } if *is_error => "failed".to_owned(),
844                ToolExecutionState::Finished { .. } => "succeeded".to_owned(),
845                ToolExecutionState::Interrupted { .. } => "interrupted/uncertain".to_owned(),
846            };
847            let presentation = match tool.execution() {
848                ToolExecutionState::Finished { presentation, .. } => presentation.clone(),
849                ToolExecutionState::NotStarted
850                | ToolExecutionState::Started { .. }
851                | ToolExecutionState::Interrupted { .. } => None,
852            };
853            (
854                *id,
855                ToolView {
856                    tool_call_id: *id,
857                    tool_name: tool.tool_name().to_owned(),
858                    arguments: tool.arguments().clone(),
859                    status,
860                    approval_decision: tool.approval_decision(),
861                    progress: None,
862                    presentation,
863                    preview: None,
864                },
865            )
866        })
867        .collect()
868}
869
870fn tool_order(
871    messages: &[CanonicalMessage],
872    tools: &BTreeMap<ToolCallId, ToolView>,
873) -> VecDeque<ToolCallId> {
874    let mut order = VecDeque::new();
875    for message in messages {
876        let CanonicalMessage::Assistant { content, .. } = message else {
877            continue;
878        };
879        for block in content {
880            if let tea_protocol::ContentBlock::ToolCall { tool_call_id, .. } = block {
881                push_unique(&mut order, *tool_call_id, MAX_ACTIVE_TOOL_ITEMS);
882            }
883        }
884    }
885    // A valid snapshot normally contains the corresponding assistant tool
886    // call. Keep malformed/legacy projections visible with a deterministic
887    // fallback instead of silently hiding a known tool state.
888    for tool_call_id in tools.keys() {
889        push_unique(&mut order, *tool_call_id, MAX_ACTIVE_TOOL_ITEMS);
890    }
891    order
892}
893
894fn prompt_is_durable(messages: &[CanonicalMessage], pending: &PendingUserPrompt) -> bool {
895    messages
896        .iter()
897        .skip(pending.durable_message_count)
898        .any(|message| match message {
899            CanonicalMessage::User { content, .. } => content
900                .iter()
901                .any(|block| matches!(block, ContentBlock::Text { text } if text == &pending.text)),
902            CanonicalMessage::Assistant { .. } | CanonicalMessage::ToolResult { .. } => false,
903        })
904}
905
906fn push_unique<T: Copy + PartialEq>(queue: &mut VecDeque<T>, value: T, capacity: usize) {
907    if queue.iter().any(|item| *item == value) {
908        return;
909    }
910    if queue.len() == capacity {
911        queue.pop_front();
912    }
913    queue.push_back(value);
914}
915
916fn pending_approval(snapshot: &SessionSnapshot) -> Option<ApprovalView> {
917    let pending = snapshot.state().pending_approvals();
918    snapshot
919        .approval_artifacts()
920        .iter()
921        .rev()
922        .find_map(|artifact| match artifact {
923            ApprovalArtifactEntry::Requested { request, .. }
924                if pending.contains_key(request.approval_id()) =>
925            {
926                Some(ApprovalView {
927                    approval_id: *request.approval_id(),
928                    tool_call_id: *request.tool_call_id(),
929                    tool_name: request.tool_name().to_string(),
930                    effects: request
931                        .effects()
932                        .iter()
933                        .map(|effect| effect.as_str().to_owned())
934                        .collect(),
935                    target: policy_target(request.environment().target()).to_owned(),
936                    resources: request.presentation().resources().to_vec(),
937                    reason: request.presentation().reason().to_owned(),
938                    arguments: serde_json::to_string(request.presentation().arguments())
939                        .unwrap_or_else(|_| "{\"redacted\":true}".to_owned()),
940                    expires_at: request.expires_at(),
941                })
942            }
943            ApprovalArtifactEntry::Requested { .. } | ApprovalArtifactEntry::Resolved { .. } => {
944                None
945            }
946        })
947}
948
949const fn policy_target(target: tea_policy::PolicyExecutionTarget) -> &'static str {
950    match target {
951        tea_policy::PolicyExecutionTarget::Native => "native",
952        tea_policy::PolicyExecutionTarget::Subprocess => "subprocess",
953        tea_policy::PolicyExecutionTarget::Sandbox => "sandbox",
954        tea_policy::PolicyExecutionTarget::Mcp => "mcp",
955        tea_policy::PolicyExecutionTarget::Remote => "remote",
956        tea_policy::PolicyExecutionTarget::Wasm => "wasm",
957    }
958}
959
960fn sanitize_summary(value: &str) -> String {
961    value
962        .chars()
963        .take(4096)
964        .map(|character| {
965            if character.is_control() {
966                ' '
967            } else {
968                character
969            }
970        })
971        .collect::<String>()
972        .trim()
973        .to_owned()
974}