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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
//! Reopening saved sessions on demand (#1661). A prompt or an attach for a
//! saved session the daemon has not loaded opens it from its file, in its
//! own workspace, and records its turns on the session's last session job,
//! or a new one when no daemon ran it. Cancel, steer, unsteer, answer, hold,
//! and configure never reopen one: a session that is not loaded has no turn to
//! act on, and a client attaches before it changes settings. A reopened
//! session runs with the settings it kept (see `open.rs`), and with the
//! directories and parts left out its file keeps, plus those of the
//! request that reopens it (see `setup.rs`).
//!
//! An observe never reopens a session: it reads one it finds unloaded and
//! leaves it so (see `observe.rs`).
//!
//! A session another process has open is refused as in use, and a workflow
//! node's session as its workflow's to continue. A finished subagent's
//! session reopens for a person's turns, held alone in this process so no
//! follow-up run of the subagent writes beside them; one whose run is under
//! way is refused as busy, or as in use when the run holds its file.
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{Arc, Mutex, MutexGuard, PoisonError},
};
use rho_protocol::{ErrorCode, RpcError};
use rho_sdk::SessionId;
use tokio::sync::OwnedMutexGuard;
use super::{
open::{config_for_saved, open_session, OpenWith, Opening},
open_failed,
store::{store_blocking, store_failed},
worktree::{Restore, Restored},
writing, LoadedSession, SessionJobRecord, Sessions, TurnSlot,
};
use crate::{
app::daemon_host::{
jobs::{JobId, JobRecord, SessionJob},
wire::session_from_wire,
},
session::{InUseBy, Session as StoredSession, SessionEngine, SessionInUse, SessionOrigin},
};
impl Sessions {
/// The session `id` names, loaded: one the daemon has loaded, which
/// leaves `with` unused, or a saved one it reopens with what `with`
/// brings. Two requests for the same unloaded session open it once;
/// different sessions open at the same time.
pub(super) async fn session(
&self,
id: &rho_protocol::SessionId,
with: &OpenWith,
) -> Result<Arc<LoadedSession>, RpcError> {
let id = parse_session(id)?;
if let Some(session) = self.loaded().get(&id) {
return Ok(Arc::clone(session));
}
let _reopening = self.reopening.lock(&id).await;
// A request that held the lock first may have opened it.
let loaded = self.loaded().get(&id).cloned();
match loaded {
Some(session) => Ok(session),
None => self.reopen(&id, with).await,
}
}
/// Runs `use_session` on the session `id` names, loaded as
/// [`Self::session`] loads it, under its turn lock and marked in use, so
/// the idle unload cannot take it meanwhile (#1661). A session the
/// unload took after the lookup is looked up again, which reopens it,
/// or finds nothing saved for one it discarded: an unloaded session is
/// never in `loaded`.
pub(super) async fn enter_session<T>(
&self,
id: &rho_protocol::SessionId,
with: &OpenWith,
use_session: impl FnOnce(&LoadedSession, &mut TurnSlot) -> Result<T, RpcError>,
) -> Result<(Arc<LoadedSession>, T), RpcError> {
loop {
let session = self.session(id, with).await?;
let Some(mut turn) = session.enter() else {
continue;
};
let used = use_session(&session, &mut turn);
drop(turn);
return used.map(|used| (session, used));
}
}
/// The loaded session `id` names, or `None` for a saved session this
/// daemon has not loaded. An id nothing is saved under is
/// `SessionNotFound`.
pub(super) async fn loaded_session(
&self,
id: &rho_protocol::SessionId,
) -> Result<Option<Arc<LoadedSession>>, RpcError> {
let id = parse_session(id)?;
if let Some(session) = self.loaded().get(&id) {
return Ok(Some(Arc::clone(session)));
}
saved_workspace(&id).await.map(|_| None)
}
/// Reopens saved session `id` from its file, with what `with` brings,
/// and records its turns on the session's last job, or a new one when
/// no daemon has run it.
async fn reopen(
&self,
id: &SessionId,
with: &OpenWith,
) -> Result<Arc<LoadedSession>, RpcError> {
// This request brings its own opening, so one an unload kept for
// pull request news goes (see `pull_request_wake`).
self.pull_requests.drop_opening(id);
self.refuse_when_stopping()?;
let mut last = match self.jobs.session_job(id) {
SessionJob::Busy(job) => return Err(writing(&job, id)),
SessionJob::Last(record) => Some(*record),
SessionJob::New => None,
};
if let Some(record) = &mut last {
// Turns never get a checkout for reading.
let _: Restored = self.restore_worktree(record, Restore::Turns).await?;
}
let stored = saved_session(id, SavedFor::Turns).await?;
let global = config_for_saved(&self.settings).await?;
// The session opens under the grant `with` brings, held to its
// job's limit, whatever its last turn ran under, so its record never
// says another than its environment carries.
let held = last
.as_ref()
.map(|record| with.granted(record.held(with.grant.clone())));
let with = held.as_ref().unwrap_or(with);
let record = match last {
Some(record) => SessionJobRecord::Reuse(JobRecord {
grant: with.grant.clone(),
..record
}),
None => SessionJobRecord::Register(JobRecord {
grant: with.grant.clone(),
..JobRecord::new_session(JobId::generate(), stored.cwd().to_path_buf(), id.clone())
}),
};
let job = record.job().id.clone();
let opened = open_session(
Opening::Saved(stored),
with,
&self.subagents,
self.run_services(),
&self.settings,
global,
&job,
)
.await?;
let session = self.add(record, opened).await?;
tracing::info!(session = %id, %job, "reopened session");
Ok(session)
}
}
/// One lock per saved session being reopened, so concurrent requests for a
/// session reopen it once while different sessions reopen at the same time.
/// The idle unload holds a session's through its teardown, so a reopen does
/// not find the file still held by the old runtime. A session's lock is
/// removed once nothing holds or waits on it.
#[derive(Default)]
pub(super) struct ReopenLocks(Mutex<HashMap<SessionId, Arc<tokio::sync::Mutex<()>>>>);
impl ReopenLocks {
/// Waits for `id`'s lock, held until the guard drops.
pub(super) async fn lock(&self, id: &SessionId) -> ReopenGuard<'_> {
let lock = Arc::clone(self.map().entry(id.clone()).or_default());
ReopenGuard {
locks: self,
id: id.clone(),
held: lock.lock_owned().await,
}
}
fn map(&self) -> MutexGuard<'_, HashMap<SessionId, Arc<tokio::sync::Mutex<()>>>> {
// Only inserted into and removed from whole.
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
#[cfg(test)]
fn is_empty(&self) -> bool {
self.map().is_empty()
}
}
/// A held [`ReopenLocks`] lock.
pub(super) struct ReopenGuard<'a> {
locks: &'a ReopenLocks,
id: SessionId,
held: OwnedMutexGuard<()>,
}
impl ReopenGuard<'_> {
/// The session whose lock this holds.
pub(super) fn id(&self) -> &SessionId {
&self.id
}
}
impl Drop for ReopenGuard<'_> {
fn drop(&mut self) {
let mut map = self.locks.map();
// The map's and this guard's are the only clones unless a request
// waits on the lock, and clones are taken only under the map's lock,
// held here. Removing a lock someone waits on would let the next
// request reopen beside that waiter. Requests never give up: the
// transport runs every request to its end. The sweeper aborted at
// the daemon's exit can leave one entry, which nothing reads then.
if Arc::strong_count(OwnedMutexGuard::mutex(&self.held)) == 2 {
map.remove(&self.id);
}
}
}
/// The workspace of the session saved under `id`; `SessionNotFound` when
/// nothing is.
pub(super) async fn saved_workspace(id: &SessionId) -> Result<PathBuf, RpcError> {
let found = {
let id = id.clone();
store_blocking(LOOK_UP, move || StoredSession::workspace_of(id.as_str())).await?
};
found.ok_or_else(|| not_found(id))
}
/// What a saved session is opened for, besides reading it
/// ([`saved_to_read`]), which any session allows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SavedFor {
/// A client's turns, which a workflow node's session refuses: only its
/// workflow continues it, and a client's turns there would interleave
/// with the workflow's when it resumes the node. A subagent's session
/// takes them while no run of the subagent writes it.
Turns,
/// Forking it, which a workflow node's session refuses as for turns,
/// and `fork.rs` refuses for other sessions it cannot run.
Fork,
}
/// The session saved under `id`, opened in its own workspace for `purpose`.
pub(super) async fn saved_session(
id: &SessionId,
purpose: SavedFor,
) -> Result<StoredSession, RpcError> {
let cwd = saved_workspace(id).await?;
let id = id.clone();
tokio::task::spawn_blocking(move || open_saved(&cwd, &id, purpose))
.await
.map_err(|error| store_failed(LOOK_UP, &error.into()))?
}
/// The session saved under `id`, opened in its own workspace to read what
/// it saved, as an observe does, a child session's too.
pub(super) async fn saved_to_read(id: &SessionId) -> Result<StoredSession, RpcError> {
let cwd = saved_workspace(id).await?;
let id = id.clone();
tokio::task::spawn_blocking(move || open_exact(&cwd, &id).map_err(RpcError::from))
.await
.map_err(|error| store_failed(LOOK_UP, &error.into()))?
}
/// What a failed lookup of a saved session could not do.
const LOOK_UP: &str = "look the session up";
/// Why [`open_exact`] could not open a session.
enum NotOpened {
/// Something else holds it.
InUse(SessionInUse),
Refused(RpcError),
}
impl From<NotOpened> for RpcError {
fn from(not_opened: NotOpened) -> Self {
match not_opened {
NotOpened::InUse(in_use) => in_use_error(&in_use),
NotOpened::Refused(error) => error,
}
}
}
/// Opens the session saved under `id` in `cwd`'s workspace, unless another
/// process has it open, or this one alone. Blocking.
fn open_exact(cwd: &Path, id: &SessionId) -> Result<StoredSession, NotOpened> {
match StoredSession::open_exact_in_workspace(cwd, id.as_str()) {
Ok(Some((stored, _history))) => Ok(stored),
// Deleted since the index named it.
Ok(None) => Err(NotOpened::Refused(not_found(id))),
Err(error) => match error.downcast::<SessionInUse>() {
Ok(in_use) => Err(NotOpened::InUse(in_use)),
Err(error) => Err(NotOpened::Refused(open_failed(error))),
},
}
}
/// [`open_exact`], for `purpose`, unless `purpose` refuses it (see
/// [`SavedFor`]). Blocking.
fn open_saved(cwd: &Path, id: &SessionId, purpose: SavedFor) -> Result<StoredSession, RpcError> {
// An external agent run's holds what the run showed, not a conversation
// Rho can continue, and an engine this Rho does not know runs nothing
// here: both refused from the header, before opening the file takes its
// lease. One whose header does not read fails to open below.
if purpose == SavedFor::Turns {
match StoredSession::engine_by_id(cwd, id.as_str()) {
Ok(Some(SessionEngine::Acp { .. })) => {
return Err(RpcError::new(
ErrorCode::SessionOpenFailed,
format!(
"session {id} is a run on another agent runtime's, which Rho cannot continue; observe it instead"
),
));
}
Ok(Some(SessionEngine::Unknown)) => {
return Err(RpcError::new(
ErrorCode::SessionOpenFailed,
format!("session {id} ran on an engine this daemon does not know"),
));
}
Ok(None | Some(SessionEngine::AcpSession { .. })) | Err(_) => {}
}
}
let stored = open_exact(cwd, id).map_err(|not_opened| match (purpose, not_opened) {
// Only a subagent's session is held alone (below), which no fork
// takes, so the fork is refused as for good, not as for now.
(SavedFor::Fork, NotOpened::InUse(in_use)) if in_use.by() == InUseBy::OpenAloneHere => {
super::fork::unforkable(id.as_str(), super::fork::SUBAGENTS)
}
(_, not_opened) => not_opened.into(),
})?;
let origin = stored.origin().map_err(open_failed)?;
match (origin, purpose) {
(Some(SessionOrigin::WorkflowNode), SavedFor::Turns | SavedFor::Fork) => {
return Err(RpcError::new(
ErrorCode::SessionOpenFailed,
format!(
"session {id} is a workflow node's; only the workflow that ran it continues it"
),
));
}
(_, SavedFor::Fork) => super::fork::refuse_unforkable(&stored, origin)?,
(Some(SessionOrigin::Subagent), SavedFor::Turns) => {
// A follow-up of the subagent opens the file in this process,
// which would share its lock and write beside these turns. A run
// of it under way already holds it, so this is refused.
stored
.hold_alone()
.map_err(|in_use| in_use_error(&in_use))?;
}
(
Some(
SessionOrigin::Interactive
| SessionOrigin::Acp
| SessionOrigin::Daemon
| SessionOrigin::Run
| SessionOrigin::Fork
| SessionOrigin::Unknown,
)
| None,
SavedFor::Turns,
) => {}
}
Ok(stored)
}
fn in_use_error(in_use: &SessionInUse) -> RpcError {
RpcError::new(ErrorCode::SessionInUse, in_use.to_string())
}
pub(super) fn parse_session(id: &rho_protocol::SessionId) -> Result<SessionId, RpcError> {
session_from_wire(id).map_err(|_| RpcError::new(ErrorCode::InvalidParams, "not a session id"))
}
pub(super) fn not_found(id: &SessionId) -> RpcError {
RpcError::new(
ErrorCode::SessionNotFound,
format!("no session is saved under {id}"),
)
}
#[cfg(test)]
#[path = "reopen_tests.rs"]
mod tests;