Skip to main content

tea_cli/tui/presentation/
cell.rs

1use std::fmt::Write as _;
2
3use tea_protocol::{CodeChange, MessageId, ToolCallId};
4
5use super::{
6    DecisionStatus, LifecycleStatus, NoticeSeverity, OutputFormat, PlanStep, QueuedInputKind,
7    TimelineDetail, TimelineSource, append_raw_details, bounded_terminal_text,
8    code_change_raw_text, queue_preview, raw_plan_text, terminal_safe_text,
9};
10
11/// Author intrinsic to a message payload.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum MessageAuthor {
14    /// User-authored message content.
15    User,
16    /// Assistant-authored message content.
17    Assistant,
18}
19
20/// Origin intrinsic to lifecycle activity.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum LifecycleKind {
23    /// A locally executed tool call.
24    ToolCall,
25    /// Provider-hosted activity.
26    HostedTool,
27    /// Overall run activity not owned by one tool.
28    RunActivity,
29}
30
31/// Origin intrinsic to a notice payload.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum NoticeKind {
34    /// A general transient notification.
35    General,
36    /// MCP connection health information.
37    McpHealth,
38}
39
40/// Typed user or assistant message source.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct MessageCell {
43    author: MessageAuthor,
44    source: String,
45    format: OutputFormat,
46}
47
48impl MessageCell {
49    pub(crate) fn new(author: MessageAuthor, source: &str, format: OutputFormat) -> Self {
50        Self {
51            author,
52            source: bounded_terminal_text(source),
53            format,
54        }
55    }
56
57    /// Returns the intrinsic message author.
58    #[must_use]
59    pub const fn author(&self) -> MessageAuthor {
60        self.author
61    }
62
63    /// Returns terminal-safe source retained for reflow and raw copy.
64    #[must_use]
65    pub fn source(&self) -> &str {
66        &self.source
67    }
68
69    /// Returns the source rendering format.
70    #[must_use]
71    pub const fn format(&self) -> OutputFormat {
72        self.format
73    }
74}
75
76/// Typed reasoning source and disclosure state.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ReasoningCell {
79    source: String,
80    collapsed: bool,
81}
82
83impl ReasoningCell {
84    pub(crate) fn new(source: &str, collapsed: bool) -> Self {
85        Self {
86            source: bounded_terminal_text(source),
87            collapsed,
88        }
89    }
90
91    /// Returns terminal-safe reasoning source.
92    #[must_use]
93    pub fn source(&self) -> &str {
94        &self.source
95    }
96
97    /// Returns whether the visible reasoning surface is collapsed.
98    #[must_use]
99    pub const fn collapsed(&self) -> bool {
100        self.collapsed
101    }
102}
103
104/// Typed plan proposal or progress update.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct PlanCell {
107    title: String,
108    source: Option<String>,
109    steps: Vec<PlanStep>,
110    note: Option<String>,
111}
112
113impl PlanCell {
114    #[cfg_attr(not(test), allow(dead_code))]
115    pub(crate) fn new(
116        title: &str,
117        source: Option<&str>,
118        steps: Vec<PlanStep>,
119        note: Option<&str>,
120    ) -> Self {
121        Self {
122            title: bounded_terminal_text(title),
123            source: source.map(bounded_terminal_text),
124            steps,
125            note: note.map(bounded_terminal_text),
126        }
127    }
128
129    /// Returns the compact plan action header.
130    #[must_use]
131    pub fn title(&self) -> &str {
132        &self.title
133    }
134
135    /// Returns optional Markdown proposal source.
136    #[must_use]
137    pub fn source(&self) -> Option<&str> {
138        self.source.as_deref()
139    }
140
141    /// Returns ordered structured plan steps.
142    #[must_use]
143    pub fn steps(&self) -> &[PlanStep] {
144        &self.steps
145    }
146
147    /// Returns an optional progress note.
148    #[must_use]
149    pub fn note(&self) -> Option<&str> {
150        self.note.as_deref()
151    }
152}
153
154/// Typed operational lifecycle activity.
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct LifecycleCell {
157    kind: LifecycleKind,
158    action: String,
159    target: Option<String>,
160    status: LifecycleStatus,
161    details: Vec<TimelineDetail>,
162    expanded: bool,
163    tick: u64,
164}
165
166impl LifecycleCell {
167    #[allow(clippy::too_many_arguments)]
168    pub(crate) fn new(
169        kind: LifecycleKind,
170        action: &str,
171        target: Option<&str>,
172        status: LifecycleStatus,
173        details: Vec<TimelineDetail>,
174        expanded: bool,
175        tick: u64,
176    ) -> Self {
177        Self {
178            kind,
179            action: bounded_terminal_text(action),
180            target: target.map(bounded_terminal_text),
181            status,
182            details,
183            expanded,
184            tick,
185        }
186    }
187
188    /// Returns the intrinsic lifecycle origin.
189    #[must_use]
190    pub const fn kind(&self) -> LifecycleKind {
191        self.kind
192    }
193
194    /// Returns the lifecycle action label.
195    #[must_use]
196    pub fn action(&self) -> &str {
197        &self.action
198    }
199
200    /// Returns the optional primary target.
201    #[must_use]
202    pub fn target(&self) -> Option<&str> {
203        self.target.as_deref()
204    }
205
206    /// Returns the protocol-backed lifecycle state.
207    #[must_use]
208    pub const fn status(&self) -> LifecycleStatus {
209        self.status
210    }
211
212    /// Returns structured progressively disclosed details.
213    #[must_use]
214    pub fn details(&self) -> &[TimelineDetail] {
215        &self.details
216    }
217
218    /// Returns whether normally hidden details are expanded.
219    #[must_use]
220    pub const fn expanded(&self) -> bool {
221        self.expanded
222    }
223
224    /// Returns the observable animation tick.
225    #[must_use]
226    pub const fn tick(&self) -> u64 {
227        self.tick
228    }
229}
230
231/// Typed tool, process, artifact, or fallback result.
232#[derive(Debug, Clone, PartialEq, Eq)]
233pub struct ResultCell {
234    action: String,
235    source_name: Option<String>,
236    content: String,
237    format: OutputFormat,
238    is_error: bool,
239}
240
241impl ResultCell {
242    pub(crate) fn new(
243        action: &str,
244        source_name: Option<&str>,
245        content: &str,
246        format: OutputFormat,
247        is_error: bool,
248    ) -> Self {
249        Self {
250            action: bounded_terminal_text(action),
251            source_name: source_name.map(bounded_terminal_text),
252            content: bounded_terminal_text(content),
253            format,
254            is_error,
255        }
256    }
257
258    /// Returns the result action label.
259    #[must_use]
260    pub fn action(&self) -> &str {
261        &self.action
262    }
263
264    /// Returns the optional source that produced the result.
265    #[must_use]
266    pub fn source_name(&self) -> Option<&str> {
267        self.source_name.as_deref()
268    }
269
270    /// Returns canonical result content.
271    #[must_use]
272    pub fn content(&self) -> &str {
273        &self.content
274    }
275
276    /// Returns the result rendering format.
277    #[must_use]
278    pub const fn format(&self) -> OutputFormat {
279        self.format
280    }
281
282    /// Returns whether the protocol identified an error result.
283    #[must_use]
284    pub const fn is_error(&self) -> bool {
285        self.is_error
286    }
287}
288
289/// Typed provider-neutral external sources.
290#[derive(Debug, Clone, PartialEq, Eq)]
291pub struct SourcesCell {
292    sources: Vec<TimelineSource>,
293}
294
295impl SourcesCell {
296    pub(crate) const fn new(sources: Vec<TimelineSource>) -> Self {
297        Self { sources }
298    }
299
300    /// Returns sources in provider order.
301    #[must_use]
302    pub fn sources(&self) -> &[TimelineSource] {
303        &self.sources
304    }
305}
306
307/// Typed persisted code change.
308#[derive(Debug, Clone, PartialEq, Eq)]
309pub struct DiffCell {
310    action: String,
311    change: CodeChange,
312}
313
314impl DiffCell {
315    pub(crate) fn new(action: &str, change: CodeChange) -> Self {
316        Self {
317            action: bounded_terminal_text(action),
318            change,
319        }
320    }
321
322    /// Returns the code-change action label.
323    #[must_use]
324    pub fn action(&self) -> &str {
325        &self.action
326    }
327
328    /// Returns the structured code change retained for reflow and raw copy.
329    #[must_use]
330    pub const fn change(&self) -> &CodeChange {
331        &self.change
332    }
333}
334
335/// Typed queued steering or follow-up preview.
336#[derive(Debug, Clone, PartialEq, Eq)]
337pub struct QueuedInputCell {
338    kind: QueuedInputKind,
339    preview: String,
340}
341
342impl QueuedInputCell {
343    pub(crate) fn new(kind: QueuedInputKind, preview: &str) -> Self {
344        Self {
345            kind,
346            preview: queue_preview(preview),
347        }
348    }
349
350    /// Returns queue ownership and consumption semantics.
351    #[must_use]
352    pub const fn kind(&self) -> QueuedInputKind {
353        self.kind
354    }
355
356    /// Returns the bounded single-line queue preview.
357    #[must_use]
358    pub fn preview(&self) -> &str {
359        &self.preview
360    }
361}
362
363/// Typed informational, warning, or error notice.
364#[derive(Debug, Clone, PartialEq, Eq)]
365pub struct NoticeCell {
366    kind: NoticeKind,
367    severity: NoticeSeverity,
368    message: String,
369    hint: Option<String>,
370}
371
372impl NoticeCell {
373    pub(crate) fn new(
374        kind: NoticeKind,
375        severity: NoticeSeverity,
376        message: &str,
377        hint: Option<&str>,
378    ) -> Self {
379        Self {
380            kind,
381            severity,
382            message: bounded_terminal_text(message),
383            hint: hint.map(bounded_terminal_text),
384        }
385    }
386
387    /// Returns the intrinsic notice origin.
388    #[must_use]
389    pub const fn kind(&self) -> NoticeKind {
390        self.kind
391    }
392
393    /// Returns the notice severity.
394    #[must_use]
395    pub const fn severity(&self) -> NoticeSeverity {
396        self.severity
397    }
398
399    /// Returns the primary notice message.
400    #[must_use]
401    pub fn message(&self) -> &str {
402        &self.message
403    }
404
405    /// Returns optional supporting text.
406    #[must_use]
407    pub fn hint(&self) -> Option<&str> {
408        self.hint.as_deref()
409    }
410}
411
412/// Typed approval or another explicit durable decision.
413#[derive(Debug, Clone, PartialEq, Eq)]
414pub struct DecisionCell {
415    action: String,
416    subject: String,
417    status: DecisionStatus,
418    details: Vec<TimelineDetail>,
419}
420
421impl DecisionCell {
422    pub(crate) fn new(
423        action: &str,
424        subject: &str,
425        status: DecisionStatus,
426        details: Vec<TimelineDetail>,
427    ) -> Self {
428        Self {
429            action: bounded_terminal_text(action),
430            subject: bounded_terminal_text(subject),
431            status,
432            details,
433        }
434    }
435
436    /// Returns the decision action label.
437    #[must_use]
438    pub fn action(&self) -> &str {
439        &self.action
440    }
441
442    /// Returns the redacted decision subject.
443    #[must_use]
444    pub fn subject(&self) -> &str {
445        &self.subject
446    }
447
448    /// Returns the current decision status.
449    #[must_use]
450    pub const fn status(&self) -> DecisionStatus {
451        self.status
452    }
453
454    /// Returns structured redacted effects and scope.
455    #[must_use]
456    pub fn details(&self) -> &[TimelineDetail] {
457        &self.details
458    }
459}
460
461/// Closed family of legal first-party cell payloads.
462#[derive(Debug, Clone, PartialEq, Eq)]
463pub enum CellContent {
464    /// User or assistant message content.
465    Message(MessageCell),
466    /// Reasoning or reasoning-summary content.
467    Reasoning(ReasoningCell),
468    /// Plan proposal or progress content.
469    Plan(PlanCell),
470    /// Active or finalized operational work.
471    Lifecycle(LifecycleCell),
472    /// Tool, process, artifact, or fallback output.
473    Result(ResultCell),
474    /// Provider-neutral external sources.
475    Sources(SourcesCell),
476    /// Persisted code change.
477    Diff(DiffCell),
478    /// Queued steering or follow-up input.
479    QueuedInput(QueuedInputCell),
480    /// Informational, warning, or error notice.
481    Notice(NoticeCell),
482    /// Approval or another durable decision.
483    Decision(DecisionCell),
484}
485
486impl CellContent {
487    /// Returns whether this payload belongs in the non-modal live timeline.
488    #[must_use]
489    pub(crate) const fn is_live_timeline_visible(&self) -> bool {
490        !matches!(self, Self::Decision(_))
491    }
492
493    /// Returns the primary source text for compatibility and search.
494    #[must_use]
495    pub fn text(&self) -> &str {
496        match self {
497            Self::Message(cell) => cell.source(),
498            Self::Reasoning(cell) => cell.source(),
499            Self::Plan(cell) => cell.source().unwrap_or_else(|| cell.title()),
500            Self::Lifecycle(cell) => cell.action(),
501            Self::Result(cell) => cell.action(),
502            Self::Sources(_) => "Sources",
503            Self::Diff(cell) => cell.action(),
504            Self::QueuedInput(cell) => cell.preview(),
505            Self::Notice(cell) => cell.message(),
506            Self::Decision(cell) => cell.action(),
507        }
508    }
509
510    /// Returns a renderer-independent, copy-friendly representation.
511    #[must_use]
512    pub fn raw_text(&self) -> String {
513        let raw = match self {
514            Self::Message(cell) => cell.source().to_owned(),
515            Self::Reasoning(cell) => cell.source().to_owned(),
516            Self::Plan(cell) => {
517                raw_plan_text(cell.title(), cell.source(), cell.steps(), cell.note())
518            }
519            Self::Lifecycle(cell) => {
520                let mut raw = cell.action().to_owned();
521                if let Some(target) = cell.target() {
522                    raw.push(' ');
523                    raw.push_str(target);
524                }
525                append_raw_details(&mut raw, cell.details());
526                raw
527            }
528            Self::Result(cell) => cell.content().to_owned(),
529            Self::Sources(cell) => {
530                let mut raw = String::new();
531                for source in cell.sources() {
532                    if !raw.is_empty() {
533                        raw.push('\n');
534                    }
535                    write!(raw, "- {} <{}>", source.label(), source.url())
536                        .expect("writing to a String cannot fail");
537                }
538                raw
539            }
540            Self::Diff(cell) => code_change_raw_text(cell.change()),
541            Self::QueuedInput(cell) => cell.preview().to_owned(),
542            Self::Notice(cell) => {
543                let mut raw = cell.message().to_owned();
544                if let Some(hint) = cell.hint() {
545                    raw.push('\n');
546                    raw.push_str(hint);
547                }
548                raw
549            }
550            Self::Decision(cell) => {
551                let mut raw = cell.action().to_owned();
552                if !cell.subject().is_empty() {
553                    raw.push(' ');
554                    raw.push_str(cell.subject());
555                }
556                append_raw_details(&mut raw, cell.details());
557                raw
558            }
559        };
560        terminal_safe_text(&raw)
561    }
562}
563
564/// Presentation lane used only when a protocol identity is unavailable.
565#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
566pub enum CellLane {
567    /// Durable history projection.
568    History,
569    /// Active streaming or local projection.
570    Active,
571    /// Transient notification projection.
572    Notifications,
573}
574
575/// Identity facet for one canonical message block.
576#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
577pub enum MessageCellFacet {
578    /// Primary content associated with the block index.
579    Content,
580    /// External sources associated with the message.
581    Sources,
582}
583
584/// Identity facet for one tool call.
585#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
586pub enum ToolCellFacet {
587    /// Tool-call lifecycle activity.
588    Call,
589    /// Approval or another explicit decision.
590    Decision,
591    /// Canonical tool result.
592    Result,
593    /// Structured code change.
594    Diff,
595    /// External sources associated with hosted work.
596    Sources,
597    /// Transient approval preview.
598    ApprovalPreview,
599}
600
601/// Identity facet for active message streaming.
602#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
603pub enum StreamCellFacet {
604    /// Visible assistant message delta.
605    Message,
606    /// Visible reasoning delta.
607    Reasoning,
608}
609
610/// Stable typed identity for one projected cell.
611#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
612pub enum CellId {
613    /// One block or facet owned by a canonical message.
614    Message {
615        /// Stable canonical message identifier.
616        message_id: MessageId,
617        /// Bounded index of the canonical content block.
618        block_index: u16,
619        /// Message-owned identity facet.
620        facet: MessageCellFacet,
621    },
622    /// One facet owned by a canonical tool call.
623    Tool {
624        /// Stable canonical tool-call identifier.
625        tool_call_id: ToolCallId,
626        /// Tool-owned identity facet.
627        facet: ToolCellFacet,
628        /// Bounded part index within the facet.
629        part_index: u16,
630    },
631    /// One active streaming block.
632    Stream {
633        /// Stable canonical streaming message identifier.
634        message_id: MessageId,
635        /// Bounded streaming block index.
636        block_index: u16,
637        /// Stream-owned identity facet.
638        facet: StreamCellFacet,
639    },
640    /// One queued local input.
641    Queue {
642        /// Queue ownership and consumption semantics.
643        kind: QueuedInputKind,
644        /// Bounded index within that queue.
645        index: u16,
646    },
647    /// One local MCP health row.
648    McpHealth {
649        /// Bounded row index.
650        index: u16,
651    },
652    /// One transient notification row.
653    Notification {
654        /// Bounded row index.
655        index: u16,
656    },
657    /// One lane-local value without a protocol identity.
658    Synthetic {
659        /// Owning presentation lane.
660        lane: CellLane,
661        /// Bounded lane-local index.
662        index: u16,
663    },
664}
665
666/// One immutable typed presentation cell with stable identity and ownership metadata.
667#[derive(Debug, Clone, PartialEq, Eq)]
668pub struct CellNode {
669    id: CellId,
670    content: CellContent,
671    tool_call_id: Option<ToolCallId>,
672}
673
674impl CellNode {
675    pub(crate) const fn new(
676        id: CellId,
677        content: CellContent,
678        tool_call_id: Option<ToolCallId>,
679    ) -> Self {
680        Self {
681            id,
682            content,
683            tool_call_id,
684        }
685    }
686
687    /// Returns the stable typed cell identity.
688    #[must_use]
689    pub const fn id(&self) -> CellId {
690        self.id
691    }
692
693    /// Returns the typed semantic payload.
694    #[must_use]
695    pub const fn content(&self) -> &CellContent {
696        &self.content
697    }
698
699    /// Returns the primary source text for compatibility and search.
700    #[must_use]
701    pub fn text(&self) -> &str {
702        self.content.text()
703    }
704
705    /// Returns a renderer-independent, copy-friendly representation.
706    #[must_use]
707    pub fn raw_text(&self) -> String {
708        self.content.raw_text()
709    }
710
711    /// Returns the owning tool call independently of payload family.
712    #[must_use]
713    pub const fn tool_call_id(&self) -> Option<ToolCallId> {
714        self.tool_call_id
715    }
716}