1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//! The session tree as `/tree` lists it.
use std::collections::HashSet;
use super::{
DisplayRowOrigin, MessageKey, NodeId, RestoredNode, SessionNodeKind, SessionTree,
StoredCompactionFacts, StoredDisplayMessage, TurnEnd,
};
/// What a [`SessionTreeItem`] row is.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum SessionTreeItemContent {
/// An empty durable root before any conversation turn.
SessionStart,
Turn {
/// `None` for a turn saved without a user message.
prompt: Option<RowPrompt>,
/// How the turn ended: the latest end its nodes record, a node
/// after a compaction it made part way included.
end: Option<TurnEnd>,
},
Compaction(StoredCompactionFacts),
}
/// The prompt a turn row starts with: the first user message its first
/// node shows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct RowPrompt {
/// Where it was saved, which with `key` names the message a replay
/// shows it as.
pub(crate) origin: DisplayRowOrigin,
pub(crate) key: Option<MessageKey>,
/// Its text; `None` for a prompt with none, such as an image alone.
pub(crate) text: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SessionTreeItem {
/// The last node of the row's run (see [`SessionTree::turn_items`]).
pub(crate) id: NodeId,
/// The row before it: the one whose last node its first node follows.
pub(crate) parent: Option<NodeId>,
/// The row's nodes, first to last.
pub(crate) run: Vec<NodeId>,
pub(crate) depth: usize,
pub(crate) content: SessionTreeItemContent,
/// When the row's last node was saved, in unix milliseconds, to the
/// second.
pub(crate) saved_at: Option<u64>,
pub(crate) active: bool,
pub(crate) on_active_path: bool,
pub(crate) ancestor_has_next_sibling: Vec<bool>,
pub(crate) is_last_sibling: bool,
}
impl SessionTree {
/// The node after `node`, when exactly one follows it.
fn only_child(&self, node: &RestoredNode) -> Option<&RestoredNode> {
match self.children.get(node.id()).map(Vec::as_slice) {
Some([only]) => self.node(only),
_ => None,
}
}
/// The node after `node` that carries its turn on: the one child that
/// shows no prompt, whatever prompts branch beside it.
fn turn_child(&self, node: &RestoredNode) -> Option<&RestoredNode> {
let mut carried = self
.children
.get(node.id())
.into_iter()
.flatten()
.filter_map(|child| self.node(child))
.filter(|child| Self::first_prompt(child).is_none());
match (carried.next(), carried.next()) {
(Some(only), None) => Some(only),
_ => None,
}
}
/// The first user message `node` shows, any prompt, an image alone
/// included, with its row.
fn first_prompt(node: &RestoredNode) -> Option<(usize, &StoredDisplayMessage)> {
node.display_messages()
.iter()
.enumerate()
.find(|(_, stored)| {
matches!(
stored.message.semantic(),
rho_sdk::model::SemanticMessage::User(_)
)
})
}
/// Whether `node` carries on the turn of the node before it: a commit
/// that shows no user message.
fn continues_turn(node: &RestoredNode) -> bool {
node.kind() == SessionNodeKind::Commit && Self::first_prompt(node).is_none()
}
/// The prompt of the turn `node` belongs to: the text of the first
/// user message at `node` or before it, whatever the turn saved after
/// its prompt. `None` for a prompt with no text, such as an image
/// alone, rather than an earlier turn's.
pub(crate) fn turn_prompt(&self, node: &NodeId) -> Option<String> {
let mut at = self.node(node);
while let Some(node) = at {
if let Some((_, prompt)) = Self::first_prompt(node) {
return super::super::persistence::user_message_text(&prompt.message);
}
at = node.parent_id().and_then(|parent| self.node(parent));
}
None
}
/// The first node a turn saved, which began at `before` and ended at
/// `last`: the node after `before` on the way to `last`. `None` when
/// `before` does not lead to `last`.
pub(crate) fn turn_start(&self, before: &NodeId, last: &NodeId) -> Option<&NodeId> {
let mut at = self.node(last)?;
loop {
let parent = at.parent_id()?;
if parent == before {
return Some(at.id());
}
at = self.node(parent)?;
}
}
/// The facts of compaction `node` read from its state and its
/// parent's, for a node saved before compactions recorded their own.
fn derived_compaction_facts(&self, node: &RestoredNode) -> StoredCompactionFacts {
let compaction = &node.facts().compaction;
StoredCompactionFacts {
previous_messages: node
.parent_id()
.and_then(|id| self.node(id))
.map_or(0, |parent| parent.facts().model_len),
current_messages: node.facts().model_len,
previous_tokens: compaction.last_previous_tokens().unwrap_or_default(),
current_tokens: compaction.last_current_tokens().unwrap_or_default(),
cost_usd_micros: None,
}
}
/// The tree as `/tree` lists it: one row for each prompt and all that
/// followed it. A node that adds no user message joins the row of the
/// node before it when nothing branches between them, and the row
/// names the last node of its run, the conversation once the turn
/// ended, since some hosts save a turn as several nodes, one for each
/// step.
pub(crate) fn turn_items(&self) -> anyhow::Result<Vec<SessionTreeItem>> {
let active_path: HashSet<_> = self
.active_path()?
.into_iter()
.map(|node| node.id().clone())
.collect();
let mut traversal = Vec::new();
let roots = self
.order
.iter()
.filter(|id| self.node(id).is_some_and(|node| node.parent_id().is_none()))
.cloned()
.collect::<Vec<_>>();
let mut stack = roots
.iter()
.enumerate()
.rev()
.map(|(index, id)| Pending {
id: id.clone(),
parent: None,
depth: 0,
ancestor_has_next_sibling: Vec::new(),
is_last_sibling: index + 1 == roots.len(),
})
.collect::<Vec<_>>();
while let Some(Pending {
id,
parent,
depth,
ancestor_has_next_sibling,
is_last_sibling,
}) = stack.pop()
{
let node = self
.node(&id)
.ok_or_else(|| anyhow::anyhow!("session tree is missing node '{id}'"))?;
// The row's run, and whether it holds the active leaf.
let mut run = vec![node];
let mut last = node;
while let Some(next) = self
.only_child(last)
.filter(|next| Self::continues_turn(next))
{
run.push(next);
last = next;
}
let content = match node.kind() {
// Classify from durable state, not missing user text: a root
// that shows nothing is the session start.
SessionNodeKind::Commit
if node.parent_id().is_none()
// Whatever the model holds: a host that saves the
// session before its first prompt saves the system
// prompt with it.
&& node.display_messages().is_empty() =>
{
SessionTreeItemContent::SessionStart
}
SessionNodeKind::Commit => SessionTreeItemContent::Turn {
prompt: Self::first_prompt(node).map(|(row, stored)| RowPrompt {
origin: DisplayRowOrigin {
node: node.id().clone(),
row,
},
key: stored.key.clone(),
text: super::super::persistence::user_message_text(&stored.message),
}),
// A turn that compacts part way saves its later steps
// after the compaction's node, on its row, which a
// prompt that branched from the row may sit beside.
end: run
.iter()
.copied()
.chain(std::iter::successors(self.turn_child(last), |at| {
self.turn_child(at)
}))
.filter_map(RestoredNode::turn_end)
.last(),
},
SessionNodeKind::Compaction => SessionTreeItemContent::Compaction(
node.compaction_facts()
.cloned()
.unwrap_or_else(|| self.derived_compaction_facts(node)),
),
};
let id = last.id().clone();
traversal.push(SessionTreeItem {
id: id.clone(),
parent,
run: run.iter().map(|node| node.id().clone()).collect(),
depth,
content,
saved_at: super::super::layout::parse_timestamp(last.timestamp())
.map(|secs| secs.saturating_mul(1000)),
active: run
.iter()
.any(|node| self.active_leaf_id() == Some(node.id())),
on_active_path: active_path.contains(node.id()),
ancestor_has_next_sibling: ancestor_has_next_sibling.clone(),
is_last_sibling,
});
let children = self.children.get(&id).map_or(&[][..], Vec::as_slice);
for (index, child_id) in children.iter().enumerate().rev() {
let mut child_ancestors = ancestor_has_next_sibling.clone();
if depth > 0 {
child_ancestors.push(!is_last_sibling);
}
stack.push(Pending {
id: child_id.clone(),
parent: Some(id.clone()),
depth: depth + 1,
ancestor_has_next_sibling: child_ancestors,
is_last_sibling: index + 1 == children.len(),
});
}
}
Ok(traversal)
}
}
/// A row [`SessionTree::turn_items`] has yet to visit, from its first node.
struct Pending {
id: NodeId,
parent: Option<NodeId>,
depth: usize,
ancestor_has_next_sibling: Vec<bool>,
is_last_sibling: bool,
}