Skip to main content

rpi_cli/remote/
session.rs

1//! Client-side session model: folds the server's event stream into a
2//! render-friendly transcript plus a small amount of session state.
3//!
4//! This is deliberately independent of any local agent harness — it is the
5//! client analogue of the TS `packages/coding-agent/src/client/` remote-session
6//! layer, built on rpi's own protocol types.
7
8use serde_json::Value;
9
10use crate::remote::protocol::{RemoteEvent, RemoteResponse, SessionState};
11
12/// Re-exported from the shared render layer so the wire `Value` parsing lives in
13/// exactly one place (the session fold and the transcript view both use it).
14pub use crate::transcript_view::tool_result_text;
15
16/// A tool invocation as rendered in the transcript.
17#[derive(Debug, Clone, PartialEq)]
18pub struct ToolItem {
19    pub id: String,
20    pub name: String,
21    pub args: Value,
22    /// Latest partial output reported via `on_update`, if any.
23    pub partial: Option<String>,
24    /// Final output once the tool finished.
25    pub result: Option<String>,
26    pub is_error: bool,
27    pub done: bool,
28}
29
30/// One item in the remote transcript.
31#[derive(Debug, Clone, PartialEq)]
32pub enum TranscriptItem {
33    /// A prompt the local user submitted.
34    User(String),
35    /// Assistant response text (grows as deltas arrive).
36    Assistant(String),
37    /// Assistant reasoning text (grows as deltas arrive).
38    Thinking(String),
39    /// A tool call with its (partial/final) output.
40    Tool(ToolItem),
41    /// A local notice (retry, error, connection status).
42    Notice(String),
43}
44
45/// The transcript the UI renders, in order.
46#[derive(Debug, Clone, Default)]
47pub struct Transcript {
48    pub items: Vec<TranscriptItem>,
49}
50
51impl Transcript {
52    pub fn is_empty(&self) -> bool {
53        self.items.is_empty()
54    }
55
56    pub fn push_user(&mut self, text: impl Into<String>) {
57        self.items.push(TranscriptItem::User(text.into()));
58    }
59
60    pub fn push_notice(&mut self, text: impl Into<String>) {
61        self.items.push(TranscriptItem::Notice(text.into()));
62    }
63
64    fn push_assistant(&mut self) -> usize {
65        self.items.push(TranscriptItem::Assistant(String::new()));
66        self.items.len() - 1
67    }
68
69    fn push_thinking(&mut self) -> usize {
70        self.items.push(TranscriptItem::Thinking(String::new()));
71        self.items.len() - 1
72    }
73
74    /// Index of the last item of a given variant kind.
75    #[allow(dead_code)]
76    fn last_index<F: Fn(&TranscriptItem) -> bool>(&self, pred: F) -> Option<usize> {
77        self.items.iter().rposition(pred)
78    }
79
80    /// Find a tool item by call id.
81    pub fn tool_mut(&mut self, id: &str) -> Option<&mut ToolItem> {
82        self.items.iter_mut().find_map(|item| match item {
83            TranscriptItem::Tool(tool) if tool.id == id => Some(tool),
84            _ => None,
85        })
86    }
87
88    /// Plain-text projection (used for logs, tests, and non-TUI output).
89    pub fn to_text(&self) -> String {
90        let mut out = String::new();
91        for item in &self.items {
92            match item {
93                TranscriptItem::User(text) => {
94                    out.push_str("> ");
95                    out.push_str(text);
96                    out.push('\n');
97                }
98                TranscriptItem::Assistant(text) => {
99                    out.push_str(text);
100                    out.push('\n');
101                }
102                TranscriptItem::Thinking(text) => {
103                    out.push_str("[thinking] ");
104                    out.push_str(text);
105                    out.push('\n');
106                }
107                TranscriptItem::Tool(tool) => {
108                    let status = if tool.done {
109                        if tool.is_error {
110                            "error"
111                        } else {
112                            "ok"
113                        }
114                    } else {
115                        "running"
116                    };
117                    out.push_str(&format!("[tool {} {}]\n", tool.name, status));
118                    if let Some(body) = tool.result.as_ref().or(tool.partial.as_ref()) {
119                        out.push_str(body);
120                        out.push('\n');
121                    }
122                }
123                TranscriptItem::Notice(text) => {
124                    out.push('[');
125                    out.push_str(text);
126                    out.push_str("]\n");
127                }
128            }
129        }
130        out
131    }
132}
133
134/// Extract concatenated text from a serialized `AgentMessage`/`AssistantMessage`
135/// (`content: [{type:"text",text:…}]`).
136pub fn message_text(message: &Value) -> String {
137    let mut out = String::new();
138    if let Some(content) = message.get("content") {
139        if let Some(text) = content.as_str() {
140            return text.to_string();
141        }
142        if let Some(blocks) = content.as_array() {
143            for block in blocks {
144                if block.get("type").and_then(Value::as_str) == Some("text") {
145                    if let Some(text) = block.get("text").and_then(Value::as_str) {
146                        out.push_str(text);
147                    }
148                }
149            }
150        }
151    }
152    out
153}
154
155/// The logical role of a serialized message (`kind` or `role`).
156pub fn message_role(message: &Value) -> &str {
157    message
158        .get("kind")
159        .or_else(|| message.get("role"))
160        .and_then(Value::as_str)
161        .unwrap_or("")
162}
163
164/// Client-side session state: the transcript plus the latest server state.
165#[derive(Debug, Clone, Default)]
166pub struct RemoteSession {
167    pub transcript: Transcript,
168    pub state: SessionState,
169    /// True between `agent_start` and `agent_end`.
170    pub streaming: bool,
171    /// Set once the server sent its `ready` line.
172    pub ready: bool,
173    /// Most recent error surfaced locally or by the server.
174    pub last_error: Option<String>,
175    /// Number of retries currently being waited on (0 when not retrying).
176    pub retry_attempt: Option<(u32, u32)>,
177    /// Delay of the pending retry in milliseconds (drives the status countdown).
178    pub retry_delay_ms: Option<u64>,
179    open_assistant: Option<usize>,
180    open_thinking: Option<usize>,
181}
182
183impl RemoteSession {
184    pub fn new() -> Self {
185        Self::default()
186    }
187
188    /// Record a locally-submitted prompt so it renders immediately.
189    pub fn on_user_prompt(&mut self, text: impl Into<String>) {
190        self.transcript.push_user(text);
191        self.streaming = true;
192        self.open_assistant = None;
193        self.open_thinking = None;
194    }
195
196    pub fn push_notice(&mut self, text: impl Into<String>) {
197        self.transcript.push_notice(text);
198    }
199
200    /// Apply a raw child line (`ready` / event / response) as forwarded by the
201    /// server's `event` notifications.
202    pub fn apply_line(&mut self, line: &Value) {
203        match line.get("type").and_then(Value::as_str) {
204            Some("ready") => self.ready = true,
205            Some("response") => {
206                if let Ok(response) = serde_json::from_value::<RemoteResponse>(line.clone()) {
207                    self.apply_response(&response);
208                }
209            }
210            Some(_) => {
211                if let Ok(event) = serde_json::from_value::<RemoteEvent>(line.clone()) {
212                    self.apply_event(&event);
213                }
214            }
215            None => {}
216        }
217    }
218
219    /// Apply a decoded response (e.g. to a `get_state` command).
220    pub fn apply_response(&mut self, response: &RemoteResponse) {
221        if !response.is_ok() {
222            if let Some(error) = &response.error {
223                self.last_error = Some(error.clone());
224                self.transcript.push_notice(format!("error: {error}"));
225            }
226            return;
227        }
228        let Some(result) = &response.result else {
229            return;
230        };
231        if result.get("sessionId").is_some() && result.get("activeTools").is_some() {
232            if let Ok(state) = serde_json::from_value::<SessionState>(result.clone()) {
233                self.state = state;
234            }
235        }
236    }
237
238    /// Fold one lifecycle event into the transcript.
239    pub fn apply_event(&mut self, event: &RemoteEvent) {
240        match event {
241            RemoteEvent::UiDialogRequest { .. } | RemoteEvent::UiDialogClosed { .. } => {}
242            RemoteEvent::AgentStart => {
243                self.streaming = true;
244                self.retry_attempt = None;
245                self.retry_delay_ms = None;
246                self.open_assistant = None;
247                self.open_thinking = None;
248            }
249            RemoteEvent::AgentEnd { .. } => {
250                self.streaming = false;
251                self.retry_attempt = None;
252                self.retry_delay_ms = None;
253                self.open_assistant = None;
254                self.open_thinking = None;
255            }
256            RemoteEvent::RetryScheduled {
257                attempt,
258                max_retries,
259                delay_ms,
260                error,
261            } => {
262                self.retry_attempt = Some((*attempt, *max_retries));
263                self.retry_delay_ms = Some(*delay_ms);
264                self.transcript.push_notice(format!(
265                    "retry {attempt}/{max_retries} in {delay_ms}ms: {error}"
266                ));
267            }
268            RemoteEvent::TurnStart | RemoteEvent::TurnEnd { .. } => {}
269            RemoteEvent::MessageStart { message, .. } => {
270                if message_role(message) == "assistant" {
271                    // If the previous assistant item is still open with no
272                    // content, reuse it; otherwise start a new block.
273                    self.open_assistant = Some(self.transcript.push_assistant());
274                    self.open_thinking = None;
275                }
276            }
277            RemoteEvent::MessageEnd { message, .. } => {
278                if message_role(message) == "assistant" {
279                    let text = message_text(message);
280                    if let Some(index) = self.open_assistant.take() {
281                        if let Some(TranscriptItem::Assistant(existing)) =
282                            self.transcript.items.get_mut(index)
283                        {
284                            if !text.is_empty() {
285                                *existing = text;
286                            }
287                        }
288                    } else if !text.is_empty() {
289                        self.transcript.items.push(TranscriptItem::Assistant(text));
290                    }
291                }
292                self.open_thinking = None;
293            }
294            RemoteEvent::MessageUpdate {
295                event_type,
296                delta,
297                content_index,
298                ..
299            } => {
300                let Some(delta) = delta else { return };
301                if delta.is_empty() {
302                    return;
303                }
304                match event_type.as_str() {
305                    "text_delta" => {
306                        let index = match self.open_assistant {
307                            Some(index) => index,
308                            None => {
309                                let index = self.transcript.push_assistant();
310                                self.open_assistant = Some(index);
311                                index
312                            }
313                        };
314                        if let Some(TranscriptItem::Assistant(text)) =
315                            self.transcript.items.get_mut(index)
316                        {
317                            text.push_str(delta);
318                        }
319                    }
320                    "thinking_delta" => {
321                        let index = match self.open_thinking {
322                            Some(index) => index,
323                            None => {
324                                let index = self.transcript.push_thinking();
325                                self.open_thinking = Some(index);
326                                index
327                            }
328                        };
329                        if let Some(TranscriptItem::Thinking(text)) =
330                            self.transcript.items.get_mut(index)
331                        {
332                            text.push_str(delta);
333                        }
334                    }
335                    "tool_call_delta" => {
336                        let _ = content_index;
337                    }
338                    _ => {}
339                }
340            }
341            RemoteEvent::ToolExecutionStart {
342                tool_call_id,
343                tool_name,
344                args,
345            } => {
346                self.transcript.items.push(TranscriptItem::Tool(ToolItem {
347                    id: tool_call_id.clone(),
348                    name: tool_name.clone(),
349                    args: args.clone(),
350                    partial: None,
351                    result: None,
352                    is_error: false,
353                    done: false,
354                }));
355            }
356            RemoteEvent::ToolExecutionUpdate {
357                tool_call_id,
358                partial_result,
359                ..
360            } => {
361                let text = tool_result_text(partial_result);
362                if let Some(tool) = self.transcript.tool_mut(tool_call_id) {
363                    tool.partial = Some(text);
364                }
365            }
366            RemoteEvent::ToolExecutionEnd {
367                tool_call_id,
368                result,
369                is_error,
370                ..
371            } => {
372                let text = tool_result_text(result);
373                if let Some(tool) = self.transcript.tool_mut(tool_call_id) {
374                    tool.result = Some(text);
375                    tool.is_error = *is_error;
376                    tool.done = true;
377                }
378            }
379        }
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386    use serde_json::json;
387
388    fn event(value: serde_json::Value) -> RemoteEvent {
389        serde_json::from_value(value).unwrap()
390    }
391
392    #[test]
393    fn folds_text_stream_into_one_assistant_block() {
394        let mut session = RemoteSession::new();
395        session.on_user_prompt("hi");
396        session.apply_event(&event(json!({"type": "agent_start"})));
397        session.apply_event(&event(json!({
398            "type": "message_start",
399            "message": {"kind": "assistant", "content": []}
400        })));
401        for delta in ["Hel", "lo", "!"] {
402            session.apply_event(&event(json!({
403                "type": "message_update",
404                "message": {"kind": "assistant", "content": []},
405                "assistantMessageEvent": {"type": "text_delta"},
406                "eventType": "text_delta",
407                "contentIndex": 0,
408                "delta": delta,
409            })));
410        }
411        session.apply_event(&event(json!({
412            "type": "message_end",
413            "message": {"kind": "assistant", "content": [{"type": "text", "text": "Hello!"}]}
414        })));
415        session.apply_event(&event(
416            json!({"type": "agent_end", "messageCount": 1, "messages": []}),
417        ));
418
419        assert!(!session.streaming);
420        assert_eq!(session.transcript.items.len(), 2); // user + assistant
421        assert_eq!(
422            session.transcript.items[1],
423            TranscriptItem::Assistant("Hello!".into())
424        );
425    }
426
427    #[test]
428    fn tracks_tool_lifecycle_and_errors() {
429        let mut session = RemoteSession::new();
430        session.apply_event(&event(json!({
431            "type": "tool_execution_start",
432            "toolCallId": "c1",
433            "toolName": "read",
434            "args": {"path": "a.txt"}
435        })));
436        session.apply_event(&event(json!({
437            "type": "tool_execution_end",
438            "toolCallId": "c1",
439            "toolName": "read",
440            "isError": true,
441            "result": {"content": [{"type": "text", "text": "missing"}]}
442        })));
443
444        match &session.transcript.items[0] {
445            TranscriptItem::Tool(tool) => {
446                assert_eq!(tool.name, "read");
447                assert!(tool.done);
448                assert!(tool.is_error);
449                assert_eq!(tool.result.as_deref(), Some("missing"));
450            }
451            other => panic!("expected tool, got {other:?}"),
452        }
453    }
454
455    #[test]
456    fn thinking_deltas_get_their_own_block() {
457        let mut session = RemoteSession::new();
458        session.apply_event(&event(json!({
459            "type": "message_update",
460            "assistantMessageEvent": {"type": "thinking_delta"},
461            "eventType": "thinking_delta",
462            "delta": "why",
463        })));
464        assert_eq!(
465            session.transcript.items[0],
466            TranscriptItem::Thinking("why".into())
467        );
468    }
469
470    #[test]
471    fn ready_and_error_lines_update_state() {
472        let mut session = RemoteSession::new();
473        session.apply_line(&json!({"type": "ready"}));
474        assert!(session.ready);
475        session.apply_line(&json!({
476            "type": "response", "id": "1", "status": "error", "error": "boom"
477        }));
478        assert_eq!(session.last_error.as_deref(), Some("boom"));
479        session.apply_line(&json!({
480            "type": "response", "id": "2", "status": "ok",
481            "result": {"model": "m", "thinkingLevel": "off",
482                       "activeTools": ["read"], "sessionId": "s1"}
483        }));
484        assert_eq!(session.state.model.as_deref(), Some("m"));
485        assert_eq!(session.state.active_tools, vec!["read".to_string()]);
486    }
487}