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