Skip to main content

ag_session/
message.rs

1use std::fmt;
2use std::hash::Hasher;
3use std::str::FromStr;
4
5use rustc_hash::FxHasher;
6
7/// Durable category for one saved session transcript message.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum SessionMessageKind {
10    /// Raw user prompt text without TUI prompt markers or transcript padding.
11    UserPrompt,
12    /// Generated agent-facing prompt retained for replay but hidden from chat.
13    AgentPrompt,
14    /// Raw assistant answer text without transcript padding.
15    AssistantAnswer,
16    /// Generic workflow notice emitted by Agentty session workflows.
17    WorkflowNotice,
18}
19
20impl SessionMessageKind {
21    /// Returns the stable database string for this message kind.
22    pub fn as_str(self) -> &'static str {
23        match self {
24            Self::UserPrompt => "user_prompt",
25            Self::AgentPrompt => "agent_prompt",
26            Self::AssistantAnswer => "assistant_answer",
27            Self::WorkflowNotice => "workflow_notice",
28        }
29    }
30
31    /// Returns whether this kind represents a raw conversation message that
32    /// belongs in the normal `session_message` store.
33    pub fn is_conversation_message(self) -> bool {
34        matches!(
35            self,
36            Self::UserPrompt | Self::AgentPrompt | Self::AssistantAnswer
37        )
38    }
39
40    /// Returns whether this kind starts one user-visible or generated turn.
41    pub fn is_prompt(self) -> bool {
42        matches!(self, Self::UserPrompt | Self::AgentPrompt)
43    }
44}
45
46impl fmt::Display for SessionMessageKind {
47    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
48        formatter.write_str(self.as_str())
49    }
50}
51
52impl FromStr for SessionMessageKind {
53    type Err = SessionMessageKindParseError;
54
55    fn from_str(value: &str) -> Result<Self, Self::Err> {
56        match value {
57            "user_prompt" => Ok(Self::UserPrompt),
58            "agent_prompt" => Ok(Self::AgentPrompt),
59            "assistant_answer" => Ok(Self::AssistantAnswer),
60            "workflow_notice" => Ok(Self::WorkflowNotice),
61            _ => Err(SessionMessageKindParseError {
62                value: value.to_string(),
63            }),
64        }
65    }
66}
67
68/// Error returned when a stored session message kind is unknown.
69#[derive(Clone, Debug, Eq, PartialEq)]
70pub struct SessionMessageKindParseError {
71    value: String,
72}
73
74impl fmt::Display for SessionMessageKindParseError {
75    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
76        write!(formatter, "unknown session message kind `{}`", self.value)
77    }
78}
79
80impl std::error::Error for SessionMessageKindParseError {}
81
82/// One persisted transcript message for a session.
83#[derive(Clone, Debug, Eq, PartialEq)]
84pub struct SessionMessage {
85    /// Canonical transcript text for this message.
86    pub content: String,
87    /// Durable message category.
88    pub kind: SessionMessageKind,
89    /// Monotonic position within the owning session transcript.
90    pub position: i64,
91}
92
93impl SessionMessage {
94    /// Creates one transcript message at a stable transcript position.
95    pub fn new(position: i64, kind: SessionMessageKind, content: impl Into<String>) -> Self {
96        Self {
97            content: content.into(),
98            kind,
99            position,
100        }
101    }
102
103    /// Creates one raw user or assistant message using kind-specific storage
104    /// normalization.
105    pub fn conversation(position: i64, kind: SessionMessageKind, content: impl AsRef<str>) -> Self {
106        Self {
107            content: stored_message_content(kind, content.as_ref()),
108            kind,
109            position,
110        }
111    }
112
113    /// Appends this message to a formatted transcript display buffer.
114    fn append_display_text(&self, output: &mut String) {
115        match self.kind {
116            SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
117                Self::append_user_prompt_display_text(output, &self.content);
118            }
119            SessionMessageKind::AssistantAnswer => {
120                Self::append_assistant_answer_display_text(output, &self.content);
121            }
122            SessionMessageKind::WorkflowNotice => output.push_str(&self.content),
123        }
124    }
125
126    /// Appends one raw user prompt using the session transcript marker and
127    /// spacing.
128    fn append_user_prompt_display_text(output: &mut String, content: &str) {
129        let content = normalized_user_prompt_content(content);
130        if content.trim().is_empty() {
131            return;
132        }
133
134        if !output.is_empty() {
135            output.push('\n');
136        }
137
138        let is_clarification_prompt = content
139            .lines()
140            .next()
141            .is_some_and(|line| line.trim() == CLARIFICATION_HEADER);
142
143        for (line_index, prompt_line) in content.split('\n').enumerate() {
144            if is_clarification_prompt
145                && line_index > 0
146                && Self::is_clarification_question_line(prompt_line)
147            {
148                output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
149                output.push('\n');
150            }
151
152            if line_index == 0 {
153                output.push_str(USER_PROMPT_PREFIX);
154            } else {
155                output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
156            }
157
158            output.push_str(prompt_line);
159            output.push('\n');
160        }
161
162        output.push('\n');
163    }
164
165    /// Returns true for raw clarification question rows like `1. Q: Need
166    /// tests?`.
167    fn is_clarification_question_line(line: &str) -> bool {
168        let trimmed_line = line.trim_start();
169        let digit_count = trimmed_line
170            .chars()
171            .take_while(char::is_ascii_digit)
172            .count();
173        if digit_count == 0 {
174            return false;
175        }
176
177        let (_, suffix) = trimmed_line.split_at(digit_count);
178
179        suffix.starts_with(". Q: ")
180    }
181
182    /// Appends one raw assistant answer using session transcript spacing.
183    fn append_assistant_answer_display_text(output: &mut String, content: &str) {
184        let content = content.trim();
185        if content.is_empty() {
186            return;
187        }
188
189        output.push_str(content);
190        output.push_str("\n\n");
191    }
192}
193
194/// Ordered transcript view assembled from persisted session messages.
195#[derive(Clone, Debug, Default, Eq, PartialEq)]
196pub struct SessionTranscript {
197    content_hash: u64,
198    messages: Vec<SessionMessage>,
199    total_content_len: usize,
200}
201
202impl SessionTranscript {
203    /// Creates an ordered transcript from persisted messages.
204    pub fn new(mut messages: Vec<SessionMessage>) -> Self {
205        messages.sort_by_key(|message| message.position);
206
207        let content_hash = Self::content_hash_for_messages(&messages);
208        let total_content_len = messages.iter().map(|message| message.content.len()).sum();
209
210        Self {
211            content_hash,
212            messages,
213            total_content_len,
214        }
215    }
216
217    /// Returns whether the transcript contains no saved messages.
218    pub fn is_empty(&self) -> bool {
219        self.messages.is_empty()
220    }
221
222    /// Returns the ordered transcript messages.
223    pub fn messages(&self) -> &[SessionMessage] {
224        &self.messages
225    }
226
227    /// Returns the cached content identity for render and projection caches.
228    pub fn content_hash(&self) -> u64 {
229        self.content_hash
230    }
231
232    /// Returns the total byte length of message content in this transcript.
233    pub fn total_content_len(&self) -> usize {
234        self.total_content_len
235    }
236
237    /// Appends one message after the ordered transcript tail using the same
238    /// content normalization as durable storage.
239    ///
240    /// [`Self::new`] sorts persisted input before this method derives the next
241    /// position, so the message slice and its cached content hash retain the
242    /// same ordering as a newly reconstructed transcript.
243    pub fn append_message(&mut self, kind: SessionMessageKind, content: &str) {
244        let content = stored_message_content(kind, content);
245        if content.trim().is_empty() {
246            return;
247        }
248
249        let position = self
250            .messages
251            .last()
252            .map_or(0, |message| message.position.saturating_add(1));
253        self.total_content_len = self.total_content_len.saturating_add(content.len());
254        self.messages
255            .push(SessionMessage::new(position, kind, content));
256        self.content_hash = Self::content_hash_for_messages(&self.messages);
257    }
258
259    /// Returns formatted transcript text for replay when content exists.
260    ///
261    /// User and assistant rows store raw content, so replay injects the prompt
262    /// marker and transcript spacing only for display and provider replay.
263    pub fn replay_text(&self) -> Option<String> {
264        let output = Self::display_text_for_messages(&self.messages);
265        if output.trim().is_empty() {
266            return None;
267        }
268
269        Some(output)
270    }
271
272    /// Returns formatted user and assistant transcript text when any
273    /// conversation messages exist.
274    pub fn conversation_replay_text(&self) -> Option<String> {
275        let mut output = String::new();
276
277        for message in self
278            .messages
279            .iter()
280            .filter(|message| message.kind.is_conversation_message())
281        {
282            message.append_display_text(&mut output);
283        }
284
285        if output.trim().is_empty() {
286            return None;
287        }
288
289        Some(output)
290    }
291
292    /// Formats an ordered message slice using canonical transcript display
293    /// markers and spacing.
294    ///
295    /// Unlike [`Self::new`], this method preserves the caller-provided order.
296    /// It is useful when rendering a selected subset of an existing transcript
297    /// without constructing another transcript aggregate.
298    pub fn display_text_for_messages(messages: &[SessionMessage]) -> String {
299        let mut output = String::new();
300
301        for message in messages {
302            message.append_display_text(&mut output);
303        }
304
305        output
306    }
307
308    /// Computes one ordered identity across message positions, kinds, and raw
309    /// content so render caches can compare transcripts without rescanning them
310    /// on every frame.
311    fn content_hash_for_messages(messages: &[SessionMessage]) -> u64 {
312        let mut hasher = FxHasher::default();
313
314        for message in messages {
315            hasher.write_i64(message.position);
316            hasher.write(message.kind.as_str().as_bytes());
317            hasher.write_u8(0xff);
318            hasher.write(message.content.as_bytes());
319            hasher.write_u8(0xfe);
320        }
321
322        hasher.finish()
323    }
324}
325
326/// Returns the durable message content for one kind.
327///
328/// User prompts preserve leading horizontal whitespace so pasted indentation
329/// survives persistence while outer line breaks and trailing whitespace are
330/// normalized. Assistant rows remove outer whitespace, while workflow notices
331/// preserve exact content so status blocks keep their spacing.
332pub fn stored_message_content(kind: SessionMessageKind, content: &str) -> String {
333    match kind {
334        SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
335            normalized_user_prompt_content(content)
336        }
337        SessionMessageKind::AssistantAnswer => normalized_message_content(content),
338        SessionMessageKind::WorkflowNotice => content.to_string(),
339    }
340}
341
342/// Returns raw persisted message content with only outer whitespace removed.
343pub fn normalized_message_content(content: &str) -> String {
344    content.trim().to_string()
345}
346
347const CLARIFICATION_HEADER: &str = "Clarifications:";
348const USER_PROMPT_CONTINUATION_PREFIX: &str = "   ";
349const USER_PROMPT_PREFIX: &str = " › ";
350
351/// Normalizes prompt boundaries without consuming indentation on the first
352/// content line.
353fn normalized_user_prompt_content(content: &str) -> String {
354    content
355        .trim_end()
356        .trim_start_matches(['\r', '\n'])
357        .to_string()
358}
359
360#[cfg(test)]
361#[path = "message_test.rs"]
362mod tests;