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
//! 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
//! subagent's or workflow node's session as its parent's to continue.
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::{Session as StoredSession, 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.pull_requests,
&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 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.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SavedFor {
/// A client's turns, which a child session refuses: only its parent
/// continues it, and a client's turns there would interleave with the
/// parent's when it resumes the child.
Turns,
/// Reading what it saved, as an observe does, a child session's too.
Reading,
/// Forking it, which a child session refuses as for turns, and a fork
/// or a session rebound to another agent too (see `fork.rs`).
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()))?
}
/// What a failed lookup of a saved session could not do.
const LOOK_UP: &str = "look the session up";
/// Opens the session saved under `id` in `cwd`'s workspace for `purpose`,
/// unless another process has it open or `purpose` refuses it (see
/// [`SavedFor`]). Blocking.
fn open_saved(cwd: &Path, id: &SessionId, purpose: SavedFor) -> Result<StoredSession, RpcError> {
let stored = match StoredSession::open_exact_in_workspace(cwd, id.as_str()) {
Ok(Some((stored, _history))) => stored,
// Deleted since the index named it.
Ok(None) => return Err(not_found(id)),
Err(error) if error.is::<SessionInUse>() => {
return Err(RpcError::new(ErrorCode::SessionInUse, format!("{error:#}")))
}
Err(error) => return Err(open_failed(error)),
};
if purpose == SavedFor::Reading {
return Ok(stored);
}
let origin = stored.origin().map_err(open_failed)?;
let child = match origin {
Some(SessionOrigin::Subagent) => Some("a subagent run"),
Some(SessionOrigin::WorkflowNode) => Some("a workflow node"),
Some(
SessionOrigin::Interactive
| SessionOrigin::Acp
| SessionOrigin::Daemon
| SessionOrigin::Run
| SessionOrigin::Fork
| SessionOrigin::Unknown,
)
| None => None,
};
if let Some(child) = child {
return Err(RpcError::new(
ErrorCode::SessionOpenFailed,
format!("session {id} is {child}'s; only the session that started it continues it"),
));
}
if purpose == SavedFor::Fork {
super::fork::refuse_unforkable(&stored, origin)?;
}
Ok(stored)
}
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;