Skip to main content

tea_cli/
session_views.rs

1use serde::Serialize;
2use tea::{RuntimeSessionState, SessionStats};
3use tea_coding::McpServiceSnapshot;
4use tea_mcp::{McpDescriptorDigest, McpErrorCode, McpServerId, McpServerState};
5use tea_protocol::{
6    ApprovalId, BranchId, ModelId, ProfileId, ProtocolTimestamp, RecordEnvelope, RecordId,
7    SessionId, SessionSequence,
8};
9use tea_session::{SessionCatalogEntry, SessionSnapshot};
10
11/// Maximum records returned by one RPC snapshot page.
12pub const MAX_SNAPSHOT_PAGE_RECORDS: usize = 64;
13
14/// One bounded safe MCP server projection for terminal and RPC hosts.
15///
16/// This intentionally excludes remote tool descriptions and annotations,
17/// executable details, environment values, stderr, and server result text.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
19#[serde(rename_all = "camelCase")]
20pub struct McpServerView {
21    server_id: McpServerId,
22    state: McpServerState,
23    #[serde(skip_serializing_if = "Option::is_none")]
24    code: Option<McpErrorCode>,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    descriptor_digest: Option<McpDescriptorDigest>,
27    restart_count: u32,
28    tools: Vec<String>,
29}
30
31impl McpServerView {
32    /// Returns the configured server identity.
33    #[must_use]
34    pub const fn server_id(&self) -> &McpServerId {
35        &self.server_id
36    }
37
38    /// Returns the host lifecycle state.
39    #[must_use]
40    pub const fn state(&self) -> McpServerState {
41        self.state
42    }
43
44    /// Returns the stable health diagnostic code.
45    #[must_use]
46    pub const fn code(&self) -> Option<McpErrorCode> {
47        self.code
48    }
49
50    /// Returns the frozen descriptor digest, when initialization completed.
51    #[must_use]
52    pub const fn descriptor_digest(&self) -> Option<&McpDescriptorDigest> {
53        self.descriptor_digest.as_ref()
54    }
55
56    /// Returns the bounded reconnect attempt count.
57    #[must_use]
58    pub const fn restart_count(&self) -> u32 {
59        self.restart_count
60    }
61
62    /// Returns local frozen aliases owned by this server.
63    #[must_use]
64    pub fn tools(&self) -> &[String] {
65        &self.tools
66    }
67}
68
69/// Creates safe MCP health/catalog projections in canonical server and alias order.
70#[must_use]
71pub fn mcp_servers(snapshot: &McpServiceSnapshot) -> Vec<McpServerView> {
72    snapshot
73        .servers()
74        .iter()
75        .map(|health| McpServerView {
76            server_id: health.server_id().clone(),
77            state: health.state(),
78            code: health.code(),
79            descriptor_digest: health.descriptor_digest().cloned(),
80            restart_count: health.restart_count(),
81            tools: snapshot
82                .catalog()
83                .iter()
84                .filter(|entry| entry.server_id() == health.server_id())
85                .map(|entry| entry.tool_name().as_str().to_owned())
86                .collect(),
87        })
88        .collect()
89}
90
91/// One bounded host-facing session catalog row.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
93#[serde(rename_all = "camelCase")]
94pub struct SessionListItem {
95    session_id: SessionId,
96    #[serde(skip_serializing_if = "Option::is_none")]
97    name: Option<String>,
98    updated_at: ProtocolTimestamp,
99    profile_id: ProfileId,
100    #[serde(skip_serializing_if = "Option::is_none")]
101    model_id: Option<ModelId>,
102    message_count: usize,
103    pending_approval_count: usize,
104}
105
106impl SessionListItem {
107    /// Returns the session identity.
108    #[must_use]
109    pub const fn session_id(&self) -> SessionId {
110        self.session_id
111    }
112
113    /// Returns the optional display name.
114    #[must_use]
115    pub fn name(&self) -> Option<&str> {
116        self.name.as_deref()
117    }
118
119    /// Returns the active transcript message count.
120    #[must_use]
121    pub const fn message_count(&self) -> usize {
122        self.message_count
123    }
124}
125
126impl From<&SessionCatalogEntry> for SessionListItem {
127    fn from(entry: &SessionCatalogEntry) -> Self {
128        Self {
129            session_id: entry.session_id(),
130            name: entry.name().map(ToString::to_string),
131            updated_at: entry.updated_at(),
132            profile_id: entry.profile_id().clone(),
133            model_id: entry.model_id().cloned(),
134            message_count: entry.message_count(),
135            pending_approval_count: entry.pending_approval_count(),
136        }
137    }
138}
139
140/// Creates stable catalog projections without exposing adapter types.
141#[must_use]
142pub fn session_list(entries: &[SessionCatalogEntry]) -> Vec<SessionListItem> {
143    entries.iter().map(SessionListItem::from).collect()
144}
145
146/// Compact mode-neutral state returned to automation clients.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
148#[serde(rename_all = "camelCase")]
149pub struct SessionStateView {
150    session_id: SessionId,
151    #[serde(skip_serializing_if = "Option::is_none")]
152    name: Option<String>,
153    profile_id: ProfileId,
154    #[serde(skip_serializing_if = "Option::is_none")]
155    model_id: Option<ModelId>,
156    #[serde(skip_serializing_if = "Option::is_none")]
157    active_branch_id: Option<BranchId>,
158    message_count: usize,
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pending_approval_id: Option<ApprovalId>,
161    is_running: bool,
162}
163
164impl SessionStateView {
165    /// Returns the session identity.
166    #[must_use]
167    pub const fn session_id(&self) -> SessionId {
168        self.session_id
169    }
170
171    /// Returns whether the live service owns an active run.
172    #[must_use]
173    pub const fn is_running(&self) -> bool {
174        self.is_running
175    }
176}
177
178impl From<&RuntimeSessionState> for SessionStateView {
179    fn from(state: &RuntimeSessionState) -> Self {
180        Self {
181            session_id: state.session_id(),
182            name: state.name().map(ToString::to_string),
183            profile_id: state.profile_id().clone(),
184            model_id: state.model_id().cloned(),
185            active_branch_id: state.active_branch_id(),
186            message_count: state.message_count(),
187            pending_approval_id: state.pending_approval_id(),
188            is_running: state.is_running(),
189        }
190    }
191}
192
193/// Rebuildable transcript statistics returned by host queries.
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
195#[serde(rename_all = "camelCase")]
196pub struct SessionStatsView {
197    message_count: usize,
198    user_messages: usize,
199    assistant_messages: usize,
200    tool_result_messages: usize,
201    tool_calls: usize,
202}
203
204impl From<SessionStats> for SessionStatsView {
205    fn from(stats: SessionStats) -> Self {
206        Self {
207            message_count: stats.message_count(),
208            user_messages: stats.user_messages(),
209            assistant_messages: stats.assistant_messages(),
210            tool_result_messages: stats.tool_result_messages(),
211            tool_calls: stats.tool_calls(),
212        }
213    }
214}
215
216/// One durable branch in the append-only session tree.
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
218#[serde(rename_all = "camelCase")]
219pub struct BranchView {
220    branch_id: BranchId,
221    #[serde(skip_serializing_if = "Option::is_none")]
222    source_branch_id: Option<BranchId>,
223    from_record_id: RecordId,
224    leaf_record_id: RecordId,
225    active: bool,
226}
227
228impl BranchView {
229    /// Returns branch identity.
230    #[must_use]
231    pub const fn branch_id(self) -> BranchId {
232        self.branch_id
233    }
234
235    /// Returns the source branch, or `None` for the root.
236    #[must_use]
237    pub const fn source_branch_id(self) -> Option<BranchId> {
238        self.source_branch_id
239    }
240
241    /// Returns the durable fork point.
242    #[must_use]
243    pub const fn from_record_id(self) -> RecordId {
244        self.from_record_id
245    }
246
247    /// Returns the current durable leaf.
248    #[must_use]
249    pub const fn leaf_record_id(self) -> RecordId {
250        self.leaf_record_id
251    }
252
253    /// Returns whether this is the active branch.
254    #[must_use]
255    pub const fn is_active(self) -> bool {
256        self.active
257    }
258}
259
260/// Deterministic tree projection over one canonical snapshot.
261#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
262#[serde(rename_all = "camelCase")]
263pub struct SessionTreeView {
264    session_id: SessionId,
265    #[serde(skip_serializing_if = "Option::is_none")]
266    active_branch_id: Option<BranchId>,
267    branches: Vec<BranchView>,
268}
269
270impl SessionTreeView {
271    /// Returns branches in stable branch-ID order.
272    #[must_use]
273    pub fn branches(&self) -> &[BranchView] {
274        &self.branches
275    }
276}
277
278/// Projects the append-only branch graph for terminal and RPC consumers.
279#[must_use]
280pub fn session_tree(snapshot: &SessionSnapshot) -> SessionTreeView {
281    let state = snapshot.state();
282    let active_branch_id = state.active_branch_id();
283    let branches = state
284        .branches()
285        .values()
286        .map(|branch| BranchView {
287            branch_id: branch.branch_id(),
288            source_branch_id: branch.source_branch_id(),
289            from_record_id: branch.from_record_id(),
290            leaf_record_id: branch.leaf_record_id(),
291            active: active_branch_id == Some(branch.branch_id()),
292        })
293        .collect();
294    SessionTreeView {
295        session_id: state.session_id(),
296        active_branch_id,
297        branches,
298    }
299}
300
301/// One bounded page of canonical durable records plus the authoritative tail.
302#[derive(Debug, Clone, PartialEq, Serialize)]
303#[serde(rename_all = "camelCase")]
304pub struct SessionSnapshotPage {
305    session_id: SessionId,
306    after_sequence: Option<SessionSequence>,
307    tail_sequence: SessionSequence,
308    records: Vec<RecordEnvelope>,
309    has_more: bool,
310}
311
312impl SessionSnapshotPage {
313    /// Returns records after the requested cursor.
314    #[must_use]
315    pub fn records(&self) -> &[RecordEnvelope] {
316        &self.records
317    }
318
319    /// Returns whether another page is required to reach the tail.
320    #[must_use]
321    pub const fn has_more(&self) -> bool {
322        self.has_more
323    }
324}
325
326/// Creates a bounded canonical replay page after an optional durable cursor.
327#[must_use]
328pub fn snapshot_page(
329    snapshot: &SessionSnapshot,
330    after_sequence: Option<SessionSequence>,
331    requested_limit: usize,
332) -> SessionSnapshotPage {
333    let limit = requested_limit.clamp(1, MAX_SNAPSHOT_PAGE_RECORDS);
334    let mut matching = snapshot
335        .records()
336        .iter()
337        .filter(|record| after_sequence.is_none_or(|cursor| record.sequence() > cursor));
338    let records = matching.by_ref().take(limit).cloned().collect::<Vec<_>>();
339    let has_more = matching.next().is_some();
340    SessionSnapshotPage {
341        session_id: snapshot.state().session_id(),
342        after_sequence,
343        tail_sequence: snapshot.state().tail_sequence(),
344        records,
345        has_more,
346    }
347}