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
//! The event streams of the subagent and workflow agent node runs the
//! daemon's sessions start (#1668), so a client follows a run as it
//! follows a session: by observing the session the run writes, or for a run
//! on an external agent runtime, the one it is recorded under.
//!
//! A run's stream is a [`Feed`] like a loaded session's, with one turn: the
//! run. It opens when the run opens its session, which may be long after
//! the run started, while it waits for capacity; an observe meanwhile is
//! refused as any other of a session a job writes, and the client asks
//! again. The stream carries the run's events as its child sends them,
//! the run's job states, and how the run ended, then closes. Nobody
//! attaches to it to prompt, steer, or answer: a run's questions go to its
//! parent session.
use std::{
collections::HashMap,
path::PathBuf,
sync::{Arc, Mutex, MutexGuard, PoisonError},
};
use rho_protocol::{self as wire, DetachReason, SessionAttachAnswer, Subscription, TurnOutcome};
use rho_sdk::SessionId;
use tokio::sync::watch;
use super::{attach_response, feed::Feed};
use crate::app::daemon_host::jobs::{JobState, Moved, TransitionError};
use crate::app::session_events::Wanted;
/// The streams of the runs under way, by the session each writes.
#[derive(Clone, Default)]
pub(in crate::app::daemon_host) struct ChildFeeds {
runs: Arc<Mutex<HashMap<SessionId, Listed>>>,
}
/// One run's stream as an observe finds it.
#[derive(Clone)]
struct Listed {
workspace: PathBuf,
/// The run's feed, once the run opened its session.
feed: watch::Receiver<Option<Arc<Feed>>>,
}
impl ChildFeeds {
/// Lists the stream of a run about to write `session` in `workspace`,
/// whose job is in `state`. The stream is listed until the returned
/// [`ChildStream`] drops.
pub(in crate::app::daemon_host) fn list(
&self,
session: SessionId,
workspace: PathBuf,
state: &JobState,
) -> ChildStream {
let (feed, listed) = watch::channel(None);
self.runs().insert(
session.clone(),
Listed {
workspace,
feed: listed,
},
);
ChildStream {
feeds: self.clone(),
session,
turn: wire::TurnId::new(uuid::Uuid::new_v4().hyphenated().to_string()),
state: state.into(),
feed,
}
}
/// The stream of the run writing `session`; `None` when no run under
/// way writes it, or the run has not opened it yet: a request never
/// waits on a run, which may be queued for long.
pub(super) fn run(&self, session: &SessionId) -> Option<RunStream> {
let listed = self.runs().get(session)?.clone();
let feed = listed.feed.borrow().clone()?;
Some(RunStream {
workspace: listed.workspace,
feed,
})
}
/// What `rho/job/list` reports of the run writing `session` from its
/// stream; `None` when no run under way writes it, or the run has not
/// opened it yet.
pub(in crate::app::daemon_host) fn live(&self, session: &SessionId) -> Option<wire::JobLive> {
let listed = self.runs().get(session)?.clone();
let feed = listed.feed.borrow().clone()?;
Some(feed.live())
}
fn runs(&self) -> MutexGuard<'_, HashMap<SessionId, Listed>> {
// Entries are only inserted and removed whole.
self.runs.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// The stream of a run under way, once it opened the session it writes.
pub(super) struct RunStream {
workspace: PathBuf,
feed: Arc<Feed>,
}
impl RunStream {
/// Subscribes a client to the run's stream, resuming after its seq
/// cursor when the stream still can, its events leaving the tool output
/// it asks out: a run's stream has no saved entries or window to resume
/// by.
pub(super) fn attach(
&self,
from: super::ResumeFrom<'_>,
) -> (SessionAttachAnswer, Subscription) {
let from = super::ResumeFrom {
deferral: from.deferral,
..super::ResumeFrom::cursor(from.after)
};
attach_response(&self.workspace, self.feed.attach(from))
}
/// Takes the wanted items the run's buffered events carry: what the
/// run showed lately.
pub(super) fn find_tool_output(&self, wanted: &mut Wanted) {
// A run's stream saves no turns of its own: its session's file
// holds them.
let _ = self.feed.find_tool_output(wanted);
}
}
/// One run's stream, as the task that follows the run writes it. Dropping
/// it closes the stream and takes it off the list.
pub(in crate::app::daemon_host) struct ChildStream {
feeds: ChildFeeds,
session: SessionId,
/// The stream's one turn: the run.
turn: wire::TurnId,
/// Where the run's job is, which the feed opens in.
state: wire::JobState,
feed: watch::Sender<Option<Arc<Feed>>>,
}
impl ChildStream {
/// Opens the stream: the run opened its session, which runs with
/// `options` as agent `agent`, on `runtime`.
pub(in crate::app::daemon_host) fn open(
&self,
options: wire::SessionOptions,
agent: String,
runtime: crate::agent::AgentRuntime,
) {
self.feed.send_if_modified(|feed| {
if feed.is_some() {
return false;
}
let opened = Feed::new(
self.state,
Some(self.turn.clone()),
/*title*/ None,
options,
agent,
);
// A run on an agent runtime defers no tool output, and its
// replay says the runtime, as a loaded session of it does; a
// rho run's stream stays as a loaded rho session's.
if runtime != crate::agent::AgentRuntime::Rho {
opened.seed_engine(runtime.into());
}
*feed = Some(Arc::new(opened));
true
});
}
/// Sends `events` to the clients following the run. A run sends none
/// before it opens its session.
pub(in crate::app::daemon_host) fn publish(
&self,
events: impl IntoIterator<Item = wire::SessionEvent>,
) {
if let Some(feed) = self.feed.borrow().as_ref() {
feed.publish(events);
}
}
/// Moves the run's job with `change`, and tells the clients following
/// the run where it left the job: a job that ended ends the run's turn
/// as `outcome`, if any, in one publish, as a session's turn ends.
/// Holds the run's feed meanwhile (see [`Feed::publish_change`]), so an
/// observe that found the move in the job list sees it too.
pub(in crate::app::daemon_host) fn record(
&mut self,
change: impl FnOnce() -> Result<Moved, TransitionError>,
outcome: Option<TurnOutcome>,
) -> Result<Moved, TransitionError> {
let feed = self.feed.borrow().clone();
let tell = || {
let moved = change();
let events = match &moved {
Ok(moved) => self.moved_to(&moved.state, outcome),
Err(_) => Vec::new(),
};
(moved, events)
};
match feed {
Some(feed) => feed.publish_change(tell),
None => tell().0,
}
}
/// Notes the run's job is in `state`, and returns the events that tell
/// its clients so.
fn moved_to(
&mut self,
state: &JobState,
outcome: Option<TurnOutcome>,
) -> Vec<wire::SessionEvent> {
self.state = state.into();
match state {
JobState::Ended(_) => turn_end(&self.turn, outcome, self.state).collect(),
JobState::Idle
| JobState::Queued
| JobState::Running
| JobState::Requeued
| JobState::WaitingForInput => vec![self.state_event()],
}
}
/// Tells the clients following the run its title is `title`, unless
/// they know.
pub(in crate::app::daemon_host) fn titled(&self, title: &str) {
if let Some(feed) = self.feed.borrow().as_ref() {
if feed.title().as_deref() != Some(title) {
feed.publish([wire::SessionEvent::TitleChanged {
title: title.to_owned(),
}]);
}
}
}
/// Detaches the clients following the run with `reason`, instead of
/// the [`DetachReason::NotLoaded`] a dropped stream closes with.
pub(in crate::app::daemon_host) fn close(&self, reason: DetachReason) {
if let Some(feed) = self.feed.borrow().as_ref() {
feed.close(reason);
}
}
fn state_event(&self) -> wire::SessionEvent {
wire::SessionEvent::State {
state: self.state,
turn: Some(self.turn.clone()),
}
}
}
/// What ends a run's turn `turn` as `outcome`, if it has one to tell, with
/// its job in `state`, for one publish, as a session's turn ends.
pub(super) fn turn_end(
turn: &wire::TurnId,
outcome: Option<TurnOutcome>,
state: wire::JobState,
) -> impl Iterator<Item = wire::SessionEvent> {
let ended = outcome.map(|outcome| wire::SessionEvent::TurnEnded {
turn: turn.clone(),
outcome,
});
ended.into_iter().chain([wire::SessionEvent::State {
state,
turn: Some(turn.clone()),
}])
}
impl Drop for ChildStream {
fn drop(&mut self) {
// The run's session is saved and no longer written: an observe
// reads it from its file from here on, or for an external run,
// from the run's attach journal its file names.
self.close(DetachReason::NotLoaded);
let mut runs = self.feeds.runs();
// A workflow node that runs again writes the same session, and may
// have listed its stream already.
if runs
.get(&self.session)
.is_some_and(|listed| listed.feed.same_channel(&self.feed.subscribe()))
{
runs.remove(&self.session);
}
}
}