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
//! Moving a session's conversation to another node of its saved tree.
//!
//! The runtime is rebuilt around the node's conversation, as a permission
//! mode change rebuilds it around the live one, and the session file's leaf
//! moves there, so later turns branch from the node and the nodes after it
//! stay in the tree. The session keeps its model, settings, tools, and
//! added directories: those belong to the session, not to a node. Clients
//! find the nodes in [`SessionRuntime::tree_rows`].
use std::collections::HashMap;
use super::{model_scoped_config, open::prompt_cache_key, SessionRuntime, SettingChangeError};
use crate::{
config::Config,
session::{
tree::{NodeId, SessionTreeItem},
workspace_checkpoint::WorkspaceCheckpointSummary,
},
};
/// A row of the session's tree as `/tree` lists it, with the workspace
/// checkpoints of the turns that started on it.
#[derive(Debug)]
pub(crate) struct TreeRow {
pub(crate) item: SessionTreeItem,
/// Oldest first: the checkpoint of the row's prompt's turn, then of
/// turns that carried the row on without a prompt, as one delivering
/// background results does. A turn that compacted part way ended on a
/// later row, and lists here still. Without the ones too old to
/// rewind.
pub(crate) checkpoints: Vec<WorkspaceCheckpointSummary>,
}
/// Why [`SessionRuntime::select_node`] left the conversation where it was.
#[derive(Debug, thiserror::Error)]
pub(crate) enum SelectNodeError {
/// Nothing is saved yet, so the session has no tree.
#[error("the session has no saved conversation yet")]
Unsaved,
/// The session's tree holds no such node.
#[error("the session's tree has no node '{0}'")]
UnknownNode(NodeId),
#[error(transparent)]
Change(SettingChangeError),
}
impl SessionRuntime {
/// The session's saved tree, one row for each prompt, each with the
/// workspace checkpoints of the turns that started on it; empty when
/// nothing is saved.
pub(crate) fn tree_rows(&self) -> anyhow::Result<Vec<TreeRow>> {
let Some(stored) = self.storage.file() else {
return Ok(Vec::new());
};
let checkpoints = match stored.workspace_checkpoint_store()? {
Some(store) => store.list()?,
None => Vec::new(),
};
stored.with_session_tree(|tree| {
let items = tree.turn_items()?;
let row_of: HashMap<&NodeId, usize> = items
.iter()
.enumerate()
.flat_map(|(row, item)| item.run.iter().map(move |node| (node, row)))
.collect();
let mut taken = vec![Vec::new(); items.len()];
for checkpoint in checkpoints {
// One saved before rewind boundaries cannot be rewound.
let Some(before) = &checkpoint.before_node_id else {
continue;
};
let row = tree
.turn_start(before, &checkpoint.node_id)
.and_then(|start| row_of.get(start));
if let Some(&row) = row {
taken[row].push(checkpoint);
}
}
Ok(items
.into_iter()
.zip(taken)
.map(|(item, checkpoints)| TreeRow { item, checkpoints })
.collect())
})
}
/// The row of the session's tree holding `node`.
pub(crate) fn tree_row_of(&self, node: &NodeId) -> anyhow::Result<NodeId> {
let stored = self
.storage
.file()
.ok_or_else(|| anyhow::anyhow!("the session has no saved conversation yet"))?;
stored.with_session_tree(|tree| {
tree.turn_items()?
.into_iter()
.find(|item| item.run.contains(node))
.map(|item| item.id)
.ok_or_else(|| anyhow::anyhow!("no row of the session's tree holds node '{node}'"))
})
}
/// How full the session's context is, between turns.
pub(crate) fn context_estimate(&self) -> rho_sdk::ContextEstimate {
self.built.session.context_estimate()
}
/// Continues the conversation from `node` of the session's saved tree.
/// On error the session keeps the conversation it had.
pub(crate) async fn select_node(
&mut self,
node: &NodeId,
process_config: &Config,
) -> Result<(), SelectNodeError> {
let stored = self
.storage
.file()
.cloned()
.ok_or(SelectNodeError::Unsaved)?;
let read = |error: anyhow::Error| SelectNodeError::Change(SettingChangeError::Apply(error));
let known = stored
.with_session_tree(|tree| Ok(tree.node(node).is_some()))
.map_err(read)?;
if !known {
return Err(SelectNodeError::UnknownNode(node.clone()));
}
let conversation = stored
.snapshot_for_node(
node,
self.built.provider.identity(),
prompt_cache_key(stored.id()),
)
.map_err(read)?;
let previous = self.built.session.snapshot();
self.rebuild_onto(conversation, process_config)
.await
.map_err(SelectNodeError::Change)?;
if let Err(error) = stored.set_leaf(node) {
// The file still continues from the old leaf; so must the
// runtime.
let error = match self.rebuild_onto(previous, process_config).await {
Ok(()) => error,
Err(rollback) => error.context(format!("rollback failed: {rollback}")),
};
return Err(SelectNodeError::Change(SettingChangeError::Apply(error)));
}
// Later turns continue another conversation, not the compacted one.
self.built.diagnostics.end_compaction_follow_up();
Ok(())
}
/// Rebuilds the runtime around `conversation`, a point of the
/// session's tree, with the session's model and permission mode.
async fn rebuild_onto(
&mut self,
conversation: rho_sdk::SessionSnapshot,
process_config: &Config,
) -> Result<(), SettingChangeError> {
let config = model_scoped_config(&self.current_model(), process_config);
let (mode, writes) = (self.permission.mode, self.permission.writes.clone());
self.rebuild_runtime_onto(&config, mode, writes, conversation)
.await
}
}
#[cfg(test)]
#[path = "tree_tests.rs"]
mod tests;