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::ExtensionUiRequest {
243                method,
244                message,
245                notify_type,
246                ..
247            } => {
248                if method == "notify" {
249                    self.transcript
250                        .push_notice(notification_text(message, *notify_type));
251                }
252            }
253            RemoteEvent::AgentStart => {
254                self.streaming = true;
255                self.retry_attempt = None;
256                self.retry_delay_ms = None;
257                self.open_assistant = None;
258                self.open_thinking = None;
259            }
260            RemoteEvent::AgentEnd { .. } => {
261                self.streaming = false;
262                self.retry_attempt = None;
263                self.retry_delay_ms = None;
264                self.open_assistant = None;
265                self.open_thinking = None;
266            }
267            RemoteEvent::RetryScheduled {
268                attempt,
269                max_retries,
270                delay_ms,
271                error,
272            } => {
273                self.retry_attempt = Some((*attempt, *max_retries));
274                self.retry_delay_ms = Some(*delay_ms);
275                self.transcript.push_notice(format!(
276                    "retry {attempt}/{max_retries} in {delay_ms}ms: {error}"
277                ));
278            }
279            RemoteEvent::TurnStart | RemoteEvent::TurnEnd { .. } => {}
280            RemoteEvent::MessageStart { message, .. } => {
281                if message_role(message) == "assistant" {
282                    // If the previous assistant item is still open with no
283                    // content, reuse it; otherwise start a new block.
284                    self.open_assistant = Some(self.transcript.push_assistant());
285                    self.open_thinking = None;
286                }
287            }
288            RemoteEvent::MessageEnd { message, .. } => {
289                if message_role(message) == "assistant" {
290                    let text = message_text(message);
291                    if let Some(index) = self.open_assistant.take() {
292                        if let Some(TranscriptItem::Assistant(existing)) =
293                            self.transcript.items.get_mut(index)
294                        {
295                            if !text.is_empty() {
296                                *existing = text;
297                            }
298                        }
299                    } else if !text.is_empty() {
300                        self.transcript.items.push(TranscriptItem::Assistant(text));
301                    }
302                }
303                self.open_thinking = None;
304            }
305            RemoteEvent::MessageUpdate {
306                event_type,
307                delta,
308                content_index,
309                ..
310            } => {
311                let Some(delta) = delta else { return };
312                if delta.is_empty() {
313                    return;
314                }
315                match event_type.as_str() {
316                    "text_delta" => {
317                        let index = match self.open_assistant {
318                            Some(index) => index,
319                            None => {
320                                let index = self.transcript.push_assistant();
321                                self.open_assistant = Some(index);
322                                index
323                            }
324                        };
325                        if let Some(TranscriptItem::Assistant(text)) =
326                            self.transcript.items.get_mut(index)
327                        {
328                            text.push_str(delta);
329                        }
330                    }
331                    "thinking_delta" => {
332                        let index = match self.open_thinking {
333                            Some(index) => index,
334                            None => {
335                                let index = self.transcript.push_thinking();
336                                self.open_thinking = Some(index);
337                                index
338                            }
339                        };
340                        if let Some(TranscriptItem::Thinking(text)) =
341                            self.transcript.items.get_mut(index)
342                        {
343                            text.push_str(delta);
344                        }
345                    }
346                    "tool_call_delta" => {
347                        let _ = content_index;
348                    }
349                    _ => {}
350                }
351            }
352            RemoteEvent::ToolExecutionStart {
353                tool_call_id,
354                tool_name,
355                args,
356            } => {
357                self.transcript.items.push(TranscriptItem::Tool(ToolItem {
358                    id: tool_call_id.clone(),
359                    name: tool_name.clone(),
360                    args: args.clone(),
361                    partial: None,
362                    result: None,
363                    is_error: false,
364                    done: false,
365                }));
366            }
367            RemoteEvent::ToolExecutionUpdate {
368                tool_call_id,
369                partial_result,
370                ..
371            } => {
372                let text = tool_result_text(partial_result);
373                if let Some(tool) = self.transcript.tool_mut(tool_call_id) {
374                    tool.partial = Some(text);
375                }
376            }
377            RemoteEvent::ToolExecutionEnd {
378                tool_call_id,
379                result,
380                is_error,
381                ..
382            } => {
383                let text = tool_result_text(result);
384                if let Some(tool) = self.transcript.tool_mut(tool_call_id) {
385                    tool.result = Some(text);
386                    tool.is_error = *is_error;
387                    tool.done = true;
388                }
389            }
390        }
391    }
392}
393
394pub(crate) fn notification_text(
395    message: &str,
396    level: Option<rpi_extensions::UiNotificationLevel>,
397) -> String {
398    use rpi_extensions::UiNotificationLevel::{Error, Info, Warning};
399    let mut text = match level.unwrap_or(Info) {
400        Info => String::new(),
401        Warning => "warning: ".to_owned(),
402        Error => "error: ".to_owned(),
403    };
404    text.extend(message.chars().filter(|&ch| !ch.is_control() || ch == '\n'));
405    text
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411    use serde_json::json;
412
413    fn event(value: serde_json::Value) -> RemoteEvent {
414        serde_json::from_value(value).unwrap()
415    }
416
417    #[test]
418    fn folds_text_stream_into_one_assistant_block() {
419        let mut session = RemoteSession::new();
420        session.on_user_prompt("hi");
421        session.apply_event(&event(json!({"type": "agent_start"})));
422        session.apply_event(&event(json!({
423            "type": "message_start",
424            "message": {"kind": "assistant", "content": []}
425        })));
426        for delta in ["Hel", "lo", "!"] {
427            session.apply_event(&event(json!({
428                "type": "message_update",
429                "message": {"kind": "assistant", "content": []},
430                "assistantMessageEvent": {"type": "text_delta"},
431                "eventType": "text_delta",
432                "contentIndex": 0,
433                "delta": delta,
434            })));
435        }
436        session.apply_event(&event(json!({
437            "type": "message_end",
438            "message": {"kind": "assistant", "content": [{"type": "text", "text": "Hello!"}]}
439        })));
440        session.apply_event(&event(
441            json!({"type": "agent_end", "messageCount": 1, "messages": []}),
442        ));
443
444        assert!(!session.streaming);
445        assert_eq!(session.transcript.items.len(), 2); // user + assistant
446        assert_eq!(
447            session.transcript.items[1],
448            TranscriptItem::Assistant("Hello!".into())
449        );
450    }
451
452    #[test]
453    fn tracks_tool_lifecycle_and_errors() {
454        let mut session = RemoteSession::new();
455        session.apply_event(&event(json!({
456            "type": "tool_execution_start",
457            "toolCallId": "c1",
458            "toolName": "read",
459            "args": {"path": "a.txt"}
460        })));
461        session.apply_event(&event(json!({
462            "type": "tool_execution_end",
463            "toolCallId": "c1",
464            "toolName": "read",
465            "isError": true,
466            "result": {"content": [{"type": "text", "text": "missing"}]}
467        })));
468
469        match &session.transcript.items[0] {
470            TranscriptItem::Tool(tool) => {
471                assert_eq!(tool.name, "read");
472                assert!(tool.done);
473                assert!(tool.is_error);
474                assert_eq!(tool.result.as_deref(), Some("missing"));
475            }
476            other => panic!("expected tool, got {other:?}"),
477        }
478    }
479
480    #[test]
481    fn thinking_deltas_get_their_own_block() {
482        let mut session = RemoteSession::new();
483        session.apply_event(&event(json!({
484            "type": "message_update",
485            "assistantMessageEvent": {"type": "thinking_delta"},
486            "eventType": "thinking_delta",
487            "delta": "why",
488        })));
489        assert_eq!(
490            session.transcript.items[0],
491            TranscriptItem::Thinking("why".into())
492        );
493    }
494
495    #[test]
496    fn ready_and_error_lines_update_state() {
497        let mut session = RemoteSession::new();
498        session.apply_line(&json!({"type": "ready"}));
499        assert!(session.ready);
500        session.apply_line(&json!({
501            "type": "response", "id": "1", "status": "error", "error": "boom"
502        }));
503        assert_eq!(session.last_error.as_deref(), Some("boom"));
504        session.apply_line(&json!({
505            "type": "response", "id": "2", "status": "ok",
506            "result": {"model": "m", "thinkingLevel": "off",
507                       "activeTools": ["read"], "sessionId": "s1"}
508        }));
509        assert_eq!(session.state.model.as_deref(), Some("m"));
510        assert_eq!(session.state.active_tools, vec!["read".to_string()]);
511    }
512}