Skip to main content

tea_cli/tui/
presentation.rs

1use std::borrow::Cow;
2use std::collections::BTreeSet;
3use std::fmt::Write as _;
4
5use tea_protocol::{
6    ApprovalDecision, CanonicalMessage, CodeChange, CodeChangeLineKind, CodeChangeTruncation,
7    ContentBlock, ExternalSource, HostedToolActivity, HostedToolOutcome, ImageSource, MessageId,
8    ToolCallId, ToolPresentation, WebFetchPresentation, WebFetchTruncation,
9};
10use unicode_segmentation::UnicodeSegmentation as _;
11use unicode_width::UnicodeWidthStr as _;
12
13use super::attachment::{decoded_inline_image_bytes, format_byte_count};
14use super::state::{ApprovalView, HostedToolView, StreamingMessage, ToolView, TuiState};
15
16mod cell;
17
18pub use cell::{
19    CellContent, CellId, CellLane, CellNode, DecisionCell, DiffCell, LifecycleCell, LifecycleKind,
20    MessageAuthor, MessageCell, MessageCellFacet, NoticeCell, NoticeKind, PlanCell,
21    QueuedInputCell, ReasoningCell, ResultCell, SourcesCell, StreamCellFacet, ToolCellFacet,
22};
23
24const MAX_CELL_TEXT_BYTES: usize = 64 * 1024;
25const MAX_QUEUE_PREVIEW_CELLS: usize = 160;
26const QUEUE_PREVIEW_ELLIPSIS: &str = "...";
27
28/// Source format owned by a typed timeline body.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
30pub enum OutputFormat {
31    /// Preserve the source as terminal-safe plain text.
32    Plain,
33    /// Project the source through the message-level Markdown writer.
34    Markdown,
35    /// Preserve process output whitespace without Markdown interpretation.
36    Terminal,
37}
38
39/// Observable lifecycle state used to choose markers and action emphasis.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
41pub enum LifecycleStatus {
42    /// Work has been proposed but not requested.
43    Proposed,
44    /// Work has been requested but has not started.
45    Requested,
46    /// Work is waiting for an explicit approval decision.
47    ApprovalPending,
48    /// Work is currently executing.
49    Running,
50    /// Work completed successfully.
51    Succeeded,
52    /// Work completed with an explicit failure.
53    Failed,
54    /// Work was interrupted before completion.
55    Interrupted,
56    /// The final effect of interrupted work is unknown.
57    Uncertain,
58    /// Work or input is queued for later execution.
59    Queued,
60}
61
62/// Semantic treatment for one structured detail row.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
64pub enum TimelineDetailKind {
65    /// Arguments, targets, identifiers, and other metadata.
66    Metadata,
67    /// Observable progress reported by the runtime.
68    Progress,
69    /// Successful tool or process output.
70    Output,
71    /// Explicit failure output.
72    Error,
73}
74
75/// One renderer-neutral, tree-prefixed detail row.
76#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
77pub struct TimelineDetail {
78    kind: TimelineDetailKind,
79    label: Option<String>,
80    text: String,
81}
82
83/// One terminal-safe source label with an optional validated OSC8 destination.
84#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
85pub struct TimelineSource {
86    label: String,
87    url: String,
88    destination: Option<String>,
89}
90
91impl TimelineSource {
92    pub(crate) fn from_external(source: &ExternalSource) -> Self {
93        Self {
94            label: terminal_safe_text(source.title().unwrap_or(source.url())),
95            url: terminal_safe_text(source.url()),
96            destination: super::hyperlink::validate_destination(source.url()),
97        }
98    }
99
100    /// Returns the visible source label.
101    #[must_use]
102    pub fn label(&self) -> &str {
103        &self.label
104    }
105
106    /// Returns the original validated source URL for copy-friendly output.
107    #[must_use]
108    pub fn url(&self) -> &str {
109        &self.url
110    }
111
112    /// Returns the canonical destination when it is safe for OSC8 output.
113    #[must_use]
114    pub fn destination(&self) -> Option<&str> {
115        self.destination.as_deref()
116    }
117}
118
119impl TimelineDetail {
120    pub(crate) fn new(kind: TimelineDetailKind, label: Option<&str>, text: &str) -> Self {
121        Self {
122            kind,
123            label: label.map(bounded_terminal_text),
124            text: bounded_terminal_text(text),
125        }
126    }
127
128    /// Returns the semantic detail category.
129    #[must_use]
130    pub const fn kind(&self) -> TimelineDetailKind {
131        self.kind
132    }
133
134    /// Returns the optional compact detail label.
135    #[must_use]
136    pub fn label(&self) -> Option<&str> {
137        self.label.as_deref()
138    }
139
140    /// Returns the terminal-safe source text.
141    #[must_use]
142    pub fn text(&self) -> &str {
143        &self.text
144    }
145}
146
147/// Severity for a typed notice surface.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
149pub enum NoticeSeverity {
150    /// Low-salience informational output.
151    Information,
152    /// A warning that may require attention.
153    Warning,
154    /// An explicit failure or error diagnostic.
155    Error,
156}
157
158/// Durable approval or decision state.
159#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
160pub enum DecisionStatus {
161    /// A user decision is still required.
162    Pending,
163    /// The action was approved.
164    Approved,
165    /// The action was denied.
166    Denied,
167    /// The request expired before a decision.
168    TimedOut,
169    /// The decision flow was aborted.
170    Aborted,
171    /// A selected decision is being submitted.
172    Submitting,
173}
174
175/// Semantic type for one queued input preview.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
177pub enum QueuedInputKind {
178    /// Input intended to steer the active run.
179    Steering,
180    /// Input intended for the next turn.
181    FollowUp,
182}
183
184/// Protocol-ready status for one plan step.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
186pub enum PlanStepStatus {
187    /// Work has not started.
188    Pending,
189    /// Work is currently active.
190    InProgress,
191    /// Work has completed.
192    Completed,
193}
194
195/// One bounded renderer-neutral plan step.
196#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
197pub struct PlanStep {
198    status: PlanStepStatus,
199    text: String,
200}
201
202impl PlanStep {
203    /// Creates one terminal-safe plan step.
204    #[must_use]
205    pub fn new(status: PlanStepStatus, text: &str) -> Self {
206        Self {
207            status,
208            text: bounded_terminal_text(text),
209        }
210    }
211
212    /// Returns the observable step status.
213    #[must_use]
214    pub const fn status(&self) -> PlanStepStatus {
215        self.status
216    }
217
218    /// Returns the terminal-safe step text.
219    #[must_use]
220    pub fn text(&self) -> &str {
221        &self.text
222    }
223}
224
225/// Pure presentation projection split by durable and transient lifetime.
226#[derive(Debug, Clone, PartialEq, Eq, Default)]
227pub struct Presentation {
228    history: Vec<CellNode>,
229    active: Vec<CellNode>,
230    notifications: Vec<CellNode>,
231}
232
233impl Presentation {
234    /// Projects one terminal state without changing canonical or local state.
235    #[must_use]
236    pub fn from_state(state: &TuiState) -> Self {
237        let history = HistoryProjection::from_state(state);
238        let active = project_active_cells(
239            state,
240            &history.represented_tools,
241            &history.represented_hosted_tools,
242        );
243
244        Self {
245            history: history.cells,
246            active,
247            notifications: project_notifications(state),
248        }
249    }
250
251    /// Returns cells backed by the durable session transcript.
252    #[must_use]
253    pub fn history(&self) -> &[CellNode] {
254        &self.history
255    }
256
257    /// Returns active or session-local activity below the durable transcript.
258    #[must_use]
259    pub fn active(&self) -> &[CellNode] {
260        &self.active
261    }
262
263    /// Returns bounded transient notifications separate from the transcript.
264    #[must_use]
265    pub fn notifications(&self) -> &[CellNode] {
266        &self.notifications
267    }
268}
269
270fn project_active_cells(
271    state: &TuiState,
272    represented_tools: &BTreeSet<ToolCallId>,
273    represented_hosted_tools: &BTreeSet<ToolCallId>,
274) -> Vec<CellNode> {
275    let mut active = Vec::new();
276    if let Some(pending) = &state.pending_user_prompt {
277        active.push(message_cell(
278            CellId::Synthetic {
279                lane: CellLane::Active,
280                index: 0,
281            },
282            MessageAuthor::User,
283            pending.text(),
284            OutputFormat::Plain,
285        ));
286    }
287    for message_id in &state.streaming_order {
288        if let Some(message) = state.streaming.get(message_id) {
289            project_stream(
290                *message_id,
291                message,
292                state.preferences.thinking_collapsed,
293                &mut active,
294            );
295        }
296    }
297    for tool_call_id in &state.tool_order {
298        if !represented_tools.contains(tool_call_id)
299            && let Some(tool) = state.tools.get(tool_call_id)
300        {
301            active.push(project_tool(
302                state,
303                tool_call_id,
304                &tool.tool_name,
305                &tool.arguments,
306                Some(tool),
307            ));
308        }
309    }
310    for tool_call_id in &state.hosted_tool_order {
311        if !represented_hosted_tools.contains(tool_call_id)
312            && let Some(tool) = state.hosted_tools.get(tool_call_id)
313        {
314            active.push(project_hosted_view(tool, state.run_elapsed_seconds));
315        }
316    }
317    project_queues(state, &mut active);
318    for (index, row) in state.mcp_health.iter().enumerate() {
319        active.push(notice_cell(
320            CellId::McpHealth {
321                index: bounded_index(index),
322            },
323            NoticeKind::McpHealth,
324            NoticeSeverity::Information,
325            row,
326            None,
327        ));
328    }
329    if let Some(approval) = &state.approval {
330        active.push(project_approval(approval, state.approval_submitting));
331        if let Some(preview) = state
332            .tools
333            .get(&approval.tool_call_id)
334            .and_then(|tool| tool.preview.as_ref())
335            .and_then(ToolPresentation::code_change)
336        {
337            active.push(preview_diff_cell(preview, approval.tool_call_id));
338        }
339    }
340    active
341}
342
343fn project_queues(state: &TuiState, active: &mut Vec<CellNode>) {
344    for (input_kind, queue) in [
345        (QueuedInputKind::Steering, &state.steering_queue),
346        (QueuedInputKind::FollowUp, &state.follow_up_queue),
347    ] {
348        for (index, text) in queue.iter().enumerate() {
349            active.push(CellNode::new(
350                CellId::Queue {
351                    kind: input_kind,
352                    index: bounded_index(index),
353                },
354                CellContent::QueuedInput(QueuedInputCell::new(input_kind, text)),
355                None,
356            ));
357        }
358    }
359}
360
361fn project_approval(approval: &ApprovalView, submitting: bool) -> CellNode {
362    let status = if submitting {
363        DecisionStatus::Submitting
364    } else {
365        DecisionStatus::Pending
366    };
367    let detail =
368        |label, text: &str| TimelineDetail::new(TimelineDetailKind::Metadata, Some(label), text);
369    decision_cell(
370        CellId::Tool {
371            tool_call_id: approval.tool_call_id,
372            facet: ToolCellFacet::Decision,
373            part_index: 0,
374        },
375        "Approval required",
376        &approval.tool_name,
377        status,
378        vec![
379            detail("target", &approval.target),
380            detail("effects", &approval.effects.join(", ")),
381            detail("resources", &approval.resources.join(", ")),
382            detail("reason", &approval.reason),
383            detail("arguments", &approval.arguments),
384            detail("expires", &approval.expires_at.to_string()),
385        ],
386        Some(approval.tool_call_id),
387    )
388}
389
390fn project_notifications(state: &TuiState) -> Vec<CellNode> {
391    state
392        .notifications
393        .iter()
394        .enumerate()
395        .map(|(index, message)| {
396            notice_cell(
397                CellId::Notification {
398                    index: bounded_index(index),
399                },
400                NoticeKind::General,
401                NoticeSeverity::Information,
402                message,
403                None,
404            )
405        })
406        .collect()
407}
408
409fn bounded_index(index: usize) -> u16 {
410    u16::try_from(index).unwrap_or(u16::MAX)
411}
412
413fn bounded_content_index(index: u32) -> u16 {
414    u16::try_from(index).unwrap_or(u16::MAX)
415}
416
417struct HistoryProjection<'a> {
418    state: &'a TuiState,
419    cells: Vec<CellNode>,
420    represented_tools: BTreeSet<ToolCallId>,
421    represented_hosted_tools: BTreeSet<ToolCallId>,
422}
423
424impl<'a> HistoryProjection<'a> {
425    fn from_state(state: &'a TuiState) -> Self {
426        let mut projection = Self {
427            state,
428            cells: Vec::new(),
429            represented_tools: BTreeSet::new(),
430            represented_hosted_tools: BTreeSet::new(),
431        };
432        for message in &state.messages {
433            projection.project_message(message);
434        }
435        projection
436    }
437
438    fn project_message(&mut self, message: &CanonicalMessage) {
439        match message {
440            CanonicalMessage::User { id, content, .. } => {
441                self.project_content(*id, content, MessageAuthor::User, OutputFormat::Plain);
442            }
443            CanonicalMessage::Assistant { id, content, .. } => {
444                self.project_content(
445                    *id,
446                    content,
447                    MessageAuthor::Assistant,
448                    OutputFormat::Markdown,
449                );
450                self.project_assistant_sources(*id, content);
451            }
452            CanonicalMessage::ToolResult {
453                tool_call_id,
454                tool_name,
455                content,
456                is_error,
457                ..
458            } => self.project_tool_result(*tool_call_id, tool_name, content, *is_error),
459        }
460    }
461
462    fn project_content(
463        &mut self,
464        message_id: MessageId,
465        content: &[ContentBlock],
466        author: MessageAuthor,
467        format: OutputFormat,
468    ) {
469        for (block_index, block) in content.iter().enumerate() {
470            self.project_content_block(
471                message_id,
472                bounded_index(block_index),
473                block,
474                author,
475                format,
476            );
477        }
478    }
479
480    fn project_assistant_sources(&mut self, message_id: MessageId, content: &[ContentBlock]) {
481        let sources = assistant_sources(content);
482        if sources.is_empty() {
483            return;
484        }
485        self.cells.push(CellNode::new(
486            CellId::Message {
487                message_id,
488                block_index: bounded_index(content.len()),
489                facet: MessageCellFacet::Sources,
490            },
491            CellContent::Sources(SourcesCell::new(
492                sources.iter().map(TimelineSource::from_external).collect(),
493            )),
494            None,
495        ));
496    }
497
498    fn project_tool_result(
499        &mut self,
500        tool_call_id: ToolCallId,
501        tool_name: &str,
502        content: &[ContentBlock],
503        is_error: bool,
504    ) {
505        if !is_error
506            && let Some(presentation) = self
507                .state
508                .tools
509                .get(&tool_call_id)
510                .and_then(|tool| tool.presentation.as_ref())
511        {
512            let cell = match presentation {
513                ToolPresentation::CodeChange(change) => diff_cell(change, tool_call_id),
514                ToolPresentation::WebFetch(fetch) => web_fetch_cell(fetch, tool_call_id),
515            };
516            self.cells.push(cell);
517            return;
518        }
519
520        let action = if is_error { "Failed" } else { "Returned" };
521        for (part_index, block) in content.iter().enumerate() {
522            let (text, format) = match block {
523                ContentBlock::Text { text } | ContentBlock::Thinking { text } => {
524                    (Cow::Borrowed(text.as_str()), OutputFormat::Terminal)
525                }
526                ContentBlock::Image { mime_type, source } => (
527                    Cow::Owned(image_metadata(mime_type, source)),
528                    OutputFormat::Plain,
529                ),
530                ContentBlock::ToolCall { .. }
531                | ContentBlock::HostedTool { .. }
532                | ContentBlock::Citation { .. } => continue,
533            };
534            self.cells.push(result_cell(
535                CellId::Tool {
536                    tool_call_id,
537                    facet: ToolCellFacet::Result,
538                    part_index: bounded_index(part_index),
539                },
540                action,
541                Some(tool_name),
542                text.as_ref(),
543                format,
544                is_error,
545                Some(tool_call_id),
546            ));
547        }
548    }
549
550    fn project_content_block(
551        &mut self,
552        message_id: MessageId,
553        block_index: u16,
554        block: &ContentBlock,
555        author: MessageAuthor,
556        format: OutputFormat,
557    ) {
558        let message_cell_id = CellId::Message {
559            message_id,
560            block_index,
561            facet: MessageCellFacet::Content,
562        };
563        match block {
564            ContentBlock::Text { text } => {
565                self.cells
566                    .push(message_cell(message_cell_id, author, text, format));
567            }
568            ContentBlock::Thinking { text } => {
569                self.cells.push(reasoning_cell(
570                    message_cell_id,
571                    text,
572                    self.state.preferences.thinking_collapsed,
573                ));
574            }
575            ContentBlock::Image { mime_type, source } => self.cells.push(message_cell(
576                message_cell_id,
577                author,
578                &image_metadata(mime_type, source),
579                OutputFormat::Plain,
580            )),
581            ContentBlock::ToolCall {
582                tool_call_id,
583                tool_name,
584                arguments,
585                ..
586            } => {
587                self.represented_tools.insert(*tool_call_id);
588                let tool = self.state.tools.get(tool_call_id);
589                self.cells.push(project_tool(
590                    self.state,
591                    tool_call_id,
592                    tool_name,
593                    arguments,
594                    tool,
595                ));
596                if let Some(decision) = tool.and_then(project_tool_decision) {
597                    self.cells.push(decision);
598                }
599            }
600            ContentBlock::HostedTool { activity } => {
601                self.represented_hosted_tools
602                    .insert(activity.tool_call_id());
603                self.cells.push(project_hosted_activity(activity));
604            }
605            ContentBlock::Citation { .. } => {}
606        }
607    }
608}
609
610fn assistant_sources(content: &[ContentBlock]) -> Vec<ExternalSource> {
611    let mut seen = BTreeSet::new();
612    let mut sources = Vec::new();
613    for block in content {
614        let candidates: &[ExternalSource] = match block {
615            ContentBlock::HostedTool { activity } => activity.sources(),
616            ContentBlock::Citation { citation } => std::slice::from_ref(citation.source()),
617            ContentBlock::Text { .. }
618            | ContentBlock::Thinking { .. }
619            | ContentBlock::Image { .. }
620            | ContentBlock::ToolCall { .. } => &[],
621        };
622        for source in candidates {
623            let deduplication_key = super::hyperlink::validate_destination(source.url())
624                .unwrap_or_else(|| source.url().to_owned());
625            if seen.insert(deduplication_key) {
626                sources.push(source.clone());
627            }
628        }
629    }
630    sources
631}
632
633fn project_hosted_activity(activity: &HostedToolActivity) -> CellNode {
634    hosted_tool_cell(
635        activity.tool_call_id(),
636        activity.tool_name(),
637        Some(activity.arguments()),
638        Some(activity.outcome()),
639        Some(u32::try_from(activity.sources().len()).unwrap_or(u32::MAX)),
640        0,
641    )
642}
643
644fn project_hosted_view(tool: &HostedToolView, tick: u64) -> CellNode {
645    hosted_tool_cell(
646        tool.tool_call_id,
647        &tool.tool_name,
648        tool.arguments.as_ref(),
649        tool.outcome.as_ref(),
650        tool.source_count,
651        tick,
652    )
653}
654
655fn hosted_tool_cell(
656    tool_call_id: ToolCallId,
657    tool_name: &str,
658    arguments: Option<&serde_json::Value>,
659    outcome: Option<&HostedToolOutcome>,
660    source_count: Option<u32>,
661    tick: u64,
662) -> CellNode {
663    let (action, status) = match outcome {
664        None if tool_name == "web_search" => ("Searching web", LifecycleStatus::Running),
665        None => ("Running hosted tool", LifecycleStatus::Running),
666        Some(HostedToolOutcome::Success) if tool_name == "web_search" => {
667            ("Searched web", LifecycleStatus::Succeeded)
668        }
669        Some(HostedToolOutcome::Success) => ("Ran hosted tool", LifecycleStatus::Succeeded),
670        Some(HostedToolOutcome::Error(_)) if tool_name == "web_search" => {
671            ("Web search failed", LifecycleStatus::Failed)
672        }
673        Some(HostedToolOutcome::Error(_)) => ("Hosted tool failed", LifecycleStatus::Failed),
674    };
675    let target = arguments
676        .and_then(|arguments| arguments.get("query"))
677        .and_then(serde_json::Value::as_str)
678        .map(bounded_terminal_text);
679    let mut details = Vec::new();
680    if let Some(source_count) = source_count {
681        details.push(TimelineDetail::new(
682            TimelineDetailKind::Output,
683            Some("sources"),
684            &source_count.to_string(),
685        ));
686    }
687    if let Some(HostedToolOutcome::Error(error)) = outcome {
688        details.push(TimelineDetail::new(
689            TimelineDetailKind::Error,
690            Some(error.code()),
691            error.message(),
692        ));
693    }
694    CellNode::new(
695        CellId::Tool {
696            tool_call_id,
697            facet: ToolCellFacet::Call,
698            part_index: 0,
699        },
700        CellContent::Lifecycle(LifecycleCell::new(
701            LifecycleKind::HostedTool,
702            action,
703            target.as_deref(),
704            status,
705            details,
706            false,
707            if status == LifecycleStatus::Running {
708                tick
709            } else {
710                0
711            },
712        )),
713        Some(tool_call_id),
714    )
715}
716
717fn image_metadata(mime_type: &str, source: &ImageSource) -> String {
718    match source {
719        ImageSource::InlineBase64 { data } => decoded_inline_image_bytes(data).map_or_else(
720            || format!("[image {mime_type}]"),
721            |bytes| format!("[image {mime_type} · {}]", format_byte_count(bytes)),
722        ),
723        ImageSource::Reference { .. } => format!("[image {mime_type}]"),
724    }
725}
726
727fn project_tool_decision(tool: &ToolView) -> Option<CellNode> {
728    let (action, status, scope) = match tool.approval_decision? {
729        ApprovalDecision::AllowOnce => ("Approved", DecisionStatus::Approved, Some("this call")),
730        ApprovalDecision::AllowSession => ("Approved", DecisionStatus::Approved, Some("session")),
731        ApprovalDecision::Deny => ("Denied", DecisionStatus::Denied, None),
732    };
733    let details = scope.map_or_else(Vec::new, |scope| {
734        vec![TimelineDetail::new(
735            TimelineDetailKind::Metadata,
736            Some("scope"),
737            scope,
738        )]
739    });
740    Some(decision_cell(
741        CellId::Tool {
742            tool_call_id: tool.tool_call_id,
743            facet: ToolCellFacet::Decision,
744            part_index: 0,
745        },
746        action,
747        &tool.tool_name,
748        status,
749        details,
750        Some(tool.tool_call_id),
751    ))
752}
753
754fn project_tool(
755    state: &TuiState,
756    tool_call_id: &ToolCallId,
757    tool_name: &str,
758    arguments: &serde_json::Value,
759    tool: Option<&ToolView>,
760) -> CellNode {
761    let pending_approval = state
762        .approval
763        .as_ref()
764        .is_some_and(|approval| approval.tool_call_id == *tool_call_id);
765    let status = if pending_approval {
766        LifecycleStatus::ApprovalPending
767    } else {
768        tool.map_or(LifecycleStatus::Requested, |tool| {
769            lifecycle_status(&tool.status)
770        })
771    };
772    let mut details = Vec::new();
773    let expanded = !pending_approval && state.preferences.expanded_tools.contains(tool_call_id);
774    if !pending_approval {
775        let arguments = serde_json::to_string(arguments).unwrap_or_else(|_| "{}".to_owned());
776        details.push(TimelineDetail::new(
777            TimelineDetailKind::Metadata,
778            Some("arguments"),
779            &arguments,
780        ));
781    }
782    if let Some(progress) = tool.and_then(|tool| tool.progress.as_ref()) {
783        let units = progress.total_units.map_or_else(
784            || progress.completed_units.to_string(),
785            |total| format!("{}/{}", progress.completed_units, total),
786        );
787        details.push(TimelineDetail::new(
788            TimelineDetailKind::Progress,
789            Some("progress"),
790            &format!("{units} {}", progress.message),
791        ));
792    }
793    let target = tool_target(tool_name, arguments);
794    CellNode::new(
795        CellId::Tool {
796            tool_call_id: *tool_call_id,
797            facet: ToolCellFacet::Call,
798            part_index: 0,
799        },
800        CellContent::Lifecycle(LifecycleCell::new(
801            LifecycleKind::ToolCall,
802            lifecycle_action(status),
803            Some(&target),
804            status,
805            details,
806            expanded,
807            if status == LifecycleStatus::Running {
808                state.run_elapsed_seconds
809            } else {
810                0
811            },
812        )),
813        Some(*tool_call_id),
814    )
815}
816
817fn tool_target(tool_name: &str, arguments: &serde_json::Value) -> String {
818    let target = arguments.as_object().and_then(|arguments| {
819        ["path", "command", "query", "url"]
820            .into_iter()
821            .find_map(|key| arguments.get(key).and_then(serde_json::Value::as_str))
822    });
823    target.map_or_else(
824        || tool_name.to_owned(),
825        |target| format!("{tool_name} {target}"),
826    )
827}
828
829fn lifecycle_status(status: &str) -> LifecycleStatus {
830    match status {
831        "proposed" => LifecycleStatus::Proposed,
832        "requested" => LifecycleStatus::Requested,
833        "running" => LifecycleStatus::Running,
834        "succeeded" => LifecycleStatus::Succeeded,
835        "failed" => LifecycleStatus::Failed,
836        "interrupted" => LifecycleStatus::Interrupted,
837        _ => LifecycleStatus::Uncertain,
838    }
839}
840
841const fn lifecycle_action(status: LifecycleStatus) -> &'static str {
842    match status {
843        LifecycleStatus::Proposed => "Proposed",
844        LifecycleStatus::Requested => "Requested",
845        LifecycleStatus::ApprovalPending => "Waiting for approval",
846        LifecycleStatus::Running => "Running",
847        LifecycleStatus::Succeeded => "Ran",
848        LifecycleStatus::Failed => "Failed",
849        LifecycleStatus::Interrupted | LifecycleStatus::Uncertain => "Interrupted",
850        LifecycleStatus::Queued => "Queued",
851    }
852}
853
854fn project_stream(
855    message_id: MessageId,
856    message: &StreamingMessage,
857    thinking_collapsed: bool,
858    output: &mut Vec<CellNode>,
859) {
860    for (block_index, block) in &message.blocks {
861        if block.thinking {
862            output.push(reasoning_cell(
863                CellId::Stream {
864                    message_id,
865                    block_index: bounded_content_index(*block_index),
866                    facet: StreamCellFacet::Reasoning,
867                },
868                &block.text,
869                thinking_collapsed,
870            ));
871        } else {
872            output.push(message_cell(
873                CellId::Stream {
874                    message_id,
875                    block_index: bounded_content_index(*block_index),
876                    facet: StreamCellFacet::Message,
877                },
878                MessageAuthor::Assistant,
879                &block.text,
880                OutputFormat::Markdown,
881            ));
882        }
883    }
884}
885
886fn message_cell(id: CellId, author: MessageAuthor, source: &str, format: OutputFormat) -> CellNode {
887    CellNode::new(
888        id,
889        CellContent::Message(MessageCell::new(author, source, format)),
890        None,
891    )
892}
893
894fn reasoning_cell(id: CellId, source: &str, collapsed: bool) -> CellNode {
895    CellNode::new(
896        id,
897        CellContent::Reasoning(ReasoningCell::new(source, collapsed)),
898        None,
899    )
900}
901
902fn result_cell(
903    id: CellId,
904    action: &str,
905    source_name: Option<&str>,
906    content: &str,
907    format: OutputFormat,
908    is_error: bool,
909    tool_call_id: Option<ToolCallId>,
910) -> CellNode {
911    CellNode::new(
912        id,
913        CellContent::Result(ResultCell::new(
914            action,
915            source_name,
916            content,
917            format,
918            is_error,
919        )),
920        tool_call_id,
921    )
922}
923
924fn web_fetch_cell(fetch: &WebFetchPresentation, tool_call_id: ToolCallId) -> CellNode {
925    result_cell(
926        CellId::Tool {
927            tool_call_id,
928            facet: ToolCellFacet::Result,
929            part_index: 0,
930        },
931        "Fetched",
932        Some("web_fetch"),
933        &web_fetch_content(fetch),
934        OutputFormat::Plain,
935        false,
936        Some(tool_call_id),
937    )
938}
939
940fn web_fetch_content(fetch: &WebFetchPresentation) -> String {
941    let mut content = format!(
942        "URL: {}\nContent-Type: {}",
943        fetch.final_url(),
944        fetch.mime_type()
945    );
946    if let Some(title) = fetch.title() {
947        content.push_str("\nTitle: ");
948        content.push_str(title);
949    }
950    if fetch.requested_url() != fetch.final_url() {
951        content.push_str("\nRequested URL: ");
952        content.push_str(fetch.requested_url());
953    }
954    if let Some(truncation) = fetch.truncation() {
955        content.push_str("\nTruncated: ");
956        content.push_str(match truncation {
957            WebFetchTruncation::CompressedBytes => "compressed bytes",
958            WebFetchTruncation::DecodedBytes => "decoded bytes",
959            WebFetchTruncation::BodyCharacters => "body characters",
960            WebFetchTruncation::ParserComplexity => "parser complexity",
961        });
962    }
963    if !fetch.redirects().is_empty() {
964        content.push_str("\nRedirects: ");
965        content.push_str(&fetch.redirects().len().to_string());
966    }
967    content.push_str("\n\n");
968    content.push_str(fetch.body());
969    content
970}
971
972fn diff_cell(change: &CodeChange, tool_call_id: ToolCallId) -> CellNode {
973    let action = match change.kind() {
974        tea_protocol::CodeChangeKind::Create => "Created",
975        tea_protocol::CodeChangeKind::Update => "Updated",
976        tea_protocol::CodeChangeKind::Delete => "Deleted",
977    };
978    CellNode::new(
979        CellId::Tool {
980            tool_call_id,
981            facet: ToolCellFacet::Diff,
982            part_index: 0,
983        },
984        CellContent::Diff(DiffCell::new(action, change.clone())),
985        Some(tool_call_id),
986    )
987}
988
989fn preview_diff_cell(change: &CodeChange, tool_call_id: ToolCallId) -> CellNode {
990    CellNode::new(
991        CellId::Tool {
992            tool_call_id,
993            facet: ToolCellFacet::ApprovalPreview,
994            part_index: 0,
995        },
996        CellContent::Diff(DiffCell::new("Preview", change.clone())),
997        Some(tool_call_id),
998    )
999}
1000
1001fn notice_cell(
1002    id: CellId,
1003    kind: NoticeKind,
1004    severity: NoticeSeverity,
1005    message: &str,
1006    hint: Option<&str>,
1007) -> CellNode {
1008    CellNode::new(
1009        id,
1010        CellContent::Notice(NoticeCell::new(kind, severity, message, hint)),
1011        None,
1012    )
1013}
1014
1015fn decision_cell(
1016    id: CellId,
1017    action: &str,
1018    subject: &str,
1019    status: DecisionStatus,
1020    details: Vec<TimelineDetail>,
1021    tool_call_id: Option<ToolCallId>,
1022) -> CellNode {
1023    CellNode::new(
1024        id,
1025        CellContent::Decision(DecisionCell::new(action, subject, status, details)),
1026        tool_call_id,
1027    )
1028}
1029
1030fn raw_plan_text(
1031    title: &str,
1032    source: Option<&str>,
1033    steps: &[PlanStep],
1034    note: Option<&str>,
1035) -> String {
1036    if let Some(source) = source {
1037        return source.to_owned();
1038    }
1039    let mut raw = title.to_owned();
1040    for step in steps {
1041        let marker = match step.status() {
1042            PlanStepStatus::Pending => "[ ]",
1043            PlanStepStatus::InProgress => "[>]",
1044            PlanStepStatus::Completed => "[x]",
1045        };
1046        if !raw.is_empty() {
1047            raw.push('\n');
1048        }
1049        raw.push_str(marker);
1050        raw.push(' ');
1051        raw.push_str(step.text());
1052    }
1053    if let Some(note) = note {
1054        if !raw.is_empty() {
1055            raw.push('\n');
1056        }
1057        raw.push_str(note);
1058    }
1059    raw
1060}
1061
1062fn append_raw_details(raw: &mut String, details: &[TimelineDetail]) {
1063    for detail in details {
1064        raw.push('\n');
1065        if let Some(label) = detail.label() {
1066            raw.push_str(label);
1067            raw.push(' ');
1068        }
1069        raw.push_str(detail.text());
1070    }
1071}
1072
1073pub(super) fn terminal_safe_text(value: &str) -> String {
1074    value.chars().map(terminal_safe_character).collect()
1075}
1076
1077fn code_change_raw_text(change: &CodeChange) -> String {
1078    if let Some(patch) = change.patch() {
1079        return patch.to_owned();
1080    }
1081    let mut raw = format!("{}\n", change.path());
1082    for hunk in change.hunks() {
1083        writeln!(
1084            raw,
1085            "@@ -{},{} +{},{} @@",
1086            hunk.old_start(),
1087            hunk.old_lines(),
1088            hunk.new_start(),
1089            hunk.new_lines()
1090        )
1091        .expect("writing to a String cannot fail");
1092        for line in hunk.lines() {
1093            let marker = match line.kind() {
1094                CodeChangeLineKind::Context => ' ',
1095                CodeChangeLineKind::Addition => '+',
1096                CodeChangeLineKind::Deletion => '-',
1097            };
1098            raw.push(marker);
1099            raw.push_str(line.text());
1100            raw.push('\n');
1101        }
1102    }
1103    if change.truncated() {
1104        raw.push_str("[diff truncated: ");
1105        raw.push_str(truncation_text(change.truncation()));
1106        raw.push_str("]\n");
1107    }
1108    raw
1109}
1110
1111fn truncation_text(truncation: Option<CodeChangeTruncation>) -> &'static str {
1112    match truncation {
1113        Some(CodeChangeTruncation::Hunks) => "hunks",
1114        Some(CodeChangeTruncation::Lines) => "lines",
1115        Some(CodeChangeTruncation::LineBytes) => "line bytes",
1116        Some(CodeChangeTruncation::PatchBytes) => "patch bytes",
1117        None => "unknown",
1118    }
1119}
1120
1121fn terminal_safe_character(character: char) -> char {
1122    match character {
1123        '\n' => '\n',
1124        '\t' => ' ',
1125        '\u{1b}' => '␛',
1126        value if value.is_control() => '�',
1127        value => value,
1128    }
1129}
1130
1131fn bounded_terminal_text(value: &str) -> String {
1132    let mut text = String::new();
1133    for character in value.chars() {
1134        let mapped = terminal_safe_character(character);
1135        if text.len().saturating_add(mapped.len_utf8()) > MAX_CELL_TEXT_BYTES {
1136            break;
1137        }
1138        text.push(mapped);
1139    }
1140    text
1141}
1142
1143fn queue_preview(value: &str) -> String {
1144    let safe = bounded_terminal_text(value);
1145    let compact = safe.split_whitespace().collect::<Vec<_>>().join(" ");
1146    if compact.width() <= MAX_QUEUE_PREVIEW_CELLS {
1147        return compact;
1148    }
1149
1150    let available = MAX_QUEUE_PREVIEW_CELLS.saturating_sub(QUEUE_PREVIEW_ELLIPSIS.width());
1151    let mut preview = String::new();
1152    for grapheme in compact.graphemes(true) {
1153        if preview.width().saturating_add(grapheme.width()) > available {
1154            break;
1155        }
1156        preview.push_str(grapheme);
1157    }
1158    preview.push_str(QUEUE_PREVIEW_ELLIPSIS);
1159    preview
1160}
1161
1162#[cfg(test)]
1163mod tests {
1164    use std::collections::BTreeSet;
1165
1166    use tea_protocol::{CodeChange, CodeChangeKind, MessageId, ToolCallId};
1167
1168    use super::{
1169        CellContent, CellId, CellLane, CellNode, DecisionCell, DecisionStatus, DiffCell,
1170        LifecycleCell, LifecycleKind, LifecycleStatus, MessageAuthor, MessageCell,
1171        MessageCellFacet, NoticeCell, NoticeKind, NoticeSeverity, OutputFormat, PlanCell,
1172        QueuedInputCell, QueuedInputKind, ReasoningCell, ResultCell, SourcesCell, StreamCellFacet,
1173        ToolCellFacet, bounded_terminal_text,
1174    };
1175
1176    fn message_id(value: &str) -> MessageId {
1177        value.parse().expect("test message ID must be valid")
1178    }
1179
1180    fn tool_call_id(value: &str) -> ToolCallId {
1181        value.parse().expect("test tool-call ID must be valid")
1182    }
1183
1184    fn code_change() -> CodeChange {
1185        CodeChange::new(
1186            "src/lib.rs",
1187            CodeChangeKind::Update,
1188            Vec::new(),
1189            false,
1190            None,
1191            Some("@@ -1 +1 @@\n-old\n+new\n".to_owned()),
1192            Some(1),
1193        )
1194        .expect("test code change must be valid")
1195    }
1196
1197    #[test]
1198    fn terminal_text_is_control_safe_and_bounded() {
1199        assert_eq!(bounded_terminal_text("a\u{1b}[31m\t\0"), "a␛[31m �");
1200    }
1201
1202    #[test]
1203    fn raw_text_is_control_safe_and_preserves_empty_canonical_results() {
1204        let notice = CellContent::Notice(NoticeCell::new(
1205            NoticeKind::General,
1206            NoticeSeverity::Warning,
1207            "warning\u{1b}[31m",
1208            Some("hint\t\0"),
1209        ));
1210        assert_eq!(notice.raw_text(), "warning␛[31m\nhint �");
1211
1212        let empty_result = CellContent::Result(ResultCell::new(
1213            "Returned",
1214            Some("custom_tool"),
1215            "",
1216            OutputFormat::Plain,
1217            false,
1218        ));
1219        assert_eq!(empty_result.raw_text(), "");
1220    }
1221
1222    #[test]
1223    fn semantic_subtypes_live_inside_typed_payloads_without_parallel_kind() {
1224        let message = MessageCell::new(MessageAuthor::User, "hello", OutputFormat::Plain);
1225        let lifecycle = LifecycleCell::new(
1226            LifecycleKind::HostedTool,
1227            "Searched",
1228            Some("docs"),
1229            LifecycleStatus::Succeeded,
1230            Vec::new(),
1231            false,
1232            0,
1233        );
1234        let notice = NoticeCell::new(
1235            NoticeKind::McpHealth,
1236            NoticeSeverity::Warning,
1237            "offline",
1238            None,
1239        );
1240
1241        assert_eq!(message.author(), MessageAuthor::User);
1242        assert_eq!(lifecycle.kind(), LifecycleKind::HostedTool);
1243        assert_eq!(notice.kind(), NoticeKind::McpHealth);
1244        assert!(matches!(
1245            CellContent::Message(message),
1246            CellContent::Message(_)
1247        ));
1248        assert!(matches!(
1249            CellContent::Lifecycle(lifecycle),
1250            CellContent::Lifecycle(_)
1251        ));
1252        assert!(matches!(
1253            CellContent::Notice(notice),
1254            CellContent::Notice(_)
1255        ));
1256    }
1257
1258    #[test]
1259    fn raw_text_is_renderer_independent_for_every_content_variant() {
1260        let values = vec![
1261            (
1262                CellContent::Message(MessageCell::new(
1263                    MessageAuthor::Assistant,
1264                    "message",
1265                    OutputFormat::Markdown,
1266                )),
1267                "message",
1268            ),
1269            (
1270                CellContent::Reasoning(ReasoningCell::new("reasoning", true)),
1271                "reasoning",
1272            ),
1273            (
1274                CellContent::Plan(PlanCell::new("Plan", Some("plan source"), Vec::new(), None)),
1275                "plan source",
1276            ),
1277            (
1278                CellContent::Lifecycle(LifecycleCell::new(
1279                    LifecycleKind::RunActivity,
1280                    "Running",
1281                    Some("tests"),
1282                    LifecycleStatus::Running,
1283                    Vec::new(),
1284                    false,
1285                    1,
1286                )),
1287                "Running tests",
1288            ),
1289            (
1290                CellContent::Result(ResultCell::new(
1291                    "Returned",
1292                    Some("tool"),
1293                    "result",
1294                    OutputFormat::Plain,
1295                    false,
1296                )),
1297                "result",
1298            ),
1299            (CellContent::Sources(SourcesCell::new(Vec::new())), ""),
1300            (
1301                CellContent::Diff(DiffCell::new("Updated", code_change())),
1302                "@@ -1 +1 @@\n-old\n+new\n",
1303            ),
1304            (
1305                CellContent::QueuedInput(QueuedInputCell::new(QueuedInputKind::Steering, "queue")),
1306                "queue",
1307            ),
1308            (
1309                CellContent::Notice(NoticeCell::new(
1310                    NoticeKind::General,
1311                    NoticeSeverity::Information,
1312                    "notice",
1313                    Some("hint"),
1314                )),
1315                "notice\nhint",
1316            ),
1317            (
1318                CellContent::Decision(DecisionCell::new(
1319                    "Approve",
1320                    "workspace",
1321                    DecisionStatus::Pending,
1322                    Vec::new(),
1323                )),
1324                "Approve workspace",
1325            ),
1326        ];
1327
1328        for (content, expected) in values {
1329            assert_eq!(content.raw_text(), expected);
1330        }
1331    }
1332
1333    #[test]
1334    fn tool_ownership_is_metadata_not_a_kind_body_convention() {
1335        let owner = tool_call_id("0195a0b1-7e00-7000-8000-000000000099");
1336        let content = CellContent::Result(ResultCell::new(
1337            "Returned",
1338            Some("custom_tool"),
1339            "ok",
1340            OutputFormat::Plain,
1341            false,
1342        ));
1343        let node = CellNode::new(
1344            CellId::Tool {
1345                tool_call_id: owner,
1346                facet: ToolCellFacet::Result,
1347                part_index: 0,
1348            },
1349            content.clone(),
1350            Some(owner),
1351        );
1352
1353        assert_eq!(node.content(), &content);
1354        assert_eq!(node.tool_call_id(), Some(owner));
1355    }
1356
1357    #[test]
1358    fn stable_cell_ids_distinguish_message_blocks_and_tool_facets() {
1359        let message = message_id("0195a0b1-7e00-7000-8000-000000000001");
1360        let tool = tool_call_id("0195a0b1-7e00-7000-8000-000000000099");
1361        let ids = BTreeSet::from([
1362            CellId::Message {
1363                message_id: message,
1364                block_index: 0,
1365                facet: MessageCellFacet::Content,
1366            },
1367            CellId::Message {
1368                message_id: message,
1369                block_index: 1,
1370                facet: MessageCellFacet::Content,
1371            },
1372            CellId::Tool {
1373                tool_call_id: tool,
1374                facet: ToolCellFacet::Call,
1375                part_index: 0,
1376            },
1377            CellId::Tool {
1378                tool_call_id: tool,
1379                facet: ToolCellFacet::Decision,
1380                part_index: 0,
1381            },
1382            CellId::Tool {
1383                tool_call_id: tool,
1384                facet: ToolCellFacet::Result,
1385                part_index: 0,
1386            },
1387            CellId::Stream {
1388                message_id: message,
1389                block_index: 0,
1390                facet: StreamCellFacet::Message,
1391            },
1392            CellId::Synthetic {
1393                lane: CellLane::Active,
1394                index: 0,
1395            },
1396        ]);
1397
1398        assert_eq!(ids.len(), 7);
1399    }
1400}