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
//! A session's finished background work, delivered to its model as one
//! [`Batch`]: collected under the delivery lock (`notification_delivery`),
//! rendered once for the model and the transcript ([`BoundaryResults`]),
//! and committed only once the model took it. A batch dropped uncommitted
//! puts its results back, so a delivery the model never took loses nothing.
//!
//! Rho's own boundaries (`session_runtime::delegation`) and the turns of a
//! daemon session an agent on another runtime runs
//! (`daemon_host::sessions::acp_background`) share these mechanics. When a
//! batch is due, and what holds a prompt open, stays each host's policy.
use tokio::sync::mpsc;
use crate::{
app::{
boundary_results::BoundaryResults,
boundary_sources::{any_arrived, Arrival, BoundarySource, Reserved},
notification_delivery::DeliveryLock,
peer_sessions::PeerInbox,
pull_requests::PullRequestInbox,
subagent_manager::SubagentManager,
subagent_messaging::{NoticePermits, SubagentNotice},
},
display_transcript::DisplayTranscript,
tools::{
process::ProcessManager, sdk_registry::AppToolSet, ui::SurfaceHost,
workflow_tracker::WorkflowRunTracker,
},
};
/// The background work a session delivers.
pub(crate) struct BackgroundSources<'a> {
pub(crate) subagents: Option<&'a SubagentManager>,
pub(crate) processes: Option<&'a ProcessManager>,
pub(crate) workflows: &'a WorkflowRunTracker,
pub(crate) surfaces: Option<&'a SurfaceHost>,
pub(crate) pull_requests: Option<&'a PullRequestInbox>,
pub(crate) peer_sessions: Option<&'a PeerInbox>,
}
impl<'a> BackgroundSources<'a> {
/// The work of the session's `tools`; a turn adds its host's notices of
/// the turns it started in other sessions.
pub(crate) fn of(tools: &'a AppToolSet) -> Self {
Self {
subagents: tools.subagents(),
processes: tools.processes(),
workflows: tools.workflow_tracker(),
surfaces: tools.surfaces(),
pull_requests: tools.pull_requests(),
peer_sessions: None,
}
}
/// Whether work of session `session_id`'s still runs or holds a result
/// no prompt delivered, whichever prompt started it: a subagent, a
/// workflow run, a live background process, task or service, or a
/// finished task's result. A finished service's result does not count:
/// it waits only for a next prompt, so it must not keep an idle
/// session loaded or a daemon upgrade waiting. Neither does pull request
/// news: it is saved, so an unloaded session or a restarted daemon still
/// delivers it.
pub(crate) fn has_work(&self, session_id: &str) -> bool {
self.subagents
.is_some_and(|manager| manager.has_active_or_pending_notification(session_id))
|| self
.workflows
.has_active_or_pending_notification(session_id)
|| self
.processes
.is_some_and(|processes| processes.has_live() || processes.has_task_result())
|| self.surfaces.is_some_and(SurfaceHost::has_action)
}
/// Whether work of session `session_id`'s still runs: a live background
/// process, task or service, or a subagent or workflow run that has not
/// finished. A subagent that waits on a person's answer to its question
/// still runs. Unlike [`Self::has_work`], no result counts: not a
/// finished task's, child's or workflow run's, nor a surface action.
///
/// For a host with no waker of its idle sessions, as for a daemon
/// session an agent of another runtime runs whose client takes no turns
/// the daemon starts: a result there waits for a turn nothing will
/// start, so counting it would keep the session loaded, and a daemon
/// upgrade waiting, forever. Such a host loses a result an unload
/// drops, which [`Self::has_work`] keeps. A session the daemon wakes
/// takes [`Self::has_work`] instead.
pub(crate) fn has_live_work(&self, session_id: &str) -> bool {
self.subagents
.is_some_and(|manager| manager.has_running(session_id))
|| self.workflows.has_live(session_id)
|| self.processes.is_some_and(ProcessManager::has_live)
}
}
/// What of a session's background work keeps it loaded and a daemon
/// upgrade waiting, as its host says.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CountedWork {
/// What still runs, or holds a result or a child's notice no prompt
/// took: something may still deliver that result, so a teardown would
/// drop it.
Results,
/// Only what still runs ([`BackgroundSources::has_live_work`]): nothing
/// will deliver a result, as for a session no waker wakes, or one whose
/// waker gave up on the result it holds.
Live,
}
/// Whether work of session `session_id` from `sources`, or a child's
/// notice `held` keeps for the next prompt, is work a teardown would stop
/// or drop, counted as `counted` says.
pub(crate) fn has_work(
session_id: &str,
sources: &BackgroundSources<'_>,
held: Option<&HeldNotices>,
counted: CountedWork,
) -> bool {
match counted {
CountedWork::Results => {
sources.has_work(session_id) || held.is_some_and(HeldNotices::has_undelivered)
}
CountedWork::Live => sources.has_live_work(session_id),
}
}
/// The session's subagent notice binding: what its children told it before
/// they finished (`message_parent`, action requests).
struct NoticeBinding {
manager: SubagentManager,
notices: mpsc::Receiver<SubagentNotice>,
permits: NoticePermits,
/// Notices received and not yet delivered, in send order.
pending: Vec<SubagentNotice>,
/// Whether `notices` may still bring one.
open: bool,
}
/// A notice binding kept between prompts. The binding stays installed, so a
/// child can still queue `message_parent` text or an action request while no
/// prompt runs, and notices a cancelled prompt never delivered reach the next.
pub(crate) struct HeldNotices(NoticeBinding);
impl HeldNotices {
/// Whether a child's notice waits for the next prompt.
pub(crate) fn has_undelivered(&self) -> bool {
let Self(binding) = self;
!binding.pending.is_empty() || !binding.notices.is_empty()
}
}
/// Finished work a delivery reserved from its sources, in their order.
/// Dropping it uncommitted puts it back.
pub(crate) struct Batch(Vec<Reserved>);
impl Batch {
/// Whether a source gave it a result.
pub(crate) fn has_results(&self) -> bool {
let Self(reserved) = self;
reserved.iter().any(|reserved| !reserved.is_empty())
}
/// Whether each source gave it a result, in their order.
#[cfg(test)]
pub(crate) fn results_by_source(&self) -> Vec<bool> {
let Self(reserved) = self;
reserved
.iter()
.map(|reserved| !reserved.is_empty())
.collect()
}
}
/// Whether a delivery gave the model the children's pending notices too.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Notices {
/// They went with it: committing it acknowledges them.
Offered,
/// They wait for a later delivery.
Kept,
}
/// Delivery of one session's background work, from its sources, for as
/// long as one prompt (or one agent's turn) runs. Dropping it retires the
/// children's notice binding; [`Self::hold`] keeps it for the next.
pub(crate) struct BackgroundDelivery {
session_id: String,
subagents: Option<NoticeBinding>,
/// The work a delivery takes, in the order the model reads it: the
/// subagents' results, the workflows', the processes', what the user
/// did on A2UI surfaces that no `ui` call waited for, news of watched
/// pull requests, and notices of turns the session started in other
/// sessions.
sources: Vec<BoundarySource>,
}
impl BackgroundDelivery {
/// Delivers session `session_id`'s work from `sources`. A binding in
/// `held` resumes the last prompt's children's notices; without one the
/// delivery binds afresh, retiring any earlier binding. The session's
/// workflow runs report to it from now on.
pub(crate) fn bind(
session_id: String,
sources: BackgroundSources<'_>,
held: Option<HeldNotices>,
) -> Self {
let mut held = held.map(|HeldNotices(binding)| binding);
let subagents = sources.subagents.map(|manager| {
held.take().unwrap_or_else(|| {
let binding = manager.rebind_notices(None);
NoticeBinding {
manager: manager.clone(),
notices: binding.receiver,
permits: binding.permits,
pending: binding.retained,
open: true,
}
})
});
sources.workflows.bind_parent_session(session_id.clone());
let sources = [
// Results come from the manager the notices are bound to, even a
// binding held over from the last prompt.
subagents.as_ref().map(|binding| BoundarySource::Subagents {
manager: Box::new(binding.manager.clone()),
session: session_id.clone(),
}),
Some(BoundarySource::Workflows {
tracker: sources.workflows.clone(),
session: session_id.clone(),
}),
sources.processes.cloned().map(BoundarySource::Processes),
sources.surfaces.cloned().map(BoundarySource::Surfaces),
sources
.pull_requests
.cloned()
.map(BoundarySource::PullRequests),
sources.peer_sessions.cloned().map(BoundarySource::Peers),
]
.into_iter()
.flatten()
.collect();
Self {
session_id,
subagents,
sources,
}
}
/// Ends the delivery but keeps its notice binding, with every notice not
/// yet delivered, for the next [`Self::bind`].
pub(crate) fn hold(mut self) -> Option<HeldNotices> {
self.subagents.take().map(HeldNotices)
}
/// The sources a delivery takes from, for a host's policy on what is
/// due and what holds a prompt open.
pub(crate) fn sources(&self) -> &[BoundarySource] {
&self.sources
}
/// Resolves once a result of any source but the subagents may have
/// arrived from now on, subscribed when called: the children reach
/// [`Self::changed`] through the notice binding. Subscribe before
/// [`Self::collect`], so a finish in between still wakes the wait.
pub(crate) fn arrivals(&self) -> Arrival {
any_arrived(self.sources.iter().filter_map(|source| match source {
BoundarySource::Subagents { .. } => None,
BoundarySource::Workflows { .. }
| BoundarySource::Processes(_)
| BoundarySource::Surfaces(_)
| BoundarySource::PullRequests(_)
| BoundarySource::Peers(_) => Some(source.arrived()),
}))
}
/// Resolves once `arrived`, from [`Self::arrivals`], does, a child ends,
/// or a child's notice arrives, which it keeps for the next delivery.
pub(crate) async fn changed(&mut self, arrived: Arrival) {
match &mut self.subagents {
Some(subagents) => tokio::select! {
notice = subagents.notices.recv(), if subagents.open => match notice {
Some(notice) => subagents.pending.push(notice),
None => subagents.open = false,
},
() = subagents.manager.wait_for_notification(&self.session_id) => {}
() = arrived => {}
},
None => arrived.await,
}
}
/// Drains the children's notices, then reserves finished work from every
/// source, under the delivery lock `_delivery` holds.
pub(crate) fn collect(&mut self, _delivery: &DeliveryLock) -> Batch {
if let Some(subagents) = &mut self.subagents {
while let Ok(notice) = subagents.notices.try_recv() {
subagents.pending.push(notice);
}
let permits = &subagents.permits;
subagents.pending.retain(|notice| {
if notice.is_acknowledged() {
permits.release_notice(notice);
false
} else {
true
}
});
}
Batch(self.sources.iter().map(BoundarySource::reserve).collect())
}
/// Whether a child's notice waits for delivery.
pub(crate) fn has_notices(&self) -> bool {
self.subagents
.as_ref()
.is_some_and(|subagents| !subagents.pending.is_empty())
}
/// Whether a child's notice that waits asks the parent to act.
pub(crate) fn action_requested(&self) -> bool {
self.subagents.as_ref().is_some_and(|subagents| {
subagents
.pending
.iter()
.any(|notice| notice.delivery.requires_parent_action())
})
}
/// Model input and display rows for `batch` and the notices that wait,
/// rendered as the TUI renders them; `None` when there is nothing.
pub(crate) fn render(&self, batch: &Batch) -> Option<(String, DisplayTranscript)> {
let Batch(batch) = batch;
BoundaryResults {
notices: self
.subagents
.as_ref()
.map(|subagents| subagents.pending.as_slice())
.unwrap_or_default(),
reserved: batch.as_slice(),
}
.render(self.subagents.as_ref().map(|subagents| &subagents.manager))
.finish()
}
/// The model took `batch`, and the notices that wait as `notices` says:
/// they are delivered.
pub(crate) fn commit(&mut self, batch: Batch, notices: Notices) {
let Batch(mut batch) = batch;
batch.iter_mut().for_each(Reserved::commit);
if let (Notices::Offered, Some(subagents)) = (notices, &mut self.subagents) {
for notice in subagents.pending.drain(..) {
notice.acknowledge();
subagents.permits.release_notice(¬ice);
}
}
}
}
impl Drop for BackgroundDelivery {
fn drop(&mut self) {
let Some(subagents) = &mut self.subagents else {
return;
};
let _delivery = crate::app::notification_delivery::lock();
subagents.manager.unbind_notices();
// Cancellation can leave queued notices behind. A host that drops the
// binding instead of holding it retires their receipts with it.
while let Ok(notice) = subagents.notices.try_recv() {
subagents.pending.push(notice);
}
for notice in subagents.pending.drain(..) {
subagents.permits.release_notice(¬ice);
}
}
}
#[cfg(test)]
#[path = "background_delivery_tests.rs"]
mod tests;