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
//! Observing sessions (`rho/session/observe`): following a session's events
//! as an attach does, for a client that only reads it, such as the `read`
//! and `wait` tools of `rho mcp serve` (#1672). Observing never loads a
//! session. One the daemon has loaded is followed as an attach follows it,
//! keeping the environment it runs with. One a subagent or workflow agent
//! node run is writing is followed through the run's stream, from when the
//! run opens it until the run ends (#1668; see `child_feeds`). A saved one it has not loaded is
//! opened only to be read, starting none of its MCP servers, OpenAPI
//! sources, or hooks, replayed as its file keeps it with how its last turn
//! ended, and shut down again; the client is then detached as
//! [`DetachReason::NotLoaded`]. A reopen would start the session's servers
//! with the reader's environment, at the reader's nesting depth rather
//! than the session's own. A saved session another engine ran, a subagent
//! run on an external agent runtime, replays what the run showed instead
//! (see `engine_replay`).
use rho_protocol::{
Cursor, DetachReason, ErrorCode, RpcError, SessionAttachResponse, SessionObserveParams,
Subscription,
};
use rho_sdk::SessionId;
use super::{
attach_response,
engine::Engine,
engine_replay::{self, saved_engine},
open::open_to_read,
opening::opening_feed,
options::available_auths,
reopen::{parse_session, saved_to_read, saved_workspace},
worktree::{Restore, Restored},
writing, Sessions,
};
use crate::app::daemon_host::jobs::{JobId, JobRecord, SessionJob};
impl Sessions {
/// Subscribes a client to a session's events without loading it: a
/// loaded session's as [`Self::attach`] does, else a replay of what the
/// session saved, after which the client is detached.
pub(in crate::app::daemon_host) async fn observe(
&self,
params: SessionObserveParams,
) -> Result<(SessionAttachResponse, Subscription), RpcError> {
self.refuse_when_stopping()?;
let id = parse_session(¶ms.session)?;
let after = params.after.as_ref();
loop {
let loaded = self.loaded().get(&id).cloned();
if let Some(session) = loaded {
// Under the turn lock and marked in use, as an attach, so
// the idle unload cannot take it meanwhile. Taken already:
// looked up again, which no longer finds it loaded.
let Some(_turn) = session.enter() else {
continue;
};
return Ok(attach_response(
&session.workspace,
session.feed.attach(after),
));
}
// A subagent run under way writes it: its stream is the run's.
if let Some(observed) = self.subagents.feeds().attach(&id, after) {
return Ok(observed);
}
// Held while reading, so no request loads the session meanwhile
// and the read does not find its file held.
let _reopening = self.reopening.lock(&id).await;
// A request that held the lock first may have loaded it.
if self.loaded().contains_key(&id) {
continue;
}
return self.read_unloaded(&id, after).await;
}
}
/// The replay of saved session `id`, which the daemon has not loaded,
/// as a client resuming from `after` gets it, then nothing: the
/// session is read and shut down again (see [`open_to_read`]). Its
/// reopen lock is held.
async fn read_unloaded(
&self,
id: &SessionId,
after: Option<&Cursor>,
) -> Result<(SessionAttachResponse, Subscription), RpcError> {
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,
};
// Read from what its run left, with no worktree to restore.
let workspace = saved_workspace(id).await?;
if let Some(engine) = saved_engine(workspace.clone(), id).await? {
let run = self.jobs.last_writer(id);
return engine_replay::read(id, &workspace, engine, after, run.as_ref()).await;
}
let restored = match &mut last {
Some(record) => self.restore_worktree(record, Restore::Reading).await?,
None => Restored::Nothing,
};
let observed = self.read_saved(id, after, last.clone()).await;
// Removed again however the read went.
if let (Restored::ForReading, Some(record)) = (restored, &last) {
Self::end_read_checkout(record).await;
}
observed
}
/// The replay of saved session `id` whose last job is `last`, as
/// [`Self::read_unloaded`] answers it once its worktree is on disk.
async fn read_saved(
&self,
id: &SessionId,
after: Option<&Cursor>,
last: Option<JobRecord>,
) -> Result<(SessionAttachResponse, Subscription), RpcError> {
let stored = saved_to_read(id).await?;
// A session no daemon has run is idle, with no last turn. Its job
// is not registered: reading it records nothing.
let job = last.unwrap_or_else(|| {
JobRecord::new_session(JobId::generate(), stored.cwd().to_path_buf(), id.clone())
});
let opened = open_to_read(stored, &self.subagents, &self.settings, &job.id).await?;
// Read through `engine_replay` before this when an agent ran it.
let Engine::Rho(runtime) = opened.engine else {
return Err(RpcError::new(
ErrorCode::SessionOpenFailed,
format!("session {id} is run by an agent, whose journal shows it"),
));
};
let (feed, _, _) = opening_feed(
&job,
&runtime,
&opened.config,
&available_auths(runtime.credentials()).await,
);
// Unloaded, so nothing of it runs or wakes it: it is settled.
feed.update_activity(|| false);
feed.close(DetachReason::NotLoaded);
let observed = attach_response(runtime.workspace_root(), feed.attach(after));
runtime.shutdown().await;
Ok(observed)
}
}