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
//! Names sessions for their host, `/resume`, and `rho sessions`, as the TUI
//! names its own: after the first turn a runtime completes, a background
//! title-agent call turns that exchange into a short title, unless the
//! session has one. A first turn the host cancelled does not count, and a
//! loaded session that was never named gets its title then. Until it lands,
//! or if it fails, or if no host runs it, the session is listed by its
//! first message.
//!
//! The runtime only asks, from the turn: the host takes the request once the
//! prompt returns, runs it, and shows the title it saves if the session is
//! still its own (ACP, as a `session_info_update`; the daemon, as a
//! `title_changed` event, #1670). The daemon titles every session it runs,
//! `rho run --detach` runs included: they are listed and followed like any
//! other. In-process headless hosts (`rho run`, subagents, workflow nodes)
//! leave the job untaken rather than spend a model call on every run.
use std::path::PathBuf;
use rho_sdk::{
model::{ContentBlock, Message},
CancellationToken, UserInput,
};
use super::{model_scoped_config, SessionRuntime};
use crate::{
agent::ResolvedRhoModel,
config::Config,
session::{NoSessionFound, Session as StoredSession},
};
/// What the title agent needs to name one session.
pub(crate) struct TitleJob {
model: ResolvedRhoModel,
/// The first exchange, as the title agent reads it.
input: String,
sdk_session_id: rho_sdk::SessionId,
stored_id: String,
cwd: PathBuf,
/// The session's credentials, which the title model signs in with.
credentials: std::sync::Arc<dyn rho_providers::credentials::CredentialStore>,
}
/// How far a runtime got asking to name its session: it asks once, from
/// the first turn that reached the model's answer.
pub(super) enum TitleState {
/// No turn has asked yet.
Unasked,
/// A turn asked, and the host has not taken the job yet.
Pending(Box<TitleJob>),
/// The host took the job; no later turn asks again.
Asked,
}
impl TitleJob {
/// Generates and saves the title. Yields it only when this request
/// saved it: a title someone else set first wins and is not resent, and
/// a session deleted since its turn gets none, so no model call names
/// it.
pub(crate) async fn generate(self) -> Option<String> {
let Self {
model,
input,
sdk_session_id,
stored_id,
cwd,
credentials,
} = self;
match StoredSession::title_is_set(&cwd, &stored_id) {
Ok(true) => return None,
Err(error) if error.is::<NoSessionFound>() => return None,
// A title that could not be read is generated all the same; the
// save keeps one set meanwhile.
Ok(false) | Err(_) => {}
}
let usage_recording = crate::usage::default_recording().await;
let title = crate::title::generate_title(
model,
input,
sdk_session_id,
cwd.clone(),
credentials,
usage_recording,
CancellationToken::new(),
)
.await;
match title.and_then(|title| StoredSession::set_generated_title(&cwd, &stored_id, &title)) {
Ok(saved) => saved.map(|update| update.title),
Err(error) => {
tracing::debug!(%error, "could not title session");
None
}
}
}
}
impl SessionRuntime {
/// Asks to name the session from `user`'s message and the model's last
/// reply, for [`Self::take_title`]. The reply may precede tool results,
/// as when a turn ends on `exit_plan_mode`; a turn calls it until one
/// has a reply to name the session from.
pub(super) fn request_title(&mut self, process_config: &Config, user: &UserInput) {
let Some(stored) = self.storage.file() else {
return;
};
let history = self.built.session.history();
let Some(reply) = history
.iter()
.rev()
.find_map(Message::completed_assistant_content)
else {
return;
};
self.title = TitleState::Pending(Box::new(TitleJob {
model: crate::title::title_model_from_config(&model_scoped_config(
&self.current_model(),
process_config,
)),
input: crate::title::first_turn_input(&text_of(user.blocks()), &text_of(reply)),
sdk_session_id: self.built.session.id().clone(),
stored_id: stored.id().to_owned(),
cwd: self.storage.cwd().to_path_buf(),
credentials: self.build.host.environment.credentials(),
}));
}
/// The title a turn of the last prompt asked for. Take it as soon as
/// the prompt returns; one a prompt dropped mid-await left behind is
/// taken after the next.
///
/// Taking the job is the only request: the runtime never asks again,
/// and the title exists only once [`TitleJob::generate`] finishes, so a
/// host that takes the job must run it.
#[must_use = "the session is titled only once the taken job runs"]
pub(crate) fn take_title(&mut self) -> Option<TitleJob> {
let (state, job) = match std::mem::replace(&mut self.title, TitleState::Asked) {
TitleState::Unasked => (TitleState::Unasked, None),
TitleState::Pending(job) => (TitleState::Asked, Some(*job)),
TitleState::Asked => (TitleState::Asked, None),
};
self.title = state;
job
}
/// The title the session's file has saved, if any: none for a session
/// not saved yet, or one whose title could not be read.
pub(crate) fn stored_title(&self) -> Option<String> {
let stored = self.storage.file()?;
StoredSession::title(self.storage.cwd(), stored.id()).unwrap_or_else(|error| {
tracing::debug!(%error, "could not read the session's title");
None
})
}
}
fn text_of(blocks: &[ContentBlock]) -> String {
blocks
.iter()
.filter_map(|block| match block {
ContentBlock::Text(text) => Some(text.as_str()),
ContentBlock::Image(_) | ContentBlock::ToolCall(_) => None,
})
.collect::<Vec<_>>()
.join("\n")
}
#[cfg(test)]
#[path = "title_tests.rs"]
mod tests;