use iced::widget::markdown;
use crate::ChatMessage;
use crate::agent::registry::RunningTool;
use crate::providers::plaintext_for_display;
use crate::session::{DecodedNativeHistoryMessage, decode_native_history_message};
use crate::util::none_if_empty;
use super::media_markers;
pub(crate) mod preview;
mod render;
pub(crate) use render::{MAX_TOOL_TOOLTIP_WIDTH, ToolBlockView, tool_block, truncate_at_boundary};
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum SessionEntry {
Message {
role: crate::ChatRole,
content: Option<String>,
thinking: Option<String>,
},
ToolRound {
narration: Option<String>,
reasoning: Option<String>,
calls: Vec<ToolCallEntry>,
},
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ToolCallEntry {
pub tool_call_id: String,
pub tool: RunningTool,
pub result: Option<String>,
}
fn split_thinking(
content: Option<String>,
reasoning: Option<String>,
) -> (Option<String>, Option<String>) {
if let Some(reasoning) = reasoning
&& !reasoning.is_empty()
{
return (Some(reasoning), content.and_then(|c| none_if_empty(&c)));
}
let Some(content) = content else {
return (None, None);
};
if let Some(thinking_start) = content.find("[thinking]") {
let body_start = thinking_start + "[thinking]".len();
if let Some(rel_end) = content[body_start..].find("[/thinking]") {
let end = body_start + rel_end;
let thinking = content[body_start..end].trim().to_string();
let after = content[end + "[/thinking]".len()..].trim().to_string();
return (Some(thinking), none_if_empty(&after));
}
}
(None, none_if_empty(&content))
}
pub(crate) fn build_ledger(messages: &[ChatMessage]) -> Vec<SessionEntry> {
build_ledger_with_sources(messages).0
}
pub(crate) fn build_ledger_with_sources(
messages: &[ChatMessage],
) -> (Vec<SessionEntry>, Vec<usize>) {
let mut entries: Vec<SessionEntry> = Vec::new();
let mut sources: Vec<usize> = Vec::new();
for (index, message) in messages.iter().enumerate() {
let before = entries.len();
match decode_native_history_message(message) {
Some(DecodedNativeHistoryMessage::Assistant {
content,
tool_calls,
reasoning,
}) => {
if let Some(calls) = tool_calls.filter(|calls| !calls.is_empty()) {
entries.push(SessionEntry::ToolRound {
narration: content.filter(|c| !c.is_empty()),
reasoning: plaintext_for_display(reasoning.as_ref()),
calls: calls
.iter()
.map(|call| ToolCallEntry {
tool_call_id: call.id.clone(),
tool: RunningTool::from_tool_call(call),
result: None,
})
.collect(),
});
} else {
let (thinking, body) =
split_thinking(content, plaintext_for_display(reasoning.as_ref()));
entries.push(SessionEntry::Message {
role: message.role,
content: body,
thinking,
});
}
}
Some(DecodedNativeHistoryMessage::ToolResult {
tool_call_id,
content,
}) => {
let mut remaining = Some(content);
let mut attached = false;
for entry in entries.iter_mut().rev() {
if let SessionEntry::ToolRound { calls, .. } = entry
&& let Some(call) = calls
.iter_mut()
.find(|c| c.tool_call_id == tool_call_id && c.result.is_none())
{
call.result = remaining.take();
attached = true;
break;
}
}
if !attached {
entries.push(SessionEntry::Message {
role: message.role,
content: remaining,
thinking: None,
});
}
}
_ => {
entries.push(SessionEntry::Message {
role: message.role,
content: Some(message.content.clone()),
thinking: None,
});
}
}
if entries.len() != before {
sources.push(index);
}
}
(entries, sources)
}
pub(crate) struct ParsedBody {
pub items: Vec<markdown::Item>,
pub attachments: Vec<media_markers::MediaAttachment>,
}
pub(crate) fn parse_entry_bodies(
entries: &[SessionEntry],
workspace: Option<&std::path::Path>,
) -> Vec<Option<ParsedBody>> {
entries
.iter()
.map(|entry| {
let display = match entry {
SessionEntry::Message { content, .. } => content.as_deref()?,
SessionEntry::ToolRound { narration, .. } => narration.as_deref()?,
};
let (items, attachments) = media_markers::parse_body(display, workspace);
Some(ParsedBody { items, attachments })
})
.collect()
}
pub(crate) fn promoted_reasoning<'a>(
narration: Option<&'a str>,
reasoning: Option<&'a str>,
) -> Option<&'a str> {
match reasoning {
Some(reasoning) if narration.is_none_or(|n| n.trim().is_empty()) => Some(reasoning),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
type SplitCase<'a> = (
&'a str,
&'a str,
Option<&'a str>,
Option<&'a str>,
Option<&'a str>,
);
#[test]
fn split_thinking_cases() {
let cases: &[SplitCase] = &[
(
"first pair only",
"intro [thinking] inner [/thinking] mid [thinking] later [/thinking] tail",
None,
Some("inner"),
Some("mid [thinking] later [/thinking] tail"),
),
(
"decoded reasoning wins",
"[thinking] literal [/thinking]",
Some("decoded reasoning"),
Some("decoded reasoning"),
Some("[thinking] literal [/thinking]"),
),
];
for &(name, content, reasoning, expected_thinking, expected_body) in cases {
let (thinking, body) =
split_thinking(Some(content.to_string()), reasoning.map(str::to_string));
assert_eq!(
thinking.as_deref(),
expected_thinking,
"case {name}: thinking"
);
assert_eq!(body.as_deref(), expected_body, "case {name}: body");
}
}
}